diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb4ec50b..1145b532 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,8 @@ jobs: # Same craft-fonts commit as release.yml. 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/freebsd.yml b/.github/workflows/freebsd.yml index 9f64bbdd..442b9fd7 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -33,4 +33,9 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc + # The VM's software Vulkan driver crashes (SIGSEGV) when several tests set up a device at + # once (photocraft serializes its GPU tests for the same reason), so tests run one at a + # time. The whole workspace is tested in one command: excluding packages would change + # feature unification and build winit without its X11/Wayland backends. + cargo-test-extra-args: "-- --test-threads=1" run-package-check: true 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/.github/workflows/release.yml b/.github/workflows/release.yml index 3ed14bca..23727788 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "44 2 * * *" push: branches: [release] workflow_dispatch: @@ -23,6 +27,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: texturecraft app-title: "TextureCraft" craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc @@ -43,3 +48,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml new file mode 100644 index 00000000..8ab024cf --- /dev/null +++ b/.github/workflows/sonarcloud.yml @@ -0,0 +1,19 @@ +name: SonarCloud + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: sonarcloud-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +jobs: + sonarcloud: + uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + secrets: inherit diff --git a/AGENTS.md b/AGENTS.md index ad435dac..9a78849f 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, @@ -58,6 +108,13 @@ replace it without touching the engine. ## 3. Golden rules +### Never name the reference product (absolutely essential) + +- The repository never names the commercial product TextureCraft is modeled on, nor its vendor, + in code, comments, docs, commit messages, test names, file names or UI text. Say "the reference + app", "the professional model-painter workflow" or describe the feature itself. +- Notes that name it may live only in the gitignored `plan/` folder or in this `AGENTS.md` file + ### Assets, icons and images (absolutely essential) - **Never use any icon, image, logo, texture, material, brush, environment, font or other asset @@ -91,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 @@ -126,7 +183,7 @@ panic. The shared standard is `../craftrules/standards/never-crash.md`. Benchmark heavy paths (bake, composite, export) in release and record numbers in the dev log. 8. **Cross-app formats are shared conventions.** MaterialCraft's `.mcmat` portable materials are read here with our own code (`formats::mcmat`): keep the manifest fields, usage ids and - mesh-map identifiers (`BakedMap::interop_id`) in step with MaterialCraft's + mesh-map identifiers (`BakedMap::id`) in step with MaterialCraft's `docs/control-protocol.md`, and never depend on MaterialCraft's crates; talk to it through `materialcraft-cli`. 9. **Verify UI changes visually.** Launch with `--control ` and call `ui.screenshot` (whole @@ -169,6 +226,10 @@ 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. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage. 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/CODE_STYLE.md b/CODE_STYLE.md new file mode 100644 index 00000000..92a74a1c --- /dev/null +++ b/CODE_STYLE.md @@ -0,0 +1,77 @@ +# Code style + +Style conventions for TextureCraft's Rust code. +Read alongside [AGENTS.md](AGENTS.md) for repository requirements. + +## Naming and Rust conventions + +- Use descriptive names that explain purpose; include units where useful. Avoid misleading names + and abbreviations whose meaning is unclear in context. +- Follow Rust naming conventions: `snake_case` for functions, variables, fields, and modules; + `UpperCamelCase` for types and traits; `SCREAMING_SNAKE_CASE` for constants and statics. +- Conventional Rust names are not cryptic abbreviations. Keep names such as `fmt`, `iter`, `len`, + `args`, `err`, `id`, and `ui` when their meaning is clear. Do not expand them just to make them + longer. +- Keep standard file and directory names such as `lib.rs`, `main.rs`, `mod.rs`, `src`, `tests`, + `examples`, and `benches`. Rust keywords such as `mut`, `ref`, `impl`, and `mod` are language + syntax, not naming problems. +- Short names are appropriate in a clear local context: `i` for an index, `x` and `y` for + coordinates, `w` and `h` for image dimensions, and conventional generic parameters such as `T`. + Use more descriptive names when scope or ambiguity makes those hard to follow. + +## Magic numbers + +- Give non-obvious limits, thresholds, sizes, and tuning values descriptive named constants + instead of leaving unexplained numeric literals in the code. +- Name constants for their purpose, with units where useful, rather than for their literal value. + Keep them in the narrowest useful scope. +- Reuse an existing constant when it represents the same concept. Equal numeric values alone do + not mean two concepts should share a constant. +- Explain the origin or rationale of non-obvious coefficients and tolerances in a short comment. + Use standard library constants for standard mathematical values. +- Keep literals inline when their role is clear, such as zero initialization, incrementing by one, + or dividing by two to find a midpoint. Do not introduce names such as `ZERO` or `TWO` that add + no meaning. +- Apply this guidance to tests too; clear fixture values and expected results can remain literal. + +## Formatting and spacing + +- Let `cargo fmt` and the repository's [rustfmt.toml](rustfmt.toml) handle mechanical formatting. + Do not introduce a competing indentation or line-wrapping convention. +- Use one blank line between distinct logical steps: input preparation, validation, computation, + mutation, and result construction. +- Keep closely related statements together. Do not add a blank line after every declaration or + fragment a single operation with extra spacing. +- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before + the next statement. +- Put a blank line before a comment introducing a new step, with no blank line between the + comment and the code it explains. +- Keep documentation and attributes attached to their declarations. +- Separate function definitions with one blank line. Avoid extra empty lines just inside braces + or between every field, argument, or statement. +- In tests, separate preparation, action, and verification with blank lines when those phases + are distinct; keep related assertions together. + +## Source organization + +- Give each struct or enum its own source file, with its implementation beside it. Use the full + type name in `snake_case`, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings`. +- Preserve conventional crate roots and module entry points such as `lib.rs`, `main.rs`, and + `mod.rs`. Follow the command and node module placement required by `AGENTS.md`. +- Prefer singular folder names for new domain modules, such as `map`, `setting`, or `tracing`. + Keep standard Rust directories and repository-mandated paths unchanged. +- Group related types into focused modules rather than collecting unrelated types in one large file. +- Apply these preferences to new types and source organization changes within scope. Do not + reorganize unrelated existing code to enforce them. + +## Comments + +- Explain intent or a non-obvious constraint rather than narrating the code. +- Use short `//` comments. Avoid block comments and wrapped prose in ordinary implementation + comments; adjacent comment lines should each express a concise point. +- Do not add trailing punctuation to 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 conventional multiline + formatting and punctuation. +- Apply the same comment guidance to production code and tests. diff --git a/Cargo.lock b/Cargo.lock index 5085d081..54f6ef82 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,50 @@ 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-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295" +dependencies = [ + "md-5", + "rayon", +] + +[[package]] +name = "craft-dialogs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" [[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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "fixed_decimal", "icu_decimal", @@ -749,10 +805,84 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-keymap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-materialx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "craft-xml", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-mcmat" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-menu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "craft-keymap", + "craft-quit", + "egui", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + +[[package]] +name = "craft-mesh" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52)", + "miniz_oxide 0.9.1", +] + +[[package]] +name = "craft-quit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "dispatch2", + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + +[[package]] +name = "craft-tcraft" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -770,10 +900,46 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "chrono", + "dunce", + "egui", + "flate2", + "getrandom 0.3.4", + "image", + "log", + "plist", + "rustix 1.1.5", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip", +] + +[[package]] +name = "craft-usd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f7655fb3ea59d6b21681700c0ff880823f5bb709#f7655fb3ea59d6b21681700c0ff880823f5bb709" +dependencies = [ + "lz4_flex", + "thiserror 2.0.21", +] + [[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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "egui", "objc2 0.6.5", @@ -781,6 +947,36 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -790,6 +986,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 +1026,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 +1076,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 +1151,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" @@ -1171,7 +1408,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -1252,6 +1489,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 +1694,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 +1714,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 +1996,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 +2387,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" @@ -2248,6 +2542,16 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -2322,6 +2626,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.60.2", +] + [[package]] name = "naga" version = "30.0.1" @@ -2417,6 +2739,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -2427,6 +2758,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" @@ -2629,6 +2966,16 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -2776,6 +3123,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" @@ -2812,7 +3165,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -2978,6 +3331,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" @@ -3062,6 +3428,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" @@ -3136,6 +3508,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" @@ -3320,6 +3701,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" @@ -3414,7 +3809,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -3427,6 +3822,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.60.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" @@ -3442,6 +3911,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" @@ -3480,6 +3958,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" @@ -3491,6 +3992,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" @@ -3572,6 +4077,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" @@ -3743,6 +4259,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" @@ -3788,6 +4310,30 @@ dependencies = [ "web-sys", ] +[[package]] +name = "sysinfo" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "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" @@ -3795,10 +4341,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -3812,8 +4358,10 @@ dependencies = [ [[package]] name = "texturecraft" -version = "0.3.0" +version = "0.6.1" dependencies = [ + "craft-menu", + "craft-update", "eframe", "egui", "image", @@ -3831,7 +4379,7 @@ dependencies = [ [[package]] name = "texturecraft-automation" -version = "0.3.0" +version = "0.6.1" dependencies = [ "base64 0.22.1", "cap-std", @@ -3852,8 +4400,9 @@ dependencies = [ [[package]] name = "texturecraft-bake" -version = "0.3.0" +version = "0.6.1" dependencies = [ + "bytemuck", "rayon", "texturecraft-core", "texturecraft-geom", @@ -3863,7 +4412,7 @@ dependencies = [ [[package]] name = "texturecraft-cli" -version = "0.3.0" +version = "0.6.1" dependencies = [ "image", "serde_json", @@ -3875,7 +4424,7 @@ dependencies = [ [[package]] name = "texturecraft-compose" -version = "0.3.0" +version = "0.6.1" dependencies = [ "half", "rayon", @@ -3886,7 +4435,7 @@ dependencies = [ [[package]] name = "texturecraft-core" -version = "0.3.0" +version = "0.6.1" dependencies = [ "serde", "serde_json", @@ -3895,7 +4444,7 @@ dependencies = [ [[package]] name = "texturecraft-engine" -version = "0.3.0" +version = "0.6.1" dependencies = [ "epaint_default_fonts", "image", @@ -3915,31 +4464,38 @@ dependencies = [ [[package]] name = "texturecraft-formats" -version = "0.3.0" +version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-cms", + "craft-materialx", + "craft-mcmat", + "craft-mesh", + "craft-tcraft", + "craft-usd", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", "exr", "flate2", "gltf", "half", "image", "lz4_flex", - "quick-xml", + "quick-xml 0.41.0", "rayon", "serde", "serde_json", + "sysinfo", "texturecraft-compose", "texturecraft-core", "texturecraft-geom", "texturecraft-texel", "thiserror 2.0.21", - "tobj", "zip", ] [[package]] name = "texturecraft-geom" -version = "0.3.0" +version = "0.6.1" dependencies = [ "glam 0.30.10", "mikktspace", @@ -3950,7 +4506,7 @@ dependencies = [ [[package]] name = "texturecraft-paint" -version = "0.3.0" +version = "0.6.1" dependencies = [ "epaint_default_fonts", "harfrust", @@ -3965,7 +4521,7 @@ dependencies = [ [[package]] name = "texturecraft-render" -version = "0.3.0" +version = "0.6.1" dependencies = [ "bytemuck", "half", @@ -3973,6 +4529,7 @@ dependencies = [ "log", "pollster 0.4.0", "rayon", + "serde", "texturecraft-bake", "texturecraft-compose", "texturecraft-core", @@ -3984,14 +4541,19 @@ dependencies = [ [[package]] name = "texturecraft-texel" -version = "0.3.0" +version = "0.6.1" [[package]] name = "texturecraft-ui-egui" -version = "0.3.0" +version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-dialogs", + "craft-i18n", + "craft-keymap", + "craft-quit", "craft-ui", + "craft-update", "craft-window", "eframe", "egui", @@ -4000,6 +4562,7 @@ dependencies = [ "image", "js-sys", "log", + "pollster 0.4.0", "rayon", "rfd", "serde", @@ -4017,7 +4580,7 @@ dependencies = [ [[package]] name = "texturecraft-web" -version = "0.3.0" +version = "0.6.1" dependencies = [ "eframe", "js-sys", @@ -4083,6 +4646,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" @@ -4094,12 +4687,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "tobj" -version = "4.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2" - [[package]] name = "tokio" version = "1.53.3" @@ -4265,6 +4852,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" @@ -4312,6 +4905,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" @@ -4327,6 +4955,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" @@ -4381,6 +5015,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" @@ -4561,7 +5205,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -4597,6 +5241,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" @@ -4786,15 +5439,37 @@ dependencies = [ "web-sys", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows" version = "0.62.2" @@ -5095,7 +5770,7 @@ dependencies = [ "calloop", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -5140,6 +5815,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" @@ -5281,7 +5966,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.3.0" +version = "0.6.1" dependencies = [ "serde_json", ] @@ -5456,6 +6141,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 d6259b75..88936e5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,13 +5,14 @@ exclude = ["vendor"] default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"] [workspace.package] -version = "0.3.0" +version = "0.6.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f7655fb3ea59d6b21681700c0ff880823f5bb709" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } @@ -32,6 +33,8 @@ serde_json = "1" glam = { version = "0.30", features = ["serde", "bytemuck"] } bytemuck = { version = "1", features = ["derive"] } rayon = "1" +# Free RAM, to size how much a project save holds in flight. +sysinfo = { version = "0.40", default-features = false, features = ["system"] } # Text alphas: shaping and glyph outlines, the versions egui's text layout already builds. harfrust = "0.12" skrifa = { version = "0.44", default-features = false, features = ["std"] } @@ -47,7 +50,6 @@ wgpu = "30" rfd = "0.17" zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } -tobj = { version = "4", default-features = false } flate2 = "1" lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } quick-xml = "0.41" @@ -63,9 +65,26 @@ 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"] } +# Shared catalog lookup, pinned with the other Craft libraries. +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } +craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } # 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] @@ -103,6 +122,13 @@ opt-level = 1 lto = "thin" codegen-units = 1 +# Fast optimized verification: each test executable otherwise repeats cross-crate LTO. +# `false` keeps thin LTO within each crate; release packaging keeps the profile above. +[profile.verify] +inherits = "release" +lto = false +codegen-units = 16 + [profile.wasm-release] inherits = "release" opt-level = "s" 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/ROADMAP.md b/ROADMAP.md index e856b3ff..1a70d26d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing wor performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and builds for Windows, macOS, Linux, FreeBSD and the web. -## Honest parity estimate (2026-11-02) +## Honest parity estimate (2026-11-04) Weighted by how much of a professional's daily work each area carries. "Done" counts what works end to end today (engine + UI + automation + tests), not what is planned. @@ -14,15 +14,18 @@ end to end today (engine + UI + automation + tests), not what is planned. | Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — | | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | +| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | | Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | -| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **skew correction** (`bake.skew.set`, painted in the 2D view with `bake.skew.paint` and saved in the project: a greyscale map over the atlas that turns the transfer rays onto the base normal, with hard-edge protection), **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly, the high polys or the skew map change); **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | +| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | -| **Total** | **100** | **≈ 94%** | | | +| **Total** | **100** | **≈ 94%** | Weighted workflow-completion estimate | | + +Baking’s 90% estimates workflow completion: all ten map types and exposed settings have implementation +paths, with the remaining work listed above. Pixel-level equivalence with Painter remains unverified. Beyond the reference app: every command is available to agents through MCP, the CLI and the app's control channel (MCP workspace tools cover every file action: projects, meshes, high polys and @@ -38,13 +41,13 @@ parallel on separate crates: | M1 Layer stack depth | Done | 0 h | | M2 Tools | Pen tilt, and pen pressure on Linux, macOS and desktop browsers, once the windowing layer reports them | 0.5 h | | M3 Assets | Done | 0 h | -| M4 Baking | Done | 0 h | +| M4 Baking | Validate outputs across reference assets, refine remaining map differences and add 3D cage editing | TBD | | M5 Viewport | Hardware ray tracing: wgpu's ray queries are experimental and need an `unsafe` opt-in, which the workspace forbids (owner decision) | 1.5 h | | M6 Shader | Done | 0 h | | M7 Formats | Done | 0 h | | M8 UX | Native review of translations | 1 h | | M9 Release | The twelve signing secrets and the Default runner group (org admin); first signed release run on every platform (v0.1.0); web deployment; Flathub submission | 3 h | -| **Total** | | **≈ 6 h** | +| **Total** | | **≈ 6 h + baking TBD** | ## Current focus diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 686bee97..4cb6a5aa 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -1,12 +1,34 @@ //! Drives the `texturecraft-cli` binary. +use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use serde_json::Value; +// Nextest 0.9.130+ remaps this variable when an archive is extracted on another +// runner. Cargo's compile-time path still supports ordinary `cargo test`. +fn cli_binary() -> OsString { + cli_binary_path(std::env::var_os("CARGO_BIN_EXE_texturecraft-cli")) +} + +fn cli_binary_path(runner_path: Option) -> OsString { + runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into()) +} + +#[test] +fn cli_binary_prefers_relocated_runner_path() { + let relocated = OsString::from("relocated archive/texturecraft-cli"); + assert_eq!(cli_binary_path(Some(relocated.clone())), relocated); +} + +#[test] +fn cli_binary_defaults_to_cargo_path() { + assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli"))); +} + fn cli(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")).args(args).output().unwrap() + Command::new(cli_binary()).args(args).output().unwrap() } fn ok(args: &[&str]) -> String { @@ -101,7 +123,7 @@ fn info_on_a_mesh_reports_uvs() { fn serve_takes_the_automation_root_spelling_too() { use std::io::Write as _; let d = tmp("automation-root"); - let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + let mut child = Command::new(cli_binary()) .args(["serve", "--automation-write-root", p(&d)]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) 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..2deac956 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) +/// Preferences needed before opening the initial project or window, with legacy storage fallback. +fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs { + if let Some(ui) = ui_file.and_then(ui_state_store::read) { + return ui.prefs; + } + + 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()).map(|ui| ui.prefs).unwrap_or_default() } /// 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,27 @@ 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 prefs = saved_prefs(ui_file.as_deref(), persistence_path.as_deref()); + prefs.apply_resource_limits(); + let session = initial_session(&args); + let title_bar = TitleBar::decide(prefs.system_title_bar); + 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 +220,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 +230,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 +305,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 +333,36 @@ 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 startup_preferences_use_ui_json_then_legacy_storage_then_defaults() { + 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. + ui.prefs.project_open_limit_gib = 16; + + // 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(); + + let legacy = saved_prefs(None, Some(&ron_path)); + assert_eq!(legacy.system_title_bar, on); + assert_eq!(legacy.project_open_limit_gib, 16); + + ui.prefs.system_title_bar = !on; + ui.prefs.project_open_limit_gib = 32; + std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); + + let current = saved_prefs(Some(&json_path), Some(&ron_path)); + assert_eq!(current.system_title_bar, !on, "ui.json comes first"); + assert_eq!(current.project_open_limit_gib, 32); } - 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_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); + std::fs::remove_file(&json_path).unwrap(); + std::fs::remove_file(&ron_path).unwrap(); + assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); } } diff --git a/craft-i18n.rev b/craft-i18n.rev new file mode 100644 index 00000000..2da99634 --- /dev/null +++ b/craft-i18n.rev @@ -0,0 +1 @@ +3cb11a36a58c5eabfd3a768448b55fdf086885bf 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..e390c239 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, }; @@ -85,7 +85,15 @@ impl Gpu { /// Render `s` with `kind` at `size` through `camera`; RGBA8 (sRGB) pixels. pub fn render(&mut self, s: &mut Session, kind: ViewKind, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera) -> Option<(u32, u32, Vec)> { self.sync(s); - let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() }; + let frame = Frame { + view_id: 1, + size, + kind, + camera, + shade: shade(s), + visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + overlay: Vec::new(), + }; self.h.render(&frame) } diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 0f5e6ab5..63c12b0e 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -178,8 +178,11 @@ pub struct ConnectionLimiter(Arc); pub struct Permit(Arc); impl ConnectionLimiter { - pub fn try_acquire(&self, max: usize) -> Option { - self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) + pub fn try_acquire(&self, max_connections: usize) -> Option { + self.0 + .try_update(Ordering::AcqRel, Ordering::Acquire, |connections| (connections < max_connections).then_some(connections + 1)) + .ok() + .map(|_| Permit(self.0.clone())) } } @@ -328,10 +331,12 @@ mod tests { #[test] fn limiter_releases() { - let l = ConnectionLimiter::default(); - let p = l.try_acquire(1).unwrap(); - assert!(l.try_acquire(1).is_none()); - drop(p); - assert!(l.try_acquire(1).is_some()); + let limiter = ConnectionLimiter::default(); + + let permit = limiter.try_acquire(1).unwrap(); + assert!(limiter.try_acquire(1).is_none()); + + drop(permit); + assert!(limiter.try_acquire(1).is_some()); } } 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/Cargo.toml b/crates/bake/Cargo.toml index 9b893562..7125135f 100644 --- a/crates/bake/Cargo.toml +++ b/crates/bake/Cargo.toml @@ -12,5 +12,6 @@ workspace = true texturecraft-core = { workspace = true } texturecraft-geom = { workspace = true } texturecraft-texel = { workspace = true } +bytemuck = { workspace = true, features = ["extern_crate_alloc"] } rayon = { workspace = true } thiserror = { workspace = true } diff --git a/crates/bake/README.md b/crates/bake/README.md index 786f69f3..0eac65cc 100644 --- a/crates/bake/README.md +++ b/crates/bake/README.md @@ -1,26 +1,41 @@ # texturecraft-bake -Mesh-map baker: `bake(&BakeRequest, &Progress) -> BakeOutput` turns one texture set's UV layout into float maps (0..1, rows top → bottom), supersampled, padded and deterministic. The supersamples are processed in batches: their high-poly transfer rays, then the secondary rays of ambient occlusion, bent normals and thickness go to a `rays::Tracer`, then all requested maps are evaluated per sample (rayon over rows). +Clean-room mesh-map baking from low-poly UVs and optional high-poly meshes. Persisted settings live in `texturecraft-core`; localized controls live in `texturecraft-ui-egui`. Types have individual files, with singular module folders. -The rays run on the CPU (`rays::CpuTracer`, the oracle) or, through `bake_on(&BakeRequest, &Progress, &dyn Tracer)`, on a GPU tracer (the render crate's `gpu_bake::GpuBaker`, wgpu compute shaders on the path tracer's BVH traversal). The GPU receives the same rays and per-sample rotations and casts the same secondary-ray directions, so both agree up to float rounding; when the tracer fails (no adapter, a mesh too large for it, a lost device) `bake_on` bakes again on the CPU. `BakeOutput::tracer` says where the rays ran. +`bake(&BakeRequest, &Progress)` runs the CPU oracle. `bake_on` accepts a `tracing::Tracer` such as the render crate's GPU baker, and retries on the CPU if that tracer fails. Both receive identical transfer rays and secondary-ray samples. Output is deterministic, floating point, and stored in rows from top to bottom. Cancellation is checked between bounded batches and before returning the result. -With a high poly (`BakeRequest::high`, every high-definition mesh appended into one), each low-poly sample casts one ray from the cage (`BakeRequest::cage`, same triangles as the low poly) or from `max_frontal` in front of the surface back through it to `max_rear` behind (both relative to the bounding-box diagonal), along normals averaged over hard edges when `average_normals` is on. With `BakeMatch::ByMeshName`, a low-poly part only sees high-poly parts of the same name once `low_suffix` / `high_suffix` are removed (`wheel_low` ↔ `wheel_high`, case-insensitive). Every map but position and world-space direction then reads the high-poly surface that ray found (AO, thickness and bent normals cast against the high poly). +## Projection and common settings -Ambient occlusion, thickness and bent normals each have their own `RaySettings`: ray count, max distance (relative to the bounding-box diagonal), spread angle (the full cone around the normal; 180° = the hemisphere) and distribution (cosine-weighted or uniform over the cone). Ambient occlusion can ignore back faces and limit occluders to parts of the same mesh name (`SelfOcclusion::SameMeshName`); bent normals follow those occluder rules and share the AO rays when their settings match. +- Independent output width and height, antialiasing, per-UV-tile dilation, and optional background diffusion +- High-to-low matching: Always by default, or By Mesh Name using the configured low/high suffixes +- Transfer-ray backface filtering, distance-based or custom-file cages, frontal/rear distances, and averaged normals +- Relative distances use the longest bounding-box extent; absolute distances use imported mesh units +- Painted cage values multiply the frontal distance; painted skew values blend toward mesh or face normals, with optional hard-edge protection -| Map | Meaning | Range | -| --- | --- | --- | -| Ambient occlusion | How open the surface is (rays over the cone, distance falloff) | 0 occluded … 1 open | -| Bent normals | Mean unoccluded direction of the bent-normal rays, world space | packed ·0.5+0.5 | -| Thickness | Mean distance through the mesh along inward rays, relative to the max distance | 0 thin … 1 thick | -| Curvature | Mean curvature of the position-welded mesh, or (`curvature_from_normal`) the divergence of the baked normal map over `curvature_radius` texels (0: by resolution) | 0 concave … 0.5 flat … 1 convex | -| Normal | Tangent-space normal from the high poly (OpenGL, +Y up); flat without one | packed ·0.5+0.5 | -| Height | High-poly offset along the ray, scaled by frontal + rear distance | 0 rear … 0.5 surface … 1 front | -| World normal | Shading normal in world space | packed ·0.5+0.5 | -| Position | Position in the low poly's bounding box (per axis) or bounding sphere (`position_mode`) | 0 … 1 | -| ID | A distinct hue per mesh part (submesh) | RGB 0 … 1 | -| Opacity | 1 where the high poly was found (times its vertex and base color alpha), 0 where the ray missed | 0 … 1 | -| Color map | The high poly's vertex colors times its materials' base color (`HighPoly::base_color`: factor × texture at the hit UV, bilinear in linear light), sRGB-encoded like a base color texture | RGB 0 … 1 | -| World space direction | Facing ratio towards `direction`: signed (0.5 perpendicular) or positive (`direction_mode`) | 0 away … 1 facing | +`BakePaintMap` contains pixel data only. Cage and skew settings remain in their respective model containers. The engine stores paint maps per texture set in document snapshots and project files. The shared 2D brush supports undo, redo, reset, and UV-layout changes. -Uncovered texels beyond the padding get `BakedMap::neutral` values. Benchmarks (2K, the 7 default maps at 64 rays): `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench` (CPU, per-map breakdown) and `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed` (CPU vs GPU). +## Map settings + +| Map | Implemented behavior | +| --- | --- | +| Normal | Tangent-space high-poly normal, internally OpenGL; flat without a high-poly transfer | +| World Normal | World-space shading normal | +| ID | Vertex Color, Material Color, Mesh ID, Submesh ID, or File ID; Hue Shift, Random, and Grayscale generation | +| Ambient Occlusion | Independent ray count, distance interval, units, cone and distribution; backface and self-occlusion modes; None, Linear or Smooth attenuation; optional ground plane | +| Bent Normal | Independent occlusion settings and mean visible direction, encoded in world space | +| Thickness | Inward ray distances with self-occlusion filtering; raw, ray-distance or per-UV-tile min/max normalization | +| Curvature | Mesh-ray curvature with radius, ray count, self-intersection and automatic/manual tonemapping; normal-map curvature with detail strength and corresponding UV-edge seam blending | +| Position | All axes or a selected axis; scene or material bounds; box, uniform sphere-style or raw coordinates | +| Height | Signed high-poly displacement with low-mesh, min/max, ray-distance or manual normalization | +| Opacity | High-poly hit coverage multiplied by source vertex/material/texture alpha | + +ID Material Color reads the material factor independently of textures and vertex colors. A source without material colors uses neutral gray (0.6). Generated IDs are deterministic. Normal maps are stored in OpenGL convention; display/export apply the project's normal format. + +All dropdowns use enums. `BakedMap::id()` and `BakedMap::parse()` provide the shared MaterialCraft mesh-map identifiers. `bake.settings` accepts the complete nested model. No legacy Color or World Orientation map migration is provided. + +## Validation and limits + +Regression tests cover projection, matching, ray filters, normalization, rectangular maps, painting, persistence, and CPU/GPU agreement. The supplied 2048² high-to-low reference is evaluated separately, outside the repository, on UV-covered pixels. Numerical differences remain, especially in curvature and occlusion; exact Painter parity is not claimed. Painted cage control currently uses the 2D UV brush; it does not provide a 3D cage-editing overlay. + +CPU benchmark: `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench`. +GPU comparison: `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed`. diff --git a/crates/bake/src/bake_error.rs b/crates/bake/src/bake_error.rs new file mode 100644 index 00000000..f9fe3879 --- /dev/null +++ b/crates/bake/src/bake_error.rs @@ -0,0 +1,9 @@ +#[derive(Debug, thiserror::Error)] +pub enum BakeError { + #[error("bake cancelled")] + Cancelled, + #[error("invalid bake request: {0}")] + Invalid(String), + #[error("ray tracer: {0}")] + Tracer(String), +} diff --git a/crates/bake/src/bake_output.rs b/crates/bake/src/bake_output.rs new file mode 100644 index 00000000..bc021f6f --- /dev/null +++ b/crates/bake/src/bake_output.rs @@ -0,0 +1,11 @@ +use std::collections::BTreeMap; +use texturecraft_core::BakedMap; + +#[derive(Clone, Debug, PartialEq)] +/// Row-major maps, with BakedMap::components() floats per texel +pub struct BakeOutput { + pub resolution: u32, + pub height: u32, + pub maps: BTreeMap>, + pub tracer: String, +} diff --git a/crates/bake/src/bake_paint_map.rs b/crates/bake/src/bake_paint_map.rs new file mode 100644 index 00000000..cf6f0b4d --- /dev/null +++ b/crates/bake/src/bake_paint_map.rs @@ -0,0 +1,130 @@ +use crate::{BakeError, MAX_TEXELS}; +use texturecraft_geom::glam::Vec2; + +pub const MAX_DABS: usize = 200_000; + +// Bound total work across all dabs before changing any pixels +pub const MAX_PAINT_TEXELS: u64 = 1 << 26; + +#[derive(Clone, Debug, PartialEq)] +pub struct BakePaintMap { + pub width: u32, + pub height: u32, + /// Values in 0..=1 over the texture set UV atlas + pub values: Vec, +} + +impl BakePaintMap { + pub fn constant(value: f32) -> BakePaintMap { + BakePaintMap { width: 1, height: 1, values: vec![value] } + } + + pub fn validate(&self) -> Result<(), BakeError> { + let invalid = |m: &str| Err(BakeError::Invalid(m.into())); + let texels = u64::from(self.width) * u64::from(self.height); + if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels { + return invalid("the bake paint map's size doesn't match its values"); + } + if self.values.iter().any(|v| !v.is_finite()) { + return invalid("the bake paint map has a value that is not a finite number"); + } + Ok(()) + } + + pub fn resized(&self, width: u32, height: u32) -> Result { + let texels = u64::from(width) * u64::from(height); + if width == 0 || height == 0 || texels > MAX_TEXELS { + return Err(BakeError::Invalid(format!("a {width} × {height} bake paint map is outside the supported size"))); + } + let mut values = Vec::with_capacity(texels as usize); + for y in 0..height { + let v = (y as f32 + 0.5) / height as f32; + for x in 0..width { + values.push(self.sample(Vec2::new((x as f32 + 0.5) / width as f32, v))); + } + } + Ok(BakePaintMap { width, height, values }) + } + + pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> { + let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite(); + if !ok || points.iter().any(|p| !p.is_finite()) { + return Err(BakeError::Invalid("the bake brush needs finite numbers and a radius above 0".into())); + } + self.validate()?; + let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0)); + let step = (radius * 0.25).max(1e-5); + let mut dabs = Vec::new(); + for (i, p) in points.iter().enumerate() { + match i.checked_sub(1).and_then(|j| points.get(j)) { + Some(prev) => { + let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize; + dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32))); + } + None => dabs.push(*p), + } + if dabs.len() > MAX_DABS { + return Err(BakeError::Invalid(format!("a bake stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points"))); + } + } + let (w, h) = (self.width as usize, self.height as usize); + let span = |c: Vec2| { + let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize; + let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize; + let y0 = (((c.y - radius) * h as f32).floor().max(0.0)) as usize; + let y1 = (((c.y + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize; + (x0, x1, y0, y1) + }; + let work: u64 = dabs + .iter() + .map(|c| { + let (x0, x1, y0, y1) = span(*c); + x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64 + }) + .fold(0, u64::saturating_add); + if work > MAX_PAINT_TEXELS { + return Err(BakeError::Invalid(format!( + "this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke" + ))); + } + for c in dabs { + let (x0, x1, y0, y1) = span(c); + for y in y0..y1 { + let dv = (y as f32 + 0.5) / h as f32 - c.y; + for x in x0..x1 { + let du = (x as f32 + 0.5) / w as f32 - c.x; + let t = (du * du + dv * dv).sqrt() / radius; + if t >= 1.0 { + continue; + } + let fall = if t <= hardness { + 1.0 + } else { + let k = (1.0 - t) / (1.0 - hardness); + k * k * (3.0 - 2.0 * k) + }; + if let Some(v) = self.values.get_mut(y * w + x) { + *v += (value - *v) * fall * strength; + } + } + } + } + Ok(()) + } + + pub fn sample(&self, uv: Vec2) -> f32 { + let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize); + if !uv.is_finite() { + return 0.0; + } + let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0); + let y = (uv.y.clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0); + let (x0, y0) = (x.floor() as usize, y.floor() as usize); + let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); + let (fx, fy) = (x - x0 as f32, y - y0 as f32); + let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0); + let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx; + let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx; + (top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0) + } +} diff --git a/crates/bake/src/bake_request.rs b/crates/bake/src/bake_request.rs new file mode 100644 index 00000000..69925325 --- /dev/null +++ b/crates/bake/src/bake_request.rs @@ -0,0 +1,19 @@ +use crate::{BakePaintMap, HighPoly}; +use std::sync::Arc; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{BaseColor, Bvh, Mesh}; + +#[derive(Clone, Copy, Debug)] +pub struct BakeRequest<'a> { + pub mesh: &'a Mesh, + pub bvh: &'a Bvh, + pub material: usize, + pub low_base_color: &'a [Option>], + pub settings: &'a BakeSettings, + pub high: Option>, + pub cage: Option<&'a Mesh>, + pub skew: Option<&'a BakePaintMap>, + pub cage_paint: Option<&'a BakePaintMap>, + /// UV atlas grid; each tile uses the configured output resolution + pub tiles: (u32, u32), +} 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..07a8eff2 --- /dev/null +++ b/crates/bake/src/cage/cage_shell.rs @@ -0,0 +1,98 @@ +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]>, + /// Corner pairs along the low poly's hard edges without a UV seam + pub missing_seams: 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)?)?; + Self::build(request, ray_frame, || { + // Each scan drops other materials' edges before the next scan starts + let wire_edges = request.mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let missing_seam_edges = request.mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + (wire_edges, missing_seam_edges) + }) + } + + /// Build a cage using edges already scanned for every material of the low mesh + pub fn new_with_edges(request: &BakeRequest, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result { + let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + Self::build(request, ray_frame, || { + ( + wire_edges.get(request.material).into_iter().flatten().copied().collect(), + missing_seam_edges.get(request.material).into_iter().flatten().copied().collect(), + ) + }) + } + + fn build( + request: &BakeRequest, + ray_frame: RayFrame, + edge_sets: impl FnOnce() -> (HashSet<(u32, u32)>, HashSet<(u32, u32)>), + ) -> Result { + 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, missing_seam_edges) = edge_sets(); + let (mut edge_corners, mut seam_corners) = (HashMap::new(), 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)); + let first_corner = (triangle_index * 3) as u32; + let corners = [first_corner + corner as u32, first_corner + next as u32]; + if wire_edges.contains(&key) { + edge_corners.entry(key).or_insert(corners); + } + if missing_seam_edges.contains(&key) { + seam_corners.entry(key).or_insert(corners); + } + } + } + let sorted = |corners: HashMap<(u32, u32), [u32; 2]>| { + let mut pairs: Vec<[u32; 2]> = corners.into_values().collect(); + pairs.sort_unstable(); + pairs + }; + + Ok(CageShell { positions, starts, edges: sorted(edge_corners), missing_seams: sorted(seam_corners), 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..2f461343 --- /dev/null +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -0,0 +1,105 @@ +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.as_chunks::<3>().0.iter().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.as_chunks::<3>().0 { + 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/high_poly.rs b/crates/bake/src/high_poly.rs new file mode 100644 index 00000000..9901f0e7 --- /dev/null +++ b/crates/bake/src/high_poly.rs @@ -0,0 +1,10 @@ +use std::sync::Arc; +use texturecraft_geom::{BaseColor, Bvh, Mesh}; + +#[derive(Clone, Copy, Debug)] +pub struct HighPoly<'a> { + pub file_ids: &'a [u32], + pub mesh: &'a Mesh, + pub bvh: &'a Bvh, + pub base_color: &'a [Option>], +} diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 39d466e1..1d99ab36 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -1,374 +1,430 @@ -//! # texturecraft-bake -//! -//! Mesh-map baking. [`bake`] rasterizes one texture set's UV layout with a supersampled -//! [`UvGBuffer`] and works through it in batches of samples: the high-poly transfer rays, then -//! the secondary rays of ambient occlusion, bent normals and thickness (each with its own -//! [`texturecraft_core::RaySettings`]) go to a [`rays::Tracer`], then every requested -//! [`BakedMap`] is evaluated per sample (rayon over rows), box-downsampled, and the UV islands -//! are padded with [`DilationMap`]. The rays run on the CPU ([`rays::CpuTracer`], the oracle) or -//! on a GPU tracer passed to [`bake_on`]. With a high poly, every map but position and -//! world-space direction reads the high-poly surface found along the cage / frontal-rear ray; -//! the color map multiplies its vertex colors by its materials' [`BaseColor`]s. Sampling is -//! deterministic, so the same request always gives the same pixels. +//! Deterministic mesh-map baking with bounded batches and CPU fallback + #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -mod maps; -pub mod rays; +mod bake_error; +mod bake_output; +mod bake_request; +mod cage; +mod high_poly; +mod mesh_extent; +mod name_pair; +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 name_pair::NamePair; +pub use progress::Progress; + +mod map; mod skew; #[cfg(test)] mod tests; +pub mod tracing; use std::collections::BTreeMap; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; +use std::sync::atomic::Ordering::Relaxed; use rayon::prelude::*; -use texturecraft_core::{BakeSettings, BakedMap}; +use texturecraft_core::{BakedMap, CurvatureMethod}; use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{BaseColor, Bvh, Mesh, NO_TRI, UvGBuffer}; +use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::DilationMap; -use crate::rays::{CpuTracer, RayScene, Tracer}; -pub use crate::skew::SkewMap; +mod bake_paint_map; +use crate::tracing::{CpuTracer, RayScene, Tracer}; +pub use bake_paint_map::BakePaintMap; -/// Largest accepted output resolution (per axis). pub const MAX_RESOLUTION: u32 = 8192; -/// Largest accepted ray count per texel (AO, thickness). pub const MAX_RAYS: u32 = 4096; -/// Largest accepted output (texels over every UV tile). pub const MAX_TEXELS: u64 = 1 << 27; -/// Supersampled texels rasterized at once: bounds the G-buffer at ~200 MB for any resolution × AA. +// Bound each supersampled G-buffer to roughly 200 MB const STRIP_TEXELS: usize = 1 << 24; -/// Supersamples ray-cast per batch: bounds the per-sample buffers (~40 MB) and a GPU submission. const BATCH: usize = 1 << 18; +// Curvature batches stay small so progress and cancellation remain responsive +const CURVATURE_BATCH: usize = 1 << 15; -/// Shared progress / cancellation flag of a running bake. -#[derive(Debug, Default)] -pub struct Progress { - /// Basis points, 0..=10_000 (all requested maps done). - pub done: AtomicU32, - pub cancel: AtomicBool, -} +fn validate(request: &BakeRequest) -> Result<(), BakeError> { + let settings = request.settings; + let invalid = |message: String| Err(BakeError::Invalid(message)); + let (resolution, resolution_height) = settings.common.output_size(); -impl Progress { - pub fn new() -> Self { - Self::default() + let (columns, rows) = request.tiles; + let width = u64::from(resolution) * u64::from(columns); + let height = u64::from(resolution_height) * u64::from(rows); + if columns == 0 || rows == 0 || width.saturating_mul(height) > MAX_TEXELS { + return invalid(format!("{columns} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", resolution)); } - /// Completed fraction, 0..=1. - pub fn fraction(&self) -> f32 { - self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 - } - - /// Ask the bake to stop; it returns [`BakeError::Cancelled`] at the next row. - pub fn cancel(&self) { - self.cancel.store(true, Relaxed); - } -} - -/// A high-poly source mesh (all high-definition meshes appended into one). -#[derive(Clone, Copy, Debug)] -pub struct HighPoly<'a> { - pub mesh: &'a Mesh, - pub bvh: &'a Bvh, - /// Base color per material of `mesh` (missing or None: white). - pub base_color: &'a [Option>], -} - -/// One texture set to bake. -#[derive(Clone, Copy, Debug)] -pub struct BakeRequest<'a> { - pub mesh: &'a Mesh, - /// BVH of the whole low-poly mesh: every material occludes. - pub bvh: &'a Bvh, - pub material: usize, - pub settings: &'a BakeSettings, - pub high: Option>, - /// Cage: the low poly inflated (same triangles); transfer rays start on it. - pub cage: Option<&'a Mesh>, - /// Skew correction of the high-poly transfer rays (see [`SkewMap`]); ignored with a cage mesh. - pub skew: Option<&'a SkewMap>, - /// UV tile grid (columns, rows) of the texture set: the maps are `settings.resolution` per - /// tile, (1, 1) for a classic set. The mesh's UVs are in atlas space (0..1 over the grid). - pub tiles: (u32, u32), -} - -/// Baked maps: row-major `resolution × height`, `BakedMap::components()` floats per texel, -/// rows top → bottom (y = v·H, as [`UvGBuffer`]). -#[derive(Clone, Debug, PartialEq)] -pub struct BakeOutput { - /// Width in texels. - pub resolution: u32, - pub height: u32, - pub maps: BTreeMap>, - /// Where the rays ran ([`Tracer::name`]). - pub tracer: String, -} - -#[derive(Debug, thiserror::Error)] -pub enum BakeError { - #[error("bake cancelled")] - Cancelled, - #[error("invalid bake request: {0}")] - Invalid(String), - /// The ray tracer failed ([`bake_on`] then bakes on the CPU). - #[error("ray tracer: {0}")] - Tracer(String), -} - -fn validate(req: &BakeRequest) -> Result<(), BakeError> { - let s = req.settings; - let invalid = |m: String| Err(BakeError::Invalid(m)); - if s.resolution == 0 || s.resolution > MAX_RESOLUTION { - return invalid(format!("resolution {} is not in 1..={MAX_RESOLUTION}", s.resolution)); - } - let (cols, rows) = req.tiles; - if cols == 0 || rows == 0 || (s.resolution as u64 * cols as u64) * (s.resolution as u64 * rows as u64) > MAX_TEXELS { - return invalid(format!("{cols} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", s.resolution)); - } - if ![1, 2, 4, 8].contains(&s.antialiasing) { - return invalid(format!("antialiasing {} is not 1, 2, 4 or 8", s.antialiasing)); - } - for (map, r) in [(BakedMap::AmbientOcclusion, &s.ao), (BakedMap::Thickness, &s.thickness), (BakedMap::BentNormal, &s.bent_normal)] { - if !s.maps.contains(&map) { + for (map, ray_settings) in [ + (BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays), + (BakedMap::Thickness, &settings.maps.thickness.parameters.rays), + (BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays), + ] { + if !settings.maps.is_enabled(map) { continue; } - if r.rays == 0 || r.rays > MAX_RAYS { - return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.label(), r.rays)); + + if ray_settings.rays == 0 || ray_settings.rays > MAX_RAYS { + return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.id(), ray_settings.rays)); } - if !(r.max_distance.is_finite() && r.max_distance > 0.0) { - return invalid(format!("{} max distance {} must be positive", map.label(), r.max_distance)); + + if !(ray_settings.max_distance.is_finite() && ray_settings.max_distance > 0.0) { + return invalid(format!("{} max distance {} must be positive", map.id(), ray_settings.max_distance)); } - if !r.spread.is_finite() { - return invalid(format!("{} spread angle is not finite", map.label())); + + if !(ray_settings.min_distance.is_finite() && ray_settings.min_distance >= 0.0 && ray_settings.min_distance <= ray_settings.max_distance) { + return invalid(format!("{} minimum distance must be finite and between zero and its maximum distance", map.id())); + } + if !ray_settings.spread.is_finite() || !(0.0..=180.0).contains(&ray_settings.spread) { + return invalid(format!("{} spread angle is not finite", map.id())); } } - if !s.curvature_strength.is_finite() { - return invalid("curvature strength is not finite".into()); + + if !(settings.cage.max_frontal.is_finite() && settings.cage.max_frontal >= 0.0 && settings.cage.max_rear.is_finite() && settings.cage.max_rear >= 0.0) { + return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", settings.cage.max_frontal, settings.cage.max_rear)); } - if !(s.direction.iter().all(|c| c.is_finite()) && s.direction.iter().any(|c| *c != 0.0)) { - return invalid(format!("direction {:?} must be finite and non-zero", s.direction)); - } - if !(s.max_frontal.is_finite() && s.max_frontal >= 0.0 && s.max_rear.is_finite() && s.max_rear >= 0.0) { - return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", s.max_frontal, s.max_rear)); - } - req.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?; - if req.material >= req.mesh.materials.len().max(1) { - return invalid(format!("material {} out of range ({} materials)", req.material, req.mesh.materials.len())); - } - if let Some(h) = &req.high { - h.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?; - } - if let Some(c) = req.cage { - c.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?; - if c.indices.len() != req.mesh.indices.len() { - return invalid(format!("the cage has {} triangles, the low poly {}", c.triangle_count(), req.mesh.triangle_count())); + let curvature = settings.maps.curvature.parameters; + if settings.maps.curvature.is_enabled { + if curvature.mesh.rays == 0 || curvature.mesh.rays > MAX_RAYS || !curvature.mesh.sampling_radius.is_finite() || curvature.mesh.sampling_radius <= 0.0 { + return invalid("curvature requires a positive finite radius and a supported ray count".into()); + } + if !curvature.mesh.value_min.is_finite() + || !curvature.mesh.value_max.is_finite() + || (!curvature.mesh.auto_tonemapping && curvature.mesh.value_min >= curvature.mesh.value_max) + { + return invalid("curvature bounds must be finite, with minimum below maximum".into()); } } + for (name, value) in [ + ("edge distance", settings.skew.edge_distance), + ("edge contrast", settings.skew.edge_contrast), + ("curvature details", curvature.normal_map.details), + ("seam intensity", curvature.normal_map.seams_intensity), + ] { + if !value.is_finite() || !(0.0..=1.0).contains(&value) { + return invalid(format!("{name} must be finite and in 0..=1")); + } + } + if settings.maps.height.is_enabled + && (!settings.maps.height.parameters.scaling_divisor.is_finite() || settings.maps.height.parameters.scaling_divisor <= 0.0) + { + return invalid("height scaling divisor must be finite and positive".into()); + } + if !settings.maps.ao.parameters.ground_plane.offset.is_finite() || settings.maps.ao.parameters.ground_plane.offset < 0.0 { + return invalid("ground plane offset must be finite and nonnegative".into()); + } + request.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?; + if request.material >= request.mesh.materials.len().max(1) { + return invalid(format!("material {} out of range ({} materials)", request.material, request.mesh.materials.len())); + } + + if let Some(high) = &request.high { + high.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?; + } + + if let Some(map) = request.cage_paint { + map.validate()?; + } + if let Some(cage) = request.cage { + cage.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?; + if cage.indices.len() != request.mesh.indices.len() { + return invalid(format!("the cage has {} triangles, the low poly {}", cage.triangle_count(), request.mesh.triangle_count())); + } + } + Ok(()) } -/// `vec![value; n]` that reports allocation failure instead of aborting. -fn alloc(n: usize, value: T) -> Result, BakeError> { - let mut v = Vec::new(); - v.try_reserve_exact(n).map_err(|_| BakeError::Invalid(format!("out of memory allocating {n} texels")))?; - v.resize(n, value); - Ok(v) +fn alloc(count: usize, value: T) -> Result, BakeError> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| BakeError::Invalid(format!("out of memory allocating {count} texels")))?; + values.resize(count, value); + Ok(values) } -/// Bake the maps in `req.settings.maps` for one material of the low-poly mesh, on the CPU. -pub fn bake(req: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(req, progress, STRIP_TEXELS, &CpuTracer) +pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { + bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) } -/// [`bake`] with the rays cast by `tracer` (a GPU); when the tracer fails (no adapter, a mesh -/// too large for it, a lost device) the bake runs again on the CPU. -pub fn bake_on(req: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result { - match bake_in_strips(req, progress, STRIP_TEXELS, tracer) { - Err(BakeError::Tracer(e)) => { - let mut out = bake(req, progress)?; - out.tracer = format!("CPU ({} unavailable: {e})", tracer.name()); - Ok(out) +/// Retry on the CPU if the supplied tracer fails +pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result { + 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_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; + output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); + Ok(output) } - r => r, + result => result, } } -/// One output row of a strip: its slice of every map. type OutRow<'a> = Vec<&'a mut [f32]>; -fn bake_in_strips(req: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result { - validate(req)?; - let s = req.settings; - let (tile_res, aa) = (s.resolution as usize, s.antialiasing as usize); - let (w, h) = (tile_res * req.tiles.0 as usize, tile_res * req.tiles.1 as usize); - let ctx = maps::Ctx::new(req)?; - let tracer = if ctx.casts_rays() { tracer } else { &CpuTracer }; - let meshes = ctx.trace_meshes(); +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); + let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize; + let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize); + let context = map::BakeContext::new(request)?; + let tracer = if context.casts_rays() { tracer } else { &CpuTracer }; + let meshes = context.trace_meshes(); let mut scene = tracer.scene(&meshes)?; progress.done.store(0, Relaxed); - // Curvature from the normal map needs the normal map: baked alongside when not requested. - let from_normal = s.curvature_from_normal && s.maps.contains(&BakedMap::Curvature); - let mut maps: Vec = s.maps.iter().copied().collect(); - if from_normal && !maps.contains(&BakedMap::Normal) { - maps.push(BakedMap::Normal); + // 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::WorldNormal) { + maps.push(BakedMap::WorldNormal); } - let mut bufs = maps.iter().map(|m| alloc(w * h * m.components(), 0.0f32)).collect::, _>>()?; - let mut covered = alloc(w * h, false)?; - let mut pad = None; - let total = h.max(1) as u64; - let mut rows_done = 0u64; - let strip_err = || BakeError::Invalid("strip out of range".into()); - // Rasterize in horizontal strips of the supersampled image: a strip's G-buffer is built from - // UVs shifted so that y = v*H - strip_top, which keeps memory bounded at 8K x 8 AA. - let (sw, full_h) = (w * aa, h * aa); - let strip_rows = (strip_texels / (sw * aa)).max(1).min(h); - let batch_rows = (BATCH / (sw * aa)).max(1); - let mut strip_mesh = Mesh { indices: req.mesh.indices.clone(), submeshes: req.mesh.submeshes.clone(), ..Mesh::default() }; - for y0 in (0..h).step_by(strip_rows) { - let rows = strip_rows.min(h - y0); - let (sy0, sh) = (y0 * aa, rows * aa); - strip_mesh.uvs = req.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * full_h as f32 - sy0 as f32) / sh as f32)).collect(); - let g = UvGBuffer::new(&strip_mesh, req.material, sw as u32, sh as u32); - // A texel is covered when any of its supersamples is. - let cov = covered.get_mut(y0 * w..(y0 + rows) * w).ok_or_else(strip_err)?; - cov.par_chunks_mut(w).enumerate().for_each(|(r, row)| { - for (x, c) in row.iter_mut().enumerate() { - *c = (0..aa * aa).any(|k| g.tri.get((r * aa + k / aa) * sw + x * aa + k % aa).is_some_and(|t| *t != NO_TRI)); + 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; + let total_rows = height.max(1) as u64; + let mut rows_done = 0u64; + let strip_error = || BakeError::Invalid("strip output of range".into()); + + let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis); + let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height); + let batch = if context.traces_curvature() { CURVATURE_BATCH } else { BATCH }; + let rows_per_batch = (batch / (sample_width * samples_per_axis)).max(1); + let mut strip_mesh = Mesh { indices: request.mesh.indices.clone(), submeshes: request.mesh.submeshes.clone(), ..Mesh::default() }; + for strip_start in (0..height).step_by(rows_per_strip) { + let rows = rows_per_strip.min(height - strip_start); + 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 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() { + *covered_pixel = (0..samples_per_axis * samples_per_axis).any(|sample_index| { + gbuffer + .tri + .get( + (row_index * samples_per_axis + sample_index / samples_per_axis) * sample_width + + x * samples_per_axis + + sample_index % samples_per_axis, + ) + .is_some_and(|triangle_index| *triangle_index != NO_TRI) + }); } }); - let mut out_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect(); - for (m, data) in maps.iter().zip(bufs.iter_mut()) { - let comps = m.components(); - let strip = data.get_mut(y0 * w * comps..(y0 + rows) * w * comps).ok_or_else(strip_err)?; - for (row, chunk) in out_rows.iter_mut().zip(strip.chunks_mut(w * comps)) { + let mut output_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect(); + for (map, data) in maps.iter().zip(buffers.iter_mut()) { + let component_count = map.components(); + let strip = data.get_mut(strip_start * width * component_count..(strip_start + rows) * width * component_count).ok_or_else(strip_error)?; + for (row, chunk) in output_rows.iter_mut().zip(strip.chunks_mut(width * component_count)) { row.push(chunk); } } let mut bake_strip = || { - for (b, batch) in out_rows.chunks_mut(batch_rows).enumerate() { + for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() { if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } - // Seed by the global supersample index so strips and batches don't change the noise. - bake_rows(&ctx, &maps, req.mesh, &g, scene.as_mut(), batch, b * batch_rows, (w, aa, sy0 * sw))?; + // Global sample indices keep noise unchanged across strip and batch sizes + bake_rows( + &context, + &maps, + request.mesh, + &gbuffer, + scene.as_mut(), + batch, + batch_index * rows_per_batch, + (width, samples_per_axis, sample_start_y * sample_width), + )?; rows_done += batch.len() as u64; - progress.done.store((rows_done.saturating_mul(10_000) / total).min(10_000) as u32, Relaxed); + progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed); } Ok(()) }; - if y0 + rows < h || s.dilation == 0 { + if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) { bake_strip()?; } else { - // The coverage is complete: find the padding (UV tile by UV tile) while the last strip bakes. - let padding = || DilationMap::in_blocks(&covered, w as u32, h as u32, Some(s.dilation), s.resolution); - let (p, baked) = rayon::join(padding, bake_strip); + let padding = + || DilationMap::in_rectangular_blocks(&covered, width as u32, height as u32, Some(settings.common.dilation), (tile_width, tile_height)); + let (padding, baked) = rayon::join(padding, bake_strip); baked?; - pad = Some(p); + padding_map = Some(padding); } } - let mut out: BTreeMap> = maps.into_iter().zip(bufs).collect(); + let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { - let normal = if s.maps.contains(&BakedMap::Normal) { out.get(&BakedMap::Normal).cloned() } else { out.remove(&BakedMap::Normal) }; - if let (Some(normal), Some(curv)) = (normal, out.get_mut(&BakedMap::Curvature)) { - maps::curvature_from_normal(&normal, &covered, w, tile_res, s.curvature_radius, s.curvature_strength, curv); + 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; + 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); + } } } - if let Some(pad) = pad { - for (m, data) in out.iter_mut() { - pad.apply(data, m.components()); + + 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 { + for (map, data) in output.iter_mut() { + padding_map.apply(data, map.components()); + if settings.common.apply_diffusion { + map::diffuse(data, map.components(), &padding_map, tile_size); + } } } + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); + } progress.done.store(10_000, Relaxed); - Ok(BakeOutput { resolution: w as u32, height: h as u32, maps: out, tracer: tracer.name() }) + Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } -/// Bake output rows `r0..` of a strip's G-buffer `g` into `rows`: gather the covered -/// supersamples, cast their transfer and secondary rays in batches on `scene`, then evaluate -/// and average every map per texel. `seed0` is the strip's first supersample index. #[allow(clippy::too_many_arguments)] fn bake_rows( - ctx: &maps::Ctx, + context: &map::BakeContext, maps: &[BakedMap], mesh: &Mesh, - g: &UvGBuffer, + gbuffer: &UvGBuffer, scene: &mut dyn RayScene, rows: &mut [OutRow], - r0: usize, - (w, aa, seed0): (usize, usize, usize), + first_row: usize, + (width, samples_per_axis, first_sample_seed): (usize, usize, usize), ) -> Result<(), BakeError> { - let sw = w * aa; - let per_row: Vec> = (r0..r0 + rows.len()) + let sample_width = width * samples_per_axis; + let samples_by_row: Vec> = (first_row..first_row + rows.len()) .into_par_iter() - .map(|r| { - let subsamples = (0..w).flat_map(|x| (0..aa * aa).map(move |k| (x, (r * aa + k / aa) * sw + x * aa + k % aa))); - subsamples.filter_map(|(x, i)| Some(maps::Sample { x, surf: g.surface(mesh, i)?, bary: *g.bary.get(i)?, seed: (seed0 + i) as u64 })).collect() + .map(|row| { + let subsamples = (0..width).flat_map(|x| { + (0..samples_per_axis * samples_per_axis).map(move |sample_index| { + (x, (row * samples_per_axis + sample_index / samples_per_axis) * sample_width + x * samples_per_axis + sample_index % samples_per_axis) + }) + }); + subsamples + .filter_map(|(x, sample_index)| { + Some(map::Sample { + x, + surface: gbuffer.surface(mesh, sample_index)?, + bary: *gbuffer.bary.get(sample_index)?, + seed: (first_sample_seed + sample_index) as u64, + }) + }) + .collect() }) .collect(); - // Index of each row's first sample in the batch arrays. - let starts: Vec = per_row + let row_offsets: Vec = samples_by_row .iter() - .scan(0, |n, r| { - *n += r.len(); - Some(*n - r.len()) + .scan(0, |sample_count, row| { + *sample_count += row.len(); + Some(*sample_count - row.len()) }) .collect(); - let samples = || per_row.par_iter().flat_map_iter(|r| r.iter()); + let samples = || samples_by_row.par_iter().flat_map_iter(|row| row.iter()); - let transfers = match ctx.has_high() { + let transfers = match context.has_high() { true => { - let (rays, fronts): (Vec, Vec) = samples().map(|p| ctx.transfer_ray(&p.surf, p.bary)).unzip(); - let hits = scene.closest(1, &rays)?; - hits.into_par_iter().zip(fronts).map(|(hit, front)| ctx.transfer(hit, front)).collect() + let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); + let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?; + hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() } false => Vec::new(), }; - let transfer = |k: usize| transfers.get(k).and_then(Option::as_ref); - let queries: Vec = match ctx.ao.is_some() || ctx.bent.is_some() || ctx.thickness.is_some() { + let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref); + let curvature = match context.traces_curvature() { true => { - per_row.par_iter().zip(&starts).flat_map_iter(|(r, &first)| r.iter().zip(first..)).map(|(p, k)| ctx.query(transfer(k), &p.surf, p.seed)).collect() + let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row + .iter() + .zip(&row_offsets) + .flat_map(|(row, &first)| row.iter().zip(first..)) + .map(|(sample, sample_index)| (&sample.surface, transfer(sample_index))) + .collect(); + context.trace_curvature(scene, &items)? } false => Vec::new(), }; - // Bent normals come with the occlusion rays when they share the settings. - let own_bent = ctx.bent.filter(|_| ctx.bent != ctx.ao); - let passes: Vec = [ctx.ao, own_bent, ctx.thickness].into_iter().flatten().collect(); + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { + true => samples_by_row + .par_iter() + .zip(&row_offsets) + .flat_map_iter(|(row, &first)| row.iter().zip(first..)) + .map(|(sample, sample_index)| context.query(transfer(sample_index), &sample.surface, sample.seed)) + .collect(), + false => Vec::new(), + }; + // Share occlusion results when the bent-normal ray settings match + let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao); + let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect(); let mut results = scene.hemispheres(&passes, &queries)?.into_iter(); - let mut next = |on: bool| if on { results.next().unwrap_or_default() } else { Vec::new() }; - let (ao, bent_own, thickness) = (next(ctx.ao.is_some()), next(own_bent.is_some()), next(ctx.thickness.is_some())); - let bent = if own_bent.is_some() { &bent_own } else { &ao }; + let mut next = |enabled: bool| if enabled { results.next().unwrap_or_default() } else { Vec::new() }; + let (occlusion_results, separate_bent_results, thickness) = + (next(context.ao.is_some()), next(separate_bent_pass.is_some()), next(context.thickness.is_some())); + let bent_results = if separate_bent_pass.is_some() { &separate_bent_results } else { &occlusion_results }; - rows.par_iter_mut().zip(&per_row).zip(&starts).for_each(|((row, samples), &first)| { - let mut sample = [[0.0f32; 3]; BakedMap::ALL.len()]; - let mut j = 0; - for x in 0..w { - let mut acc = [[0.0f32; 3]; BakedMap::ALL.len()]; - let mut n = 0u32; - while let Some(p) = samples.get(j).filter(|p| p.x == x) { - let k = first + j; - let traced = maps::Traced { - ao: ao.get(k).map_or(1.0, |v| v[0]), - bent: bent.get(k).map(|v| Vec3::new(v[1], v[2], v[3])), - thickness: thickness.get(k).map_or(1.0, |v| v[0]), + rows.par_iter_mut().zip(&samples_by_row).zip(&row_offsets).for_each(|((row, samples), &first)| { + let mut sample_values = [[0.0f32; 3]; BakedMap::ALL.len()]; + let mut row_sample_index = 0; + for x in 0..width { + let mut accumulated = [[0.0f32; 3]; BakedMap::ALL.len()]; + let mut sample_count = 0u32; + while let Some(sample) = samples.get(row_sample_index).filter(|sample| sample.x == x) { + let sample_index = first + row_sample_index; + let traced = map::Traced { + ao: occlusion_results.get(sample_index).map_or(1.0, |value| value[0]), + bent: bent_results.get(sample_index).map(|value| Vec3::new(value[1], value[2], value[3])), + thickness: thickness.get(sample_index).map_or(1.0, |value| value[0]), + curvature: curvature.get(sample_index).copied().unwrap_or(0.5), }; - ctx.evaluate(maps, &p.surf, p.bary, transfer(k), &traced, &mut sample); - for (a, v) in acc.iter_mut().zip(&sample) { - a.iter_mut().zip(v).for_each(|(a, v)| *a += v); + context.evaluate(maps, &sample.surface, sample.bary, transfer(sample_index), &traced, &mut sample_values); + for (sum, value) in accumulated.iter_mut().zip(&sample_values) { + sum.iter_mut().zip(value).for_each(|(sum, value)| *sum += value); } - n += 1; - j += 1; + sample_count += 1; + row_sample_index += 1; } - for ((m, dst), a) in maps.iter().zip(row.iter_mut()).zip(&acc) { - let comps = m.components(); - let mean = a.map(|a| a / n.max(1) as f32); - let v = if n == 0 || mean.iter().any(|v| !v.is_finite()) { m.neutral() } else { mean }; - if let Some(d) = dst.get_mut(x * comps..(x + 1) * comps) { - d.iter_mut().zip(v).for_each(|(d, v)| *d = v); + + for ((map, destination), sum) in maps.iter().zip(row.iter_mut()).zip(&accumulated) { + let component_count = map.components(); + let mean = sum.map(|sum| sum / sample_count.max(1) as f32); + let value = if sample_count == 0 || mean.iter().any(|value| !value.is_finite()) { map.neutral() } else { mean }; + if let Some(pixel) = destination.get_mut(x * component_count..(x + 1) * component_count) { + pixel.iter_mut().zip(value).for_each(|(component, value)| *component = value); } } } diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs new file mode 100644 index 00000000..08a98224 --- /dev/null +++ b/crates/bake/src/map.rs @@ -0,0 +1,29 @@ +mod bake_context; +mod curvature; +mod curvature_tuning; +mod diffusion; +mod normal_curvature; +mod normalization; +mod part_key; +pub(crate) use diffusion::diffuse; +pub(crate) use normalization::normalize; +pub(crate) use part_key::part_key; +mod sample; +mod seam; +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 new file mode 100644 index 00000000..f3e35df6 --- /dev/null +++ b/crates/bake/src/map/bake_context.rs @@ -0,0 +1,255 @@ +use super::curvature::Curvature; +use super::sampling::{pack, splitmix64, tangent_normal}; +use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; +use crate::cage::{RayFrame, RayStart}; +use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use texturecraft_core::{ + AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, +}; +use texturecraft_geom::{Hit, Surface, surface_at}; + +const CURVATURE_CHUNK: usize = 1 << 15; + +pub(crate) struct BakeContext<'a> { + low: Source<'a>, + high: Option>, + ray_frame: RayFrame<'a>, + settings: &'a BakeSettings, + frontal: f32, + rear: f32, + position: PositionProjection, + curvature_method: CurvatureMethod, + curvature: Curvature, + pub ao: Option, + pub bent: Option, + pub thickness: Option, +} + +impl<'a> BakeContext<'a> { + pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { + let settings = request.settings; + 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 }; + settings.maps.is_enabled(map).then_some(Hemisphere { + kind, + rays: ray_settings.rays, + dmax: ray_settings.max_distance * units, + min_distance: ray_settings.min_distance * units, + attenuation: AmbientOcclusionAttenuation::None, + ground_height: None, + eps: ray_epsilon, + cos_max: half_angle_radians.cos(), + sin_max: half_angle_radians.sin(), + uniform: ray_settings.distribution == RayDistribution::Uniform, + ignore_backface: BackfaceMode::Never, + same_key: false, + }) + }; + + let mut ao = pass(BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays, RayKind::Occlusion); + if let Some(pass) = &mut ao { + let parameters = settings.maps.ao.parameters; + 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(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 = ray_frame.cage_units; + Ok(BakeContext { + low, + high, + ray_frame, + settings, + 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), + curvature_method: settings.maps.curvature.parameters.method, + curvature: Curvature::new(settings, request.mesh, mesh_scale, request.tiles), + ao, + bent, + thickness, + }) + } + + pub(crate) fn ignore_transfer_backface(&self) -> bool { + self.settings.high_poly.ignore_backface + } + + pub(crate) fn has_high(&self) -> bool { + self.high.is_some() + } + + pub(crate) fn casts_rays(&self) -> bool { + self.has_high() || self.curvature.is_enabled || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some() + } + + pub(crate) fn trace_meshes(&self) -> Vec> { + std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect() + } + + pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { + 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, + MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY), + }; + (Ray { origin, direction, max_distance: front + self.rear, key }, front) + } + + pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + let (high, hit) = (self.high.as_ref()?, hit?); + let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front }) + } + + pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { + let (source, surface, mesh) = match (&self.high, transfer) { + (Some(high), Some(transfer_hit)) => (high, &transfer_hit.surface, 1), + _ => (&self.low, low_surface, 0), + }; + let seed_hash = splitmix64(seed); + let rot = [(seed_hash >> 40) as f32 / (1u64 << 24) as f32, ((seed_hash >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32]; + let geo = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm }; + Query { pos: surface.pos, nrm: surface.nrm, geo, rot, key: source.key.get(surface.tri as usize).copied().unwrap_or(ANY), mesh } + } + + pub(crate) fn traces_curvature(&self) -> bool { + self.curvature.is_enabled + } + + pub(crate) fn trace_curvature(&self, scene: &mut dyn RayScene, samples: &[(&Surface, Option<&Transfer>)]) -> Result, BakeError> { + let mut output = vec![0.5; samples.len()]; + let curvature = &self.curvature; + for mesh in [0usize, 1] { + let Some(source) = (if mesh == 0 { Some(&self.low) } else { self.high.as_ref() }) else { continue }; + let tuning = if mesh == 0 { &curvature.low } else { &curvature.high }; + let chosen: Vec<(usize, &Surface, f32)> = samples + .par_iter() + .enumerate() + .filter_map(|(sample_index, (low_surface, transfer_hit))| { + let surface = match (mesh, transfer_hit) { + (1, Some(hit)) => &hit.surface, + (0, None) => *low_surface, + _ => return None, + }; + Some((sample_index, surface, curvature.texel(low_surface.tri))) + }) + .collect(); + let rays_per_sample = curvature.rays_per_sample.max(1); + let key_for = |surface: &Surface| { + if self.settings.maps.curvature.parameters.mesh.self_intersection == SelfOcclusion::SameMeshName { + source.key.get(surface.tri as usize).copied().unwrap_or(ANY) + } else { + ANY + } + }; + let chunk_size = CURVATURE_CHUNK.min((1_048_576 / rays_per_sample).max(1)); + for chunk in chosen.chunks(chunk_size) { + let mut rays: Vec = bytemuck::zeroed_vec(chunk.len() * rays_per_sample); + rays.par_chunks_mut(rays_per_sample) + .zip(chunk) + .for_each(|(output, (_, surface, texel))| curvature.rays(tuning, surface, *texel, key_for(surface), output)); + let hits = scene.closest(mesh, &rays, false)?; + let walls = + |chunk_index: usize| hits.get(chunk_index * rays_per_sample..chunk_index * rays_per_sample + curvature.wall_count).unwrap_or_default(); + let grounds: Vec = chunk + .par_iter() + .enumerate() + .flat_map_iter(|(chunk_index, (_, surface, texel))| { + let mut value = Vec::new(); + curvature.ground_rays(surface, *texel, key_for(surface), walls(chunk_index), &mut value); + value + }) + .collect(); + let ground_hits = scene.closest(mesh, &grounds, false)?; + let ground_offsets: Vec = (0..chunk.len()) + .scan(0, |first, chunk_index| { + let offset = *first; + *first += walls(chunk_index).iter().flatten().count(); + Some(offset) + }) + .collect(); + let values: Vec<(usize, f32)> = chunk + .par_iter() + .zip(&ground_offsets) + .enumerate() + .map(|(chunk_index, ((sample_index, surface, texel), first))| { + let ground_count = walls(chunk_index).iter().flatten().count(); + let sample_ground_hits = ground_hits.get(*first..*first + ground_count).unwrap_or_default(); + let sample_hits = hits.get(chunk_index * rays_per_sample..(chunk_index + 1) * rays_per_sample).unwrap_or_default(); + (*sample_index, curvature.value(tuning, source, surface, *texel, sample_hits, sample_ground_hits)) + }) + .collect(); + for (sample_index, value) in values { + if let Some(destination) = output.get_mut(sample_index) { + *destination = value; + } + } + } + } + Ok(output) + } + + pub(crate) fn evaluate( + &self, + maps: &[BakedMap], + low_surface: &Surface, + barycentric: [f32; 2], + transfer: Option<&Transfer>, + traced: &Traced, + outputs: &mut [[f32; 3]], + ) { + let (source, surface, source_barycentric) = match (&self.high, transfer) { + (Some(high), Some(hit)) => (high, &hit.surface, hit.bary), + _ => (&self.low, low_surface, barycentric), + }; + + let missed = self.high.is_some() && transfer.is_none(); + for (&map, output) in maps.iter().zip(outputs.iter_mut()) { + *output = match map { + BakedMap::AmbientOcclusion => [traced.ao; 3], + BakedMap::BentNormal => pack(traced.bent.unwrap_or(surface.nrm)), + BakedMap::Thickness => [traced.thickness; 3], + BakedMap::Curvature if self.curvature_method == CurvatureMethod::NormalMap => [0.5; 3], + BakedMap::Curvature => [traced.curvature; 3], + BakedMap::WorldNormal => pack(surface.nrm), + BakedMap::Position => self.position.evaluate(surface.pos), + BakedMap::Id => source.id_color(surface, source_barycentric, self.settings.maps.id.parameters), + BakedMap::Normal => transfer.map_or(map.neutral(), |hit| tangent_normal(low_surface, hit.surface.nrm)), + BakedMap::Height => { + let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances; + [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| { + let height = hit.front - hit.t; + if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height } + }); 3] + } + BakedMap::Opacity if missed => [0.0; 3], + BakedMap::Opacity => [source.color(surface, source_barycentric).w; 3], + }; + } + } +} diff --git a/crates/bake/src/map/curvature.rs b/crates/bake/src/map/curvature.rs new file mode 100644 index 00000000..eac8dd52 --- /dev/null +++ b/crates/bake/src/map/curvature.rs @@ -0,0 +1,217 @@ +use super::{curvature_tuning::CurvatureTuning, sampling::interpolate, source::Source}; +use crate::tracing::Ray; +use rayon::prelude::*; +use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Hit, Mesh, Surface}; + +const RING_COUNT: usize = 4; +const WALL_RADIUS_TEXELS: f32 = 1.5; +const CONCAVE_WEIGHT: f32 = 1.5; +const LOW_POLY_CONVEX_WEIGHT: f32 = 1.5; +const HIGH_POLY_CONVEX_WEIGHT: f32 = 0.5; +const LOW_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.003; +const LOW_POLY_CURVATURE_WEIGHT: f32 = 1.3; +const HIGH_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.0007; +const HIGH_POLY_CURVATURE_WEIGHT: f32 = 1.6; +const HARD_EDGE_NORMAL_CHANGE_THRESHOLD: f32 = 0.05; +const GENTLE_CURVATURE_THRESHOLD: f32 = 0.1; + +pub(super) struct Curvature { + pub(super) is_enabled: bool, + walls: f32, + spread: f32, + fallback: f32, + texels: Vec, + ring: [Vec<(f32, f32)>; RING_COUNT], + pub(super) rays_per_sample: usize, + pub(super) wall_count: usize, + pub(super) low: CurvatureTuning, + pub(super) high: CurvatureTuning, +} + +impl Curvature { + pub(super) fn new(settings: &BakeSettings, low: &Mesh, mesh_scale: f32, tiles: (u32, u32)) -> Curvature { + let is_enabled = settings.maps.is_enabled(BakedMap::Curvature) && settings.maps.curvature.parameters.method == CurvatureMethod::Mesh; + let (width, height) = settings.common.output_size(); + let resolution = (width as f32 * height as f32 * tiles.0.max(1) as f32 * tiles.1.max(1) as f32).sqrt(); + let texel = |triangle: usize| { + let [a, b, c] = low.tri(triangle)?; + let (position_a, position_b, position_c) = (*low.positions.get(a)?, *low.positions.get(b)?, *low.positions.get(c)?); + let (uv_a, uv_b, uv_c) = (*low.uvs.get(a)?, *low.uvs.get(b)?, *low.uvs.get(c)?); + let world_area = (position_b - position_a).cross(position_c - position_a).length(); + let uv_area = (uv_b - uv_a).perp_dot(uv_c - uv_a).abs(); + (uv_area > 1e-12 && world_area > 0.0).then(|| (world_area / uv_area).sqrt() / resolution) + }; + let fallback = mesh_scale * 1e-3; + let triangle_count = if is_enabled { low.triangle_count() } else { 0 }; + let parameters = settings.maps.curvature.parameters.mesh; + let radius = parameters.sampling_radius * if parameters.relative_to_bounding_box { mesh_scale } else { 1.0 }; + let radius_scale = radius / (mesh_scale * 0.001); + let walls = WALL_RADIUS_TEXELS * radius_scale; + let rays_per_sample = parameters.rays as usize; + let ring: [Vec<(f32, f32)>; RING_COUNT] = std::array::from_fn(|ring_index| { + let count = rays_per_sample / RING_COUNT + usize::from(ring_index < rays_per_sample % RING_COUNT); + (0..count) + .map(|index| { + let angle = std::f32::consts::TAU * index as f32 / count.max(1) as f32; + (angle.cos(), angle.sin()) + }) + .collect() + }); + Curvature { + is_enabled, + rays_per_sample, + wall_count: ring.first().map_or(0, Vec::len), + walls, + spread: walls * 4.0 / 3.0, + fallback, + texels: (0..triangle_count).into_par_iter().map(|t| texel(t).filter(|v| v.is_finite()).unwrap_or(fallback)).collect(), + low: CurvatureTuning { + convex: LOW_POLY_CONVEX_WEIGHT, + true_radius: mesh_scale * LOW_POLY_CURVATURE_RADIUS_RATIO * radius_scale, + true_strength: LOW_POLY_CURVATURE_WEIGHT, + }, + high: CurvatureTuning { + convex: HIGH_POLY_CONVEX_WEIGHT, + true_radius: mesh_scale * HIGH_POLY_CURVATURE_RADIUS_RATIO * radius_scale, + true_strength: HIGH_POLY_CURVATURE_WEIGHT, + }, + ring, + } + } + + pub(super) fn texel(&self, tri: u32) -> f32 { + self.texels.get(tri as usize).copied().unwrap_or(self.fallback) + } + + fn radii(&self, tuning: &CurvatureTuning, texel: f32) -> [f32; RING_COUNT] { + let r = self.walls * texel; + [r, r, self.spread * texel, tuning.true_radius] + } + + fn directions(&self, ring: usize, tangent: Vec3, bitangent: Vec3) -> impl Iterator + '_ { + self.ring.get(ring).into_iter().flatten().map(move |(cosine, sine)| tangent * *cosine + bitangent * *sine) + } + + pub(super) fn rays(&self, tuning: &CurvatureTuning, surface: &Surface, texel_size: f32, key: u32, output: &mut [Ray]) { + let (geometric_normal, tangent, bitangent) = surface_frame(surface); + let mut output = output.iter_mut(); + for (ring, radius) in self.radii(tuning, texel_size).into_iter().enumerate() { + for direction in self.directions(ring, tangent, bitangent) { + let Some(ray) = output.next() else { + return; + }; + *ray = match ring { + 0 => Ray { origin: surface.pos + geometric_normal * (0.15 * radius), direction, max_distance: radius, key }, + 1 => Ray { origin: surface.pos - geometric_normal * (0.15 * radius), direction, max_distance: radius, key }, + _ => Ray { + origin: surface.pos + direction * radius + geometric_normal * (0.25 * radius), + direction: -geometric_normal, + max_distance: 2.25 * radius, + key, + }, + }; + } + } + } + + pub(super) fn ground_rays(&self, surface: &Surface, texel_size: f32, key: u32, walls: &[Option], output: &mut Vec) { + let (geometric_normal, tangent, bitangent) = surface_frame(surface); + let radius = self.walls * texel_size; + for (w, direction) in walls.iter().zip(self.directions(0, tangent, bitangent)) { + if let Some(hit) = w { + output.push(Ray { + origin: surface.pos + geometric_normal * (0.15 * radius) + direction * (hit.t * 0.85), + direction: -geometric_normal, + max_distance: 0.5 * radius, + key, + }); + } + } + } + + fn wall(&self, source: &Source, surface: &Surface, geometric_normal: Vec3, radius: f32, hits: &[Option], keep: &mut dyn FnMut() -> bool) -> f32 { + let mut sum = 0.0; + for hit in hits.iter().flatten() { + if !keep() { + continue; + } + let upright = triangle_normal(source.mesh, hit.tri).map_or(1.0, |normal| (1.0 - normal.dot(geometric_normal).powi(2)).max(0.0).sqrt()); + let shaded = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let hard = ((1.0 - shaded.dot(surface.nrm)) / HARD_EDGE_NORMAL_CHANGE_THRESHOLD).clamp(0.0, 1.0); + sum += (1.0 - hit.t / radius) * upright * hard; + } + sum / hits.len().max(1) as f32 + } + + fn spread( + &self, + source: &Source, + surface: &Surface, + geometric_normal: Vec3, + directions: impl Iterator, + hits: &[Option], + turn: f32, + ) -> (f32, f32) { + let (mut shading, mut faces) = (0.0, 0.0); + for (hit, direction) in hits.iter().zip(directions) { + let Some(hit) = hit else { continue }; + let normal = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + if 1.0 - normal.dot(surface.nrm) <= turn { + shading += (normal - surface.nrm).dot(direction); + if let Some(f) = triangle_normal(source.mesh, hit.tri) { + let f = if f.dot(geometric_normal) < 0.0 { -f } else { f }; + faces += (f - geometric_normal).dot(direction); + } + } + } + (shading / hits.len().max(1) as f32, faces / hits.len().max(1) as f32) + } + + pub(super) fn value( + &self, + tuning: &CurvatureTuning, + source: &Source, + surface: &Surface, + texel_size: f32, + hits: &[Option], + ground_hits: &[Option], + ) -> f32 { + let (geometric_normal, tangent, bitangent) = surface_frame(surface); + let ring = |ring_index: usize| { + let start: usize = self.ring.iter().take(ring_index).map(Vec::len).sum(); + let count = self.ring.get(ring_index).map_or(0, Vec::len); + hits.get(start..start + count).unwrap_or_default() + }; + let radius = self.walls * texel_size; + let mut next = ground_hits.iter(); + let above = self.wall(source, surface, geometric_normal, radius, ring(0), &mut || next.next().copied().flatten().is_some_and(|g| g.t < 0.3 * radius)); + let below = self.wall(source, surface, geometric_normal, radius, ring(1), &mut || true); + let (shading, _) = self.spread(source, surface, geometric_normal, self.directions(2, tangent, bitangent), ring(2), 2.0); + let (true_shading, true_faces) = self.spread(source, surface, geometric_normal, self.directions(3, tangent, bitangent), ring(3), 2.0); + let value = + -above * CONCAVE_WEIGHT + (below - above).max(0.0) * tuning.convex + shading * 0.5 + tight(agreed(true_shading, true_faces) * tuning.true_strength); + (value * 2.0).clamp(-1.0, 1.0) + } +} + +fn triangle_normal(mesh: &Mesh, tri: u32) -> Option { + let [a, b, c] = mesh.tri(tri as usize)?; + let p = |i: usize| mesh.positions.get(i).copied(); + (p(b)? - p(a)?).cross(p(c)? - p(a)?).try_normalize() +} + +fn surface_frame(surface: &Surface) -> (Vec3, Vec3, Vec3) { + let geometric_normal = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm }; + let (tangent, bitangent) = geometric_normal.any_orthonormal_pair(); + (geometric_normal, tangent, bitangent) +} + +fn tight(v: f32) -> f32 { + v.signum() * (v.abs() - GENTLE_CURVATURE_THRESHOLD).max(0.0) +} + +fn agreed(shading: f32, faces: f32) -> f32 { + if shading * faces <= 0.0 { 0.0 } else { shading.abs().min(faces.abs()).copysign(shading) } +} diff --git a/crates/bake/src/map/curvature_tuning.rs b/crates/bake/src/map/curvature_tuning.rs new file mode 100644 index 00000000..753edfb6 --- /dev/null +++ b/crates/bake/src/map/curvature_tuning.rs @@ -0,0 +1,5 @@ +pub(super) struct CurvatureTuning { + pub(super) convex: f32, + pub(super) true_radius: f32, + pub(super) true_strength: f32, +} diff --git a/crates/bake/src/map/diffusion.rs b/crates/bake/src/map/diffusion.rs new file mode 100644 index 00000000..eb59801f --- /dev/null +++ b/crates/bake/src/map/diffusion.rs @@ -0,0 +1,89 @@ +use texturecraft_texel::DilationMap; + +pub(crate) fn diffuse(pixels: &mut [f32], components: usize, padding: &DilationMap, tile_size: (usize, usize)) { + let width = padding.width as usize; + let height = padding.height as usize; + for start_y in (0..height).step_by(tile_size.1) { + for start_x in (0..width).step_by(tile_size.0) { + let tile_width = tile_size.0.min(width - start_x); + let tile_height = tile_size.1.min(height - start_y); + let mut values = vec![0.0; tile_width * tile_height * components]; + let mut valid = vec![false; tile_width * tile_height]; + for (index, covered) in valid.iter_mut().enumerate() { + let source = (start_y + index / tile_width) * width + start_x + index % tile_width; + *covered = padding.src.get(source).is_some_and(|source| *source != u32::MAX); + if let (Some(destination), Some(pixel)) = + (values.get_mut(index * components..(index + 1) * components), pixels.get(source * components..(source + 1) * components)) + { + destination.copy_from_slice(pixel); + } + } + if !valid.iter().any(|covered| *covered) { + continue; + } + fill(&mut values, &valid, tile_width, tile_height, components); + for (index, covered) in valid.iter().enumerate() { + if *covered { + continue; + } + let destination = (start_y + index / tile_width) * width + start_x + index % tile_width; + if let (Some(pixel), Some(value)) = + (pixels.get_mut(destination * components..(destination + 1) * components), values.get(index * components..(index + 1) * components)) + { + pixel.copy_from_slice(value); + } + } + } + } +} + +fn fill(values: &mut [f32], valid: &[bool], width: usize, height: usize, components: usize) { + if width == 1 && height == 1 { + return; + } + let (small_width, small_height) = (width.div_ceil(2), height.div_ceil(2)); + let mut small = vec![0.0; small_width * small_height * components]; + let mut small_valid = vec![false; small_width * small_height]; + for (index, covered) in small_valid.iter_mut().enumerate() { + let (x, y) = (index % small_width * 2, index / small_width * 2); + let mut count = 0; + for child_y in y..(y + 2).min(height) { + for child_x in x..(x + 2).min(width) { + let child = child_y * width + child_x; + if valid.get(child) != Some(&true) { + continue; + } + count += 1; + for component in 0..components { + if let Some(value) = small.get_mut(index * components + component) { + *value += values.get(child * components + component).copied().unwrap_or(0.0); + } + } + } + } + *covered = count > 0; + if let Some(pixel) = small.get_mut(index * components..(index + 1) * components) { + pixel.iter_mut().for_each(|value| *value /= count.max(1) as f32); + } + } + fill(&mut small, &small_valid, small_width, small_height, components); + for (index, covered) in valid.iter().enumerate() { + if *covered { + continue; + } + let (x, y) = ((index % width) as f32 * 0.5 - 0.25, (index / width) as f32 * 0.5 - 0.25); + let (fraction_x, fraction_y) = (x - x.floor(), y - y.floor()); + let sample = |offset_x: i32, offset_y: i32, component: usize| { + let sample_x = (x.floor() as i32 + offset_x).clamp(0, small_width as i32 - 1) as usize; + let sample_y = (y.floor() as i32 + offset_y).clamp(0, small_height as i32 - 1) as usize; + small.get((sample_y * small_width + sample_x) * components + component).copied().unwrap_or(0.0) + }; + for component in 0..components { + let top = sample(0, 0, component) * (1.0 - fraction_x) + sample(1, 0, component) * fraction_x; + let bottom = sample(0, 1, component) * (1.0 - fraction_x) + sample(1, 1, component) * fraction_x; + if let Some(value) = values.get_mut(index * components + component) { + *value = top * (1.0 - fraction_y) + bottom * fraction_y; + } + } + } +} diff --git a/crates/bake/src/map/normal_curvature.rs b/crates/bake/src/map/normal_curvature.rs new file mode 100644 index 00000000..c96163c7 --- /dev/null +++ b/crates/bake/src/map/normal_curvature.rs @@ -0,0 +1,120 @@ +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( + world_normal: &[f32], + mesh: &Mesh, + material: usize, + grid: &TexelGrid, + settings: NormalMapCurvatureSettings, + output: &mut [f32], +) { + 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 + }; + + // 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() { + let index = y * size.0 + x; + if covered.get(index) != Some(&true) { + continue; + } + + // 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/normalization.rs b/crates/bake/src/map/normalization.rs new file mode 100644 index 00000000..b1de9812 --- /dev/null +++ b/crates/bake/src/map/normalization.rs @@ -0,0 +1,91 @@ +use rayon::prelude::*; +use std::collections::BTreeMap; +use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod, HeightNormalization, ThicknessNormalization}; + +pub(crate) fn normalize( + maps: &mut BTreeMap>, + covered: &[bool], + width: usize, + tile_size: (usize, usize), + settings: &BakeSettings, + mesh_scale: f32, +) { + for (map, pixels) in maps { + if !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) { + continue; + } + if *map == BakedMap::Height && settings.maps.height.parameters.normalization == HeightNormalization::RelativeToRayDistances { + continue; + } + if *map == BakedMap::Curvature && settings.maps.curvature.parameters.method != CurvatureMethod::Mesh { + continue; + } + pixels.par_chunks_mut(width * tile_size.1).enumerate().for_each(|(tile_row, rows)| { + let coverage = covered.get(tile_row * width * tile_size.1..).unwrap_or_default(); + for start_x in (0..width).step_by(tile_size.0) { + let end_x = (start_x + tile_size.0).min(width); + let mut minimum = f32::INFINITY; + let mut maximum = f32::NEG_INFINITY; + for (row_index, row) in rows.chunks(width).enumerate() { + for (x, value) in row.iter().enumerate().take(end_x).skip(start_x) { + if coverage.get(row_index * width + x) == Some(&true) && value.is_finite() { + minimum = minimum.min(*value); + maximum = maximum.max(*value); + } + } + } + if !minimum.is_finite() { + continue; + } + let (lower, upper, flat, raw) = match map { + BakedMap::Thickness => { + let parameters = settings.maps.thickness.parameters; + match parameters.normalization { + ThicknessNormalization::RelativeToMinMax => (minimum, maximum, 1.0, false), + ThicknessNormalization::RelativeToRayDistances => { + let units = if parameters.rays.relative_to_bounding_box { mesh_scale } else { 1.0 }; + (parameters.rays.min_distance * units, parameters.rays.max_distance * units, 1.0, false) + } + ThicknessNormalization::None => (0.0, 1.0, 1.0, true), + } + } + BakedMap::Height => match settings.maps.height.parameters.normalization { + HeightNormalization::RelativeToRayDistances => { + let units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; + (-settings.cage.max_rear * units, settings.cage.max_frontal * units, 0.5, false) + } + HeightNormalization::RelativeToMinMax => (minimum, maximum, 0.5, false), + HeightNormalization::RelativeToLowMesh => { + let magnitude = minimum.abs().max(maximum.abs()); + (-magnitude, magnitude, 0.5, false) + } + HeightNormalization::Manual => { + let half_range = settings.maps.height.parameters.scaling_divisor * 0.5; + (-half_range, half_range, 0.5, false) + } + }, + _ => { + let parameters = settings.maps.curvature.parameters.mesh; + if parameters.auto_tonemapping { + let magnitude = minimum.abs().max(maximum.abs()); + (-magnitude, magnitude, 0.5, false) + } else { + (parameters.value_min, parameters.value_max, 0.5, false) + } + } + }; + if raw { + continue; + } + let range = upper - lower; + for (row_index, row) in rows.chunks_mut(width).enumerate() { + for (x, value) in row.iter_mut().enumerate().take(end_x).skip(start_x) { + if coverage.get(row_index * width + x) == Some(&true) { + *value = if range > f32::EPSILON { ((*value - lower) / range).clamp(0.0, 1.0) } else { flat }; + } + } + } + } + }); + } +} diff --git a/crates/bake/src/map/part_key.rs b/crates/bake/src/map/part_key.rs new file mode 100644 index 00000000..bda45809 --- /dev/null +++ b/crates/bake/src/map/part_key.rs @@ -0,0 +1,18 @@ +use std::collections::HashMap; + +/// A mesh part's key in `keys` (shared by names that agree once `suffix` is dropped), whether it ignores backfaces, and its lowercase name without that suffix +pub(crate) fn part_key(name: &str, suffix: &str, backface_suffix: &str, keys: &mut HashMap) -> (u32, bool, String) { + let name = name.trim().to_lowercase(); + let ignore_backface = !backface_suffix.is_empty() && name.ends_with(backface_suffix); + let name = if ignore_backface { name.strip_suffix(backface_suffix).unwrap_or(&name).to_owned() } else { name }; + + (match_key(&name, suffix, keys), ignore_backface, name) +} + +/// The key in `keys` of the lowercase part name `name` without `suffix` +fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { + let suffix = suffix.trim().to_lowercase(); + let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(name).to_string(); + let next = keys.len() as u32; + *keys.entry(base).or_insert(next) +} diff --git a/crates/bake/src/map/position_projection.rs b/crates/bake/src/map/position_projection.rs new file mode 100644 index 00000000..eccff2eb --- /dev/null +++ b/crates/bake/src/map/position_projection.rs @@ -0,0 +1,45 @@ +use texturecraft_core::{PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings}; +use texturecraft_geom::{Mesh, glam::Vec3}; + +pub(super) struct PositionProjection { + settings: PositionSettings, + minimum: Vec3, + extent: Vec3, + center: Vec3, + diameter: f32, +} + +impl PositionProjection { + pub(super) fn new(mesh: &Mesh, material: usize, settings: PositionSettings) -> Self { + let initial = (Vec3::splat(f32::INFINITY), Vec3::splat(f32::NEG_INFINITY)); + let expand = |(minimum, maximum): (Vec3, Vec3), position: &Vec3| (minimum.min(*position), maximum.max(*position)); + let (minimum, maximum) = match settings.scale { + PositionNormalizationScale::FullScene => mesh.positions.iter().fold(initial, expand), + PositionNormalizationScale::PerMaterial => mesh + .triangles_of(material) + .filter_map(|triangle| mesh.tri(triangle)) + .flatten() + .filter_map(|index| mesh.positions.get(index)) + .fold(initial, expand), + }; + let minimum = if minimum.is_finite() { minimum } else { Vec3::ZERO }; + let maximum = if maximum.is_finite() { maximum } else { Vec3::ZERO }; + let center = (minimum + maximum) * 0.5; + let extent = maximum - minimum; + Self { settings, minimum, extent, center, diameter: extent.max_element().max(1e-20) } + } + + pub(super) fn evaluate(&self, position: Vec3) -> [f32; 3] { + let value = match self.settings.normalization { + PositionMode::BoundingBox => ((position - self.minimum) / self.extent.max(Vec3::splat(1e-20))).clamp(Vec3::ZERO, Vec3::ONE), + PositionMode::BoundingSphere => ((position - self.center) / self.diameter + 0.5).clamp(Vec3::ZERO, Vec3::ONE), + PositionMode::None => position, + }; + match self.settings.axis { + PositionAxis::All => value.to_array(), + PositionAxis::X => [value.x; 3], + PositionAxis::Y => [value.y; 3], + PositionAxis::Z => [value.z; 3], + } + } +} diff --git a/crates/bake/src/map/sample.rs b/crates/bake/src/map/sample.rs new file mode 100644 index 00000000..2ff9a10e --- /dev/null +++ b/crates/bake/src/map/sample.rs @@ -0,0 +1,8 @@ +use texturecraft_geom::Surface; + +pub(crate) struct Sample { + pub x: usize, + pub surface: Surface, + pub bary: [f32; 2], + pub seed: u64, +} diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs new file mode 100644 index 00000000..5f2d2677 --- /dev/null +++ b/crates/bake/src/map/sampling.rs @@ -0,0 +1,76 @@ +use std::collections::HashMap; +use std::ops::{Add, Mul}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +/// `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) +} + +/// 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(|(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(normal_sum) = normal_sums.get_mut(welded_index as usize) { + *normal_sum += *normal; + } + welded_index + }) + .collect(); + + 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 { + let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +pub(super) fn pack(v: Vec3) -> [f32; 3] { + (v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array() +} + +pub(super) fn generated_hue(part: usize) -> [f32; 3] { + let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32; + let (s, v) = (0.7f32, 0.95f32); + let f = h.fract(); + let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); + match h as u32 { + 0 => [v, t, p], + 1 => [q, v, p], + 2 => [p, v, t], + 3 => [p, q, v], + 4 => [t, p, v], + _ => [v, p, q], + } +} + +pub(super) fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] { + let z = s.nrm; + let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector()); + let b = z.cross(t) * s.tangent.w; + pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n))) +} diff --git a/crates/bake/src/map/seam.rs b/crates/bake/src/map/seam.rs new file mode 100644 index 00000000..4065fd52 --- /dev/null +++ b/crates/bake/src/map/seam.rs @@ -0,0 +1,64 @@ +use std::collections::HashMap; +use texturecraft_geom::{Mesh, glam::Vec2}; + +pub(crate) fn fix_seams(mesh: &Mesh, material: usize, covered: &[bool], size: (usize, usize), intensity: f32, pixels: &mut [f32]) { + if intensity <= 0.0 { + return; + } + let (minimum, maximum) = mesh.bounds(); + let tolerance = (maximum - minimum).length().max(1e-6) * 1e-6; + let position_key = |index: usize| mesh.positions.get(index).map(|position| position.to_array().map(|value| (value / tolerance).round() as i64)); + let mut edges = HashMap::new(); + let source = pixels.to_vec(); + let texel_scale = Vec2::new(size.0 as f32, size.1 as f32); + let texel = |point: Vec2| { + if point.x < 0.0 || point.y < 0.0 || point.x >= size.0 as f32 || point.y >= size.1 as f32 { + return None; + } + let index = point.y.floor() as usize * size.0 + point.x.floor() as usize; + (covered.get(index) == Some(&true)).then_some(index) + }; + for triangle in mesh.triangles_of(material) { + let Some(corners) = mesh.tri(triangle) else { + continue; + }; + for edge in 0..3 { + let (Some(&first), Some(&second), Some(&third)) = (corners.get(edge), corners.get((edge + 1) % 3), corners.get((edge + 2) % 3)) else { + continue; + }; + let (Some(first_key), Some(second_key)) = (position_key(first), position_key(second)) else { + continue; + }; + let (first, second, key) = + if first_key <= second_key { (first, second, (first_key, second_key)) } else { (second, first, (second_key, first_key)) }; + let (Some(start), Some(end), Some(interior)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { + continue; + }; + let (start, end, interior) = (*start * texel_scale, *end * texel_scale, *interior * texel_scale); + let inward = (interior - (start + end) * 0.5).try_normalize().unwrap_or(Vec2::ZERO) * 0.75; + let Some((other_start, other_end, other_inward)) = edges.insert(key, (start, end, inward)) else { + continue; + }; + if start.distance_squared(other_start) + end.distance_squared(other_end) < 0.25 { + continue; + } + let steps = start.distance(end).max(other_start.distance(other_end)).ceil().clamp(1.0, size.0.max(size.1) as f32 * 2.0) as usize; + for step in 0..=steps { + let fraction = step as f32 / steps as f32; + let (Some(first), Some(second)) = (texel(start.lerp(end, fraction) + inward), texel(other_start.lerp(other_end, fraction) + other_inward)) + else { + continue; + }; + let (Some(&first_value), Some(&second_value)) = (source.get(first), source.get(second)) else { + continue; + }; + let average = (first_value + second_value) * 0.5; + for (index, value) in [(first, first_value), (second, second_value)] { + if let Some(destination) = pixels.get_mut(index) { + *destination = value + (average - value) * intensity; + } + } + } + } + } +} diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs new file mode 100644 index 00000000..c5cd5f3f --- /dev/null +++ b/crates/bake/src/map/source.rs @@ -0,0 +1,144 @@ +use super::part_key::part_key; +use super::sampling::{generated_hue, interpolate, splitmix64}; +use crate::BakeRequest; +use crate::tracing::{ANY, TraceMesh}; +use std::collections::HashMap; +use std::sync::Arc; +use texturecraft_core::{HighPolySettings, IdColorGenerator, IdColorSource, IdSettings}; +use texturecraft_geom::glam::{Vec2, Vec4}; +use texturecraft_geom::{BaseColor, Bvh, Mesh, Surface}; +use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; + +pub(super) struct Source<'a> { + pub(super) mesh: &'a Mesh, + bvh: &'a Bvh, + pub(super) part: Vec, + pub(super) key: Vec, + backface_culling: Vec, + file_ids: &'a [u32], + mesh_ids: Vec, + file_count: u32, + mesh_count: u32, + base_color: &'a [Option>], +} + +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, + base_color: &'a [Option>], + file_ids: &'a [u32], + suffix: &str, + settings: &HighPolySettings, + keys: &mut HashMap, + ) -> Source<'a> { + let triangle_count = mesh.triangle_count(); + let mut part = vec![ANY; triangle_count]; + let mut backface_culling = vec![false; triangle_count]; + let mut mesh_keys = HashMap::new(); + let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len()); + let mut part_keys = Vec::with_capacity(mesh.submeshes.len()); + let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase(); + + for (part_index, submesh) in mesh.submeshes.iter().enumerate() { + let first_triangle = (submesh.start / 3) as usize; + let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize; + let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count); + part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32); + + let (key, ignore_backface, name) = part_key(&submesh.name, suffix, &backface_suffix, keys); + backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface); + part_keys.push(key); + + let next = mesh_keys.len() as u32; + let file_id = file_ids.get(part_index).copied().unwrap_or(0); + mesh_ids.push(*mesh_keys.entry((file_id, name)).or_insert(next)); + } + + let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect(); + + Source { + mesh, + bvh, + part, + key, + backface_culling, + file_ids, + file_count: file_ids.iter().copied().max().unwrap_or(0).saturating_add(1), + mesh_count: mesh_keys.len() as u32, + mesh_ids, + base_color, + } + } + + pub(super) fn trace(&self) -> TraceMesh<'_> { + TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key, backface_culling: &self.backface_culling } + } + + pub(super) fn id_color(&self, surface: &Surface, barycentric: [f32; 2], settings: IdSettings) -> [f32; 3] { + let part_index = self.part.get(surface.tri as usize).copied().unwrap_or(0) as usize; + match settings.source { + IdColorSource::VertexColor => interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE).truncate().to_array(), + IdColorSource::MaterialColor => { + let material = self.mesh.submeshes.get(part_index).map(|part| part.material); + material.and_then(|index| self.base_color.get(index)?.as_ref()).map_or([0.6; 3], |color| color.factor.truncate().to_array()) + } + source => { + let (identity, count) = match source { + IdColorSource::FileId => (self.file_ids.get(part_index).copied().unwrap_or(0), self.file_count), + IdColorSource::MeshId => (self.mesh_ids.get(part_index).copied().unwrap_or(0), self.mesh_count), + _ => (part_index as u32, self.mesh.submeshes.len() as u32), + }; + match settings.generator { + IdColorGenerator::HueShift => generated_hue(identity as usize), + IdColorGenerator::Grayscale => [(identity + 1) as f32 / count.max(1) as f32; 3], + IdColorGenerator::Random => { + let seed = splitmix64(u64::from(identity)); + [0, 16, 32].map(|shift| ((seed >> shift) & 0xffff) as f32 / 65535.0) + } + } + } + } + } + + pub(super) fn color(&self, surface: &Surface, barycentric: [f32; 2]) -> Vec4 { + let vertex = interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE); + let material = self.part.get(surface.tri as usize).and_then(|part_index| self.mesh.submeshes.get(*part_index as usize)).map(|submesh| submesh.material); + match material.and_then(|material_index| self.base_color.get(material_index)?.as_deref()) { + Some(material_color) => vertex * base_color(material_color, surface.uv), + None => vertex, + } + } +} + +fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { + let sampled_color = if material.texels.is_empty() || !uv.is_finite() { + Vec4::ONE + } else { + let (width, height) = (i64::from(material.width.max(1)), i64::from(material.height.max(1))); + let texel = |x: i64, y: i64| { + let rgba = material.texels.get((y.rem_euclid(height) * width + x.rem_euclid(width)) as usize).copied().unwrap_or([255; 4]); + let color = |component: usize| f32::from(rgba[component]) / 255.0; + Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3)) + }; + let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x, y) = (x0 as i64, y0 as i64); + texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) + }; + let color = sampled_color * material.factor; + Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) +} 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/traced.rs b/crates/bake/src/map/traced.rs new file mode 100644 index 00000000..45107d66 --- /dev/null +++ b/crates/bake/src/map/traced.rs @@ -0,0 +1,8 @@ +use texturecraft_geom::glam::Vec3; + +pub(crate) struct Traced { + pub ao: f32, + pub bent: Option, + pub thickness: f32, + pub curvature: f32, +} diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs new file mode 100644 index 00000000..c1200053 --- /dev/null +++ b/crates/bake/src/map/transfer.rs @@ -0,0 +1,8 @@ +use texturecraft_geom::Surface; + +pub(crate) struct Transfer { + pub(super) surface: Surface, + pub(super) bary: [f32; 2], + pub(super) t: f32, + pub(super) front: f32, +} 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/maps.rs b/crates/bake/src/maps.rs deleted file mode 100644 index 5aa60ba1..00000000 --- a/crates/bake/src/maps.rs +++ /dev/null @@ -1,440 +0,0 @@ -//! Per-sample evaluation of every baked map. - -use std::collections::HashMap; -use std::ops::{Add, Mul}; -use std::sync::Arc; - -use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; -use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; -use texturecraft_geom::{BaseColor, Bvh, Hit, Mesh, Surface, surface_at}; -use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; - -use crate::rays::{ANY, Hemisphere, Query, Ray, RayKind, TraceMesh}; -use crate::skew::Prepared; -use crate::{BakeError, BakeRequest}; - -/// A mesh the bakers sample: the low poly, or the high poly detail is transferred from. -struct Source<'a> { - mesh: &'a Mesh, - bvh: &'a Bvh, - /// Per-vertex curvature offset from 0.5 (empty unless mesh curvature is baked). - curvature: Vec, - /// Submesh (part) index of each triangle ([`ANY`] outside every part). - part: Vec, - /// Match key of each triangle: its part name without the low / high suffix. - key: Vec, - /// Base color per material (empty: vertex colors only). - base_color: &'a [Option>], -} - -impl<'a> Source<'a> { - fn new( - mesh: &'a Mesh, - bvh: &'a Bvh, - base_color: &'a [Option>], - s: &BakeSettings, - diag: f32, - suffix: &str, - keys: &mut HashMap, - ) -> Source<'a> { - let mesh_curvature = s.maps.contains(&BakedMap::Curvature) && !s.curvature_from_normal; - let tris = mesh.triangle_count(); - let mut part = vec![ANY; tris]; - for (i, sm) in mesh.submeshes.iter().enumerate() { - let (a, b) = ((sm.start / 3) as usize, (sm.start.saturating_add(sm.count) / 3) as usize); - part.get_mut(a.min(b)..b.min(tris)).unwrap_or_default().fill(i as u32); - } - let ids: Vec = mesh.submeshes.iter().map(|sm| match_key(&sm.name, suffix, keys)).collect(); - let key = part.iter().map(|p| ids.get(*p as usize).copied().unwrap_or(ANY)).collect(); - let curvature = if mesh_curvature { vertex_curvature(mesh, diag, s.curvature_strength) } else { Vec::new() }; - Source { mesh, bvh, curvature, part, key, base_color } - } - - fn trace(&self) -> TraceMesh<'_> { - TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key } - } - - fn curvature(&self, s: &Surface, bary: [f32; 2]) -> f32 { - (0.5 + interpolate(self.mesh, &self.curvature, s.tri, bary).unwrap_or(0.0)).clamp(0.0, 1.0) - } - - /// Vertex color times the material's base color (color sRGB-encoded like a base color - /// texture, alpha linear). - fn color(&self, s: &Surface, bary: [f32; 2]) -> Vec4 { - let vertex = interpolate(self.mesh, &self.mesh.colors, s.tri, bary).unwrap_or(Vec4::ONE); - let material = self.part.get(s.tri as usize).and_then(|p| self.mesh.submeshes.get(*p as usize)).map(|sm| sm.material); - match material.and_then(|m| self.base_color.get(m)?.as_deref()) { - Some(b) => vertex * base_color(b, s.uv), - None => vertex, - } - } -} - -/// `b` at `uv` (bilinear in linear light, wrapped) times its factor: color sRGB-encoded, -/// alpha linear. -fn base_color(b: &BaseColor, uv: Vec2) -> Vec4 { - let tex = if b.texels.is_empty() || !uv.is_finite() { - Vec4::ONE - } else { - let (w, h) = (i64::from(b.width.max(1)), i64::from(b.height.max(1))); - let texel = |x: i64, y: i64| { - let t = b.texels.get((y.rem_euclid(h) * w + x.rem_euclid(w)) as usize).copied().unwrap_or([255; 4]); - let c = |k: usize| f32::from(t[k]) / 255.0; - Vec4::new(srgb_to_linear(c(0)), srgb_to_linear(c(1)), srgb_to_linear(c(2)), c(3)) - }; - let (fx, fy) = (uv.x * w as f32 - 0.5, uv.y * h as f32 - 0.5); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x, y) = (x0 as i64, y0 as i64); - texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) - }; - let c = tex * b.factor; - Vec4::new(linear_to_srgb(c.x), linear_to_srgb(c.y), linear_to_srgb(c.z), c.w) -} - -/// The part name without its low / high suffix (case-insensitive), as a shared id. -fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { - let name = name.trim().to_lowercase(); - let suffix = suffix.trim().to_lowercase(); - let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string(); - let next = keys.len() as u32; - *keys.entry(base).or_insert(next) -} - -/// Barycentric interpolation of a per-vertex attribute over triangle `tri`. -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) -} - -/// A covered low-poly supersample of a batch. -pub(crate) struct Sample { - /// Output column. - pub x: usize, - pub surf: Surface, - pub bary: [f32; 2], - pub seed: u64, -} - -/// The high-poly surface found for a low-poly sample, and where along the ray. -pub(crate) struct Transfer { - surf: Surface, - bary: [f32; 2], - /// Hit distance from the ray origin, and the origin's distance in front of the low poly. - t: f32, - front: f32, -} - -/// A sample's secondary-ray results. -pub(crate) struct Traced { - pub ao: f32, - /// None when bent normals are not baked. - pub bent: Option, - pub thickness: f32, -} - -/// Everything a sample needs, computed once per bake. -pub(crate) struct Ctx<'a> { - low: Source<'a>, - high: Option>, - cage: Option<&'a Mesh>, - skew: Option>, - /// Normals averaged over coincident vertices (rays don't split at hard edges); empty when off. - ray_normals: Vec, - lo: Vec3, - extent: Vec3, - /// Ray offset off the surface. - eps: f32, - frontal: f32, - rear: f32, - by_name: bool, - direction: Vec3, - direction_mode: DirectionMode, - position_mode: PositionMode, - curvature_from_normal: bool, - /// Secondary-ray passes of the requested maps. - pub ao: Option, - pub bent: Option, - pub thickness: Option, -} - -impl<'a> Ctx<'a> { - pub(crate) fn new(req: &BakeRequest<'a>) -> Result, BakeError> { - let s = req.settings; - let (lo, hi) = req.mesh.bounds(); - let diag = (hi - lo).length().max(1e-6); - if !diag.is_finite() { - return Err(BakeError::Invalid("mesh bounds are too large".into())); - } - let mut keys = HashMap::new(); - let low = Source::new(req.mesh, req.bvh, &[], s, diag, &s.low_suffix, &mut keys); - let high = req.high.map(|h| Source::new(h.mesh, h.bvh, h.base_color, s, diag, &s.high_suffix, &mut keys)); - let ray_normals = match s.average_normals && high.is_some() { - true => { - let (weld, _, nrm) = welded(req.mesh, diag); - weld.iter().map(|w| nrm.get(*w as usize).copied().unwrap_or(Vec3::Y)).collect() - } - false => Vec::new(), - }; - let skew = req.skew.map(|m| Prepared::new(m, req.mesh, diag)).transpose()?; - let eps = 1e-4 * diag; - let pass = |map: BakedMap, r: &RaySettings, kind: RayKind| { - let half = (r.spread.clamp(0.0, 180.0) * 0.5).to_radians(); - let occlusion = kind == RayKind::Occlusion; - s.maps.contains(&map).then_some(Hemisphere { - kind, - rays: r.rays, - dmax: r.max_distance * diag, - eps, - cos_max: half.cos(), - sin_max: half.sin(), - uniform: r.distribution == RayDistribution::Uniform, - ignore_backface: occlusion && s.ao_ignore_backface, - same_key: occlusion && s.ao_self_occlusion == SelfOcclusion::SameMeshName, - }) - }; - Ok(Ctx { - low, - high, - cage: req.cage, - skew, - ray_normals, - lo, - extent: hi - lo, - eps, - frontal: s.max_frontal * diag, - rear: s.max_rear * diag, - by_name: s.matching == BakeMatch::ByMeshName, - direction: Vec3::from(s.direction).try_normalize().unwrap_or(Vec3::Y), - direction_mode: s.direction_mode, - position_mode: s.position_mode, - curvature_from_normal: s.curvature_from_normal, - ao: pass(BakedMap::AmbientOcclusion, &s.ao, RayKind::Occlusion), - bent: pass(BakedMap::BentNormal, &s.bent_normal, RayKind::Occlusion), - thickness: pass(BakedMap::Thickness, &s.thickness, RayKind::Thickness), - }) - } - - pub(crate) fn has_high(&self) -> bool { - self.high.is_some() - } - - /// Whether the bake casts any ray. - pub(crate) fn casts_rays(&self) -> bool { - self.has_high() || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some() - } - - /// The meshes rays are cast against: the low poly, then the high poly. - pub(crate) fn trace_meshes(&self) -> Vec> { - std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect() - } - - /// The transfer ray of a low-poly sample: from the cage (or `frontal` in front of the low - /// poly) back through it to `rear` behind, onto the matching high-poly part; and the - /// origin's distance in front of the low poly. Parts without a key cast nothing when - /// matched by name. - pub(crate) fn transfer_ray(&self, s: &Surface, bary: [f32; 2]) -> (Ray, f32) { - let n = interpolate(self.low.mesh, &self.ray_normals, s.tri, bary).and_then(Vec3::try_normalize).unwrap_or(s.nrm); - let cage = self.cage.and_then(|c| interpolate(c, &c.positions, s.tri, bary)).map(|c| s.pos - c).filter(|v| v.length() > self.eps); - let (origin, dir, front) = match cage { - Some(v) => (s.pos - v, v.normalize(), v.length()), - None => { - // Skew correction turns the averaged direction towards the base normal. - let up = match &self.skew { - Some(k) => k.correct(self.low.mesh, s, n), - None => n, - }; - (s.pos + up * self.frontal, -up, self.frontal) - } - }; - let key = if self.by_name { self.low.key.get(s.tri as usize).copied().unwrap_or(ANY) } else { ANY }; - let tmax = if self.by_name && key == ANY { 0.0 } else { front + self.rear }; - (Ray { origin, dir, tmax, key }, front) - } - - /// The high-poly surface a transfer ray hit. - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { - let (high, hit) = (self.high.as_ref()?, hit?); - let surf = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; - Some(Transfer { surf, bary: [hit.u, hit.v], t: hit.t, front }) - } - - /// The secondary-ray query of a sample: on the high poly where the transfer found it. - pub(crate) fn query(&self, transfer: Option<&Transfer>, s: &Surface, seed: u64) -> Query { - let (src, surf, mesh) = match (&self.high, transfer) { - (Some(h), Some(tr)) => (h, &tr.surf, 1), - _ => (&self.low, s, 0), - }; - let h = splitmix64(seed); - let rot = [(h >> 40) as f32 / (1u64 << 24) as f32, ((h >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32]; - // The geometric normal on the side of the shading normal. - let geo = if surf.geo_nrm.dot(surf.nrm) < 0.0 { -surf.geo_nrm } else { surf.geo_nrm }; - Query { pos: surf.pos, nrm: surf.nrm, geo, rot, key: src.key.get(surf.tri as usize).copied().unwrap_or(ANY), mesh } - } - - /// Every map of `maps` at one low-poly sample, into `out` (scalars fill all three). - pub(crate) fn evaluate(&self, maps: &[BakedMap], s: &Surface, bary: [f32; 2], transfer: Option<&Transfer>, traced: &Traced, out: &mut [[f32; 3]]) { - // The surface the bakers read: the high poly where a ray found it, else the low poly. - let (src, surf, sb) = match (&self.high, transfer) { - (Some(h), Some(tr)) => (h, &tr.surf, tr.bary), - _ => (&self.low, s, bary), - }; - let missed = self.high.is_some() && transfer.is_none(); - for (&map, o) in maps.iter().zip(out.iter_mut()) { - *o = match map { - BakedMap::AmbientOcclusion => [traced.ao; 3], - BakedMap::BentNormal => pack(traced.bent.unwrap_or(surf.nrm)), - BakedMap::Thickness => [traced.thickness; 3], - BakedMap::Curvature if self.curvature_from_normal => [0.5; 3], - BakedMap::Curvature => [src.curvature(surf, sb); 3], - BakedMap::WorldNormal => pack(surf.nrm), - BakedMap::Position => self.position(surf.pos), - BakedMap::Id => material_color(src.part.get(surf.tri as usize).copied().unwrap_or(0) as usize), - BakedMap::Normal => transfer.map_or(map.neutral(), |tr| tangent_normal(s, tr.surf.nrm)), - BakedMap::Height => [transfer.map_or(0.5, |tr| (0.5 + (tr.front - tr.t) / (tr.front + self.rear)).clamp(0.0, 1.0)); 3], - BakedMap::Opacity if missed => [0.0; 3], - BakedMap::Opacity => [src.color(surf, sb).w; 3], - BakedMap::ColorMap if missed => map.neutral(), - BakedMap::ColorMap => src.color(surf, sb).truncate().to_array(), - BakedMap::WorldDirection => { - let f = surf.nrm.dot(self.direction); - [match self.direction_mode { - DirectionMode::Signed => f * 0.5 + 0.5, - DirectionMode::Positive => f.clamp(0.0, 1.0), - }; 3] - } - }; - } - } - - /// `p` normalized to 0..1 over the low poly's bounding box or bounding sphere. - fn position(&self, p: Vec3) -> [f32; 3] { - let v = match self.position_mode { - PositionMode::BoundingBox => (p - self.lo) / self.extent.max(Vec3::splat(1e-20)), - PositionMode::BoundingSphere => (p - (self.lo + self.extent * 0.5)) / self.extent.length().max(1e-20) + 0.5, - }; - v.clamp(Vec3::ZERO, Vec3::ONE).to_array() - } -} - -/// A unit vector packed to 0..1. -fn pack(v: Vec3) -> [f32; 3] { - (v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array() -} - -/// `n` in the tangent space of low-poly sample `s` (OpenGL: +Y up the image), packed to 0..1. -fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] { - let z = s.nrm; - let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector()); - let b = z.cross(t) * s.tangent.w; - pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n))) -} - -/// Curvature from a baked tangent-space normal map: the divergence of its XY over `radius` -/// texels (convex = above 0.5; 0: one texel per 512 of a UV tile's resolution). Writes covered -/// texels of `out` (one float per texel). `res` is the image width. -pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], res: usize, tile_res: usize, radius: u32, strength: f32, out: &mut [f32]) { - use rayon::prelude::*; - let r = if radius > 0 { radius as usize } else { (tile_res / 512).max(1) }; - let n = |x: usize, y: usize, c: usize, fallback: f32| match covered.get(y * res + x) { - Some(true) => normal.get((y * res + x) * 3 + c).copied().unwrap_or(fallback), - _ => fallback, - }; - out.par_chunks_mut(res).enumerate().for_each(|(y, row)| { - for (x, v) in row.iter_mut().enumerate() { - if covered.get(y * res + x) != Some(&true) { - continue; - } - let (cx, cy) = (n(x, y, 0, 0.5), n(x, y, 1, 0.5)); - let (l, r_) = (n(x.saturating_sub(r), y, 0, cx), if x + r < res { n(x + r, y, 0, cx) } else { cx }); - let (u, d) = (n(x, y.saturating_sub(r), 1, cy), if y + r < res { n(x, y + r, 1, cy) } else { cy }); - // Image rows run down while +Y (OpenGL) points up: convex bumps tilt +Y above. - *v = (0.5 + strength * ((r_ - l) + (u - d))).clamp(0.0, 1.0); - } - }); -} - -/// Position-welded copy of `mesh` (UV seams and hard edges share neighbours): the weld id of -/// every vertex, welded positions and their averaged normals. -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 - .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 - }); - if let Some(acc) = nrm.get_mut(id as usize) { - *acc += *n; - } - id - }) - .collect(); - let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); - (weld, pos, nrm) -} - -/// Per-vertex curvature offset `−k · avg_edge · strength`, where `k` is the mean of -/// `n·(p_j − p_i)/|p_j − p_i|²` over the 1-ring of the welded mesh. Convex edges give a -/// positive offset. -fn vertex_curvature(mesh: &Mesh, diag: f32, strength: f32) -> Vec { - let q = diag * 1e-5; - let (weld, pos, nrm) = welded(mesh, diag); - let (mut ksum, mut kcnt) = (vec![0.0f32; pos.len()], vec![0u32; pos.len()]); - let (mut edge_sum, mut edge_cnt) = (0.0f64, 0u64); - for t in mesh.indices.chunks_exact(3) { - for (a, b) in [(0, 1), (1, 2), (2, 0), (1, 0), (2, 1), (0, 2)] { - let (Some(&wa), Some(&wb)) = (t.get(a).and_then(|v| weld.get(*v as usize)), t.get(b).and_then(|v| weld.get(*v as usize))) else { continue }; - let (Some(pa), Some(pb), Some(na)) = (pos.get(wa as usize), pos.get(wb as usize), nrm.get(wa as usize)) else { continue }; - let d = *pb - *pa; - let l2 = d.length_squared(); - if wa == wb || l2 <= q * q { - continue; - } - if let (Some(k), Some(c)) = (ksum.get_mut(wa as usize), kcnt.get_mut(wa as usize)) { - *k += na.dot(d) / l2; - *c += 1; - } - edge_sum += f64::from(l2.sqrt()); - edge_cnt += 1; - } - } - let scale = (edge_sum / edge_cnt.max(1) as f64) as f32 * strength; - weld.iter() - .map(|w| { - let i = *w as usize; - let k = ksum.get(i).copied().unwrap_or(0.0) / kcnt.get(i).copied().unwrap_or(0).max(1) as f32; - if k.is_finite() { -k * scale } else { 0.0 } - }) - .collect() -} - -/// A well-separated hue per part (golden-ratio steps around the HSV wheel). -fn material_color(part: usize) -> [f32; 3] { - let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32; - let (s, v) = (0.7f32, 0.95f32); - let f = h.fract(); - let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); - match h as u32 { - 0 => [v, t, p], - 1 => [q, v, p], - 2 => [p, v, t], - 3 => [p, q, v], - 4 => [t, p, v], - _ => [v, p, q], - } -} - -fn splitmix64(x: u64) -> u64 { - let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15); - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) -} 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/name_pair.rs b/crates/bake/src/name_pair.rs new file mode 100644 index 00000000..8863cc58 --- /dev/null +++ b/crates/bake/src/name_pair.rs @@ -0,0 +1,103 @@ +//! How "By Mesh Name" pairs low-poly parts with high-poly parts, listed before a bake runs + +use std::collections::{HashMap, HashSet}; + +use texturecraft_core::HighPolySettings; +use texturecraft_geom::Mesh; + +use crate::map::part_key; + +/// A low-poly part and the high-poly part its rays may hit under "By Mesh Name"; one side is missing when that part pairs with nothing +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NamePair { + /// The low-poly part's name as in its mesh + pub low: Option, + /// The high-poly part's name as in its mesh + pub high: Option, +} + +impl NamePair { + /// Each part of `low` in `material` with every `high` part it pairs with (a row per pair), then the `high` parts pairing with none; keyed like the bake, low poly first + pub fn list(low: &Mesh, material: usize, high: &Mesh, settings: &HighPolySettings) -> Vec { + let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase(); + let mut keys = HashMap::new(); + let mut keyed = |mesh: &Mesh, suffix: &str, only_material: Option| { + let mut seen = HashSet::new(); + let mut parts = Vec::new(); + for part in mesh.submeshes.iter().filter(|part| only_material.is_none_or(|material| part.material == material)) { + let (key, ..) = part_key(&part.name, suffix, &backface_suffix, &mut keys); + if seen.insert(part.name.as_str()) { + parts.push((key, part.name.clone())); + } + } + parts + }; + let low_parts = keyed(low, &settings.low_suffix, Some(material)); + let high_parts = keyed(high, &settings.high_suffix, None); + + let mut pairs = Vec::new(); + for (key, low_name) in &low_parts { + let matches: Vec<&String> = high_parts.iter().filter(|(high_key, _)| high_key == key).map(|(_, name)| name).collect(); + if matches.is_empty() { + pairs.push(NamePair { low: Some(low_name.clone()), high: None }); + } + pairs.extend(matches.into_iter().map(|high_name| NamePair { low: Some(low_name.clone()), high: Some(high_name.clone()) })); + } + + let low_keys: HashSet = low_parts.iter().map(|(key, _)| *key).collect(); + pairs.extend(high_parts.into_iter().filter(|(key, _)| !low_keys.contains(key)).map(|(_, name)| NamePair { low: None, high: Some(name) })); + pairs + } + + /// Whether one side is missing: a part the bake will leave unpaired + pub fn unpaired(&self) -> bool { + self.low.is_none() || self.high.is_none() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_geom::SubMesh; + + /// A mesh with one empty part per (name, material) + fn parts(names: &[(&str, usize)]) -> Mesh { + Mesh { + submeshes: names.iter().map(|(name, material)| SubMesh { name: (*name).into(), material: *material, start: 0, count: 0 }).collect(), + materials: vec!["first".into(), "second".into()], + ..Default::default() + } + } + + fn pair(low: Option<&str>, high: Option<&str>) -> NamePair { + NamePair { low: low.map(Into::into), high: high.map(Into::into) } + } + + #[test] + fn parts_pair_by_name_without_their_suffixes() { + let low = parts(&[("Barrel_low", 0), ("Base_low", 0), ("Slide_low", 1)]); + let high = parts(&[("Barrel_high", 0), ("Slide_high", 0), ("Grip_high", 0), ("BARREL_high_ignorebf", 0)]); + let settings = HighPolySettings::default(); + + assert_eq!( + NamePair::list(&low, 0, &high, &settings), + vec![ + pair(Some("Barrel_low"), Some("Barrel_high")), + pair(Some("Barrel_low"), Some("BARREL_high_ignorebf")), + pair(Some("Base_low"), None), + pair(None, Some("Slide_high")), + pair(None, Some("Grip_high")), + ], + "another material's parts are left out, so its high-poly part counts as unpaired here" + ); + assert_eq!(NamePair::list(&low, 1, &high, &settings).iter().filter(|pair| !pair.unpaired()).count(), 1); + } + + #[test] + fn a_part_split_over_triangle_ranges_is_listed_once() { + let low = parts(&[("Body_low", 0), ("Body_low", 0)]); + let high = parts(&[("Body_high", 0), ("Body_high", 0)]); + + assert_eq!(NamePair::list(&low, 0, &high, &HighPolySettings::default()), vec![pair(Some("Body_low"), Some("Body_high"))]); + } +} diff --git a/crates/bake/src/progress.rs b/crates/bake/src/progress.rs new file mode 100644 index 00000000..5bb924ec --- /dev/null +++ b/crates/bake/src/progress.rs @@ -0,0 +1,22 @@ +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; + +#[derive(Debug, Default)] +pub struct Progress { + /// Completed basis points, from 0 to 10,000 + pub done: AtomicU32, + pub cancel: AtomicBool, +} + +impl Progress { + pub fn new() -> Self { + Self::default() + } + + pub fn fraction(&self) -> f32 { + self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 + } + + pub fn cancel(&self) { + self.cancel.store(true, Relaxed); + } +} diff --git a/crates/bake/src/rays.rs b/crates/bake/src/rays.rs deleted file mode 100644 index 6e1ce02a..00000000 --- a/crates/bake/src/rays.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! The ray casts of a bake, in batches. [`CpuTracer`] is the oracle; a GPU [`Tracer`] (the -//! render crate's compute baker) must give the same results: it receives the same rays and -//! queries, and generates the same secondary-ray directions from each query's rotation. - -use std::f32::consts::TAU; - -use rayon::prelude::*; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::{Bvh, Hit, Mesh}; - -use crate::BakeError; - -/// A ray or query key that matches every triangle (no part filter). -pub const ANY: u32 = u32::MAX; - -/// A mesh rays are cast against: [`RayScene`] mesh 0 is the low poly, mesh 1 the high poly. -#[derive(Clone, Copy, Debug)] -pub struct TraceMesh<'a> { - pub mesh: &'a Mesh, - pub bvh: &'a Bvh, - /// Part key of every triangle (original order); triangles of no part hold [`ANY`]. - pub keys: &'a [u32], -} - -impl TraceMesh<'_> { - fn key_matches(&self, tri: u32, key: u32) -> bool { - key == ANY || self.keys.get(tri as usize) == Some(&key) - } - - /// Whether `d` meets triangle `tri` from behind (against its winding's normal). - fn back_facing(&self, tri: u32, d: Vec3) -> bool { - let p = |i: usize| self.mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); - self.mesh.tri(tri as usize).is_some_and(|[a, b, c]| (p(b) - p(a)).cross(p(c) - p(a)).dot(d) > 0.0) - } -} - -/// A closest-hit ray (the high-poly transfer). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Ray { - pub origin: Vec3, - pub dir: Vec3, - pub tmax: f32, - /// Only triangles with this part key are hit ([`ANY`]: all). - pub key: u32, -} - -/// One sample's secondary rays (ambient occlusion, bent normal or thickness). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Query { - pub pos: Vec3, - /// Shading normal: the axis of the ray cone. - pub nrm: Vec3, - /// Geometric normal on the shading normal's side: rays below its plane are skipped. - pub geo: Vec3, - /// Cranley–Patterson rotation of the sample's ray set. - pub rot: [f32; 2], - /// Part key of the sample's triangle (for [`Hemisphere::same_key`]). - pub key: u32, - /// Scene mesh the rays are cast against. - pub mesh: u32, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum RayKind { - /// Out of the surface: ambient occlusion and the bent normal. - Occlusion, - /// Into the surface: the distance through the mesh. - Thickness, -} - -/// Parameters of one pass of secondary rays (distances absolute). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Hemisphere { - pub kind: RayKind, - pub rays: u32, - pub dmax: f32, - /// Ray start offset along the geometric normal. - pub eps: f32, - /// Cosine and sine of the cone's half angle. - pub cos_max: f32, - pub sin_max: f32, - /// Uniform over the cone's solid angle (else cosine-weighted). - pub uniform: bool, - pub ignore_backface: bool, - /// Only triangles with the query's part key occlude. - pub same_key: bool, -} - -impl Hemisphere { - /// Direction `i` of a query's ray set around `axis` (basis `t`, `b`): Hammersley points - /// rotated by `rot`, mapped onto the cone. - pub fn direction(&self, (t, b, axis): (Vec3, Vec3, Vec3), i: u32, rot: [f32; 2]) -> Vec3 { - let u1 = (i as f32 / self.rays as f32 + rot[0]).fract(); - let u2 = (i.reverse_bits() as f32 / 4_294_967_296.0 + rot[1]).fract(); - let (r, z) = if self.uniform { - let z = 1.0 - u2 * (1.0 - self.cos_max); - ((1.0 - z * z).max(0.0).sqrt(), z) - } else { - let r = self.sin_max * u2.sqrt(); - (r, (1.0 - r * r).max(0.0).sqrt()) - }; - let phi = TAU * u1; - t * (r * phi.cos()) + b * (r * phi.sin()) + axis * z - } - - /// The axis, geometric normal and ray origin of `q` for this kind of rays. - fn frame(&self, q: &Query) -> (Vec3, Vec3, Vec3) { - let (axis, geo) = match self.kind { - RayKind::Occlusion => (q.nrm, q.geo), - RayKind::Thickness => (-q.nrm, -q.geo), - }; - (axis, geo, q.pos + geo * self.eps) - } - - /// `q`'s result on `m`: occlusion gives (ambient occlusion, bent normal), thickness gives - /// (thickness, 0, 0, 0); both relative and in 0..1 (1 = open / thick). - pub fn evaluate(&self, m: &TraceMesh, q: &Query) -> [f32; 4] { - let (axis, geo, o) = self.frame(q); - let (t, b) = axis.any_orthonormal_pair(); - let key = if self.same_key && self.kind == RayKind::Occlusion { q.key } else { ANY }; - let filtered = key != ANY || (self.ignore_backface && self.kind == RayKind::Occlusion); - let (mut sum, mut bent, mut n) = (0.0f32, Vec3::ZERO, 0u32); - for i in 0..self.rays { - let d = self.direction((t, b, axis), i, q.rot); - if d.dot(geo) <= 0.0 { - continue; - } - let hit = match filtered { - true => m.bvh.closest_filtered(o, d, self.dmax, &|tri| m.key_matches(tri, key) && !(self.ignore_backface && m.back_facing(tri, d))), - false => m.bvh.closest(o, d, self.dmax), - }; - match self.kind { - RayKind::Occlusion => { - let v = hit.map_or(0.0, |h| 1.0 - (h.t / self.dmax).powi(2)); - sum += v; - bent += d * (1.0 - v); - } - RayKind::Thickness => sum += hit.map_or(self.dmax, |h| h.t), - } - n += 1; - } - match self.kind { - RayKind::Occlusion => { - let ao = if n == 0 { 1.0 } else { (1.0 - sum / n as f32).clamp(0.0, 1.0) }; - let bent = bent.try_normalize().unwrap_or(q.nrm); - [ao, bent.x, bent.y, bent.z] - } - RayKind::Thickness => [if n == 0 { 1.0 } else { (sum / n as f32 / self.dmax).clamp(0.0, 1.0) }, 0.0, 0.0, 0.0], - } - } -} - -/// Ray casts on the meshes of one bake. -pub trait RayScene: Send { - /// The closest hit of every ray on scene mesh `mesh` (triangles of the ray's key). - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError>; - /// [`Hemisphere::evaluate`] of every query, for each pass. - fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError>; -} - -/// Where ray casts run. -pub trait Tracer: Send + Sync { - /// Shown in logs and command results ("CPU", the GPU's name). - fn name(&self) -> String; - /// Prepare `meshes` (low poly, then the high poly if any) for ray casts. - fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError>; -} - -/// Ray casts on the CPU (rayon over the batch). -#[derive(Clone, Copy, Debug, Default)] -pub struct CpuTracer; - -struct CpuScene<'a>(Vec>); - -impl CpuScene<'_> { - fn mesh(&self, i: usize) -> Result<&TraceMesh<'_>, BakeError> { - self.0.get(i).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {i}"))) - } -} - -impl RayScene for CpuScene<'_> { - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> { - let m = self.mesh(mesh)?; - Ok(rays - .par_iter() - .map(|r| match r.key { - ANY => m.bvh.closest(r.origin, r.dir, r.tmax), - key => m.bvh.closest_filtered(r.origin, r.dir, r.tmax, &|t| m.key_matches(t, key)), - }) - .collect()) - } - - fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> { - passes.iter().map(|h| queries.par_iter().map(|q| Ok(h.evaluate(self.mesh(q.mesh as usize)?, q))).collect()).collect() - } -} - -impl Tracer for CpuTracer { - fn name(&self) -> String { - "CPU".into() - } - - fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError> { - Ok(Box::new(CpuScene(meshes.to_vec()))) - } -} diff --git a/crates/bake/src/skew.rs b/crates/bake/src/skew.rs index 28cd4c92..61104cb7 100644 --- a/crates/bake/src/skew.rs +++ b/crates/bake/src/skew.rs @@ -1,261 +1,19 @@ -//! Skew correction: a greyscale map over the UV atlas that turns the transfer rays of a -//! high-poly bake from the averaged cage direction towards the low poly's own normal. Where the -//! averaged direction leans away from a surface (the classic "skewed" details on a bevelled -//! edge or a cylinder's cap), painting the map white there sends the rays straight along the -//! surface normal instead, and grey values blend the two. -//! -//! Ported from SurfaceCraft's baker (`crates/bake`, MIT OR Apache-2.0), adapted to this crate's -//! [`crate::maps::Ctx`] rays. Like the averaged cage it only changes rays that start from the -//! built-in distance cage: a custom cage mesh sets its own directions and ignores the map. +//! Skew correction adapted from SurfaceCraft's baker (MIT OR Apache-2.0) -use std::collections::HashMap; +mod prepared_skew; -use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{Mesh, Surface}; - -use crate::{BakeError, MAX_TEXELS}; - -/// Most dabs one [`SkewMap::paint`] call places. -pub const MAX_DABS: usize = 200_000; - -/// Most texels one [`SkewMap::paint`] call may visit, summed over its dabs (about 70 ms of work): -/// a big brush on a big map costs per dab what a whole-map pass costs, so dabs alone don't bound it. -pub const MAX_PAINT_TEXELS: u64 = 1 << 26; - -/// Edges steeper than this cosine between two faces count as hard (about 30 degrees). -const HARD_EDGE_COS: f32 = 0.866; - -/// A skew map over the whole UV atlas. -#[derive(Clone, Debug, PartialEq)] -pub struct SkewMap { - pub width: u32, - pub height: u32, - /// `width * height` values in 0..=1, row 0 at the top (v = 1): 0 keeps a ray on the cage's - /// averaged direction, 1 turns it fully onto the base normal. - pub values: Vec, - /// Edge protection: the correction fades out within this fraction of the mesh diagonal of a - /// hard edge (0: off). - pub edge_distance: f32, - /// Edge protection's falloff exponent: 1 is linear, more holds the correction back longer. - pub edge_contrast: f32, - /// Correct towards each triangle's flat normal instead of the interpolated vertex normal. - pub per_triangle: bool, -} - -impl SkewMap { - /// A map of one value everywhere. - pub fn constant(value: f32) -> SkewMap { - SkewMap { width: 1, height: 1, values: vec![value], edge_distance: 0.0, edge_contrast: 1.0, per_triangle: false } - } - - /// Refuses maps whose size doesn't match their values, non-finite numbers and absurd sizes. - pub fn validate(&self) -> Result<(), BakeError> { - let invalid = |m: &str| Err(BakeError::Invalid(m.into())); - let texels = u64::from(self.width) * u64::from(self.height); - if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels { - return invalid("the skew map's size doesn't match its values"); - } - if !(self.edge_distance.is_finite() && self.edge_distance >= 0.0 && self.edge_contrast.is_finite() && self.edge_contrast > 0.0) { - return invalid("the skew edge distance must be 0 or more and the contrast above 0"); - } - if self.values.iter().any(|v| !v.is_finite()) { - return invalid("the skew map has a value that is not a finite number"); - } - Ok(()) - } - - /// The map resampled (bilinear) to `width` × `height`; the other settings carry over. - pub fn resized(&self, width: u32, height: u32) -> Result { - let texels = u64::from(width) * u64::from(height); - if width == 0 || height == 0 || texels > MAX_TEXELS { - return Err(BakeError::Invalid(format!("a {width} × {height} skew map is outside the supported size"))); - } - let mut values = Vec::with_capacity(texels as usize); - for y in 0..height { - let v = 1.0 - (y as f32 + 0.5) / height as f32; - for x in 0..width { - values.push(self.at(Vec2::new((x as f32 + 0.5) / width as f32, v))); - } - } - Ok(SkewMap { width, height, values, ..self.clone() }) - } - - /// Paint round dabs along `points` (atlas uv): `value` is blended in with `strength` (0..=1), - /// fully inside `hardness` (0..=1) of `radius` (in uv units) and fading to nothing at the rim. - /// Dabs are placed a quarter radius apart along each segment; `MAX_DABS` bounds one call. - pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> { - let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite(); - if !ok || points.iter().any(|p| !p.is_finite()) { - return Err(BakeError::Invalid("the skew brush needs finite numbers and a radius above 0".into())); - } - self.validate()?; - let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0)); - let step = (radius * 0.25).max(1e-5); - let mut dabs = Vec::new(); - for (i, p) in points.iter().enumerate() { - match i.checked_sub(1).and_then(|j| points.get(j)) { - Some(prev) => { - let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize; - dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32))); - } - None => dabs.push(*p), - } - if dabs.len() > MAX_DABS { - return Err(BakeError::Invalid(format!("a skew stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points"))); - } - } - let (w, h) = (self.width as usize, self.height as usize); - // The texel box of a dab, row 0 at the top (v = 1). - let span = |c: Vec2| { - let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize; - let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize; - let y0 = ((((1.0 - c.y) - radius) * h as f32).floor().max(0.0)) as usize; - let y1 = ((((1.0 - c.y) + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize; - (x0, x1, y0, y1) - }; - // Refuse a stroke that would take too long before the first texel changes. - let work: u64 = dabs - .iter() - .map(|c| { - let (x0, x1, y0, y1) = span(*c); - x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64 - }) - .fold(0, u64::saturating_add); - if work > MAX_PAINT_TEXELS { - return Err(BakeError::Invalid(format!( - "this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke" - ))); - } - for c in dabs { - let (x0, x1, y0, y1) = span(c); - for y in y0..y1 { - let dv = (1.0 - (y as f32 + 0.5) / h as f32) - c.y; - for x in x0..x1 { - let du = (x as f32 + 0.5) / w as f32 - c.x; - let t = (du * du + dv * dv).sqrt() / radius; - if t >= 1.0 { - continue; - } - let fall = if t <= hardness { - 1.0 - } else { - let k = (1.0 - t) / (1.0 - hardness); - k * k * (3.0 - 2.0 * k) - }; - if let Some(v) = self.values.get_mut(y * w + x) { - *v += (value - *v) * fall * strength; - } - } - } - } - Ok(()) - } - - /// The map at atlas `uv`: bilinear, edges clamped. - pub(crate) fn at(&self, uv: Vec2) -> f32 { - let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize); - if !uv.is_finite() { - return 0.0; - } - let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0); - let y = ((1.0 - uv.y).clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0); - let (x0, y0) = (x.floor() as usize, y.floor() as usize); - let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); - let (fx, fy) = (x - x0 as f32, y - y0 as f32); - let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0); - let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx; - let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx; - (top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0) - } -} - -/// A skew map ready for a bake: the map plus what edge protection needs. -pub(crate) struct Prepared<'a> { - map: &'a SkewMap, - /// Per triangle, which of its edges (v0-v1, v1-v2, v2-v0) are hard; only with edge protection. - hard: Vec<[bool; 3]>, - diag: f32, -} - -impl<'a> Prepared<'a> { - pub(crate) fn new(map: &'a SkewMap, mesh: &Mesh, diag: f32) -> Result, BakeError> { - map.validate()?; - let hard = if map.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() }; - Ok(Prepared { map, hard, diag }) - } - - /// The ray direction `up` (unit, away from the surface) at the low-poly sample `s` turned - /// towards its base normal: the interpolated vertex normal, or the flat one per triangle. - pub(crate) fn correct(&self, mesh: &Mesh, s: &Surface, up: Vec3) -> Vec3 { - let amount = self.map.at(s.uv); - if amount <= 0.0 { - return up; - } - let protect = match (self.hard.get(s.tri as usize), mesh.tri(s.tri as usize)) { - (Some(edges), Some(c)) => { - let near = (0..3) - .filter(|&k| edges[k]) - .filter_map(|k| { - let a = mesh.positions.get(*c.get(k)?)?; - let b = mesh.positions.get(*c.get((k + 1) % 3)?)?; - Some(segment_distance(s.pos, *a, *b)) - }) - .fold(f32::INFINITY, f32::min); - (near / (self.map.edge_distance * self.diag).max(1e-9)).clamp(0.0, 1.0).powf(self.map.edge_contrast) - } - _ => 1.0, - }; - let base = if self.map.per_triangle { s.geo_nrm } else { s.nrm }; - let t = amount * protect; - (up * (1.0 - t) + base * t).try_normalize().unwrap_or(up) - } -} - -/// Per triangle, which edges are hard: shared with a triangle whose face normal is more than -/// about 30 degrees away. Edges are matched by position, so split vertices still pair up. -fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> { - let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); - let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits())); - let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) }; - let count = mesh.triangle_count(); - let mut face = vec![Vec3::ZERO; count]; - let mut edges: HashMap<([u32; 3], [u32; 3]), Vec> = HashMap::new(); - for (t, f) in face.iter_mut().enumerate() { - let Some(c) = mesh.tri(t) else { continue }; - *f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO); - for k in 0..3 { - edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t); - } - } - (0..count) - .map(|t| { - let mut out = [false; 3]; - if let Some(c) = mesh.tri(t) { - let own = face.get(t).copied().unwrap_or(Vec3::ZERO); - for (k, hard) in out.iter_mut().enumerate() { - let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3]))); - *hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS))); - } - } - out - }) - .collect() -} - -/// Distance from `p` to the segment `a`-`b`. -fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 { - let ab = b - a; - let len2 = ab.length_squared(); - let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; - (p - (a + ab * t)).length() -} +#[cfg(test)] +use crate::BakePaintMap; +pub(crate) use prepared_skew::PreparedSkew; #[cfg(test)] mod tests { + use super::prepared_skew::{hard_edges, segment_distance}; use super::*; + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::{Mesh, Surface}; fn fold() -> Mesh { - // Two triangles folded 90 degrees along (0,0,0)-(1,0,0), and a third continuing flat. Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, Vec3::new(1.0, 1.0, 0.0)], indices: vec![0, 1, 2, 0, 3, 1, 1, 4, 2], ..Mesh::default() } } @@ -270,19 +28,19 @@ mod tests { #[test] fn maps_sample_bilinearly_and_bad_ones_are_refused() { - let map = SkewMap { width: 2, height: 1, values: vec![0.0, 1.0], ..SkewMap::constant(0.0) }; + let map = BakePaintMap { width: 2, height: 1, values: vec![0.0, 1.0] }; assert!(map.validate().is_ok()); assert!( - map.at(Vec2::new(0.0, 0.5)).abs() < 1e-6 && (map.at(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6 && (map.at(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6 + map.sample(Vec2::new(0.0, 0.5)).abs() < 1e-6 + && (map.sample(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6 + && (map.sample(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6 ); - assert!(map.at(Vec2::new(-3.0, 9.0)).is_finite() && map.at(Vec2::new(f32::NAN, 0.0)) == 0.0); + assert!(map.sample(Vec2::new(-3.0, 9.0)).is_finite() && map.sample(Vec2::new(f32::NAN, 0.0)) == 0.0); for bad in [ - SkewMap { values: vec![0.0], ..map.clone() }, - SkewMap { width: 0, values: vec![], ..map.clone() }, - SkewMap { values: vec![0.0, f32::NAN], ..map.clone() }, - SkewMap { edge_distance: -1.0, ..map.clone() }, - SkewMap { edge_contrast: 0.0, ..map.clone() }, - SkewMap { width: u32::MAX, height: u32::MAX, ..map.clone() }, + BakePaintMap { values: vec![0.0], ..map.clone() }, + BakePaintMap { width: 0, values: vec![], ..map.clone() }, + BakePaintMap { values: vec![0.0, f32::NAN], ..map.clone() }, + BakePaintMap { width: u32::MAX, height: u32::MAX, ..map.clone() }, ] { assert!(bad.validate().is_err()); } @@ -293,50 +51,51 @@ mod tests { let mesh = fold(); let up = Vec3::new(0.6, 0.8, 0.0); let base = Vec3::Y; - let go = |map: &SkewMap, pos: Vec3| { + let go = |map: &BakePaintMap, pos: Vec3, edge_distance: f32| { let s = Surface { pos, nrm: base, geo_nrm: base, tangent: Default::default(), uv: Vec2::splat(0.5), tri: 0 }; - Prepared::new(map, &mesh, 1.0).unwrap().correct(&mesh, &s, up) + PreparedSkew::new( + map, + &mesh, + 1.0, + texturecraft_core::SkewSettings { edge_protection: edge_distance > 0.0, edge_distance, edge_contrast: 1.0, ..Default::default() }, + ) + .unwrap() + .correct(&mesh, &s, up) }; - assert!((go(&SkewMap::constant(0.0), Vec3::ZERO) - up).length() < 1e-6, "black leaves the ray alone"); - assert!((go(&SkewMap::constant(1.0), Vec3::ZERO) - base).length() < 1e-6, "white turns it onto the base normal"); - let half = go(&SkewMap::constant(0.5), Vec3::ZERO); + assert!((go(&BakePaintMap::constant(0.0), Vec3::ZERO, 0.0) - up).length() < 1e-6, "black leaves the ray alone"); + assert!((go(&BakePaintMap::constant(1.0), Vec3::ZERO, 0.0) - base).length() < 1e-6, "white turns it onto the base normal"); + let half = go(&BakePaintMap::constant(0.5), Vec3::ZERO, 0.0); assert!(half.x > 0.0 && half.x < up.x && (half.length() - 1.0).abs() < 1e-5, "grey is in between and still unit: {half}"); - // Triangle 0's edge (0,0,0)-(1,0,0) is hard: on it the correction is held back, far from it it is not. - let guarded = SkewMap { edge_distance: 0.5, ..SkewMap::constant(1.0) }; - assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0)) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction"); - assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0)) - base).length() < 1e-6, "away from every hard edge the correction is full"); + let guarded = BakePaintMap::constant(1.0); + assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0), 0.5) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction"); + assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0), 0.5) - base).length() < 1e-6, "away from every hard edge the correction is full"); } #[test] fn painting_blends_dabs_in_and_resizing_keeps_the_picture() { - let mut map = SkewMap::constant(0.0).resized(64, 64).unwrap(); + let mut map = BakePaintMap::constant(0.0).resized(64, 64).unwrap(); assert!(map.values.iter().all(|v| *v == 0.0)); - // One hard dab at the centre: white inside, untouched outside, in between at the rim. map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 1.0, 1.0, 1.0).unwrap(); - let at = |m: &SkewMap, u: f32, v: f32| m.at(Vec2::new(u, v)); + let at = |m: &BakePaintMap, u: f32, v: f32| m.sample(Vec2::new(u, v)); assert!(at(&map, 0.5, 0.5) > 0.99 && at(&map, 0.95, 0.95) == 0.0, "{} {}", at(&map, 0.5, 0.5), at(&map, 0.95, 0.95)); - // Strength blends one dab in part of the way; a stroke's overlapping dabs build up towards the value; v is up. - let mut dab = SkewMap::constant(0.0).resized(64, 64).unwrap(); + let mut dab = BakePaintMap::constant(0.0).resized(64, 64).unwrap(); dab.paint(&[Vec2::new(0.5, 0.5)], 0.1, 0.8, 1.0, 0.5).unwrap(); assert!((at(&dab, 0.5, 0.5) - 0.4).abs() < 0.02, "{}", at(&dab, 0.5, 0.5)); - let mut line = SkewMap::constant(0.0).resized(64, 64).unwrap(); + let mut line = BakePaintMap::constant(0.0).resized(64, 64).unwrap(); line.paint(&[Vec2::new(0.1, 0.9), Vec2::new(0.9, 0.9)], 0.05, 0.5, 1.0, 0.5).unwrap(); assert!(at(&line, 0.5, 0.9) > 0.45 && at(&line, 0.5, 0.9) <= 0.5 + 1e-4, "{}", at(&line, 0.5, 0.9)); assert!(at(&line, 0.5, 0.1) == 0.0, "the other end of v is untouched"); - // Erasing (value 0) brings a painted area back down. map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 0.0, 1.0, 1.0).unwrap(); assert!(at(&map, 0.5, 0.5) < 0.01); - // Resampling keeps the picture and the edge settings. - let mut small = SkewMap { edge_distance: 0.1, ..SkewMap::constant(0.0).resized(8, 8).unwrap() }; + let mut small = BakePaintMap::constant(0.0).resized(8, 8).unwrap(); small.paint(&[Vec2::new(0.25, 0.75)], 0.2, 1.0, 1.0, 1.0).unwrap(); let big = small.resized(32, 32).unwrap(); - assert_eq!(big.edge_distance, 0.1); assert!((at(&big, 0.25, 0.75) - at(&small, 0.25, 0.75)).abs() < 0.1 && at(&big, 0.9, 0.1) == 0.0); } #[test] fn hostile_brushes_are_refused_and_change_nothing() { - let mut map = SkewMap::constant(0.3).resized(16, 16).unwrap(); + let mut map = BakePaintMap::constant(0.3).resized(16, 16).unwrap(); let before = map.clone(); let c = [Vec2::new(0.5, 0.5)]; for (pts, r, v) in @@ -344,17 +103,15 @@ mod tests { { assert!(map.paint(pts, r, v, 0.5, 1.0).is_err(), "{pts:?} {r} {v}"); } - // Points far outside the atlas are harmless; a huge stroke is refused before any dab lands. map.paint(&[Vec2::new(1e6, -1e6)], 0.1, 1.0, 0.5, 1.0).unwrap(); assert_eq!(map, before); assert!(map.paint(&[Vec2::ZERO, Vec2::new(1e6, 1e6)], 1e-4, 1.0, 0.5, 1.0).is_err()); assert_eq!(map, before); - // A big brush over a big map is refused up front, whatever the dab count: one dab here covers 16.7 M texels. - let mut big = SkewMap::constant(0.0).resized(4096, 4096).unwrap(); + let mut big = BakePaintMap::constant(0.0).resized(4096, 4096).unwrap(); let untouched = big.clone(); assert!(big.paint(&[Vec2::splat(0.5); 8], 1.0, 1.0, 0.5, 1.0).is_err()); assert_eq!(big, untouched, "nothing was painted before the refusal"); assert!(big.paint(&[Vec2::splat(0.5)], 1.0, 1.0, 0.5, 1.0).is_ok(), "one such dab is within the budget"); - assert!(SkewMap::constant(0.0).resized(0, 4).is_err() && SkewMap::constant(0.0).resized(100_000, 100_000).is_err()); + assert!(BakePaintMap::constant(0.0).resized(0, 4).is_err() && BakePaintMap::constant(0.0).resized(100_000, 100_000).is_err()); } } diff --git a/crates/bake/src/skew/prepared_skew.rs b/crates/bake/src/skew/prepared_skew.rs new file mode 100644 index 00000000..e6cce826 --- /dev/null +++ b/crates/bake/src/skew/prepared_skew.rs @@ -0,0 +1,92 @@ +use crate::BakeError; +use crate::BakePaintMap; +use std::collections::HashMap; +use texturecraft_core::{SkewCorrectionMethod, SkewSettings}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +const HARD_EDGE_COS: f32 = 0.866; + +pub(crate) struct PreparedSkew<'a> { + map: &'a BakePaintMap, + settings: SkewSettings, + hard: Vec<[bool; 3]>, + mesh_scale: f32, +} + +impl<'a> PreparedSkew<'a> { + pub(crate) fn new(map: &'a BakePaintMap, mesh: &Mesh, mesh_scale: f32, settings: SkewSettings) -> Result, BakeError> { + map.validate()?; + let hard = if settings.edge_protection && settings.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() }; + Ok(PreparedSkew { map, settings, hard, mesh_scale }) + } + + pub(crate) fn correct(&self, mesh: &Mesh, surface: &Surface, up: Vec3) -> Vec3 { + let amount = self.map.sample(surface.uv); + if amount <= 0.0 { + return up; + } + let protection = match (self.hard.get(surface.tri as usize), mesh.tri(surface.tri as usize)) { + (Some(edges), Some(corners)) => { + let nearest_edge_distance = (0..3) + .filter(|&edge_index| edges[edge_index]) + .filter_map(|edge_index| { + let edge_start = mesh.positions.get(*corners.get(edge_index)?)?; + let edge_end = mesh.positions.get(*corners.get((edge_index + 1) % 3)?)?; + Some(segment_distance(surface.pos, *edge_start, *edge_end)) + }) + .fold(f32::INFINITY, f32::min); + (nearest_edge_distance / (self.settings.edge_distance * self.mesh_scale).max(1e-9)).clamp(0.0, 1.0).powf(self.settings.edge_contrast.max(1e-6)) + } + _ => 1.0, + }; + let base = match self.settings.method { + SkewCorrectionMethod::MeshNormalsBased => surface.nrm, + SkewCorrectionMethod::FaceNormalsBased => { + if surface.geo_nrm.dot(surface.nrm) < 0.0 { + -surface.geo_nrm + } else { + surface.geo_nrm + } + } + }; + let blend = amount * protection; + (up * (1.0 - blend) + base * blend).try_normalize().unwrap_or(up) + } +} + +pub(super) fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> { + let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); + let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits())); + let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) }; + let count = mesh.triangle_count(); + let mut face = vec![Vec3::ZERO; count]; + let mut edges: HashMap<([u32; 3], [u32; 3]), Vec> = HashMap::new(); + for (t, f) in face.iter_mut().enumerate() { + let Some(c) = mesh.tri(t) else { continue }; + *f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO); + for k in 0..3 { + edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t); + } + } + (0..count) + .map(|t| { + let mut out = [false; 3]; + if let Some(c) = mesh.tri(t) { + let own = face.get(t).copied().unwrap_or(Vec3::ZERO); + for (k, hard) in out.iter_mut().enumerate() { + let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3]))); + *hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS))); + } + } + out + }) + .collect() +} + +pub(super) fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 { + let ab = b - a; + let len2 = ab.length_squared(); + let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (p - (a + ab * t)).length() +} diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs new file mode 100644 index 00000000..40edd3b8 --- /dev/null +++ b/crates/bake/src/test/cage_shell.rs @@ -0,0 +1,192 @@ +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)); +} + +#[test] +fn the_cage_lists_its_hard_edges_without_a_uv_seam() { + // A quad whose diagonal is split into two vertices with the same UV, smooth or hard by the copy's normal + let quad_with_diagonal_normal = |normal: Vec3| { + let mut mesh = Mesh::from_parts( + vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y], + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(normal); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(mesh.uvs[0]); + mesh.indices[3] = 4; + mesh + }; + let shell_of = |low: &Mesh| { + let bvh = Bvh::new(low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: low, bvh: &bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let shared = CageShell::new_with_edges(&request, &low.wire_edges(), &low.missing_seam_edges()).unwrap(); + assert_eq!(shared.positions, shell.positions); + assert_eq!(shared.corners(0.1), shell.corners(0.1)); + assert_eq!(shared.edges, shell.edges); + assert_eq!(shared.missing_seams, shell.missing_seams); + shell + }; + + let smooth = quad_with_diagonal_normal(Vec3::Z); + assert!(shell_of(&smooth).missing_seams.is_empty(), "the same normal on both sides is a smooth edge"); + + let hard = quad_with_diagonal_normal(Vec3::new(1.0, 0.0, 1.0).normalize()); + let shell = shell_of(&hard); + let diagonal = [Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)]; + assert_eq!(shell.missing_seams.len(), 2, "the diagonal, once per triangle"); + for [from, to] in &shell.missing_seams { + let mut ends = [shell.positions[*from as usize], shell.positions[*to as usize]]; + ends.sort_by(|a, b| a.x.total_cmp(&b.x)); + assert_eq!(ends, diagonal, "the line runs along the hard diagonal"); + } +} + +#[test] +fn shared_edges_select_the_requested_material() { + let mut mesh = primitives::cube(1.0); + mesh.append(&primitives::cube(1.0)); + let bvh = Bvh::new(&mesh); + let bake_settings = settings(16, &[BakedMap::Normal]); + let wire_edges = mesh.wire_edges(); + let missing_seam_edges = mesh.missing_seam_edges(); + + for material in 0..mesh.materials.len() { + let request = BakeRequest { + low_base_color: &[], + mesh: &mesh, + bvh: &bvh, + material, + settings: &bake_settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let direct = CageShell::new(&request).unwrap(); + let shared = CageShell::new_with_edges(&request, &wire_edges, &missing_seam_edges).unwrap(); + + assert_eq!(shared.positions, direct.positions); + assert_eq!(shared.starts, direct.starts); + assert_eq!(shared.edges, direct.edges); + assert_eq!(shared.missing_seams, direct.missing_seams); + } +} 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..8a4f83c4 --- /dev/null +++ b/crates/bake/src/test/high_poly_reach.rs @@ -0,0 +1,223 @@ +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.as_chunks_mut::<3>().0 { + 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/setting.rs b/crates/bake/src/test/setting.rs new file mode 100644 index 00000000..668338a7 --- /dev/null +++ b/crates/bake/src/test/setting.rs @@ -0,0 +1,206 @@ +use super::*; +use texturecraft_core::{ + AmbientOcclusionAttenuation, HeightNormalization, IdColorSource, MeshMatchMode, PositionAxis, PositionNormalizationScale, ThicknessNormalization, +}; + +#[test] +fn rectangular_bakes_and_diffusion_preserve_surface_pixels() { + let mut mesh = quad(); + for uv in &mut mesh.uvs { + uv.x *= 0.5; + } + let mut parameters = settings(64, &[BakedMap::Position]); + parameters.common.resolution_height = Some(BakeResolution::R32); + let plain = run(&mesh, ¶meters).unwrap(); + assert_eq!((plain.resolution, plain.height), (64, 32)); + assert_eq!(plain.maps[&BakedMap::Position].len(), 64 * 32 * 3); + parameters.common.apply_diffusion = true; + let diffused = run(&mesh, ¶meters).unwrap(); + for row in 0..32 { + let covered = row * 64 * 3..(row * 64 + 32) * 3; + assert_eq!(plain.maps[&BakedMap::Position][covered.clone()], diffused.maps[&BakedMap::Position][covered]); + } + let background = (20 * 64 + 50) * 3; + assert_eq!(plain.maps[&BakedMap::Position][background], 0.0); + assert!(diffused.maps[&BakedMap::Position][background] > 0.0); +} + +#[test] +fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() { + let mut low = quad(); + low.submeshes[0].name = "Panel_low".into(); + let mut high = quad(); + high.submeshes[0].name = "Panel_high".into(); + high.positions.iter_mut().for_each(|position| position.y = 0.02); + let mut unrelated = quad(); + unrelated.submeshes[0].name = "Other_high".into(); + unrelated.positions.iter_mut().for_each(|position| position.y = 0.04); + high.append(&unrelated); + let mut parameters = settings(16, &[BakedMap::Height]); + parameters.cage.max_frontal = 0.1; + parameters.cage.relative_to_bounding_box = false; + parameters.maps.height.parameters.normalization = HeightNormalization::Manual; + let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128]; + + assert!((height(¶meters, &high) - 0.54).abs() < 1e-5); + + parameters.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); + + for triangle in high.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); + } + + assert_eq!(height(¶meters, &high), 0.5); + + parameters.high_poly.ignore_backface = false; + assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); +} + +#[test] +fn occlusion_honors_minimum_distance_units_attenuation_and_named_backfaces() { + let mut mesh = quad(); + let mut ceiling = quad(); + ceiling.positions.iter_mut().for_each(|position| position.y = 0.1); + ceiling.submeshes[0].name = "Roof_ignorebf".into(); + mesh.append(&ceiling); + let mut parameters = settings(16, &[BakedMap::AmbientOcclusion]); + parameters.maps.ao.parameters.rays = + RaySettings { rays: 1, spread: 0.0, min_distance: 0.0, max_distance: 1.0, relative_to_bounding_box: false, ..Default::default() }; + let value = |parameters: &BakeSettings| run(&mesh, parameters).unwrap().maps[&BakedMap::AmbientOcclusion][128]; + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None; + assert_eq!(value(¶meters), 0.0); + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Linear; + assert!((value(¶meters) - 0.1).abs() < 1e-4); + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Smooth; + assert!((value(¶meters) - 0.028).abs() < 1e-4); + parameters.maps.ao.parameters.rays.min_distance = 0.15; + assert_eq!(value(¶meters), 1.0); + parameters.maps.ao.parameters.rays.min_distance = 0.0; + parameters.maps.ao.parameters.rays.max_distance = 0.075; + assert_eq!(value(¶meters), 1.0); + parameters.maps.ao.parameters.rays.relative_to_bounding_box = true; + assert!(value(¶meters) < 0.8); + parameters.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName; + assert_eq!(value(¶meters), 1.0); + parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Never; + parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + assert_eq!(value(¶meters), 1.0); +} + +#[test] +fn bent_normal_settings_are_independent_of_ambient_occlusion() { + let mesh = primitives::material_ball(); + let mut parameters = settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]); + let original = run(&mesh, ¶meters).unwrap(); + parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Always; + parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None; + let changed = run(&mesh, ¶meters).unwrap(); + assert_eq!(original.maps[&BakedMap::BentNormal], changed.maps[&BakedMap::BentNormal]); +} + +#[test] +fn id_sources_keep_material_color_separate_from_vertex_color_and_textures() { + let low = quad(); + let mut high = quad(); + high.colors = vec![Vec4::new(0.8, 0.1, 0.3, 1.0); high.vertex_count()]; + let colors = vec![Some(Arc::new(BaseColor { factor: Vec4::new(0.2, 0.4, 0.7, 1.0), width: 1, height: 1, texels: vec![[255, 0, 0, 255]] }))]; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let mut parameters = settings(16, &[BakedMap::Id]); + for (source, expected) in [(IdColorSource::MaterialColor, [0.2, 0.4, 0.7]), (IdColorSource::VertexColor, [0.8, 0.1, 0.3])] { + parameters.maps.id.parameters.source = source; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: ¶meters, + high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &colors, file_ids: &[0] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let output = bake(&request, &Progress::new()).unwrap(); + for (value, expected) in output.maps[&BakedMap::Id][128 * 3..129 * 3].iter().zip(expected) { + assert!((value - expected).abs() < 1e-6); + } + } +} + +#[test] +fn painted_cage_limits_frontal_projection() { + let low = quad(); + let mut high = quad(); + high.positions.iter_mut().for_each(|position| position.y = 0.08); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let mut parameters = settings(16, &[BakedMap::Opacity]); + parameters.cage.max_frontal = 0.1; + parameters.cage.relative_to_bounding_box = false; + let reduced = BakePaintMap::constant(0.5); + let mut request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: ¶meters, + high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &[], file_ids: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 1.0); + request.cage_paint = Some(&reduced); + assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 0.0); +} + +#[test] +fn position_axis_and_material_bounds_change_only_the_requested_space() { + let mut mesh = quad(); + let mut distant = quad(); + distant.positions.iter_mut().for_each(|position| position.x += 10.0); + mesh.append(&distant); + let mut parameters = settings(16, &[BakedMap::Position]); + parameters.maps.position.parameters.axis = PositionAxis::X; + + let global = run(&mesh, ¶meters).unwrap(); + parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial; + let local = run(&mesh, ¶meters).unwrap(); + + assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2)); + assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9)); + assert!(local.maps[&BakedMap::Position].as_chunks::<3>().0.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2])); +} + +#[test] +fn curvature_radius_and_manual_bounds_control_edge_response() { + let mesh = primitives::cube(2.0); + let mut parameters = settings(64, &[BakedMap::Curvature]); + let narrow = run(&mesh, ¶meters).unwrap(); + parameters.maps.curvature.parameters.mesh.sampling_radius *= 4.0; + let wide = run(&mesh, ¶meters).unwrap(); + let edge_count = |output: &BakeOutput| covered_values(&mesh, output, BakedMap::Curvature).iter().filter(|(_, value)| *value > 0.6).count(); + assert!(edge_count(&wide) > edge_count(&narrow)); + parameters.maps.curvature.parameters.mesh.value_min = -2.0; + parameters.maps.curvature.parameters.mesh.value_max = 2.0; + let reduced = run(&mesh, ¶meters).unwrap(); + assert!(reduced.maps[&BakedMap::Curvature].iter().all(|value| (0.25..=0.75).contains(value))); +} + +#[test] +fn thickness_can_preserve_distance_or_normalize_each_tile() { + let mesh = primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0); + let mut parameters = settings(32, &[BakedMap::Thickness]); + parameters.maps.thickness.parameters.normalization = ThicknessNormalization::None; + parameters.maps.thickness.parameters.rays.relative_to_bounding_box = false; + parameters.maps.thickness.parameters.rays.max_distance = 0.3; + let distance = run(&mesh, ¶meters).unwrap(); + assert!(covered_values(&mesh, &distance, BakedMap::Thickness).iter().all(|(_, value)| *value <= 0.30001)); + parameters.maps.thickness.parameters.normalization = ThicknessNormalization::RelativeToMinMax; + let normalized = run(&mesh, ¶meters).unwrap(); + let values = covered_values(&mesh, &normalized, BakedMap::Thickness); + assert!(values.iter().any(|(_, value)| *value == 0.0)); + assert!(values.iter().any(|(_, value)| *value == 1.0)); +} 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 8fcca53f..0c313462 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -1,18 +1,58 @@ +use std::sync::Arc; +use texturecraft_geom::{BaseColor, Bvh}; + +use texturecraft_core::{ + AmbientOcclusionSettings, BakeAntialiasing, BakeResolution, BakeSettings, BentNormalSettings, CageSettings, CommonBakeSettings, CurvatureSettings, + PositionSettings, +}; + use std::sync::atomic::Ordering::Relaxed; -use texturecraft_core::{BakeMatch, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; +use texturecraft_core::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use texturecraft_geom::primitives; use super::*; -fn settings(res: u32, maps: &[BakedMap]) -> BakeSettings { - with_rays(BakeSettings { resolution: res, dilation: 0, maps: maps.iter().copied().collect(), ..BakeSettings::default() }, 64, 0.25) +#[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( + { + let mut base = BakeSettings::default(); + base.common = + CommonBakeSettings { resolution: BakeResolution::from_pixels(resolution).unwrap(), dilation: 0, apply_diffusion: false, ..base.common }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters }; + base.maps.position.parameters = PositionSettings { normalization: PositionMode::BoundingBox, ..base.maps.position.parameters }; + base.maps.curvature.parameters.mesh.auto_tonemapping = false; + base.maps.height.parameters.normalization = texturecraft_core::HeightNormalization::RelativeToRayDistances; + base.maps.thickness.parameters.normalization = texturecraft_core::ThicknessNormalization::RelativeToRayDistances; + base.maps.select(maps.iter().copied()); + base + }, + 64, + 0.25, + ) } -/// `s` with every secondary-ray map at `rays` rays of length `max_distance`. fn with_rays(mut s: BakeSettings, rays: u32, max_distance: f32) -> BakeSettings { - for r in [&mut s.ao, &mut s.thickness, &mut s.bent_normal] { + for r in [&mut s.maps.ao.parameters.rays, &mut s.maps.thickness.parameters.rays, &mut s.maps.bent_normal.parameters.rays] { *r = RaySettings { rays, max_distance, ..*r }; } s @@ -20,10 +60,12 @@ fn with_rays(mut s: BakeSettings, rays: u32, max_distance: f32) -> BakeSettings fn run(mesh: &Mesh, s: &BakeSettings) -> Result { let bvh = Bvh::new(mesh); - bake(&BakeRequest { mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()) + bake( + &BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) }, + &Progress::new(), + ) } -/// Values of `map` (first component) at texels the UV layout covers, with their surface positions. fn covered_values(mesh: &Mesh, out: &BakeOutput, map: BakedMap) -> Vec<(Vec3, f32)> { let res = out.resolution; let g = UvGBuffer::new(mesh, 0, res, res); @@ -58,41 +100,160 @@ fn open_quad_is_unoccluded() { #[test] fn inside_of_a_closed_box_is_occluded() { - let mut m = primitives::cube(2.0); - for t in m.indices.chunks_exact_mut(3) { - t.swap(1, 2); + let mut mesh = primitives::cube(2.0); + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); } - for n in &mut m.normals { - *n = -*n; + for normal in &mut mesh.normals { + *normal = -*normal; } - m.compute_tangents(); - let s = with_rays(settings(48, &[BakedMap::AmbientOcclusion]), 64, 4.0); - let out = run(&m, &s).unwrap(); - let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); - assert!(ao < 0.3, "{ao}"); + mesh.compute_tangents(); + let parameters = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); + + let output = run(&mesh, ¶meters).unwrap(); + + let mean_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); + assert!(mean_occlusion < 0.3, "{mean_occlusion}"); } #[test] fn thin_slab_is_thinner_than_a_block() { - let thick = |m: &Mesh| mean(covered_values(m, &run(m, &settings(48, &[BakedMap::Thickness])).unwrap(), BakedMap::Thickness).into_iter().map(|v| v.1)); + let thick = |m: &Mesh| mean(covered_values(m, &run(m, &settings(64, &[BakedMap::Thickness])).unwrap(), BakedMap::Thickness).into_iter().map(|v| v.1)); let slab = thick(&primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0)); let block = thick(&primitives::cube(2.0)); assert!(slab < 0.4 && block > 0.6, "slab {slab}, block {block}"); } #[test] -fn sphere_curvature_is_nearly_constant() { - let m = primitives::sphere(1.0, 64, 32); +fn sphere_curvature_stays_calm() { + for (rings, res) in [(64, 64), (12, 128)] { + let m = primitives::sphere(1.0, rings * 2, rings); + let s = settings(res, &[BakedMap::Curvature]); + let out = run(&m, &s).unwrap(); + let c: Vec = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect(); + let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.08, "{rings} rings: {lo}..{hi}"); + } +} + +#[test] +fn flat_surface_is_exactly_mid_grey() { + let m = quad(); let out = run(&m, &settings(64, &[BakedMap::Curvature])).unwrap(); - let c: Vec = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect(); - let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); - assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.03, "{lo}..{hi}"); + let c = covered_values(&m, &out, BakedMap::Curvature); + assert!(c.iter().filter(|(p, _)| p.x.abs() < 0.9 && p.z.abs() < 0.9).all(|(_, v)| *v == 0.5)); +} + +#[test] +fn contact_with_a_wall_is_a_dark_line_and_the_rest_stays_flat() { + let m = floor_and_wall(false); + let s = settings(128, &[BakedMap::Curvature]); + let line = floor_mean(&m, &s, BakedMap::Curvature, 0.96..1.0); + assert!(line < 0.47, "beside the wall {line}"); + assert_eq!(floor_mean(&m, &s, BakedMap::Curvature, -0.9..0.5), 0.5); +} + +fn smooth_shaded_box() -> Mesh { + let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let faces: [(Vec3, Vec3, Vec3); 6] = [ + (Vec3::X, Vec3::Y, Vec3::Z), + (Vec3::NEG_X, Vec3::Z, Vec3::Y), + (Vec3::Y, Vec3::Z, Vec3::X), + (Vec3::NEG_Y, Vec3::X, Vec3::Z), + (Vec3::Z, Vec3::X, Vec3::Y), + (Vec3::NEG_Z, Vec3::Y, Vec3::X), + ]; + for (f, (n, a, b)) in faces.iter().enumerate() { + let base = pos.len() as u32; + let cell = Vec2::new((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0); + for (u, v) in [(-1.0f32, -1.0f32), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] { + let p = *n + *a * u + *b * v; + pos.push(p); + nrm.push(p.normalize()); + uvs.push(cell + Vec2::new((u * 0.5 + 0.5) * 0.3 + 0.015, (v * 0.5 + 0.5) * 0.45 + 0.025)); + } + idx.extend([base, base + 1, base + 2, base, base + 2, base + 3]); + } + Mesh::from_parts(pos, Some(nrm), uvs, idx, "Smooth box").unwrap() +} + +fn edge_peak(m: &Mesh, res: u32, band: f32) -> f32 { + let c = covered_values(m, &run(m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|v| **v > 1.0 - band).count() >= 2).map(|(_, v)| (v - 0.5).abs()).fold(0.0, f32::max) +} + +#[test] +fn smooth_shaded_corners_draw_no_hard_line() { + let (hard, smooth) = (edge_peak(&primitives::cube(2.0), 256, 0.03), edge_peak(&smooth_shaded_box(), 256, 0.03)); + assert!(hard > 0.05, "hard {hard}"); + assert!(smooth < hard * 0.5, "smooth {smooth} hard {hard}"); +} + +#[test] +fn lines_are_as_wide_in_texels_at_any_scale_of_the_part() { + let width = |res: u32| { + let m = primitives::cube(2.0); + let c = covered_values(&m, &run(&m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + c.iter() + .filter(|(p, v)| (v - 0.5).abs() > 0.02 && p.abs().to_array().iter().filter(|a| **a > 0.999).count() == 1) + .map(|(p, _)| { + let mut a = p.abs().to_array(); + a.sort_by(f32::total_cmp); + 1.0 - a[1] + }) + .fold(0.0, f32::max) + }; + let (coarse, fine) = (width(128), width(256)); + assert!(fine > 0.0 && (fine / coarse - 0.5).abs() < 0.2, "world widths {coarse} and {fine}"); +} + +fn barrel(radius: f32) -> Mesh { + const N: u32 = 128; + let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for i in 0..=N { + let u = i as f32 / N as f32; + let (s, c) = (u * std::f32::consts::TAU).sin_cos(); + for (y, v) in [(-1.0f32, 0.0f32), (1.0, 1.0)] { + pos.push(Vec3::new(c * radius, y, s * radius)); + nrm.push(Vec3::new(c, 0.0, s)); + uvs.push(Vec2::new(u, v)); + } + } + for i in 0..N { + let b = i * 2; + idx.extend([b, b + 1, b + 2, b + 1, b + 3, b + 2]); + } + Mesh::from_parts(pos, Some(nrm), uvs, idx, "Barrel").unwrap() +} + +#[test] +fn a_gently_round_barrel_stays_below_the_wear_masks() { + let m = barrel(0.1); + let c = covered_values(&m, &run(&m, &settings(512, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + let (lo, hi) = c.iter().filter(|(p, _)| p.y.abs() < 0.9).fold((1.0f32, 0.0f32), |(lo, hi), (_, v)| (lo.min(*v), hi.max(*v))); + assert!(hi < 0.53 && hi - lo < 0.02, "{lo}..{hi}"); +} + +#[test] +fn a_rounded_bevel_reads_the_same_at_any_map_size() { + let m = primitives::rounded_box(Vec3::ONE, 0.05); + let peak = |res: u32| { + let c = covered_values(&m, &run(&m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + let mut v: Vec = c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|a| **a > 0.97).count() >= 2).map(|v| v.1).collect(); + v.sort_by(f32::total_cmp); + v.get(v.len() / 2).copied().unwrap_or(0.5) + }; + let (coarse, fine) = (peak(512), peak(1024)); + assert!(coarse > 0.58, "bevel at 512: {coarse}"); + assert!((coarse - fine).abs() < 0.1, "512: {coarse}, 1024: {fine}"); } -/// Bevel / edge texels (two coordinates near the half extent) are convex-bright; face centres -/// stay mid-grey. fn check_box_curvature(m: &Mesh, edge: f32) { - let s = BakeSettings { dilation: 4, ..settings(128, &[BakedMap::Curvature]) }; + let s = { + let mut base = settings(128, &[BakedMap::Curvature]); + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; let c = covered_values(m, &run(m, &s).unwrap(), BakedMap::Curvature); let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count(); let edges: Vec = c.iter().filter(|(p, _)| near(*p, edge) >= 2).map(|v| v.1).collect(); @@ -116,13 +277,22 @@ fn cube_edges_are_convex() { #[test] fn two_runs_are_identical_and_sized() { let m = primitives::material_ball(); - let s = with_rays(BakeSettings { antialiasing: 2, dilation: 2, maps: BakedMap::ALL.into_iter().collect(), ..settings(40, &[]) }, 8, 0.25); + let s = with_rays( + { + let mut base = settings(32, &[]); + base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, dilation: 2, ..base.common }; + base.maps.select(BakedMap::ALL); + base + }, + 8, + 0.25, + ); let a = run(&m, &s).unwrap(); let b = run(&m, &s).unwrap(); assert_eq!(a, b); assert_eq!(a.maps.len(), BakedMap::ALL.len()); for (map, data) in &a.maps { - assert_eq!(data.len(), 40 * 40 * map.components(), "{map:?}"); + assert_eq!(data.len(), 32 * 32 * map.components(), "{map:?}"); assert!(data.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{map:?}"); } } @@ -131,11 +301,30 @@ fn two_runs_are_identical_and_sized() { fn strips_match_a_single_pass() { let m = primitives::material_ball(); let bvh = Bvh::new(&m); - let s = with_rays(BakeSettings { antialiasing: 2, maps: BakedMap::ALL.into_iter().collect(), ..settings(64, &[]) }, 4, 0.25); - let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let s = with_rays( + { + let mut base = settings(64, &[]); + base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, ..base.common }; + base.maps.select(BakedMap::ALL); + base + }, + 4, + 0.25, + ); + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; let whole = bake(&req, &Progress::new()).unwrap(); - // 128 × 2 supersampled texels per strip = 1 output row: 64 strips. - 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(); @@ -148,7 +337,18 @@ fn cancel_and_progress() { let m = primitives::sphere(1.0, 16, 8); let bvh = Bvh::new(&m); let s = settings(16, &[BakedMap::AmbientOcclusion, BakedMap::Position]); - let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; let p = Progress::new(); p.cancel(); assert!(matches!(bake(&req, &p), Err(BakeError::Cancelled))); @@ -158,29 +358,112 @@ fn cancel_and_progress() { assert_eq!(p.fraction(), 1.0); } +#[test] +fn a_curvature_bake_can_be_cancelled_midway_and_reports_progress() { + let m = primitives::rounded_box(Vec3::ONE, 0.15); + let bvh = Bvh::new(&m); + let s = settings(2048, &[BakedMap::Curvature]); + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let p = Progress::new(); + std::thread::scope(|t| { + let baking = t.spawn(|| bake(&req, &p)); + let start = std::time::Instant::now(); + while p.done.load(Relaxed) == 0 { + assert!(!baking.is_finished() && start.elapsed().as_secs() < 120, "the bake ended or stalled before reporting progress"); + std::thread::yield_now(); + } + let partway = p.fraction(); + p.cancel(); + assert!(partway < 1.0, "{partway}"); + assert!(matches!(baking.join().unwrap(), Err(BakeError::Cancelled))); + }); +} + +#[test] +fn hostile_tile_dimensions_are_rejected() { + let mesh = quad(); + let bvh = Bvh::new(&mesh); + let settings = settings(16, &[BakedMap::Position]); + + for tiles in [(1 << 31, 1 << 31), (u32::MAX, u32::MAX), (MAX_TEXELS as u32, 1), (0, 1), (1, 0)] { + let request = BakeRequest { + low_base_color: &[], + mesh: &mesh, + bvh: &bvh, + material: 0, + settings: &settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles, + }; + + assert!(matches!(validate(&request), Err(BakeError::Invalid(_))), "{tiles:?}"); + assert!(matches!(bake(&request, &Progress::new()), Err(BakeError::Invalid(_))), "{tiles:?}"); + } +} + #[test] fn invalid_requests_are_errors() { let m = quad(); - let ok = settings(8, &[BakedMap::AmbientOcclusion]); + let ok = settings(16, &[BakedMap::AmbientOcclusion]); let bad = [ - BakeSettings { resolution: 0, ..ok.clone() }, - BakeSettings { resolution: 8193, ..ok.clone() }, - BakeSettings { antialiasing: 3, ..ok.clone() }, - BakeSettings { antialiasing: 0, ..ok.clone() }, - BakeSettings { ao: RaySettings { rays: 0, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { rays: MAX_RAYS + 1, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { max_distance: f32::NAN, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { max_distance: 0.0, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { spread: f32::INFINITY, ..ok.ao }, ..ok.clone() }, - BakeSettings { max_rear: -1.0, ..ok.clone() }, - BakeSettings { curvature_strength: f32::INFINITY, ..ok.clone() }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { rays: RaySettings { rays: 0, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { rays: MAX_RAYS + 1, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { max_distance: f32::NAN, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { max_distance: 0.0, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { spread: f32::INFINITY, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.cage = CageSettings { max_rear: -1.0, ..base.cage }; + base + }, ]; for s in &bad { assert!(matches!(run(&m, s), Err(BakeError::Invalid(_))), "{s:?}"); } let bvh = Bvh::new(&m); let req = |mesh: &Mesh, material| { - bake(&BakeRequest { mesh, bvh: &bvh, material, settings: &ok, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()) + bake( + &BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material, settings: &ok, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) }, + &Progress::new(), + ) }; assert!(matches!(req(&m, 1), Err(BakeError::Invalid(_)))); let mut broken = m.clone(); @@ -189,7 +472,6 @@ fn invalid_requests_are_errors() { let mut nan = m.clone(); nan.positions[0].x = f32::NAN; assert!(matches!(req(&nan, 0), Err(BakeError::Invalid(_)))); - // An empty mesh bakes to neutral values. let empty = Mesh { materials: vec!["m".into()], ..Mesh::default() }; let out = req(&empty, 0).unwrap(); assert!(out.maps[&BakedMap::AmbientOcclusion].iter().all(|v| *v == 1.0)); @@ -197,13 +479,17 @@ fn invalid_requests_are_errors() { #[test] fn neutral_values_and_padding() { - // The quad covers only the left half of UV space. let mut m = quad(); for uv in &mut m.uvs { uv.x *= 0.5; } let maps = [BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Thickness, BakedMap::Normal, BakedMap::Position]; - let out = run(&m, &BakeSettings { dilation: 2, ..settings(16, &maps) }).unwrap(); + let out = run(&m, &{ + let mut base = settings(16, &maps); + base.common = CommonBakeSettings { dilation: 2, ..base.common }; + base + }) + .unwrap(); let pos = &out.maps[&BakedMap::Position]; let at = |x: usize, y: usize| &pos[(y * 16 + x) * 3..(y * 16 + x) * 3 + 3]; assert_eq!(at(9, 5)[0], at(7, 5)[0], "padded texel copies a texel of the last covered column"); @@ -228,13 +514,15 @@ fn normal_and_height_transfer_from_a_high_poly() { let s = settings(16, &[BakedMap::Normal, BakedMap::Height]); let out = bake( &BakeRequest { + low_base_color: &[], mesh: &low, bvh: &lb, material: 0, settings: &s, - high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &[] }), + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &hb, base_color: &[] }), cage: None, skew: None, + cage_paint: None, tiles: (1, 1), }, &Progress::new(), @@ -242,12 +530,10 @@ fn normal_and_height_transfer_from_a_high_poly() { .unwrap(); let i = 8 * 16 + 8; let n = &out.maps[&BakedMap::Normal][i * 3..i * 3 + 3]; - // Tangent = +X (u), bitangent = −Z (up the image), normal = +Y. assert!((n[0] - (0.5 + 0.5 * tilt.x)).abs() < 1e-3 && (n[1] - 0.5).abs() < 1e-3 && (n[2] - (0.5 + 0.5 * tilt.y)).abs() < 1e-3, "{n:?}"); - let diag = 8.0f32.sqrt(); + let diag = 2.0; let expected = 0.5 + 0.005 / (0.02 * diag); assert!((out.maps[&BakedMap::Height][i] - expected).abs() < 1e-3, "{}", out.maps[&BakedMap::Height][i]); - // Without a high poly both maps are flat. let flat = run(&low, &s).unwrap(); assert_eq!(&flat.maps[&BakedMap::Normal][i * 3..i * 3 + 3], [0.5, 0.5, 1.0]); assert_eq!(flat.maps[&BakedMap::Height][i], 0.5); @@ -255,28 +541,101 @@ fn normal_and_height_transfer_from_a_high_poly() { fn transfer(low: &Mesh, high: &Mesh, cage: Option<&Mesh>, s: &BakeSettings) -> Result { let (lb, hb) = (Bvh::new(low), Bvh::new(high)); + let mut settings = s.clone(); + if cage.is_some() { + settings.cage.kind = texturecraft_core::CageType::CustomFile; + } bake( &BakeRequest { + low_base_color: &[], mesh: low, bvh: &lb, material: 0, - settings: s, - high: Some(HighPoly { mesh: high, bvh: &hb, base_color: &[] }), + settings: &settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &hb, base_color: &[] }), cage, skew: None, + cage_paint: None, tiles: (1, 1), }, &Progress::new(), ) } -/// Texel (x, y) of a `res`² bake of [`quad`] sits over world (2u − 1, 0, 2v − 1). +#[test] +fn a_high_poly_box_has_bright_edges_and_flat_faces() { + let s = { + let mut base = settings(128, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; + for (m, edge) in [(primitives::cube(2.0), 0.97), (primitives::rounded_box(Vec3::ONE, 0.15), 0.9)] { + let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); + let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count(); + let brightest = c.iter().filter(|(p, _)| near(*p, edge) >= 2).map(|v| v.1).fold(0.0, f32::max); + assert!(brightest > 0.55, "edge {brightest}"); + assert!(c.iter().filter(|(p, _)| near(*p, 0.5) == 1).all(|v| (0.45..=0.55).contains(&v.1)), "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 = { + let mut base = settings(1024, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; + let brightest = |bevel: f32| { + let m = primitives::rounded_box(Vec3::ONE, bevel); + let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); + let edge = 1.0 - bevel * 0.7; + c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|c| **c > edge).count() >= 2).map(|v| v.1).fold(0.0, f32::max) + }; + let (narrow, wide) = (brightest(0.01), brightest(0.05)); + assert!(narrow > 0.8, "narrow: {narrow}"); + assert!(wide > 0.55, "wide: {wide}"); +} + +#[test] +fn a_gently_round_high_poly_stays_below_the_wear_masks() { + let m = primitives::sphere(1.0, 96, 48); + let s = { + let mut base = settings(256, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; + let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); + let over = c.iter().filter(|v| v.1 > 0.65).count() as f32 / c.len() as f32; + assert!(over < 0.01, "{over}"); +} + fn quad_texel(res: u32, x: f32, z: f32) -> usize { let t = |c: f32| (((c + 1.0) * 0.5 * res as f32) as usize).min(res as usize - 1); t(z) * res as usize + t(x) } -/// [`quad`]'s footprint with a smooth bump `h · exp(−r²/σ²)`. fn bumped(h: f32, sigma: f32) -> Mesh { let mut m = primitives::plane(2.0, 128); for p in &mut m.positions { @@ -290,17 +649,19 @@ fn bumped(h: f32, sigma: f32) -> Mesh { #[test] fn bump_tilts_the_baked_normal() { let (h, sigma) = (0.1f32, 0.4f32); - let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, ..settings(64, &[BakedMap::Normal, BakedMap::Height]) }; + let s = { + let mut base = settings(64, &[BakedMap::Normal, BakedMap::Height]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base + }; let out = transfer(&quad(), &bumped(h, sigma), None, &s).unwrap(); let normal = &out.maps[&BakedMap::Normal]; for (x, z) in [(0.3f32, 0.0f32), (-0.3, 0.0), (0.0, 0.3), (0.0, -0.3), (0.25, 0.25)] { let i = quad_texel(64, x, z); - // Analytic normal of the bump at the texel centre. let (cx, cz) = (((i % 64) as f32 + 0.5) / 32.0 - 1.0, ((i / 64) as f32 + 0.5) / 32.0 - 1.0); let f = h * (-(cx * cx + cz * cz) / (sigma * sigma)).exp(); let (dx, dz) = (-2.0 * cx / (sigma * sigma) * f, -2.0 * cz / (sigma * sigma) * f); let n = Vec3::new(-dx, 1.0, -dz).normalize(); - // Tangent = +X, bitangent = −Z, normal = +Y. let expected = [0.5 + 0.5 * n.x, 0.5 - 0.5 * n.z, 0.5 + 0.5 * n.y]; let got = &normal[i * 3..i * 3 + 3]; assert!(got.iter().zip(expected).all(|(g, e)| (g - e).abs() < 0.02), "at {x},{z}: {got:?} vs {expected:?}"); @@ -310,57 +671,8 @@ 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 = BakeSettings { max_frontal: 0.06, max_rear: 0.02, curvature_from_normal: true, ..settings(64, &[BakedMap::Curvature]) }; - 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)]); -} - -/// Two unit boxes 0.2 apart: "A" (material 0, centre x = −0.6) and "B" (material 1, x = +0.6). -fn two_boxes(suffix: &str, colors: Option<[Vec4; 2]>) -> Mesh { - let part = |name: &str, x: f32, color: Option| { - let mut b = primitives::cube(1.0); - b.positions.iter_mut().for_each(|p| p.x += x); - b.submeshes[0].name = format!("{name}{suffix}"); - b.colors = color.map(|c| vec![c; b.positions.len()]).unwrap_or_default(); - b - }; - let mut m = part("A", -0.6, colors.map(|c| c[0])); - m.append(&part("B", 0.6, colors.map(|c| c[1]))); - m -} - -#[test] -fn match_by_mesh_name_pairs_the_right_parts() { - let (red, blue) = (Vec4::new(1.0, 0.0, 0.0, 1.0), Vec4::new(0.0, 0.0, 1.0, 1.0)); - let (low, high) = (two_boxes("_low", None), two_boxes("_HIGH", Some([red, blue]))); - // Rays start 1.3 in front of A's +X face: beyond B, so B's high poly is hit first unless - // parts are matched by name. - let s = BakeSettings { max_frontal: 0.5, ..settings(64, &[BakedMap::ColorMap]) }; - let face = |s: &BakeSettings| { - let out = transfer(&low, &high, None, s).unwrap(); - covered_values(&low, &out, BakedMap::ColorMap) - .into_iter() - .filter(|(p, _)| p.x > -0.105 && p.y.abs() < 0.4 && p.z.abs() < 0.4) - .map(|v| v.1) - .collect::>() - }; - let always = face(&s); - assert!(!always.is_empty() && always.iter().all(|r| *r < 0.01), "always: B's (blue) high poly occludes A's face"); - let by_name = face(&BakeSettings { matching: BakeMatch::ByMeshName, ..s.clone() }); - assert!(by_name.iter().all(|r| *r > 0.99), "by name: A's face gets A's red"); - // Parts without a counterpart get nothing. - let lonely = BakeSettings { matching: BakeMatch::ByMeshName, low_suffix: "_none".into(), ..s }; - assert!(face(&lonely).iter().all(|r| *r == 0.0)); -} - #[test] fn bent_normals_point_away_from_occluders() { - // A floor (material 0) with a wall standing at x = +1, facing −X (material 1). let mut m = quad(); let wall = Mesh::from_parts( vec![Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(1.0, 2.0, 1.0), Vec3::new(1.0, 2.0, -1.0)], @@ -387,20 +699,17 @@ fn bent_normals_point_away_from_occluders() { } #[test] -fn opacity_and_color_transfer_where_the_high_poly_is() { - // The high poly covers x < 0 only, colored green. +fn opacity_transfers_where_the_high_poly_is() { let mut high = quad(); high.positions.iter_mut().for_each(|p| p.x = p.x.min(0.0)); high.colors = vec![Vec4::new(0.0, 1.0, 0.0, 0.5); 4]; - let out = transfer(&quad(), &high, None, &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap(); - let (op, col) = (&out.maps[&BakedMap::Opacity], &out.maps[&BakedMap::ColorMap]); + let out = transfer(&quad(), &high, None, &settings(32, &[BakedMap::Opacity])).unwrap(); + let opacity = &out.maps[&BakedMap::Opacity]; let (left, right) = (quad_texel(32, -0.5, 0.0), quad_texel(32, 0.5, 0.0)); - assert_eq!((op[left], op[right]), (0.5, 0.0), "vertex alpha where covered, 0 where missed"); - assert_eq!(&col[left * 3..left * 3 + 3], [0.0, 1.0, 0.0]); - assert_eq!(&col[right * 3..right * 3 + 3], BakedMap::ColorMap.neutral()); - // Without a high poly the low poly covers itself (white, opaque). - let own = run(&quad(), &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap(); - assert_eq!((own.maps[&BakedMap::Opacity][right], own.maps[&BakedMap::ColorMap][right * 3]), (1.0, 1.0)); + assert_eq!((opacity[left], opacity[right]), (0.5, 0.0), "vertex alpha where covered, 0 where missed"); + + let low_poly_bake = run(&quad(), &settings(32, &[BakedMap::Opacity])).unwrap(); + assert_eq!(low_poly_bake.maps[&BakedMap::Opacity][right], 1.0); } #[test] @@ -408,66 +717,111 @@ fn ray_distances_and_the_cage_limit_hits() { let low = quad(); let mut high = quad(); high.positions.iter_mut().for_each(|p| p.y += 0.2); - let diag = 8.0f32.sqrt(); + let diag = 2.0; let opacity = |s: &BakeSettings, cage: Option<&Mesh>| transfer(&low, &high, cage, s).map(|o| o.maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]); let near = settings(16, &[BakedMap::Opacity]); assert_eq!(opacity(&near, None).unwrap(), 0.0, "0.2 above is beyond the default frontal distance"); - assert_eq!(opacity(&BakeSettings { max_frontal: 0.25 / diag, ..near.clone() }, None).unwrap(), 1.0); - // The rear distance only reaches below the surface. + assert_eq!( + opacity( + &{ + let mut base = near.clone(); + base.cage = CageSettings { max_frontal: 0.25 / diag, ..base.cage }; + base + }, + None + ) + .unwrap(), + 1.0 + ); let mut below = high.clone(); below.positions.iter_mut().for_each(|p| p.y -= 0.4); - let rear = |r: f32| transfer(&low, &below, None, &BakeSettings { max_rear: r, ..near.clone() }).unwrap().maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]; + let rear = |r: f32| { + transfer(&low, &below, None, &{ + let mut base = near.clone(); + base.cage = CageSettings { max_rear: r, ..base.cage }; + base + }) + .unwrap() + .maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)] + }; assert_eq!((rear(0.1 / diag), rear(0.25 / diag)), (0.0, 1.0)); - // A cage 0.3 above the low poly starts the rays above the high poly. let mut cage = low.clone(); cage.positions.iter_mut().for_each(|p| p.y += 0.3); assert_eq!(opacity(&near, Some(&cage)).unwrap(), 1.0); - // A cage 0.1 above starts below it. cage.positions.iter_mut().for_each(|p| p.y -= 0.2); assert_eq!(opacity(&near, Some(&cage)).unwrap(), 0.0); - // The cage must have the low poly's triangles. assert!(matches!(opacity(&near, Some(&primitives::cube(1.0))), Err(BakeError::Invalid(_)))); } -#[test] -fn world_space_direction_is_a_facing_ratio() { - let m = quad(); - let at = - |d: [f32; 3]| run(&m, &BakeSettings { direction: d, ..settings(8, &[BakedMap::WorldDirection]) }).map(|o| o.maps[&BakedMap::WorldDirection][4 * 8 + 4]); - assert_eq!(at([0.0, 2.0, 0.0]).unwrap(), 1.0); - assert_eq!(at([1.0, 0.0, 0.0]).unwrap(), 0.5); - assert_eq!(at([0.0, -1.0, 0.0]).unwrap(), 0.0); - assert!(matches!(at([0.0; 3]), Err(BakeError::Invalid(_)))); -} - -/// `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench` #[test] #[ignore] fn bench_material_ball_2k() { let m = primitives::material_ball(); let bvh = Bvh::new(&m); - let all = with_rays(BakeSettings { resolution: 2048, ..BakeSettings::default() }, 64, 0.25); - for maps in - [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness], vec![BakedMap::Curvature], all.maps.iter().copied().collect()] + let all = with_rays( + { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R2048, ..base.common }; + base + }, + 64, + 0.25, + ); + for maps in [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness], vec![BakedMap::Curvature], all.maps.enabled().collect()] { - let s = BakeSettings { maps: maps.into_iter().collect(), ..all.clone() }; + let s = { + let mut base = all.clone(); + base.maps.select(maps); + base + }; let t = std::time::Instant::now(); - let out = - bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()).unwrap(); - println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.ao.rays, t.elapsed()); + let out = bake( + &BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }, + &Progress::new(), + ) + .unwrap(); + println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.maps.ao.parameters.rays.rays, t.elapsed()); } } #[test] fn uv_tiles_bake_side_by_side_in_one_atlas() { - // Tiles 1001 (x < 0) and 1002 (x > 0) of the UDIM plane, in atlas UVs. let mut m = primitives::udim_plane(); let grid = texturecraft_core::TileGrid::of(&[1001, 1002]).unwrap(); m.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array()))); - let s = BakeSettings { dilation: 4, ..settings(32, &[BakedMap::Position]) }; + let s = { + let mut base = settings(32, &[BakedMap::Position]); + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; let bvh = Bvh::new(&m); - let out = - bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (2, 1) }, &Progress::new()).unwrap(); + let out = bake( + &BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (2, 1), + }, + &Progress::new(), + ) + .unwrap(); assert_eq!((out.resolution, out.height), (64, 32)); let pos = &out.maps[&BakedMap::Position]; assert_eq!(pos.len(), 64 * 32 * 3); @@ -476,12 +830,45 @@ fn uv_tiles_bake_side_by_side_in_one_atlas() { assert!(x_at(2, y) < 0.3 && x_at(29, y) < 0.5, "tile 1001 holds the left plane"); assert!(x_at(34, y) > 0.5 && x_at(62, y) > 0.7, "tile 1002 holds the right plane"); } - let too_many = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (0, 1) }; + let too_many = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (0, 1), + }; assert!(bake(&too_many, &Progress::new()).is_err()); } -/// A floor ([`quad`], part "Quad") with a wall (part "Wall") standing at x = +1, facing the -/// floor (−X) or, when `away`, away from it (+X); winding and normals agree. +#[test] +fn curvature_on_uv_tiles_matches_a_single_tile() { + let one = primitives::rounded_box(Vec3::ONE, 0.15); + let mut two = one.clone(); + two.uvs.iter_mut().for_each(|uv| uv.x *= 0.5); + let s = { + let mut base = settings(64, &[BakedMap::Curvature]); + base.common = CommonBakeSettings { dilation: 0, ..base.common }; + base + }; + let bake_tiles = |m: &Mesh, tiles| { + let bvh = Bvh::new(m); + bake( + &BakeRequest { low_base_color: &[], mesh: m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, cage_paint: None, tiles }, + &Progress::new(), + ) + .unwrap() + }; + let (a, b) = (bake_tiles(&one, (1, 1)), bake_tiles(&two, (2, 1))); + let (a, b) = (&a.maps[&BakedMap::Curvature], &b.maps[&BakedMap::Curvature]); + let worst = (0..64 * 64).map(|i| (a[i] - b[(i / 64) * 128 + i % 64]).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "{worst}"); +} + fn floor_and_wall(away: bool) -> Mesh { let mut m = quad(); let (n, indices) = if away { (Vec3::X, vec![0, 2, 1, 0, 3, 2]) } else { (-Vec3::X, vec![0, 1, 2, 0, 2, 3]) }; @@ -497,45 +884,116 @@ fn floor_and_wall(away: bool) -> Mesh { m } -/// Mean of `map` (first component) over the floor where `x` is in `range` (the wall is at 1). fn floor_mean(m: &Mesh, s: &BakeSettings, map: BakedMap, range: std::ops::Range) -> f32 { let out = run(m, s).unwrap(); mean(covered_values(m, &out, map).into_iter().filter(|(p, _)| range.contains(&p.x)).map(|v| v.1)) } -/// [`floor_mean`] next to the wall. fn near_wall(m: &Mesh, s: &BakeSettings, map: BakedMap) -> f32 { floor_mean(m, s, map, 0.6..1.0) } #[test] fn ambient_occlusion_settings_shape_the_occlusion() { - let m = floor_and_wall(false); - let base = with_rays(settings(32, &[BakedMap::AmbientOcclusion]), 64, 2.0); - let ao = |f: &dyn Fn(&mut BakeSettings)| { - let mut s = base.clone(); - f(&mut s); - near_wall(&m, &s, BakedMap::AmbientOcclusion) + let mesh = floor_and_wall(false); + let mut base = with_rays(settings(32, &[BakedMap::AmbientOcclusion]), 64, 2.0); + base.maps.ao.parameters.rays.relative_to_bounding_box = false; + base.maps.ao.parameters.rays.max_distance = (mesh.bounds().1 - mesh.bounds().0).length() * 2.0; + let ao = |configure: &dyn Fn(&mut BakeSettings)| { + let mut bake_settings = base.clone(); + configure(&mut bake_settings); + near_wall(&mesh, &bake_settings, BakedMap::AmbientOcclusion) }; let wide = ao(&|_| {}); assert!(wide < 0.85, "the wall occludes the floor beside it: {wide}"); - // A wider spread gathers occlusion from farther away: the wall darkens a wider, softer band. - let far = |spread: f32| floor_mean(&m, &BakeSettings { ao: RaySettings { spread, ..base.ao }, ..base.clone() }, BakedMap::AmbientOcclusion, -1.0..-0.2); + + let far = |spread: f32| { + floor_mean( + &mesh, + &{ + let mut base = base.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { rays: RaySettings { spread, ..base.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + BakedMap::AmbientOcclusion, + -1.0..-0.2, + ) + }; let (narrow, wide_far) = (far(60.0), far(180.0)); assert!(narrow > 0.99 && wide_far < narrow - 0.05, "far from the wall: spread 60° {narrow}, 180° {wide_far}"); - // Uniform rays graze the floor more often than cosine-weighted ones: they reach the wall - // from farther away. - let uniform = BakeSettings { ao: RaySettings { distribution: RayDistribution::Uniform, ..base.ao }, ..base.clone() }; - let uniform_far = floor_mean(&m, &uniform, BakedMap::AmbientOcclusion, -1.0..-0.2); + + let uniform = { + let mut base = base.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { + rays: RaySettings { distribution: RayDistribution::Uniform, ..base.maps.ao.parameters.rays }, + ..base.maps.ao.parameters + }; + base + }; + let uniform_far = floor_mean(&mesh, &uniform, BakedMap::AmbientOcclusion, -1.0..-0.2); assert!(uniform_far < wide_far - 0.02, "far from the wall: uniform {uniform_far}, cosine {wide_far}"); - // Parts only occlude themselves when matched by name: the wall is another part. - let own = ao(&|s| s.ao_self_occlusion = SelfOcclusion::SameMeshName); + + let own = ao(&|bake_settings| bake_settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName); assert!(own > 0.999, "{own}"); - // Back faces are ignored on request: a wall turned away no longer occludes. - let back = - |away: bool, ignore: bool| near_wall(&floor_and_wall(away), &BakeSettings { ao_ignore_backface: ignore, ..base.clone() }, BakedMap::AmbientOcclusion); - assert!((back(true, false) - wide).abs() < 1e-6, "without the option a wall occludes from either side"); - assert!(back(true, true) > 0.999 && (back(false, true) - wide).abs() < 1e-6); + + let back = |away: bool, ignore: BackfaceMode| { + near_wall( + &floor_and_wall(away), + &{ + let mut base = base.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { ignore_backface: ignore, ..base.maps.ao.parameters }; + base + }, + BakedMap::AmbientOcclusion, + ) + }; + assert!((back(true, BackfaceMode::Never) - wide).abs() < 1e-6, "without the option a wall occludes from either side"); + assert!(back(true, BackfaceMode::Always) > 0.999 && (back(false, BackfaceMode::Always) - wide).abs() < 1e-6); +} + +#[test] +fn occlusion_falls_off_linearly_to_the_max_distance() { + let ceiling_height = 0.5; + let corners = |height: f32| [Vec3::new(-1.0, height, -1.0), Vec3::new(1.0, height, -1.0), Vec3::new(1.0, height, 1.0), Vec3::new(-1.0, height, 1.0)]; + let mut uvs = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)]; + // The ceiling occludes the floor without contributing baked texels + uvs.extend([Vec2::ZERO; 4]); + let normals = [[Vec3::Y; 4], [Vec3::NEG_Y; 4]].concat(); + let mesh = Mesh::from_parts( + corners(0.0).into_iter().chain(corners(ceiling_height)).collect(), + Some(normals), + uvs, + vec![0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7], + "Room", + ) + .unwrap(); + + // Nearly vertical rays meet the ceiling at half their maximum distance + let mut parameters = settings(16, &[BakedMap::AmbientOcclusion]); + parameters.maps.ao.parameters.rays = + RaySettings { max_distance: 2.0 * ceiling_height, relative_to_bounding_box: false, spread: 2.0, ..parameters.maps.ao.parameters.rays }; + let output = run(&mesh, ¶meters).unwrap(); + let ambient_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|(_, value)| value)); + + assert!((ambient_occlusion - 0.5).abs() < 0.01, "{ambient_occlusion}"); +} + +#[test] +fn secondary_ray_defaults_preserve_per_map_distances() { + let parameters = BakeSettings::default(); + let expected_rays = RaySettings { + rays: 64, + min_distance: 0.00001, + max_distance: 1.0, + relative_to_bounding_box: true, + spread: 180.0, + distribution: RayDistribution::Cosine, + }; + + assert_eq!(parameters.maps.ao.parameters.rays, expected_rays); + assert_eq!(parameters.maps.ao.parameters.attenuation, texturecraft_core::AmbientOcclusionAttenuation::Linear); + assert_eq!(parameters.maps.bent_normal.parameters.rays, expected_rays); + assert_eq!(parameters.maps.thickness.parameters.rays, RaySettings { max_distance: 0.1, ..expected_rays }); } #[test] @@ -544,16 +1002,18 @@ fn bent_normals_and_thickness_have_their_own_rays() { let s = with_rays(settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]), 64, 2.0); let lean = |s: &BakeSettings| near_wall(&m, s, BakedMap::BentNormal) * 2.0 - 1.0; assert!(lean(&s) < -0.15, "{}", lean(&s)); - // Bent-normal rays shorter than the gap to the wall see nothing; the AO keeps its own rays. - let short = BakeSettings { bent_normal: RaySettings { max_distance: 0.05, rays: 16, ..s.bent_normal }, ..s.clone() }; + let short = { + let mut base = s.clone(); + base.maps.bent_normal.parameters = + BentNormalSettings { rays: RaySettings { max_distance: 0.05, rays: 16, ..s.maps.bent_normal.parameters.rays }, ..base.maps.bent_normal.parameters }; + base + }; assert!(lean(&short) > 0.5 * lean(&s), "{} vs {}", lean(&short), lean(&s)); assert_eq!(near_wall(&m, &short, BakedMap::AmbientOcclusion), near_wall(&m, &s, BakedMap::AmbientOcclusion)); - // Thickness of the slab's top and bottom: a wider spread sends rays through it at grazing - // angles (longer paths). let slab = primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0); let thick = |spread: f32| { - let mut s = settings(48, &[BakedMap::Thickness]); - s.thickness.spread = spread; + let mut s = settings(64, &[BakedMap::Thickness]); + s.maps.thickness.parameters.rays.spread = spread; mean( covered_values(&slab, &run(&slab, &s).unwrap(), BakedMap::Thickness) .into_iter() @@ -566,83 +1026,78 @@ fn bent_normals_and_thickness_have_their_own_rays() { } #[test] -fn position_and_direction_modes() { - let m = quad(); - let pos = |mode: PositionMode| { - let out = run(&m, &BakeSettings { position_mode: mode, ..settings(16, &[BakedMap::Position]) }).unwrap(); - let g = UvGBuffer::new(&m, 0, 16, 16); - (0..256).filter(|i| g.surface(&m, *i).is_some()).map(|i| [0, 1, 2].map(|k| out.maps[&BakedMap::Position][i * 3 + k])).collect::>() +fn position_modes() { + let mesh = quad(); + let positions = |mode: PositionMode| { + let out = run(&mesh, &{ + let mut base = settings(16, &[BakedMap::Position]); + base.maps.position.parameters = PositionSettings { normalization: mode, ..base.maps.position.parameters }; + base + }) + .unwrap(); + let gbuffer = UvGBuffer::new(&mesh, 0, 16, 16); + (0..256).filter(|i| gbuffer.surface(&mesh, *i).is_some()).map(|i| [0, 1, 2].map(|k| out.maps[&BakedMap::Position][i * 3 + k])).collect::>() }; - // The flat quad: the box squashes y to 0 and stretches x, z over 0..1; the sphere keeps - // proportions around the centre (half diagonal √2 of 2√2 per unit). - let (bbox, sphere) = (pos(PositionMode::BoundingBox), pos(PositionMode::BoundingSphere)); - assert!(bbox.iter().all(|p| p[1] == 0.0) && bbox.iter().any(|p| p[0] < 0.05) && bbox.iter().any(|p| p[0] > 0.95)); - let r = 0.5 / 8.0f32.sqrt(); - assert!(sphere.iter().all(|p| p[1] == 0.5 && (p[0] - 0.5).abs() <= 2.0 * r + 1e-4 && (p[2] - 0.5).abs() <= 2.0 * r + 1e-4)); - let dir = |d: [f32; 3], mode| { - run(&m, &BakeSettings { direction: d, direction_mode: mode, ..settings(8, &[BakedMap::WorldDirection]) }).unwrap().maps[&BakedMap::WorldDirection] - [4 * 8 + 4] + + let (box_positions, sphere_positions) = (positions(PositionMode::BoundingBox), positions(PositionMode::BoundingSphere)); + assert!(box_positions.iter().all(|p| p[1] == 0.0) && box_positions.iter().any(|p| p[0] < 0.05) && box_positions.iter().any(|p| p[0] > 0.95)); + let unit_scale = 0.25; + assert!(sphere_positions.iter().all(|p| p[1] == 0.5 && (p[0] - 0.5).abs() <= 2.0 * unit_scale + 1e-4 && (p[2] - 0.5).abs() <= 2.0 * unit_scale + 1e-4)); + + let raw_settings = { + let mut base = settings(16, &[BakedMap::Position]); + base.maps.position.parameters = PositionSettings { normalization: PositionMode::None, ..base.maps.position.parameters }; + base }; - assert_eq!( - (dir([1.0, 0.0, 0.0], DirectionMode::Positive), dir([0.0, -1.0, 0.0], DirectionMode::Positive), dir([0.0, 1.0, 0.0], DirectionMode::Positive)), - (0.0, 0.0, 1.0) - ); - assert_eq!(dir([1.0, 0.0, 0.0], DirectionMode::Signed), 0.5); + let raw = run(&mesh, &raw_settings).unwrap(); + let gbuffer = UvGBuffer::new(&mesh, 0, 16, 16); + for texel in 0..16 * 16 { + let Some(surface) = gbuffer.surface(&mesh, texel) else { continue }; + + let actual = &raw.maps[&BakedMap::Position][texel * 3..texel * 3 + 3]; + assert!(actual.iter().zip(surface.pos.to_array()).all(|(actual, expected)| (actual - expected).abs() < 1e-6)); + } } #[test] -fn curvature_radius_widens_the_normal_map_sampling() { - let at_top = |radius: u32| { - let s = - BakeSettings { max_frontal: 0.06, max_rear: 0.02, curvature_from_normal: true, curvature_radius: radius, ..settings(64, &[BakedMap::Curvature]) }; - transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap().maps[&BakedMap::Curvature][quad_texel(64, 0.0, 0.0)] - }; - let (one, four) = (at_top(1), at_top(4)); - assert!(one > 0.5 && four > one + 0.02, "radius 1: {one}, radius 4: {four}"); -} - -#[test] -fn color_map_samples_the_high_poly_base_color_texture() { +fn opacity_samples_the_high_poly_base_color_texture() { let low = quad(); let mut high = quad(); high.positions.iter_mut().for_each(|p| p.y += 0.005); - // Four texels across u: red, red, blue (half transparent), blue; a second material tinted - // by its factor only. + let red = [255, 0, 0, 255]; let blue = [0, 0, 255, 128]; - let tex = BaseColor { factor: Vec4::ONE, width: 4, height: 1, texels: vec![red, red, blue, blue] }; - let hb = Bvh::new(&high); - let lb = Bvh::new(&low); - let s = settings(32, &[BakedMap::ColorMap, BakedMap::Opacity]); - let bake_with = |c: BaseColor| { - let base_color = [Some(Arc::new(c))]; - let req = BakeRequest { + let texture = BaseColor { factor: Vec4::ONE, width: 4, height: 1, texels: vec![red, red, blue, blue] }; + let high_bvh = Bvh::new(&high); + let low_bvh = Bvh::new(&low); + let bake_settings = settings(32, &[BakedMap::Opacity]); + let bake_with = |base_color: BaseColor| { + let base_color = [Some(Arc::new(base_color))]; + let request = BakeRequest { + low_base_color: &[], mesh: &low, - bvh: &lb, + bvh: &low_bvh, material: 0, - settings: &s, - high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &base_color }), + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &base_color }), cage: None, skew: None, + cage_paint: None, tiles: (1, 1), }; - bake(&req, &Progress::new()).unwrap() + bake(&request, &Progress::new()).unwrap() }; - let out = bake_with(tex); - // Row 16 (v ≈ 0.5); columns 8 and 24 sit inside the red and blue halves (u ≈ 0.27, 0.77). + + let out = bake_with(texture); + let (left, right) = (16 * 32 + 8, 16 * 32 + 24); - let (color, opacity) = (&out.maps[&BakedMap::ColorMap], &out.maps[&BakedMap::Opacity]); - let near = |a: &[f32], b: [f32; 3]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3); - assert!(near(&color[left * 3..left * 3 + 3], [1.0, 0.0, 0.0]), "{:?}", &color[left * 3..left * 3 + 3]); - assert!(near(&color[right * 3..right * 3 + 3], [0.0, 0.0, 1.0]), "{:?}", &color[right * 3..right * 3 + 3]); + let opacity = &out.maps[&BakedMap::Opacity]; assert!((opacity[left] - 1.0).abs() < 1e-6 && (opacity[right] - 128.0 / 255.0).abs() < 1e-3); - // A factor alone tints in linear light; the map holds display-encoded color like a texture. - let half = bake_with(BaseColor { factor: Vec4::new(0.5, 1.0, 1.0, 1.0), width: 0, height: 0, texels: Vec::new() }); - let r = half.maps[&BakedMap::ColorMap][left * 3]; - assert!((r - texturecraft_texel::linear_to_srgb(0.5)).abs() < 1e-4, "{r}"); + + let half = bake_with(BaseColor { factor: Vec4::new(1.0, 1.0, 1.0, 0.5), width: 0, height: 0, texels: Vec::new() }); + assert_eq!(half.maps[&BakedMap::Opacity][left], 0.5); } -/// A tracer that never works (no GPU). struct Broken; impl Tracer for Broken { @@ -650,7 +1105,7 @@ impl Tracer for Broken { "Broken".into() } - fn scene<'a>(&'a self, _: &[rays::TraceMesh<'a>]) -> Result, BakeError> { + fn scene<'a>(&'a self, _: &[tracing::TraceMesh<'a>]) -> Result, BakeError> { Err(BakeError::Tracer("no device".into())) } } @@ -660,16 +1115,29 @@ fn a_failing_tracer_falls_back_to_the_cpu() { let m = floor_and_wall(false); let bvh = Bvh::new(&m); let s = with_rays(settings(16, &[BakedMap::AmbientOcclusion, BakedMap::Thickness]), 8, 1.0); - let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; let out = bake_on(&req, &Progress::new(), &Broken).unwrap(); assert_eq!(out.tracer, "CPU (Broken unavailable: no device)"); assert_eq!(out.maps, bake(&req, &Progress::new()).unwrap().maps); - // Bakes without rays never ask the tracer. - let flat = BakeSettings { maps: [BakedMap::Position].into_iter().collect(), ..s.clone() }; - assert_eq!(bake_on(&BakeRequest { settings: &flat, ..req }, &Progress::new(), &Broken).unwrap().tracer, "CPU"); + let flat = { + let mut base = s.clone(); + base.maps.select([BakedMap::Position]); + base + }; + assert_eq!(bake_on(&BakeRequest { low_base_color: &[], settings: &flat, ..req }, &Progress::new(), &Broken).unwrap().tracer, "CPU"); } -/// A flat quad of half-size `half` at height `y`, every vertex normal `n`. fn plane(y: f32, half: f32, n: Vec3) -> Mesh { Mesh::from_parts( vec![Vec3::new(-half, y, -half), Vec3::new(half, y, -half), Vec3::new(half, y, half), Vec3::new(-half, y, half)], @@ -682,41 +1150,49 @@ fn plane(y: f32, half: f32, n: Vec3) -> Mesh { } #[test] -fn skew_correction_turns_transfer_rays_from_the_averaged_direction_to_the_base_normal() { - // A flat low poly whose smooth normals lean (0.6, 0.8, 0); the high poly is a plane 0.3 above it. +fn skew_correction_preserves_uniform_mesh_normals_and_rejects_invalid_values() { let lean = Vec3::new(0.6, 0.8, 0.0); let (low, high) = (plane(0.0, 1.0, lean), plane(0.3, 4.0, Vec3::Y)); let (lb, hb) = (Bvh::new(&low), Bvh::new(&high)); - let s = BakeSettings { max_frontal: 0.5, max_rear: 0.1, average_normals: true, ..settings(16, &[BakedMap::Height]) }; - let diag = (low.bounds().1 - low.bounds().0).length(); + let s = { + let mut base = settings(16, &[BakedMap::Height]); + base.cage = CageSettings { max_frontal: 0.5, max_rear: 0.1, average_normals: true, ..base.cage }; + base + }; + let diag = (low.bounds().1 - low.bounds().0).max_element(); let (front, rear) = (0.5 * diag, 0.1 * diag); - let height = |skew: Option<&SkewMap>| { + let height = |skew: Option<&BakePaintMap>| { let req = BakeRequest { + low_base_color: &[], mesh: &low, bvh: &lb, material: 0, settings: &s, - high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &[] }), + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &hb, base_color: &[] }), cage: None, skew, + cage_paint: None, tiles: (1, 1), }; bake(&req, &Progress::new()).unwrap().maps[&BakedMap::Height][8 * 16 + 8] }; - // Along a direction with vertical component c the ray meets the plane at t = front - 0.3 / c. let expect = |c: f32| 0.5 + (0.3 / c) / (front + rear); - let map = |v: f32, per_triangle: bool| SkewMap { per_triangle, ..SkewMap::constant(v) }; let plain = height(None); assert!((plain - expect(0.8)).abs() < 1e-3, "leaning rays: {plain} vs {}", expect(0.8)); - assert!((height(Some(&map(0.0, true))) - plain).abs() < 1e-6, "black leaves the rays alone"); - let full = height(Some(&map(1.0, true))); - assert!((full - expect(1.0)).abs() < 1e-3, "white turns them onto the flat normal: {full} vs {}", expect(1.0)); - let half = height(Some(&map(0.5, true))); - assert!(half > full.min(plain) && half < full.max(plain), "grey is in between: {half}"); - // With the interpolated vertex normal as the base, correcting changes nothing on this mesh. - assert!((height(Some(&map(1.0, false))) - plain).abs() < 1e-4); - // A bad map is refused, not baked. - let bad = SkewMap { values: vec![f32::NAN], ..SkewMap::constant(0.0) }; - let req = BakeRequest { mesh: &low, bvh: &lb, material: 0, settings: &s, high: None, cage: None, skew: Some(&bad), tiles: (1, 1) }; + assert!((height(Some(&BakePaintMap::constant(0.0))) - plain).abs() < 1e-6, "black leaves the rays alone"); + assert!((height(Some(&BakePaintMap::constant(1.0))) - plain).abs() < 1e-4); + let bad = BakePaintMap { values: vec![f32::NAN], ..BakePaintMap::constant(0.0) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &lb, + material: 0, + settings: &s, + high: None, + cage: None, + skew: Some(&bad), + cage_paint: None, + tiles: (1, 1), + }; assert!(matches!(bake(&req, &Progress::new()), Err(BakeError::Invalid(_)))); } diff --git a/crates/bake/src/tracing.rs b/crates/bake/src/tracing.rs new file mode 100644 index 00000000..c07596f6 --- /dev/null +++ b/crates/bake/src/tracing.rs @@ -0,0 +1,21 @@ +mod cpu_scene; +mod cpu_tracer; +mod hemisphere; +mod query; +mod ray; +mod ray_kind; +mod ray_scene; +mod trace_mesh; +mod tracer; + +pub use cpu_tracer::CpuTracer; +pub use hemisphere::Hemisphere; +pub use query::Query; +pub use ray::Ray; +pub use ray_kind::RayKind; +pub use ray_scene::RayScene; +pub use trace_mesh::TraceMesh; +pub use tracer::Tracer; + +/// Part key that disables triangle filtering +pub const ANY: u32 = u32::MAX; diff --git a/crates/bake/src/tracing/cpu_scene.rs b/crates/bake/src/tracing/cpu_scene.rs new file mode 100644 index 00000000..12f85f8b --- /dev/null +++ b/crates/bake/src/tracing/cpu_scene.rs @@ -0,0 +1,34 @@ +use super::{ANY, Hemisphere, Query, Ray, RayScene, TraceMesh}; +use crate::BakeError; +use rayon::prelude::*; +use texturecraft_geom::Hit; + +pub(super) struct CpuScene<'a>(pub(super) Vec>); + +impl CpuScene<'_> { + fn mesh(&self, index: usize) -> Result<&TraceMesh<'_>, BakeError> { + self.0.get(index).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {index}"))) + } +} + +impl RayScene for CpuScene<'_> { + fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError> { + let trace_mesh = self.mesh(mesh)?; + Ok(rays + .par_iter() + .map(|ray| { + if ray.key == ANY && !ignore_backface { + trace_mesh.bvh.closest(ray.origin, ray.direction, ray.max_distance) + } else { + trace_mesh.bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| { + trace_mesh.key_matches(triangle, ray.key) && !(ignore_backface && trace_mesh.back_facing(triangle, ray.direction)) + }) + } + }) + .collect()) + } + + fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> { + passes.iter().map(|hemisphere| queries.par_iter().map(|query| Ok(hemisphere.evaluate(self.mesh(query.mesh as usize)?, query))).collect()).collect() + } +} diff --git a/crates/bake/src/tracing/cpu_tracer.rs b/crates/bake/src/tracing/cpu_tracer.rs new file mode 100644 index 00000000..5276e6aa --- /dev/null +++ b/crates/bake/src/tracing/cpu_tracer.rs @@ -0,0 +1,16 @@ +use super::cpu_scene::CpuScene; +use super::{RayScene, TraceMesh, Tracer}; +use crate::BakeError; + +#[derive(Clone, Copy, Debug, Default)] +pub struct CpuTracer; + +impl Tracer for CpuTracer { + fn name(&self) -> String { + "CPU".into() + } + + fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError> { + Ok(Box::new(CpuScene(meshes.to_vec()))) + } +} diff --git a/crates/bake/src/tracing/hemisphere.rs b/crates/bake/src/tracing/hemisphere.rs new file mode 100644 index 00000000..25d63e0c --- /dev/null +++ b/crates/bake/src/tracing/hemisphere.rs @@ -0,0 +1,107 @@ +use super::{ANY, Query, RayKind, TraceMesh}; +use std::f32::consts::TAU; +use texturecraft_core::{AmbientOcclusionAttenuation, BackfaceMode}; +use texturecraft_geom::glam::Vec3; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hemisphere { + pub kind: RayKind, + pub rays: u32, + /// Maximum ray distance in mesh units + pub dmax: f32, + pub min_distance: f32, + pub attenuation: AmbientOcclusionAttenuation, + pub ground_height: Option, + /// Ray origin offset along the geometric normal + pub eps: f32, + pub cos_max: f32, + pub sin_max: f32, + pub uniform: bool, + pub ignore_backface: BackfaceMode, + pub same_key: bool, +} + +impl Hemisphere { + pub fn direction(&self, (tangent, bitangent, axis): (Vec3, Vec3, Vec3), ray_index: u32, rotation: [f32; 2]) -> Vec3 { + let azimuth_sample = (ray_index as f32 / self.rays as f32 + rotation[0]).fract(); + let elevation_sample = (ray_index.reverse_bits() as f32 / 4_294_967_296.0 + rotation[1]).fract(); + let (radius, height) = if self.uniform { + let height = 1.0 - elevation_sample * (1.0 - self.cos_max); + ((1.0 - height * height).max(0.0).sqrt(), height) + } else { + let radius = self.sin_max * elevation_sample.sqrt(); + (radius, (1.0 - radius * radius).max(0.0).sqrt()) + }; + let azimuth = TAU * azimuth_sample; + tangent * (radius * azimuth.cos()) + bitangent * (radius * azimuth.sin()) + axis * height + } + + fn frame(&self, query: &Query) -> (Vec3, Vec3, Vec3) { + let (axis, geometric_normal) = match self.kind { + RayKind::Occlusion => (query.nrm, query.geo), + RayKind::Thickness => (-query.nrm, -query.geo), + }; + (axis, geometric_normal, query.pos + geometric_normal * self.eps) + } + + pub fn evaluate(&self, mesh: &TraceMesh, query: &Query) -> [f32; 4] { + let (axis, geometric_normal, origin) = self.frame(query); + let (tangent, bitangent) = axis.any_orthonormal_pair(); + let key = if self.same_key { query.key } else { ANY }; + let filtered = key != ANY || self.ignore_backface != BackfaceMode::Never; + let (mut accumulated, mut bent_normal, mut accepted_ray_count) = (0.0f32, Vec3::ZERO, 0u32); + for ray_index in 0..self.rays { + let direction = self.direction((tangent, bitangent, axis), ray_index, query.rot); + if direction.dot(geometric_normal) <= 0.0 { + continue; + } + let ray_origin = origin + direction * self.min_distance; + let ray_length = (self.dmax - self.min_distance).max(0.0); + let hit = if filtered { + mesh.bvh.closest_filtered(ray_origin, direction, ray_length, &|triangle| { + let ignore_backface = match self.ignore_backface { + BackfaceMode::Never => false, + BackfaceMode::Always => true, + BackfaceMode::ByMeshName => mesh.backface_culling.get(triangle as usize).copied().unwrap_or(false), + }; + mesh.key_matches(triangle, key) && !(ignore_backface && mesh.back_facing(triangle, direction)) + }) + } else { + mesh.bvh.closest(ray_origin, direction, ray_length) + }; + let mut distance = hit.map(|hit| hit.t + self.min_distance); + if let Some(height) = self.ground_height.filter(|_| direction.y < -1e-8) { + let ground_distance = (height - origin.y) / direction.y; + if (self.min_distance..=self.dmax).contains(&ground_distance) { + distance = Some(distance.map_or(ground_distance, |distance| distance.min(ground_distance))); + } + } + match self.kind { + RayKind::Occlusion => { + let occlusion = distance.map_or(0.0, |distance| self.occlusion(distance)); + accumulated += occlusion; + bent_normal += direction * (1.0 - occlusion); + } + RayKind::Thickness => accumulated += distance.unwrap_or(self.dmax), + } + accepted_ray_count += 1; + } + match self.kind { + RayKind::Occlusion => { + let ambient_occlusion = if accepted_ray_count == 0 { 1.0 } else { (1.0 - accumulated / accepted_ray_count as f32).clamp(0.0, 1.0) }; + let bent_normal = bent_normal.try_normalize().unwrap_or(query.nrm); + [ambient_occlusion, bent_normal.x, bent_normal.y, bent_normal.z] + } + RayKind::Thickness => [if accepted_ray_count == 0 { self.dmax } else { accumulated / accepted_ray_count as f32 }, 0.0, 0.0, 0.0], + } + } + + fn occlusion(&self, distance: f32) -> f32 { + let fraction = ((distance - self.min_distance) / (self.dmax - self.min_distance).max(f32::EPSILON)).clamp(0.0, 1.0); + match self.attenuation { + AmbientOcclusionAttenuation::None => 1.0, + AmbientOcclusionAttenuation::Linear => 1.0 - fraction, + AmbientOcclusionAttenuation::Smooth => 1.0 - fraction * fraction * (3.0 - 2.0 * fraction), + } + } +} diff --git a/crates/bake/src/tracing/query.rs b/crates/bake/src/tracing/query.rs new file mode 100644 index 00000000..a42e7091 --- /dev/null +++ b/crates/bake/src/tracing/query.rs @@ -0,0 +1,11 @@ +use texturecraft_geom::glam::Vec3; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Query { + pub pos: Vec3, + pub nrm: Vec3, + pub geo: Vec3, + pub rot: [f32; 2], + pub key: u32, + pub mesh: u32, +} diff --git a/crates/bake/src/tracing/ray.rs b/crates/bake/src/tracing/ray.rs new file mode 100644 index 00000000..85303f1e --- /dev/null +++ b/crates/bake/src/tracing/ray.rs @@ -0,0 +1,11 @@ +use texturecraft_geom::glam::Vec3; + +/// GPU buffer layout; batches upload without repacking +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Ray { + pub origin: Vec3, + pub max_distance: f32, + pub direction: Vec3, + pub key: u32, +} diff --git a/crates/bake/src/tracing/ray_kind.rs b/crates/bake/src/tracing/ray_kind.rs new file mode 100644 index 00000000..1ce6eed9 --- /dev/null +++ b/crates/bake/src/tracing/ray_kind.rs @@ -0,0 +1,5 @@ +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RayKind { + Occlusion, + Thickness, +} diff --git a/crates/bake/src/tracing/ray_scene.rs b/crates/bake/src/tracing/ray_scene.rs new file mode 100644 index 00000000..9a800452 --- /dev/null +++ b/crates/bake/src/tracing/ray_scene.rs @@ -0,0 +1,8 @@ +use super::{Hemisphere, Query, Ray}; +use crate::BakeError; +use texturecraft_geom::Hit; + +pub trait RayScene: Send { + fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError>; + fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError>; +} diff --git a/crates/bake/src/tracing/trace_mesh.rs b/crates/bake/src/tracing/trace_mesh.rs new file mode 100644 index 00000000..f4db3b14 --- /dev/null +++ b/crates/bake/src/tracing/trace_mesh.rs @@ -0,0 +1,23 @@ +use super::ANY; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh}; + +#[derive(Clone, Copy, Debug)] +pub struct TraceMesh<'a> { + pub mesh: &'a Mesh, + pub bvh: &'a Bvh, + /// Part key per triangle in original mesh order + pub keys: &'a [u32], + pub backface_culling: &'a [bool], +} + +impl TraceMesh<'_> { + pub(super) fn key_matches(&self, triangle: u32, key: u32) -> bool { + key == ANY || self.keys.get(triangle as usize) == Some(&key) + } + + pub(super) fn back_facing(&self, triangle: u32, direction: Vec3) -> bool { + let position = |vertex_index: usize| self.mesh.positions.get(vertex_index).copied().unwrap_or(Vec3::ZERO); + self.mesh.tri(triangle as usize).is_some_and(|[a, b, c]| (position(b) - position(a)).cross(position(c) - position(a)).dot(direction) > 0.0) + } +} diff --git a/crates/bake/src/tracing/tracer.rs b/crates/bake/src/tracing/tracer.rs new file mode 100644 index 00000000..cda49f13 --- /dev/null +++ b/crates/bake/src/tracing/tracer.rs @@ -0,0 +1,7 @@ +use super::{RayScene, TraceMesh}; +use crate::BakeError; + +pub trait Tracer: Send + Sync { + fn name(&self) -> String; + fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError>; +} 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/below.rs b/crates/compose/src/below.rs index d5345c92..81868e66 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -10,10 +10,12 @@ use std::collections::{BTreeSet, HashMap, VecDeque}; use std::sync::Arc; use texturecraft_core::project::MAX_DEPTH; -use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet}; +use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet}; use texturecraft_texel::TileImage; use crate::eval::{Inputs, PaintTarget}; +use crate::held_fields::HeldFields; +use crate::image_identity::ImageIdentity; use crate::store::{BakedMaps, ImageStore, PixelStore}; /// Default byte budget of a [`BelowCache`], per nesting level it holds (see @@ -40,11 +42,28 @@ pub struct BelowCache { /// Tiles of the whole pass a caller splits into several composites (0: each composite is a /// pass). A pass larger than the cache records only what fits. pub pass: usize, + /// Tiles the caller composites next in this pass, after those of the coming composite (empty: none, or a pass that is one + /// composite). A stack with neighbourhood filters then filters the coming tiles and these at once and keeps the result for + /// the composites that follow, instead of filtering each small chunk's surroundings again. + pub ahead: Vec<(u32, u32)>, + pub(crate) held: Option, } impl Default for BelowCache { fn default() -> Self { - BelowCache { hot: None, key: None, tiles: HashMap::new(), order: VecDeque::new(), clock: 0, bytes: 0, budget: BELOW_BUDGET, levels: 1, pass: 0 } + BelowCache { + hot: None, + key: None, + tiles: HashMap::new(), + order: VecDeque::new(), + clock: 0, + bytes: 0, + budget: BELOW_BUDGET, + levels: 1, + pass: 0, + ahead: Vec::new(), + held: None, + } } } @@ -78,48 +97,83 @@ pub struct StackKey { layers: Vec, pixels: Vec<(LayerId, Option, Shared)>, baked: (u32, Vec<(BakedMap, usize)>), - images: Vec<(String, usize)>, + images: Vec<(String, ImageIdentity)>, } impl StackKey { - /// The key of `roots` (layers of texture set `ts`, bottom → top) and their effects. - pub fn new(project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, ts: usize, roots: &[LayerId]) -> Option { - StackKey::of_tree(project, pixels, baked, images, ts, roots.to_vec(), &project.render_tree(roots)) + /// The key of `roots` (layers of a texture set, bottom → top) and their effects. + pub fn new( + project: &Project, + pixels: &PixelStore, + baked: &BakedMaps, + images: &ImageStore, + texture_set_index: usize, + roots: &[LayerId], + ) -> Option { + StackKey::of_tree(project, pixels, baked, images, texture_set_index, roots.to_vec(), &project.render_tree(roots)) } - /// The key of the layers in `tree` (and their effects), drawn as `roots` arrange them. + /// The key of the layers in `render_tree` (and their effects), drawn as `roots` arrange them. fn of_tree( project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, - ts: usize, + texture_set_index: usize, roots: Vec, - tree: &BTreeSet, + render_tree: &BTreeSet, ) -> Option { - let mut set = project.texture_set(ts).ok()?.clone(); + let mut set = project.texture_set(texture_set_index).ok()?.clone(); set.name.clear(); set.description.clear(); set.stack.clear(); set.bake = Default::default(); - let effects: BTreeSet = tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect(); - let pixels = tree + + let effect_ids: BTreeSet = render_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect(); + let pixel_handles = render_tree .iter() - .chain(&effects) + .chain(&effect_ids) .flat_map(|id| { - let layer = Channel::ALL.into_iter().filter_map(move |c| pixels.layer(*id, c).map(|img| (*id, Some(c), Shared(img.clone())))); - layer.chain(pixels.masks.get(id).map(|img| (*id, None, Shared(img.clone())))) + let layer_channels = + Channel::ALL.into_iter().filter_map(move |channel| pixels.layer(*id, channel).map(|image| (*id, Some(channel), Shared(image.clone())))); + layer_channels.chain(pixels.masks.get(id).map(|image| (*id, None, Shared(image.clone())))) }) .collect(); - let mut images: Vec<(String, usize)> = images.iter().map(|(n, i)| (n.clone(), Arc::as_ptr(i) as usize)).collect(); - images.sort(); + + let mut referenced_images = BTreeSet::new(); + if !images.is_empty() { + let mut record_image_reference = |source: &Source| { + if let Source::Image { name, .. } = source + && let Some((name, _)) = images.get_key_value(name) + { + referenced_images.insert(name); + } + }; + for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) { + if let LayerKind::Fill(fill) = &layer.kind { + fill.sources.values().for_each(&mut record_image_reference); + } + for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + match &effect.kind { + EffectKind::Fill { source, .. } => record_image_reference(source), + EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference), + EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference), + _ => {} + } + } + } + } + + let image_identities = + referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect(); + Some(StackKey { set, roots, - layers: tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(), - pixels, - baked: (baked.resolution, baked.maps.iter().map(|(m, d)| (*m, Arc::as_ptr(d) as usize)).collect()), - images, + layers: render_tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(), + pixels: pixel_handles, + baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()), + images: image_identities, }) } } @@ -137,25 +191,31 @@ impl StackKey { } let size = self.set.size(); let mut changed = BTreeSet::new(); - for ((id_a, ch_a, a), (id_b, ch_b, b)) in self.pixels.iter().zip(&other.pixels) { - let (a, b) = (&a.0, &b.0); - let same_shape = id_a == id_b && ch_a == ch_b && a.width() == b.width() && a.height() == b.height() && a.comps() == b.comps(); - // Image tiles are composite tiles only when the grids coincide. - if !same_shape || (a.width(), a.height()) != size { + for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { + let (left_image, right_image) = (&left_image.0, &right_image.0); + let same_shape = left_id == right_id + && left_channel == right_channel + && left_image.width() == right_image.width() + && left_image.height() == right_image.height() + && left_image.comps() == right_image.comps(); + + // Image tiles are composite tiles only when the grids coincide + if !same_shape || (left_image.width(), left_image.height()) != size { return None; } - if a.same_tiles(b) { + if left_image.same_tiles(right_image) { continue; } - for ty in 0..a.tiles_y() { - for tx in 0..a.tiles_x() { - let equal = match (a.tile_handle(tx, ty), b.tile_handle(tx, ty)) { + + for tile_y in 0..left_image.tiles_y() { + for tile_x in 0..left_image.tiles_x() { + let equal = match (left_image.tile_handle(tile_x, tile_y), right_image.tile_handle(tile_x, tile_y)) { (None, None) => true, - (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (Some(left_tile), Some(right_tile)) => Arc::ptr_eq(left_tile, right_tile), _ => false, }; if !equal { - changed.insert((tx, ty)); + changed.insert((tile_x, tile_y)); } } } @@ -172,17 +232,18 @@ struct Shared(TileImage); impl PartialEq for Shared { fn eq(&self, other: &Self) -> bool { - let (a, b) = (&self.0, &other.0); - a.width() == b.width() - && a.height() == b.height() - && a.comps() == b.comps() - && (0..a.tiles_y()).all(|ty| { - (0..a.tiles_x()).all(|tx| match (a.tile_handle(tx, ty), b.tile_handle(tx, ty)) { - (None, None) => true, - (Some(x), Some(y)) => Arc::ptr_eq(x, y), - _ => false, - }) - }) + let (left_image, right_image) = (&self.0, &other.0); + left_image.width() == right_image.width() + && left_image.height() == right_image.height() + && left_image.comps() == right_image.comps() + && (left_image.same_tiles(right_image) + || (0..left_image.tiles_y()).all(|tile_y| { + (0..left_image.tiles_x()).all(|tile_x| match (left_image.tile_handle(tile_x, tile_y), right_image.tile_handle(tile_x, tile_y)) { + (None, None) => true, + (Some(left_tile), Some(right_tile)) => Arc::ptr_eq(left_tile, right_tile), + _ => false, + }) + })) } } @@ -213,23 +274,30 @@ impl BelowCache { pub fn clear(&mut self) { let tiles = std::mem::take(&mut self.tiles); - // Freeing a full cache (up to the byte budget in small bands) can take most of a - // second: a thread does it so the frame that switched the hot layer doesn't stall. + + // Native builds free cached bands off-thread to avoid a frame stall #[cfg(not(target_arch = "wasm32"))] if !tiles.is_empty() { let _ = std::thread::Builder::new().name("texturecraft-free".into()).spawn(move || drop(tiles)); } #[cfg(target_arch = "wasm32")] drop(tiles); + self.order.clear(); self.bytes = 0; self.key = None; + self.held = None; } pub fn bytes(&self) -> usize { self.bytes } + /// Whether neighbourhood-filter fields are kept for the composites that follow (see [`BelowCache::ahead`]). + pub fn holds_fields(&self) -> bool { + self.held.is_some() + } + /// The byte limit: the budget for the top level and as much again for a hot layer nested in /// folders (each tile then holds the stack at two or more levels). pub fn limit(&self) -> usize { @@ -259,7 +327,7 @@ impl BelowCache { self.clock += 1; *stamp = self.clock; self.order.push_back((t, self.clock)); - // Drop superseded uses once they outnumber the tiles. + // Drop superseded uses once they outnumber the tiles if self.order.len() > 2 * self.tiles.len() + 64 { let tiles = &self.tiles; self.order.retain(|(t, s)| tiles.get(t).is_some_and(|(stamp, _)| stamp == s)); @@ -296,43 +364,53 @@ impl BelowCache { /// live stroke). Empties the cache when what the cached part reads changed. pub(crate) fn prepare(&mut self, inp: &Inputs) -> Option> { let hot = self.hot?; - let p = inp.project; - let set = p.texture_set(inp.ts).ok()?; - // Anchor readers depend on the stack below them. - if p.render_tree(&set.stack).iter().any(|id| p.layers.get(id).is_some_and(Layer::reads_anchor)) { + let project = inp.project; + let set = project.texture_set(inp.ts).ok()?; + + // Anchor readers depend on the stack below them + if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) { return None; } - let levels = path(p, &set.stack, hot)?; - let rest: Vec = levels.iter().flat_map(|l| l.below.iter().chain(&l.above)).copied().collect(); - if rest.is_empty() && levels.len() == 1 { + + let levels = path(project, &set.stack, hot)?; + let off_path_roots: Vec = levels.iter().flat_map(|level| level.below.iter().chain(&level.above)).copied().collect(); + if off_path_roots.is_empty() && levels.len() == 1 { return None; } - let mut tree = p.render_tree(&rest); - // Folders holding the hot layer (and the folders their instances draw) count with their - // own state only, not their children. - for l in levels.iter().take(levels.len() - 1) { - let mut id = Some(l.at); + + let mut cached_tree = project.render_tree(&off_path_roots); + + // Cache containing folders by state, without their children + for level in levels.iter().take(levels.len() - 1) { + let mut id = Some(level.at); for _ in 0..=MAX_DEPTH { - let Some(i) = id.filter(|i| tree.insert(*i)) else { break }; - id = p.layers.get(&i).and_then(Layer::instance_source); + let Some(instance_id) = id.filter(|instance_id| cached_tree.insert(*instance_id)) else { break }; + id = project.layers.get(&instance_id).and_then(Layer::instance_source); } } - if tree.contains(&hot) { + + // Repeated hot instances cannot share the off-path cache + if cached_tree.contains(&hot) { return None; } - if let Some(pv) = inp.preview { - let (PaintTarget::Layer(t) | PaintTarget::Mask(t)) = pv.target; - if tree.contains(&t) || tree.iter().filter_map(|id| p.layers.get(id)).flat_map(effect_ids).any(|e| e == t) { + + if let Some(preview) = inp.preview { + let (PaintTarget::Layer(target) | PaintTarget::Mask(target)) = preview.target; + if cached_tree.contains(&target) + || cached_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).any(|effect_id| effect_id == target) + { return None; } } - let roots = set.stack.iter().chain(levels.iter().map(|l| &l.at)).copied().collect(); - let key = StackKey::of_tree(p, inp.pixels, inp.baked, inp.images, inp.ts, roots, &tree)?; + + let roots = set.stack.iter().chain(levels.iter().map(|level| &level.at)).copied().collect(); + let key = StackKey::of_tree(project, inp.pixels, inp.baked, inp.images, inp.ts, roots, &cached_tree)?; self.levels = levels.len(); if self.key.as_ref() != Some(&key) { self.clear(); self.key = Some(key); } + Some(levels) } } 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..0b7138bc --- /dev/null +++ b/crates/compose/src/curvature_sizes.rs @@ -0,0 +1,476 @@ +//! 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 + }; + + // Keep layout variants so thumbnails and the viewport reuse their own levels + cache.retain(|entry| entry.0.strong_count() > 0 && !is_entry_for(entry, curvature, key, scales)); + 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 _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + 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)); + } + } + } + + // Cache lifecycle tests must not evict each other's entries in parallel + static CACHE_TESTS: Mutex<()> = Mutex::new(()); + + #[test] + fn alternating_layouts_reuse_their_cached_sizes() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let viewport_key = ((4, 4), (4, 4), (4, 4)); + let thumbnail_key = ((4, 4), (4, 4), (2, 2)); + let viewport = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() }); + let thumbnail = store(&curvature, thumbnail_key, &scales, CurvatureSizes { levels: Vec::new() }); + + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "a thumbnail must not evict the viewport layout"); + assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "both layouts stay reusable"); + let mut set = texturecraft_core::TextureSet::new("Tiles", 0, 4); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 2); + let scaled = set.block_scales(); + assert_ne!(scaled, scales); + assert!(cached(&curvature, viewport_key, &scaled).is_none(), "different tile scales cannot read the unscaled result"); + let scaled_sizes = store(&curvature, viewport_key, &scaled, CurvatureSizes { levels: Vec::new() }); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scaled).unwrap(), &scaled_sizes)); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "scale variants also coexist"); + let replacement = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() }); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &replacement)); + assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "updating one layout keeps the other"); + } + + #[test] + fn layout_variants_obey_the_entry_limit() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let key = |size| ((4, 4), (4, 4), (size, size)); + for size in 1..=CACHE_MAPS as u32 + 1 { + store(&curvature, key(size), &scales, CurvatureSizes { levels: Vec::new() }); + } + assert!(cached(&curvature, key(1), &scales).is_none(), "layout variants cannot grow without bound"); + assert!(cached(&curvature, key(CACHE_MAPS as u32 + 1), &scales).is_some(), "the newest layout 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 56a4d4e1..5ebb667b 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -93,20 +93,21 @@ fn u8_of(v: u16) -> u8 { (v >> 8) as u8 } -/// Tile bytes (`TILE × TILE`, row-major) for `kind` from the composite, or None when the tile is -/// absent in every source (the GPU texture keeps its cleared default). -pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { - let bpt = kind.bytes_per_texel(); - let mut out = vec![0u8; TILE_AREA * bpt]; - let lut = srgb_lut(); - let get = |c: Channel| comp.channels.get(&c).and_then(|img| img.tile(tx, ty)); - let res = comp.resolution; +/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles. +pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { + let bytes_per_texel = kind.bytes_per_texel(); + let mut out = vec![0u8; TILE_AREA * bytes_per_texel]; + let srgb = srgb_lut(); + let get = |c: Channel| composite.channels.get(&c).and_then(|img| img.tile(tx, ty)); + let resolution = composite.resolution; let default16 = |c: Channel| texturecraft_texel::to_u16(c.default_value()[0]); - // A scalar channel's texel `i` as 8 bits (its default where the set lacks it). + + // A scalar channel's texel `i` as 8 bits (its default where the set lacks it) let scalar8 = |c: Channel| { let (t, d) = (get(c), default16(c)); move |i: usize| u8_of(t.and_then(|t| t.get(i).copied()).unwrap_or(d)) }; + match kind { DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => { let (c, alpha) = match kind { @@ -117,81 +118,87 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (src, alpha) = (get(c), scalar8(alpha)); let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8); for i in 0..TILE_AREA { - let px = &mut out[i * 4..i * 4 + 4]; + let pixel = &mut out[i * 4..i * 4 + 4]; match src { Some(s) => { for k in 0..3 { - px[k] = lut[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; + pixel[k] = srgb[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; } } - None => px[..3].copy_from_slice(&d), + None => pixel[..3].copy_from_slice(&d), } - px[3] = alpha(i); + pixel[3] = alpha(i); } } DisplayKind::Lobes => { let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8); - for (i, px) in out.chunks_exact_mut(4).enumerate() { - for (d, lane) in px.iter_mut().zip(&lanes) { + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (d, lane) in pixel.iter_mut().zip(&lanes) { *d = lane(i); } } } DisplayKind::Extra => { let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission)); - // Signed 8-bit around 128 so the flat normal packs exactly. - let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; - // A TILE never straddles two atlas blocks. - let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; - for (i, px) in out.chunks_exact_mut(4).enumerate() { - for (k, d) in px.iter_mut().take(2).enumerate() { - *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v)); + + // Signed 8-bit around 128 so the flat normal packs exactly + let pack_signed_normal = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; + + // A TILE never straddles two atlas blocks + let scale = (-32.0 * composite.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (k, d) in pixel.iter_mut().take(2).enumerate() { + *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| pack_signed_normal(*v)); } - px[2] = transmission(i); - px[3] = scale; + pixel[2] = transmission(i); + pixel[3] = scale; } } DisplayKind::Orm => { let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel)); - // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness. - let gloss = comp.channels.contains_key(&Channel::Glossiness); + + // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness + let gloss = composite.channels.contains_key(&Channel::Glossiness); let (r, r_default) = 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).unwrap_or(1.0); + let baked_ao = baked + .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.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; + let pixel = &mut out[i * 4..i * 4 + 4]; + pixel[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default); - px[1] = u8_of(if gloss { 65535 - v } else { v }); - px[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); - px[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); + pixel[1] = u8_of(if gloss { 65535 - v } else { v }); + pixel[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); + pixel[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); } } DisplayKind::Normal => { - let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); + let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); for i in 0..TILE_AREA { - 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 pixel = &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); + let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales); match (n, base) { (Some(t), None) => { - for (k, d) in px.iter_mut().take(3).enumerate() { + for (k, d) in pixel.iter_mut().take(3).enumerate() { *d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0)); } } (detail, Some(base)) => { let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); let v = texturecraft_core::blend::rnm(base, detail); - for (d, v) in px.iter_mut().zip(v) { + for (d, v) in pixel.iter_mut().zip(v) { *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } } - (None, None) => px[..3].copy_from_slice(&[128, 128, 255]), + (None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]), } - px[3] = sheen_rough(i); + pixel[3] = sheen_roughness(i); } } DisplayKind::Height => { @@ -206,6 +213,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 } } } + out } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index d98b1fe6..1e077cbe 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,19 +2,25 @@ //! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport //! and for export. +pub(crate) mod thumbnail; + 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::below::{Band, BelowCache, Level, StackKey}; +use crate::curvature_sizes::CurvatureSizes; +use crate::held_fields::HeldFields; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -93,6 +99,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 +210,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,48 +274,67 @@ 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() } -/// Whether any effect (mask or content) of a layer drawn in texture set `ts` reads texels -/// around each texel (blur, sharpen, warp, edge, bevel, glow, mosaic, slope blur). Conservative: -/// hidden layers and disabled masks count too. -pub fn stack_reads_neighbours(project: &Project, ts: usize) -> bool { - let Some(set) = project.texture_sets.get(ts) else { return false }; - project - .render_tree(&set.stack) - .iter() - .filter_map(|id| project.layers.get(id)) - .any(|l| neighbourhood(&l.content_effects, 2048).is_some() || l.mask.as_ref().is_some_and(|m| neighbourhood(&m.effects, 2048).is_some())) +/// Below this a coverage weight counts as no coverage at all. +const MIN_COVERAGE_WEIGHT: f32 = 1e-6; +/// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. +const FILTER_SIZE_RESOLUTION: f32 = 2048.0; +/// The smallest radius a filter runs at, in texels. +const MIN_FILTER_RADIUS: f32 = 0.5; +/// Sharpen's blur radius at [`FILTER_SIZE_RESOLUTION`], and the smallest it runs at, in texels. +const SHARPEN_RADIUS: f32 = 1.5; +const MIN_SHARPEN_RADIUS: f32 = 0.75; + +/// 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 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); + 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, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), 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)), + // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them + EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { + Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + } + EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { + Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) + } + _ => None, + }) +} + +/// Whether any mask or content effect in a texture set reads neighbouring texels. Includes +/// filters, blurred generators and reduced-resolution generators. Hidden layers and disabled +/// masks count too, so partial invalidation remains conservative. +pub fn stack_reads_neighbours(project: &Project, texture_set_index: usize) -> bool { + const NEIGHBOUR_PROBE_RESOLUTION: u32 = 2048; + + let Some(set) = project.texture_sets.get(texture_set_index) else { + return false; + }; + + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + neighbourhood(&layer.content_effects, NEIGHBOUR_PROBE_RESOLUTION).is_some() + || layer.mask.as_ref().is_some_and(|mask| neighbourhood(&mask.effects, NEIGHBOUR_PROBE_RESOLUTION).is_some()) + }) } /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn @@ -316,6 +344,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; @@ -433,27 +467,45 @@ 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); +/// Texels one parallel task of a neighbourhood filter handles at least. Compositing in frame slices filters regions of a few tiles: split per texel, +/// handing that little work to every thread costs far more than the work itself. Each texel is computed on its own, so the split does not change results. +const MIN_PARALLEL_TEXELS: usize = 1 << 14; + +/// How many lines of `length` texels make a parallel task of at least [`MIN_PARALLEL_TEXELS`]. +fn lines_per_task(length: usize) -> usize { + (MIN_PARALLEL_TEXELS / length.max(1)).max(1) } +/// 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) { + // Bound samples before fixed-point accumulation + const MAX_INPUT_MAGNITUDE: f32 = 1e6; + + let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-MAX_INPUT_MAGNITUDE, MAX_INPUT_MAGNITUDE)) * FIX).round() as i64 } else { 0 }; + let mut fixed: Vec = data.par_iter().with_min_len(MIN_PARALLEL_TEXELS).map(to_fixed).collect(); + blur_rows(&mut fixed, width, radius); + + let mut columns = transpose(&fixed, width, height); + blur_rows(&mut columns, height, radius); + transpose_into(&columns, height, width, &mut fixed); + + data.par_iter_mut().with_min_len(MIN_PARALLEL_TEXELS).zip(fixed).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 { return; } - data.par_chunks_mut(w).for_each(|row| { - let mut tmp = vec![0i64; row.len()]; - for _ in 0..3 { - box_line(row, &mut tmp, r); - row.copy_from_slice(&tmp); + + data.par_chunks_mut(w).with_min_len(lines_per_task(w)).for_each(|row| { + let mut scratch = vec![0i64; row.len()]; + for _ in 0..BLUR_BOX_PASSES { + box_line(row, &mut scratch, r); + row.copy_from_slice(&scratch); } }); } @@ -461,7 +513,8 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { /// One box blur of radius `r` of a line (texels past the ends count as 0). fn box_line(src: &[i64], dst: &mut [i64], r: usize) { let n = (2 * r + 1) as i64; - // Rounded division of a window sum. + + // Rounded division of a window sum let avg = |acc: i64| (2 * acc + n).div_euclid(2 * n); let mut acc: i64 = src.iter().take(r + 1).sum(); for (i, d) in dst.iter_mut().enumerate() { @@ -476,14 +529,18 @@ fn box_line(src: &[i64], dst: &mut [i64], r: usize) { /// `src` (`w × h`, row-major) transposed to `h × w`. fn transpose(src: &[i64], w: usize, h: usize) -> Vec { let mut out = vec![0i64; src.len()]; + transpose_into(src, w, h, &mut out); + out +} + +fn transpose_into(src: &[i64], w: usize, h: usize, out: &mut [i64]) { if h > 0 { - out.par_chunks_mut(h).enumerate().for_each(|(x, col)| { + out.par_chunks_mut(h).with_min_len(lines_per_task(h)).enumerate().for_each(|(x, col)| { for (y, d) in col.iter_mut().enumerate() { *d = src.get(y * w + x).copied().unwrap_or(0); } }); } - out } /// Covered texels of tile (tx, ty): (x, y, offset inside the tile). @@ -540,164 +597,358 @@ 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 comps = match job { + + 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( + inputs: &Inputs, + channels: &[Channel], + below: &Fields, + id: LayerId, + job: Job, + effects: &[Effect], + (index, radius, op): (usize, f32, Op), + (region_x, region_y, width, height): (u32, u32, u32, u32), + start: Option<(usize, &Field)>, +) -> Option { + let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); + let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); + + // Generator stages keep their ramp beside the mask stack below + let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) { + (Job::Mask(_), Some((EffectKind::Generator(generator), blend))) => Some((generator, blend)), + _ => None, + }; + let components = match job { + Job::Mask(_) if generator.is_some() => 2, Job::Mask(_) => 1, Job::Content(_) => 4, }; - // Evaluate the stack before the filter, tile by tile (content premultiplied by coverage). - 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(); + + // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) + let (region_right, region_bottom) = (region_x + width, region_y + height); + let region_tiles: Vec<(u32, u32)> = + (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.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)); + .map(|&(tile_x, tile_y)| { + let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below)); + let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); let mut mask = None; let mut nodes = Vec::new(); + let mut generator_sizes = None; 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(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() }; + + generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); + 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(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below)); + if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { + channel_plan.effects.truncate(index); + channel_plan.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)); - if !full.is_empty() { - tex.anchors_below(&full, id); + tile_texels(inputs.gbuf, tile_x, tile_y) + .map(|(x, y, offset)| { + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + texel.anchors_below(&anchor_nodes, 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), _) => { + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); + [texel.mask(mask_stack), ramp, 0.0, 0.0] + } + (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { + Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], 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]; - 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]); + + // Scatter into the region, a row of tiles at a time (the region is tile aligned) + let texel_count = (width * height) as usize; + let mut stack_values = vec![0.0f32; texel_count * components]; + let mut cover = vec![0.0f32; texel_count]; + let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize; + let band = (TILE * width) as usize; + stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| { + for &(x, y, value) in row.iter().flatten() { + let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; + if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) { + *covered = 1.0; + pixel.copy_from_slice(&value[..components]); } } }); - // 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, + + // Release tile scatter data before allocating filter buffers + drop(parts); + + // High pass centers on the channel's middle value (0 for signed channels like height) + let middle = match job { + 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 tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1); + if let Some((generator, blend)) = generator { + let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution); + return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); } - // Weighted so uncovered texels don't bleed in. - let (wu, hu, ru) = (w as usize, h as usize, r as usize); + let scaled_radius = neighbourhood_filters(effects, tile_resolution) + .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, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity); + } + + // Weighted so uncovered texels don't bleed in + let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize); let mut weights = cover.clone(); - blur(&mut weights, wu, hu, ru); - 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) + blur(&mut weights, columns, rows, blur_radius); + let mut filtered_values = stack_values.clone(); + for component in 0..components { + let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); + blur(&mut sums, columns, rows, blur_radius); + filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { + // Content is premultiplied, so the middle value is too (coverage itself is kept) + let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *weight > MIN_COVERAGE_WEIGHT + && 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 + middle * coverage, + // 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 + filtered_values }; - // 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(); + + // Each block keeps the result at its tile's scale (blocks are TILE aligned) + let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default(); + let mut levels: Vec = (region_y..region_bottom) + .step_by(TILE as usize) + .flat_map(|y| (region_x..region_right).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 mut data = filtered(first); + let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest)); + + // A generator stage's field is the mask alone + let field_components = if generator.is_some() { 1 } else { components }; + let mut result = 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() { - if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { - d.copy_from_slice(s); + let rescaled = filtered(scale); + let row = width as usize * field_components; + result.par_chunks_mut(row).zip(rescaled.par_chunks(row)).enumerate().for_each(|(y, (target_row, source_row))| { + for (x, (target, source)) in target_row.chunks_mut(field_components).zip(source_row.chunks(field_components)).enumerate() { + if scales.at(region_x + x as u32, region_y + y as u32) == scale { + target.copy_from_slice(source); } } }); } - unpremultiply(&mut data, comps); - Some(Field { x0: rx0, y0: ry0, w, h, comps, data }) + + unpremultiply(&mut result, field_components); + Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result }) +} + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +fn generator_region( + generator: &Generator, + blend: BlendMode, + opacity: f32, + stack: &[f32], + cover: &[f32], + (region_x, region_y, width, height): (u32, u32, u32, u32), + (uv_tile, texture_set): (u32, u32), +) -> Vec { + let (columns, rows) = (width as usize, height as usize); + let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + + // Coarser than the UV tile: averaged over cells, then the blur around them + let cell = generator.resolution.cell(uv_tile, texture_set) as usize; + if cell > 1 { + ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); + } + + let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; + if blur_radius > 0 { + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, blur_radius); + let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); + blur(&mut sums, columns, rows, blur_radius); + ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { + if *weight > MIN_COVERAGE_WEIGHT { + *ramp = sum / weight; + } + }); + } + + // Finished and blended over the stack below, like the generator effect itself + stack + .par_chunks(2) + .zip(ramps.par_iter()) + .map(|(texel, ramp)| { + let below = texel.first().copied().unwrap_or(0.0); + let generated = finish_generator(generator, *ramp); + below + (blend1(blend, below, generated) - below) * opacity + }) + .collect() +} + +/// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. +fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { + // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region + let (first_column, first_row) = (region_x / cell, region_y / cell); + let columns = (region_x + width).div_ceil(cell) - first_column; + let rows = (region_y + height).div_ceil(cell) - first_row; + + // Each cell's coverage-weighted average, a row of cells at a time + let averages: Vec> = (0..rows) + .into_par_iter() + .flat_map_iter(|row| { + let mut sums = vec![(0.0f32, 0.0f32); columns]; + let first_y = ((first_row + row) * cell).saturating_sub(region_y); + let last_y = ((first_row + row + 1) * cell).saturating_sub(region_y).min(height); + for y in first_y..last_y { + for x in 0..width { + let texel = y * width + x; + let covered = cover.get(texel).copied().unwrap_or(0.0); + if let Some((sum, weight)) = sums.get_mut((region_x + x) / cell - first_column) { + *sum += values.get(texel).copied().unwrap_or(0.0) * covered; + *weight += covered; + } + } + } + sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight)) + }) + .collect(); + let average = |column: isize, row: isize| -> Option { + let column = column.clamp(0, columns as isize - 1) as usize; + let row = row.clamp(0, rows as isize - 1) as usize; + averages.get(row * columns + column).copied().flatten() + }; + + let cell_size = cell as f32; + (0..height) + .into_par_iter() + .flat_map_iter(|y| (0..width).map(move |x| (x, y))) + .map(|(x, y)| { + // Position in cells, relative to the first cell's center + let cell_x = ((region_x + x) as f32 + 0.5) / cell_size - 0.5 - first_column as f32; + let cell_y = ((region_y + y) as f32 + 0.5) / cell_size - 0.5 - first_row as f32; + let (left, top) = (cell_x.floor(), cell_y.floor()); + let (offset_x, offset_y) = (cell_x - left, cell_y - top); + let (left, top) = (left as isize, top as isize); + let corners = [ + (left, top, (1.0 - offset_x) * (1.0 - offset_y)), + (left + 1, top, offset_x * (1.0 - offset_y)), + (left, top + 1, (1.0 - offset_x) * offset_y), + (left + 1, top + 1, offset_x * offset_y), + ]; + let (sum, weight) = corners.iter().fold((0.0, 0.0), |(sum, weight), &(column, row, corner_weight)| match average(column, row) { + Some(value) => (sum + value * corner_weight, weight + corner_weight), + None => (sum, weight), + }); + if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } + }) + .collect() +} + +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset. +fn finish_generator(generator: &Generator, ramp: f32) -> f32 { + let value = generator.global.apply(ramp); + let value = if generator.invert { 1.0 - value } else { value }; + let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; + (value + offset).clamp(0.0, 1.0) } /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. fn unpremultiply(data: &mut [f32], comps: usize) { - data.par_chunks_mut(comps).for_each(|px| match px { + // Avoid amplifying rounding error near transparent texels + const MIN_COVERAGE: f32 = 1e-5; + + data.par_chunks_mut(comps).with_min_len(MIN_PARALLEL_TEXELS).for_each(|px| match px { [v] => *v = v.clamp(0.0, 1.0), [r, g, b, cov] => { *cov = cov.clamp(0.0, 1.0); - let inv = if *cov > 1e-5 { 1.0 / *cov } else { 0.0 }; + let inv = if *cov > MIN_COVERAGE { 1.0 / *cov } else { 0.0 }; *r *= inv; *g *= inv; *b *= inv; @@ -720,28 +971,55 @@ 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>, @@ -759,21 +1037,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() @@ -1055,7 +1338,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.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 @@ -1085,131 +1372,202 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } - fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] { - match s { - Source::Uniform(v) => *v, + /// The value `source` gives this texel through `projection`, read as a channel of `kind` + fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + match source { + Source::Uniform(value) => *value, Source::Procedural { pattern, low, high } => { - let (c, proj, _) = self.projected(proj); - let t = procedural(pattern, proj, &c); - mix3(*low, *high, t) + let (coords, projection, _) = self.projected(projection); + let amount = procedural(pattern, projection, &coords); + mix3(*low, *high, amount) } Source::Image { name, normal_format } => { - let Some(img) = self.inp.images.get(name) else { return [0.5; 3] }; - let (c, proj, _) = self.projected(proj); - let mut acc = [0.0f32; 4]; - for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) { - let s = img.sample(uv.x, uv.y); - for k in 0..4 { - acc[k] += s[k] * w; + let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; + + let (coords, projection, _) = self.projected(projection); + let mut sum = [0.0f32; 4]; + for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { + for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + *total += value * weight; } } + + let rgb = [sum[0], sum[1], sum[2]]; match kind { - ChannelKind::Color if img.srgb => [acc[0], acc[1], acc[2]].map(texturecraft_texel::srgb_to_linear), - // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips. - ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [acc[0], 1.0 - acc[1], acc[2]], - ChannelKind::Color | ChannelKind::NormalMap => [acc[0], acc[1], acc[2]], - ChannelKind::Scalar => [acc[0]; 3], - ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3], + ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips + ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], + ChannelKind::Color | ChannelKind::NormalMap => rgb, + // A one-value channel or mask reads the image's gray, so a color image works as a mask + ChannelKind::Scalar => [lum(rgb); 3], + ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], } } Source::Anchor { anchor, channel } => { - // An anchor not evaluated yet (above this layer, hidden) reads the channel default. - let v = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, acc)| acc.get(channel.index()).copied()); - let v = v.unwrap_or_else(|| channel.default_value()); + // An anchor not evaluated yet (above this layer, hidden) reads the channel default + let anchored = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, values)| values.get(channel.index()).copied()); + let value = anchored.unwrap_or_else(|| channel.default_value()); let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); - if gray { [lum(v); 3] } else { v } + if gray { [lum(value); 3] } else { value } } } } - 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, + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert. + fn generator_ramp(&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)) => { + // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let curvature = self.generator_input(generator, BakedMap::Curvature); + self.curvature_detail(detail, sizes, curvature) + } + (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, 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(Generator::MIN_SOFTNESS); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + ramp * ramp * (3.0 - 2.0 * ramp) } - 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 generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let ramp = self.generator_ramp(generator, curvature_sizes); + finish_generator(generator, ramp) + } + + /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). + fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]), + None => self.baked(map), } - for e in m.effects.iter().skip(skip) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + } + + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> 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) = 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)); + } + + 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); - 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` @@ -1523,7 +1881,7 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) } /// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory). -const BLOCK: u32 = 16; +pub const BLOCK: u32 = 16; /// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and /// filling it). Results are identical to [`composite_tiles`]. @@ -1532,9 +1890,10 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { return; } + let split = below.as_deref_mut().and_then(|b| b.prepare(inp)); - // A pass over more tiles than the cache holds records only what fits: recording the rest - // would just evict it again. Tiles hold the stack per level plus a tape of varying size. + + // Avoid caching tiles that would immediately evict each other let levels = split.as_ref().map_or(1, Vec::len); let estimate = TILE_AREA * levels * set.channel_list().iter().map(|c| c.components()).sum::() * std::mem::size_of::(); let tile_bytes = below.as_deref().and_then(BelowCache::tile_bytes).unwrap_or(estimate).max(1); @@ -1543,14 +1902,66 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, for t in tiles { blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); } - for block in blocks.values() { + + let channels = set.channel_list(); + let hot = split.as_deref().and_then(<[Level]>::last); + + // A stroke preview is absent from StackKey, so it disables field retention + let retain_fields = below.is_some() && inp.preview.is_none() && has_neighbourhood(inp, &set.stack); + let key = if retain_fields { StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new) } else { None }; + let size = (inp.gbuf.width, inp.gbuf.height); + + // Release fields when a stroke or stack change disables retention + if key.is_none() + && let Some(cache) = below.as_deref_mut() + { + cache.held = None; + } + + for (block_index, block) in &blocks { + let uncached = |tile: &(u32, u32)| below.as_deref().zip(split.as_deref()).is_none_or(|(cache, _)| cache.tile(*tile).is_none()); + let fresh: Vec<(u32, u32)> = block.iter().copied().filter(uncached).collect(); + let held = below.as_deref().and_then(|cache| cache.held.as_ref()).filter(|held| { + key.as_ref().is_some_and(|key| **key == *held.key) + && held.size == size + && fresh.iter().all(|tile| held.stack_tiles.contains(tile)) + && block.iter().all(|tile| held.hot_tiles.contains(tile)) + }); + let ahead: Vec<(u32, u32)> = match (&key, below.as_deref()) { + (Some(_), Some(cache)) if held.is_none() => { + cache.ahead.iter().copied().filter(|tile| (tile.1 / BLOCK, tile.0 / BLOCK) == *block_index && !block.contains(tile)).collect() + } + _ => Vec::new(), + }; + let fields: Arc = match (held, &key) { + (Some(held), _) => held.fields.clone(), + (None, Some(key)) if !ahead.is_empty() => { + // Filter the current and following tiles as one run + let planned_tiles: Vec<(u32, u32)> = block.iter().chain(&ahead).copied().collect(); + let uncached_planned_tiles: Vec<(u32, u32)> = planned_tiles.iter().copied().filter(uncached).collect(); + let fields = Arc::new(block_fields(inp, &channels, &set.stack, hot, &uncached_planned_tiles, &planned_tiles)); + let hot_tiles: std::collections::BTreeSet<(u32, u32)> = planned_tiles.iter().copied().collect(); + let stack_tiles = if hot.is_some() && uncached_planned_tiles.len() < planned_tiles.len() { + uncached_planned_tiles.into_iter().collect() + } else { + hot_tiles.clone() + }; + if let Some(cache) = below.as_deref_mut() { + cache.held = Some(HeldFields { key: key.clone(), size, stack_tiles, hot_tiles, fields: fields.clone() }); + } + fields + } + _ => Arc::new(block_fields(inp, &channels, &set.stack, hot, &fresh, block)), + }; + let quota = match below.as_deref() { Some(_) if fits => usize::MAX, Some(b) => b.limit().saturating_sub(b.bytes()) / tile_bytes, None => 0, }; + let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota); + let records = composite_block(inp, &set.stack, out, block, cached, quota, &fields); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -1560,6 +1971,35 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, } } } + + // Release fields at the end of the pass + if let Some(cache) = below.filter(|cache| cache.ahead.is_empty()) { + cache.held = None; + } +} + +/// Whether a layer drawn by `stack` has a neighbourhood filter in its mask or content effects. +fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { + let working_width = inp.gbuf.width; + let mut order = Vec::new(); + draw_order(inp.project, stack, 0, &mut order); + order.into_iter().any(|id| { + let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); + masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some()) + }) +} + +/// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`), +/// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`. +fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { + match hot { + Some(hot) if fresh.len() < tiles.len() => { + let mut fields = fields_of(inp, channels, stack, fresh); + fields.extend(fields_of(inp, channels, &[hot.at], tiles)); + fields + } + _ => fields_of(inp, channels, stack, tiles), + } } /// Rows of a tile composited as one parallel task. @@ -1581,6 +2021,7 @@ fn composite_block( tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, quota: usize, + fields: &Fields, ) -> Vec<((u32, u32), Vec)> { let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); let (w, h) = (out.resolution, out.height); @@ -1588,20 +2029,12 @@ fn composite_block( let cached = |t: (u32, u32)| below.and_then(|(b, _)| b.tile(t)); let fresh: Vec<(u32, u32)> = tiles.iter().copied().filter(|t| cached(*t).is_none()).collect(); let recorded: std::collections::BTreeSet<(u32, u32)> = if split.is_some() { fresh.iter().copied().take(quota).collect() } else { Default::default() }; - // Off the path, layers are only evaluated on tiles the cache lacks. - let fields = match split.and_then(<[Level]>::last) { - Some(hot) if fresh.len() < tiles.len() => { - let mut fields = fields_of(inp, &channels, stack, &fresh); - fields.extend(fields_of(inp, &channels, &[hot.at], tiles)); - fields - } - _ => fields_of(inp, &channels, stack, tiles), - }; let lanes: Vec = channels.iter().map(|c| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed }).collect(); let stride: usize = lanes.iter().map(|l| l.n).sum(); - let nlev = split.map_or(0, <[Level]>::len); + let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); - // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy. + + // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy let bands = TILE / BAND; let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect(); let mut results: Vec = tasks @@ -1609,20 +2042,20 @@ fn composite_block( .map(|&((tx, ty), band)| { let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); - let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some())); - let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() }; + let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, fields, warm.is_some())); + let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(fields)) } else { Vec::new() }; let rows = (BAND * TILE) as usize; - let mut accs = vec![defaults; nlev]; - let mut masks = vec![0.0f32; nlev]; + let mut level_values = vec![defaults; level_count]; + let mut masks = vec![0.0f32; level_count]; let mut tape = match warm { Some(b) => Tape::Replay(b, 0), None if record => Tape::Record(Vec::new()), None => Tape::Off, }; - // The levels whose stack the band stores (its header): a level with nothing drawn - // before the path layer repeats the level above it. + + // Empty lower stacks reuse the enclosing level instead of storing a duplicate let stored: Vec = match (&levels, warm) { - (Some(_), Some(_)) => tape.take(nlev).iter().map(|v| *v > 0.0).collect(), + (Some(_), Some(_)) => tape.take(level_count).iter().map(|v| *v > 0.0).collect(), (Some(levels), None) => levels.iter().map(|l| !l.below.is_empty()).collect(), (None, _) => Vec::new(), }; @@ -1631,7 +2064,7 @@ fn composite_block( } let slots = stored.iter().filter(|s| **s).count() * stride; let preview_tile = inp.preview.and_then(|p| p.alpha.tile(tx, ty)); - let mut bufs: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); + let mut channel_buffers: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); let mut anchors = Vec::new(); let mut any = false; for ly in band * BAND..(band + 1) * BAND { @@ -1644,20 +2077,20 @@ fn composite_block( if x >= w { break; } - let gi = (y * w + x) as usize; - // Offset in the tile, and in this band. - let o = (ly * TILE + lx) as usize; - let ob = ((ly - band * BAND) * TILE + lx) as usize; - let covered = inp.gbuf.tri.get(gi).is_some_and(|t| *t != NO_TRI); + let gbuffer_index = (y * w + x) as usize; + let tile_offset = (ly * TILE + lx) as usize; + let band_offset = ((ly - band * BAND) * TILE + lx) as usize; + let covered = inp.gbuf.tri.get(gbuffer_index).is_some_and(|t| *t != NO_TRI); let mut acc = defaults; if covered { any = true; - let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); - // Reuse one anchor buffer per band. - tex.anchors = std::mem::take(&mut anchors); + let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset)); + + // Reuse one anchor buffer per band + texel.anchors = std::mem::take(&mut anchors); match &levels { Some(levels) => { - // The texel's stream starts with the stack at each level. + // The texel's stream starts with the stack at each level let start = match &mut tape { Tape::Record(t) => { t.resize(t.len() + slots, 0.0); @@ -1666,38 +2099,39 @@ fn composite_block( _ => 0, }; if warm.is_some() { - load_levels(tape.take(slots), &lanes, stride, &stored, &defaults, &mut accs); + load_levels(tape.take(slots), &lanes, stride, &stored, &defaults, &mut level_values); } - acc = tex.eval_split(defaults, levels, &mut accs, &mut masks, warm.is_some(), &mut tape); + acc = texel.eval_split(defaults, levels, &mut level_values, &mut masks, warm.is_some(), &mut tape); if let Tape::Record(t) = &mut tape && let Some(below) = t.get_mut(start..start + slots) { - store_levels(below, &lanes, stride, &stored, &accs); + store_levels(below, &lanes, stride, &stored, &level_values); } } None => { - tex.eval(&nodes, &mut acc); + texel.eval(&nodes, &mut acc); } } - anchors = tex.anchors; + anchors = texel.anchors; anchors.clear(); } - for (l, buf) in lanes.iter().zip(&mut bufs) { + for (l, buf) in lanes.iter().zip(&mut channel_buffers) { let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); for (k, x) in v.iter().take(l.n).enumerate() { - let enc = if l.signed { to_u16_signed(*x) } else { to_u16(*x) }; - if let Some(slot) = buf.get_mut(ob * l.n + k) { - *slot = enc; + let encoded = if l.signed { to_u16_signed(*x) } else { to_u16(*x) }; + if let Some(slot) = buf.get_mut(band_offset * l.n + k) { + *slot = encoded; } } } } } let cache = if let Tape::Record(t) = tape { Some(t) } else { None }; - (bufs, cache, any) + (channel_buffers, cache, any) }) .collect(); - // Join the bands of each tile (in parallel; uncovered tiles are freed). + + // Join the bands of each tile (in parallel; uncovered tiles are freed) let joined: Vec = results .par_chunks(bands as usize) .map(|parts| { @@ -1723,7 +2157,8 @@ fn composite_block( img.set_tile(tx, ty, d); } } - // Tiles without covered texels cost nothing to composite: not worth caching. + + // Tiles without covered texels cost nothing to composite: not worth caching if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::>>() { records.push(((tx, ty), bands)); } @@ -1847,47 +2282,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). @@ -1925,7 +2436,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 @@ -1991,67 +2502,74 @@ pub type FlatTile = (Channel, (u32, u32), Vec); /// Flatten one paint or fill layer: its content (with content effects) times its mask, as /// premultiplied (value, coverage) tiles per enabled channel, ready to become a plain paint /// layer. Groups are not supported (None). -pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> { - let set = inp.project.texture_set(inp.ts).ok()?; - if inp.project.content_layer(id)?.is_group() { +pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> { + let set = inputs.project.texture_set(inputs.ts).ok()?; + if inputs.project.content_layer(id)?.is_group() { return None; } + let channels: Vec = set.channel_list(); - // Plan the layer forced visible so hidden layers flatten too. - let mut solo = inp.project.clone(); + + // Plan the layer forced visible so hidden layers flatten too + let mut solo = inputs.project.clone(); if let Some(l) = solo.layers.get_mut(&id) { l.visible = true; } - let solo_inp = Inputs { project: &solo, preview: None, ..*inp }; - let fields = neighbourhood_fields(&solo_inp, &channels, tiles); + let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let fields = neighbourhood_fields(&visible_inputs, &channels, tiles); + let out: Vec> = tiles .par_iter() .map(|&(tx, ty)| { - let nodes = plan(&solo_inp, &[id], &channels, tx, ty, 0, Some(&fields)); + let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); let Some(n) = nodes.first() else { return Vec::new() }; - let full = anchor_plan(&solo_inp, id, &channels, tx, ty, Some(&fields)); - let mut bufs: Vec<(Channel, Vec, bool)> = + let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields)); + let mut buffers: Vec<(Channel, Vec, bool)> = n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); - for (ch, buf, _) in &mut bufs { + for (ch, buffer, _) in &mut buffers { if ch.kind() == ChannelKind::Signed { - for px in buf.chunks_exact_mut(2) { - px[0] = to_u16_signed(0.0); + for pixel in buffer.as_chunks_mut::<2>().0 { + pixel[0] = to_u16_signed(0.0); } } } - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(&solo_inp, x, y, o, 0.0); + + for (x, y, o) in tile_texels(inputs.gbuf, tx, ty) { + let mut tex = Texel::new(&visible_inputs, x, y, o, 0.0); if !full.is_empty() { tex.anchors_below(&full, id); } let m = tex.node_mask(n); - for (c, (ch, buf, any)) in n.chans.iter().zip(bufs.iter_mut()) { + for (c, (ch, buffer, any)) in n.chans.iter().zip(buffers.iter_mut()) { let Some((v, cov)) = tex.content(&n.content, c) else { continue }; let a = (cov * m).clamp(0.0, 1.0); if a <= 0.0 { continue; } + *any = true; let comps = c.comps; - let Some(px) = buf.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue }; - for (slot, pv) in px.iter_mut().zip(v.iter().take(comps)) { + let Some(pixel) = buffer.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue }; + for (slot, pv) in pixel.iter_mut().zip(v.iter().take(comps)) { *slot = if ch.kind() == ChannelKind::Signed { to_u16_signed(pv * a) } else { to_u16(pv * a) }; } - if let Some(slot) = px.get_mut(comps) { + if let Some(slot) = pixel.get_mut(comps) { *slot = to_u16(a); } } } - bufs.into_iter().filter(|(_, _, any)| *any).map(|(ch, buf, _)| (ch, (tx, ty), buf)).collect() + + buffers.into_iter().filter(|(_, _, any)| *any).map(|(ch, buffer, _)| (ch, (tx, ty), buffer)).collect() }) .collect(); + Some(out.into_iter().flatten().collect()) } #[cfg(test)] mod tests { use super::*; - use texturecraft_core::{ChannelBlend, Effect, Layer, Procedural, ProceduralKind, TextureSet}; + use texturecraft_core::{ChannelBlend, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; use texturecraft_geom::primitives; struct Fixture { @@ -2079,6 +2597,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(), @@ -2101,6 +2620,53 @@ mod tests { (0..3).all(|i| (a[i] - b[i]).abs() < 2e-4) } + #[test] + fn retained_filter_buffers_release_after_the_last_tile() { + let mut fixture = fixture(); + const RESOLUTION: u32 = 128; + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, RESOLUTION, RESOLUTION); + fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, RESOLUTION); + let layer = fill_layer(&mut fixture.project, [0.4; 3], 0.5); + let mut mask = Mask::new(MaskBackground::White); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 8.0 }))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + + let second_layer = fill_layer(&mut fixture.project, [0.2; 3], 0.7); + let mut second_mask = Mask::new(MaskBackground::White); + second_mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 4.0 }))); + fixture.project.layer_mut(second_layer).unwrap().mask = Some(second_mask); + + let images = ImageStore::default(); + let input = 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 mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RESOLUTION); + let mut cache = BelowCache::default(); + cache.ahead = vec![(1, 0), (0, 1), (1, 1)]; + + composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); + let retained = cache.held.as_ref().expect("filter fields should be retained while tiles follow"); + let field_bytes: usize = retained.fields.values().map(|field| field.data.capacity() * std::mem::size_of::()).sum(); + let field_count = retained.fields.len(); + let weak_fields = Arc::downgrade(&retained.fields); + assert_eq!(field_count, 2); + assert!(field_bytes > 0); + println!("retained fields: {field_count}, buffer capacity: {field_bytes} bytes"); + + cache.ahead.clear(); + composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache)); + assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers"); + } + #[test] fn histogram_samples_spread_over_every_column() { assert_eq!(histogram_tiles(1024, 1024), all_tiles(1024, 1024), "small sets are read whole"); @@ -2187,6 +2753,347 @@ 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"); + } + + /// A 256² set whose curvature map has a one-texel ridge in column `ridge_x` (flat elsewhere), and a white fill layer to mask. + fn ridge_fixture(ridge_x: usize) -> (Fixture, LayerId) { + 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 == ridge_x { 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); + (fixture, layer) + } + + /// `layer`'s mask made of `effects` (bottom first) on black, read along row 128 over `xs`. + fn mask_row(fixture: &mut Fixture, layer: LayerId, effects: Vec, xs: std::ops::Range) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects = effects; + 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, &xs.map(|x| (x, 128)).collect::>()).unwrap() + } + + /// A generator effect of `fixture`'s project. + fn generator_effect(fixture: &mut Fixture, generator: Generator) -> Effect { + Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)) + } + + /// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step). + fn ridge_generator() -> Generator { + Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) } + } + + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let (mut fixture, layer) = ridge_fixture(128); + let mut row_with = |weights: [f32; 7]| { + 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 effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 120..137) + }; + + // The sampled ridge is index 8; five texels to its left is index 3 + let (ridge, five_texels_away) = (8, 3); + let finest = row_with([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with([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 a_replaced_curvature_input_is_read_at_its_own_size_only() { + let (mut fixture, layer) = ridge_fixture(128); + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] }; + let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + generator.inputs.insert(BakedMap::Curvature, Source::Uniform([0.5; 3])); + let effect = generator_effect(&mut fixture, generator); + let row = mask_row(&mut fixture, layer, vec![effect], 120..137); + + // The largest size alone would mark the ridge and texels around it; the flat input marks nothing + assert!(row.iter().all(|value| *value < 0.01), "the detail sizes of the mesh map are not read: {row:?}"); + } + + #[test] + fn generator_blur_softens_only_the_generator_not_the_stack_below() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |blur: f32| { + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }); + let mut generator = ridge_generator(); + generator.global.blur = blur; + let mut lighten = generator_effect(&mut fixture, generator); + lighten.blend = BlendMode::Lighten; + mask_row(&mut fixture, layer, vec![below, lighten], 40..111) + }; + + // The sampled row crosses a checker edge; indices below 30 are outside the blur + let (ridge, five_texels_away, far) = (60, 55, 0..30); + let sharp = row_with(0.0); + let blurred = row_with(1.0); + assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}"); + assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}"); + assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}"); + for texel in far { + assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}"); + } + } + + #[test] + fn a_lower_generator_resolution_spreads_a_ridge_over_its_cell() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |factor: i8| { + let mut generator = ridge_generator(); + generator.resolution.factor = factor; + let effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 80..121) + }; + + // At one eighth resolution, each cell spans eight texels + let (ridge, beside, far) = (20, 18, 0); + let full = row_with(0); + let eighth = row_with(-3); + assert!(full[ridge] > 0.99 && full[beside] < 0.01, "at full resolution the ridge is one texel: {full:?}"); + assert!(eighth[ridge] < 0.5 && eighth[beside] > 0.01, "an eighth of the resolution averages it over its cell: {eighth:?}"); + assert!(eighth[far] < 0.01, "texels a few cells away stay black: {eighth:?}"); + } + + #[test] + fn every_caller_lists_the_same_generator_stages_whatever_resolution_it_passes() { + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 1024, factor: 0 }; + let effects = [Effect::new(LayerId(1), EffectKind::Generator(Generator { resolution: custom, ..Generator::new(GeneratorKind::Dirt) }))]; + + // Tile and whole-set resolutions must select the same generator stage + let at_tile: Vec = neighbourhood_filters(&effects, 1024).map(|stage| stage.0).collect(); + let at_set_width: Vec = neighbourhood_filters(&effects, 2048).map(|stage| stage.0).collect(); + assert_eq!(at_tile, at_set_width); + assert_eq!(at_tile, [0], "a custom resolution can be coarser than some UV tile, so it is a stage"); + } + + #[test] + fn a_generator_input_replaced_by_a_value_is_read_instead_of_the_mesh_map() { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let value_with = |fixture: &mut Fixture, input: Option| -> f32 { + let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) }; + if let Some(value) = input { + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3])); + } + 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); + run(fixture, None).value(Channel::BaseColor, 20, 20)[0] + }; + + // Dark occlusion reveals dirt while the baked white map stays clear + let (baked, black) = (value_with(&mut fixture, None), value_with(&mut fixture, Some(0.0))); + assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}"); + } + + #[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 stack_reads_neighbours_sees_blurs_in_masks_and_content() { let mut f = fixture(); @@ -2461,6 +3368,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(), @@ -2522,6 +3430,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/eval/thumbnail.rs b/crates/compose/src/eval/thumbnail.rs new file mode 100644 index 00000000..92290afe --- /dev/null +++ b/crates/compose/src/eval/thumbnail.rs @@ -0,0 +1,30 @@ +//! Isolated folder evaluation with the original stack available for anchor inputs. + +use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed}; + +/// Composite one layer over channel defaults, keeping anchors from the stack below it. +pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option { + let set = inputs.project.texture_set(inputs.ts).ok()?; + let channels = set.channel_list(); + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let tiles = all_tiles(width, height); + let fields = neighbourhood_fields(inputs, &channels, &tiles); + let mut composite = Composite::with_size(&[channel], width, height); + let output = composite.channels.get_mut(&channel)?; + + for (tile_x, tile_y) in tiles { + let nodes = plan(inputs, &[layer], &channels, tile_x, tile_y, 0, Some(&fields)); + let full_stack = if set.stack.as_slice() == [layer] { Vec::new() } else { plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)) }; + for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) { + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + texel.anchors_below(&full_stack, layer); + let mut values = Channel::ALL.map(Channel::default_value); + texel.eval(&nodes, &mut values); + let value = values.get(channel.index()).copied().unwrap_or_else(|| channel.default_value()); + let encoded = value.map(|component| if channel.kind() == ChannelKind::Signed { to_u16_signed(component) } else { to_u16(component) }); + output.set(x, y, &encoded[..channel.components()]); + } + } + + Some(composite) +} diff --git a/crates/compose/src/held_fields.rs b/crates/compose/src/held_fields.rs new file mode 100644 index 00000000..476b92d4 --- /dev/null +++ b/crates/compose/src/held_fields.rs @@ -0,0 +1,24 @@ +use std::collections::BTreeSet; +use std::sync::Arc; + +use crate::below::StackKey; +use crate::eval::Fields; + +/// Neighbourhood-filter fields kept between the composites of one pass. +pub(crate) struct HeldFields { + /// Everything the fields read. + pub key: Arc, + /// The working size they were built at. + pub size: (u32, u32), + /// The tiles every layer's fields hold. + pub stack_tiles: BTreeSet<(u32, u32)>, + /// The tiles the hot layer's fields hold (the same tiles when the stack was not split). + pub hot_tiles: BTreeSet<(u32, u32)>, + pub fields: Arc, +} + +impl std::fmt::Debug for HeldFields { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HeldFields").field("stack_tiles", &self.stack_tiles.len()).field("hot_tiles", &self.hot_tiles.len()).finish_non_exhaustive() + } +} diff --git a/crates/compose/src/image_identity.rs b/crates/compose/src/image_identity.rs new file mode 100644 index 00000000..28584ba8 --- /dev/null +++ b/crates/compose/src/image_identity.rs @@ -0,0 +1,19 @@ +use std::sync::{Arc, Weak}; + +use crate::store::ImageRes; + +/// Keeps an image's allocation identity stable without retaining pixels after resource removal. +#[derive(Debug)] +pub(crate) struct ImageIdentity(Weak); + +impl ImageIdentity { + pub(crate) fn new(image: &Arc) -> Self { + Self(Arc::downgrade(image)) + } +} + +impl PartialEq for ImageIdentity { + fn eq(&self, other: &Self) -> bool { + self.0.ptr_eq(&other.0) + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b73231c8..a181a337 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -7,16 +7,23 @@ #![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; +mod held_fields; +mod image_identity; pub mod pattern; pub mod store; +pub mod thumb; 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, stack_reads_neighbours, + BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, + flatten_layer, mask_at, mask_image, pad_tiles, stack_reads_neighbours, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; +pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 0924c351..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 -/// maps cover the texture set's texels at another density: `resolution` wide, and as tall as -/// the set's aspect makes them (square for classic sets, the UV tile grid's aspect otherwise). -#[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 map `m` at texel (x, y) of an image `res` wide with the same aspect (nearest texel - /// of the bake). - pub fn sample(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option<[f32; 3]> { - let data = self.maps.get(&m)?; - let r = self.resolution.max(1) as u64; - let (bx, by) = ((x as u64 * r / res.max(1) as u64).min(r - 1), (y as u64 * r / res.max(1) as u64).min(self.height(m).max(1) as u64 - 1)); - let comps = m.components(); - let i = ((by * r + bx) as usize) * comps; - let s = data.get(i..i + comps)?; - Some(if comps == 3 { [s[0], s[1], s[2]] } else { [s[0]; 3] }) - } - - pub fn scalar(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option { - self.sample(m, x, y, res).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/src/thumb.rs b/crates/compose/src/thumb.rs new file mode 100644 index 00000000..b4c59a15 --- /dev/null +++ b/crates/compose/src/thumb.rs @@ -0,0 +1,206 @@ +//! Small previews of one layer's content, one mask, or one effect stage, computed without +//! touching the main composite. +//! +//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: only the +//! requested layer is drawn, forced visible at Normal / 100 %, and +//! the layer's effect list is truncated after the effect being previewed. The evaluator is the +//! same code the viewport uses (just on a small G-buffer), so a thumbnail always agrees with +//! what the stack really computes. Nothing here mutates the caller's project. + +use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; +use texturecraft_texel::{TILE, from_u16, from_u16_signed, linear_to_srgb}; + +use crate::eval::{Composite, FlatTile, Inputs, all_tiles, flatten_layer, mask_image}; + +/// Edge length (texels) the thumbnails are computed at. +pub const THUMB_TEXELS: u32 = 64; + +/// What a thumbnail shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ThumbTarget { + /// The content of a layer (content effects included, mask ignored) in `channel`. + Content { layer: LayerId, channel: Channel }, + /// The mask of a layer (an instance without its own mask shows its source's). + Mask { layer: LayerId }, + /// The result up to and including `effect`, in the layer's content (`channel`) or in its + /// mask (the channel is ignored). An effect that is hidden shows the bypassed result. + Stage { effect: LayerId, channel: Channel }, +} + +/// An 8-bit RGBA thumbnail (straight alpha). Alpha is 0 where the mesh does not cover the +/// texture and, for a paint or fill layer's content, where the layer has nothing; the view +/// paints its own background there. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ThumbImage { + pub width: u32, + pub height: u32, + pub rgba: Vec, +} + +/// The thumbnail of `target`, computed at `inp.gbuf`'s size, which must be square (use a +/// [`THUMB_TEXELS`] G-buffer; None otherwise). None for an unknown layer or effect, a layer without that channel, or a +/// mask that does not exist. +pub fn render(inp: &Inputs, target: ThumbTarget) -> Option { + if inp.gbuf.width != inp.gbuf.height { + return None; + } + match target { + ThumbTarget::Content { layer, channel } => content(inp, layer, channel, None), + ThumbTarget::Mask { layer } => mask(inp, layer, None), + ThumbTarget::Stage { effect, channel } => { + let (owner, _) = inp.project.effect(effect)?; + let in_mask = inp.project.layers.get(&owner)?.mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == effect)); + if in_mask { mask(inp, owner, Some(effect)) } else { content(inp, owner, channel, Some(effect)) } + } + } +} + +/// Force the requested layer visible, retaining the stack needed by anchor readers. +fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option) -> Option { + let mut cut = project.clone(); + + // Ordinary previews need no neighbouring layers or their filter allocations + if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_anchor(project, *layer)) { + cut.texture_sets.get_mut(texture_set)?.stack = vec![id]; + } + + cut.layers.get_mut(&id)?.visible = true; + if let Some(channel) = channel { + // Instances inherit channels from their source + let owner = cut.content_layer(id)?.id; + *cut.layers.get_mut(&owner)?.channels.get_mut(&channel)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + + Some(cut) +} + +/// Keep the effects of `list` up to and including `last`. +fn truncate_after(list: &mut Vec, last: LayerId) -> bool { + match list.iter().position(|e| e.id == last) { + Some(k) => { + list.truncate(k + 1); + true + } + None => false, + } +} + +fn content(inputs: &Inputs, layer: LayerId, channel: Channel, through_effect: Option) -> Option { + let set = inputs.project.texture_set(inputs.ts).ok()?; + if !set.channel_list().contains(&channel) { + return None; + } + + // An instance draws its source's effects + let mut cut = solo(inputs.project, inputs.ts, layer, Some(channel))?; + let owner = cut.content_layer(layer)?.id; + for id in [layer, owner] { + let content = cut.layers.get_mut(&id)?; + content.mask = None; + content.visible = true; + } + + if let Some(effect) = through_effect + && !truncate_after(&mut cut.layers.get_mut(&owner)?.content_effects, effect) + { + return None; + } + + let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + + // Paint and fill previews retain coverage; folders composite over channel defaults + if !cut.layers.get(&owner)?.is_group() { + let flat = flatten_layer(&cut_inputs, layer, &all_tiles(width, height))?; + return Some(encode_flat(&flat, channel, width, height)); + } + + let comp = crate::eval::thumbnail::composite_layer(&cut_inputs, layer, channel)?; + Some(encode_channel(&comp, channel, inputs)) +} + +/// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage. +fn encode_flat(flat: &[FlatTile], channel: Channel, w: u32, h: u32) -> ThumbImage { + let mut rgba = vec![0u8; (w * h) as usize * 4]; + let comps = channel.components(); + let signed = channel.kind() == ChannelKind::Signed; + for (c, (tx, ty), buf) in flat { + if *c != channel { + continue; + } + for (o, px) in buf.chunks_exact(comps + 1).enumerate() { + let (x, y) = (tx * TILE + o as u32 % TILE, ty * TILE + o as u32 / TILE); + let a = px.get(comps).map_or(0.0, |v| from_u16(*v)); + if x >= w || y >= h || a <= 0.0 { + continue; + } + let mut v = [0.0f32; 3]; + for (k, slot) in v.iter_mut().enumerate() { + let raw = px.get(k.min(comps - 1)).copied().unwrap_or(0); + *slot = if signed { from_u16_signed(raw) } else { from_u16(raw) } / a; + } + let p = display(channel, v); + let i = ((y * w + x) * 4) as usize; + if let Some(d) = rgba.get_mut(i..i + 4) { + d.copy_from_slice(&[p[0], p[1], p[2], to_byte(a)]); + } + } + } + ThumbImage { width: w, height: h, rgba } +} + +/// A channel value as display bytes: colors linear → sRGB, signed values with 0 at mid gray, +/// normal maps and scalars as stored. +fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] { + match channel.kind() { + ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), + ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), + } +} + +fn mask(inputs: &Inputs, layer: LayerId, through_effect: Option) -> Option { + let mut cut = solo(inputs.project, inputs.ts, layer, None)?; + let owner = cut.mask_owner(layer); + let mask = cut.layers.get_mut(&owner)?.mask.as_mut()?; + mask.enabled = true; + if let Some(effect) = through_effect + && !truncate_after(&mut mask.effects, effect) + { + return None; + } + + let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let gray = mask_image(&cut_inputs, layer, width)?; + let mut rgba = Vec::with_capacity((width * height) as usize * 4); + for y in 0..height { + for x in 0..width { + let offset = (y * width + x) as usize; + let value = gray.get(offset).copied().unwrap_or(0); + rgba.extend_from_slice(&[value, value, value, if inputs.gbuf.covered(offset) { 255 } else { 0 }]); + } + } + + Some(ThumbImage { width, height, rgba }) +} + +/// Encode the composited `channel` for display: colors linear → sRGB, signed values 0 → mid +/// gray, normal maps and scalars as stored (data channels raw). +fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImage { + let (w, h) = (comp.resolution, comp.height); + let mut rgba = Vec::with_capacity((w * h) as usize * 4); + for y in 0..h { + for x in 0..w { + let v = comp.value(channel, x, y); + let px = display(channel, v); + let covered = inp.gbuf.covered((y * w + x) as usize); + rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]); + } + } + ThumbImage { width: w, height: h, rgba } +} + +fn to_byte(v: f32) -> u8 { + if v.is_finite() { (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 } else { 0 } +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 020a9de0..ead117eb 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -6,8 +6,8 @@ use std::collections::BTreeMap; use texturecraft_compose::{BelowCache, Composite, Inputs, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached}; use texturecraft_core::{ - BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, - ProceduralKind, Project, Projection, Source, TextureSet, + BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, + Procedural, ProceduralKind, Project, Projection, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use texturecraft_texel::{TILE, TileImage, to_u16}; @@ -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 { @@ -562,3 +573,262 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } + +/// Composite every tile in chunks of `chunk`, telling the cache the `ahead` tiles that follow each chunk, as a pass spread over frames does. +fn run_sliced(fixture: &Fixture, cache: &mut BelowCache, chunk: usize, ahead: usize) -> Composite { + let all = all_tiles(RES, RES); + let (images, baked) = (Default::default(), Default::default()); + let mut out = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + + for (index, tiles) in all.chunks(chunk).enumerate() { + let done = (index * chunk + tiles.len()).min(all.len()); + cache.ahead = all.iter().skip(done).take(ahead).copied().collect(); + composite_tiles_cached(&inputs(fixture, 0, &images, &baked), &mut out, tiles, Some(&mut *cache)); + assert_eq!(cache.holds_fields(), !cache.ahead.is_empty(), "fields are kept exactly while tiles follow (chunk {chunk}, ahead {ahead})"); + } + + out +} + +#[test] +fn filter_fields_kept_across_the_chunks_of_a_pass_composite_exactly() { + let mut fixture = fixture(); + let top = heavy_stack(&mut fixture); + let blurred_fill = fixture.project.texture_sets[0].stack[1]; + let expected = reference(&fixture, 0); + + for hot in [None, Some(top), Some(blurred_fill)] { + // Exercise reuse within and recomputation beyond retained runs + for (chunk, ahead) in [(1, 1), (1, 5), (3, 4), (5, 16), (2, 0)] { + let mut cache = BelowCache::default(); + cache.set_hot(hot); + assert!(run_sliced(&fixture, &mut cache, chunk, ahead) == expected, "a cold sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})"); + + // A warm hot-layer cache needs fewer fields + assert!(run_sliced(&fixture, &mut cache, chunk, ahead) == expected, "a warm sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})"); + } + } + + // Evicted tiles need fields from every layer again + let mut full = BelowCache::default(); + full.set_hot(Some(top)); + run(&fixture, 0, &all_tiles(RES, RES), Some(&mut full)); + let tile_bytes = full.tile_bytes().unwrap(); + for tiles_held in [2, 5, 9] { + for (chunk, ahead) in [(1, 5), (3, 4), (2, 16)] { + let mut cache = BelowCache::default(); + cache.budget = tiles_held * tile_bytes; + cache.set_hot(Some(top)); + for pass in 0..3 { + assert!( + run_sliced(&fixture, &mut cache, chunk, ahead) == expected, + "pass {pass} differs with {tiles_held} cached tiles (chunk {chunk}, ahead {ahead})" + ); + } + } + } +} + +#[test] +fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { + let mut fixture = fixture(); + let top = heavy_stack(&mut fixture); + let all = all_tiles(RES, RES); + let (first, rest) = all.split_at(3); + let mut cache = BelowCache::default(); + cache.set_hot(Some(top)); + + // Keep fields for the remaining tiles + cache.ahead = rest.to_vec(); + let mut out = run(&fixture, 0, first, Some(&mut cache)); + assert!(cache.holds_fields()); + + // Changing the hot mask must invalidate the retained fields + let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); + mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); + let (images, baked) = (Default::default(), Default::default()); + cache.ahead = Vec::new(); + composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); + assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it"); + assert!(!cache.holds_fields()); + + // A live stroke must bypass retained fields + let preview = stroke(top); + cache.ahead = rest.to_vec(); + let mut live = run_with(&fixture, 0, first, Some(&mut cache), Some(&preview)); + assert!(!cache.holds_fields()); + + let mut inp = inputs(&fixture, 0, &images, &baked); + inp.preview = Some(&preview); + composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs"); +} + +/// Kept fields hold a layer off the hot path only over the tiles the cache lacked when they were built. A tile the cache drops +/// while they are in use needs that layer's fields again. +#[test] +fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { + const SIZE: u32 = 512; + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, SIZE, SIZE); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, SIZE)); + let mut fixture = Fixture { project, mesh, gbuf, pixels: PixelStore::default() }; + add(&mut fixture, 0, fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); + + // Pattern detail exposes any missing blur field + let mut blurred = Mask::new(MaskBackground::Black); + blurred.effects.push(effect(&mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); + add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred)); + + // Keep the blurred layer visible under the hot layer + let hot = add(&mut fixture, 0, LayerKind::Paint, None); + paint_rect_at(&mut fixture, hot, SIZE, (10, 10), (40, 40), 0.2); + + let mut all = all_tiles(SIZE, SIZE); + all.sort_by_key(|&(x, y)| (y, x)); + let channels = fixture.project.texture_sets[0].channel_list(); + let (images, baked) = (Default::default(), Default::default()); + let mut expected = Composite::new(&channels, SIZE); + composite_tiles(&inputs(&fixture, 0, &images, &baked), &mut expected, &all); + + // Prime the cache with only the two bottom rows + let rows = (SIZE / TILE) as usize; + let (above, bottom) = all.split_at(all.len() - 2 * rows); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot)); + let mut out = Composite::new(&channels, SIZE); + composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache)); + assert_eq!(cache.len(), bottom.len()); + cache.budget = cache.bytes(); + + // Cache eviction during the run must rebuild missing lower-layer fields + let mut out = Composite::new(&channels, SIZE); + for (index, tile) in all.iter().enumerate() { + cache.ahead = all.iter().skip(index + 1).copied().collect(); + composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &[*tile], Some(&mut cache)); + if index == 0 { + assert!(cache.holds_fields()); + } + } + assert!(above.len() > bottom.len()); + assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path"); +} + +/// A stroke that starts while fields are kept must not leave them allocated for as long as it lasts, even though tiles still follow. +#[test] +fn a_live_stroke_releases_the_fields_kept_before_it_started() { + let mut fixture = fixture(); + let top = heavy_stack(&mut fixture); + let all = all_tiles(RES, RES); + let (first, rest) = all.split_at(3); + let mut cache = BelowCache::default(); + cache.set_hot(Some(top)); + + cache.ahead = rest.to_vec(); + run(&fixture, 0, first, Some(&mut cache)); + assert!(cache.holds_fields()); + + // A stroke must release fields even while tiles remain + let preview = stroke(top); + let mut live = run_with(&fixture, 0, first, Some(&mut cache), Some(&preview)); + assert!(!cache.holds_fields(), "fields kept before the stroke stay allocated while it lasts"); + + let (images, baked) = (Default::default(), Default::default()); + let mut inp = inputs(&fixture, 0, &images, &baked); + inp.preview = Some(&preview); + composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a stroke that starts during a sliced pass differs"); +} + +#[test] +fn cached_stack_tracks_referenced_images_only() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore}; + + let mut fixture = fixture(); + let hot_layer = heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") }; + + fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() }); + let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let mut images = ImageStore::default(); + let baked = Default::default(); + let tiles = all_tiles(RES, RES); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot_layer)); + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + let mut previous_image = None; + + for stage in ["cold", "resolve", "unused1", "unused2", "unused3", "replace", "remove"] { + match stage { + "resolve" => { + let image = image_with_value(1.0); + previous_image = Some(Arc::downgrade(&image)); + images.insert("used".into(), image); + } + "replace" => { + let replacement = image_with_value(0.4); + let replacement_weak = Arc::downgrade(&replacement); + images.insert("used".into(), replacement); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels"); + previous_image = Some(replacement_weak); + } + "remove" => { + images.remove("used"); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels"); + } + "cold" => {} + _ => { + images.insert(stage.into(), image_with_value(0.5)); + } + } + + fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); + let input = inputs(&fixture, 0, &images, &baked); + composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; + composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}"); + + let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); + } +} + +#[test] +fn generator_input_image_changes_invalidate_stack_key() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore, StackKey}; + + let mut fixture = fixture(); + heavy_stack(&mut fixture); + let generated_layer = fixture.project.texture_sets[0].stack[1]; + let mask = fixture.project.layer_mut(generated_layer).unwrap().mask.as_mut().unwrap(); + let EffectKind::Generator(generator) = &mut mask.effects[0].kind else { panic!("expected generator") }; + *generator = Generator::new(GeneratorKind::Dirt); + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used")); + + let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let mut images = ImageStore::default(); + images.insert("used".into(), image(0.1)); + let baked = Default::default(); + let roots = &fixture.project.texture_sets[0].stack; + let key = |images: &ImageStore| StackKey::new(&fixture.project, &fixture.pixels, &baked, images, 0, roots).unwrap(); + let original = key(&images); + + images.insert("unrelated".into(), image(0.5)); + assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged"); + + let old_image = Arc::downgrade(&images["used"]); + images.insert("used".into(), image(0.9)); + assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels"); + assert!(key(&images) != original, "replacing a generator input must invalidate the cache"); + + images.remove("used"); + assert!(key(&images) != original, "removing a generator input must invalidate the cache"); +} diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs new file mode 100644 index 00000000..4b21a20d --- /dev/null +++ b/crates/core/src/bake.rs @@ -0,0 +1,77 @@ +//! Bake model types and component defaults + +mod ambient_occlusion_attenuation; +mod ambient_occlusion_settings; +mod backface_mode; +mod bake_antialiasing; +mod bake_paint_target; +mod bake_resolution; +mod bake_settings; +mod mesh_match_mode; +mod skew_correction_method; +pub use bake_paint_target::BakePaintTarget; +mod baked_map; +mod bent_normal_settings; +mod cage_settings; +mod cage_type; +mod common_bake_settings; +mod curvature_method; +mod curvature_settings; +mod ground_plane_settings; +mod height_normalization; +mod height_settings; +mod high_poly_settings; +mod id_color_generator; +mod id_color_source; +mod id_settings; +mod map_settings; +mod mesh_curvature_settings; +mod mesh_map_settings; +mod normal_map_curvature_settings; +mod position_axis; +mod position_mode; +mod position_normalization_scale; +mod position_settings; +mod ray_distribution; +mod ray_settings; +mod self_occlusion; +mod skew_settings; +mod thickness_normalization; +mod thickness_settings; + +pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation; +pub use ambient_occlusion_settings::AmbientOcclusionSettings; +pub use backface_mode::BackfaceMode; +pub use bake_antialiasing::BakeAntialiasing; +pub use bake_resolution::BakeResolution; +pub use bake_settings::BakeSettings; +pub use baked_map::BakedMap; +pub use bent_normal_settings::BentNormalSettings; +pub use cage_settings::CageSettings; +pub use cage_type::CageType; +pub use common_bake_settings::CommonBakeSettings; +pub use curvature_method::CurvatureMethod; +pub use curvature_settings::CurvatureSettings; +pub use ground_plane_settings::GroundPlaneSettings; +pub use height_normalization::HeightNormalization; +pub use height_settings::HeightSettings; +pub use high_poly_settings::HighPolySettings; +pub use id_color_generator::IdColorGenerator; +pub use id_color_source::IdColorSource; +pub use id_settings::IdSettings; +pub use map_settings::MapSettings; +pub use mesh_curvature_settings::MeshCurvatureSettings; +pub use mesh_map_settings::MeshMapSettings; +pub use mesh_match_mode::MeshMatchMode; +pub use normal_map_curvature_settings::NormalMapCurvatureSettings; +pub use position_axis::PositionAxis; +pub use position_mode::PositionMode; +pub use position_normalization_scale::PositionNormalizationScale; +pub use position_settings::PositionSettings; +pub use ray_distribution::RayDistribution; +pub use ray_settings::RaySettings; +pub use self_occlusion::SelfOcclusion; +pub use skew_correction_method::SkewCorrectionMethod; +pub use skew_settings::SkewSettings; +pub use thickness_normalization::ThicknessNormalization; +pub use thickness_settings::ThicknessSettings; diff --git a/crates/core/src/bake/ambient_occlusion_attenuation.rs b/crates/core/src/bake/ambient_occlusion_attenuation.rs new file mode 100644 index 00000000..92e2dffb --- /dev/null +++ b/crates/core/src/bake/ambient_occlusion_attenuation.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AmbientOcclusionAttenuation { + None, + Smooth, + #[default] + Linear, +} diff --git a/crates/core/src/bake/ambient_occlusion_settings.rs b/crates/core/src/bake/ambient_occlusion_settings.rs new file mode 100644 index 00000000..3ba308c0 --- /dev/null +++ b/crates/core/src/bake/ambient_occlusion_settings.rs @@ -0,0 +1,12 @@ +use super::{AmbientOcclusionAttenuation, BackfaceMode, GroundPlaneSettings, RaySettings, SelfOcclusion}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct AmbientOcclusionSettings { + pub rays: RaySettings, + pub ignore_backface: BackfaceMode, + pub self_occlusion: SelfOcclusion, + pub attenuation: AmbientOcclusionAttenuation, + pub ground_plane: GroundPlaneSettings, +} diff --git a/crates/core/src/bake/backface_mode.rs b/crates/core/src/bake/backface_mode.rs new file mode 100644 index 00000000..2b46f585 --- /dev/null +++ b/crates/core/src/bake/backface_mode.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum BackfaceMode { + #[default] + Never, + Always, + ByMeshName, +} diff --git a/crates/core/src/bake/bake_antialiasing.rs b/crates/core/src/bake/bake_antialiasing.rs new file mode 100644 index 00000000..8d7cff98 --- /dev/null +++ b/crates/core/src/bake/bake_antialiasing.rs @@ -0,0 +1,27 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum BakeAntialiasing { + #[default] + None, + Subsampling2x2, + Subsampling4x4, + Subsampling8x8, +} + +impl BakeAntialiasing { + pub const ALL: [Self; 4] = [Self::None, Self::Subsampling2x2, Self::Subsampling4x4, Self::Subsampling8x8]; + + pub fn samples_per_axis(self) -> u32 { + match self { + Self::None => 1, + Self::Subsampling2x2 => 2, + Self::Subsampling4x4 => 4, + Self::Subsampling8x8 => 8, + } + } + + pub fn from_samples_per_axis(samples: u32) -> Option { + Self::ALL.into_iter().find(|antialiasing| antialiasing.samples_per_axis() == samples) + } +} diff --git a/crates/core/src/bake/bake_paint_target.rs b/crates/core/src/bake/bake_paint_target.rs new file mode 100644 index 00000000..ed59c5c6 --- /dev/null +++ b/crates/core/src/bake/bake_paint_target.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum BakePaintTarget { + Cage, + #[default] + Skew, +} diff --git a/crates/core/src/bake/bake_resolution.rs b/crates/core/src/bake/bake_resolution.rs new file mode 100644 index 00000000..1ff49186 --- /dev/null +++ b/crates/core/src/bake/bake_resolution.rs @@ -0,0 +1,39 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum BakeResolution { + R16, + R32, + R64, + R128, + R256, + R512, + R1024, + #[default] + R2048, + R4096, + R8192, +} + +impl BakeResolution { + pub const ALL: [Self; 10] = [Self::R16, Self::R32, Self::R64, Self::R128, Self::R256, Self::R512, Self::R1024, Self::R2048, Self::R4096, Self::R8192]; + + pub fn pixels(self) -> u32 { + match self { + Self::R16 => 16, + Self::R32 => 32, + Self::R64 => 64, + Self::R128 => 128, + Self::R256 => 256, + Self::R512 => 512, + Self::R1024 => 1024, + Self::R2048 => 2048, + Self::R4096 => 4096, + Self::R8192 => 8192, + } + } + + pub fn from_pixels(pixels: u32) -> Option { + Self::ALL.into_iter().find(|resolution| resolution.pixels() == pixels) + } +} diff --git a/crates/core/src/bake/bake_settings.rs b/crates/core/src/bake/bake_settings.rs new file mode 100644 index 00000000..8d121419 --- /dev/null +++ b/crates/core/src/bake/bake_settings.rs @@ -0,0 +1,20 @@ +use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; +use serde::{Deserialize, Serialize}; + +/// Persisted clean-room bake settings, grouped by the controls they belong to +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeSettings { + pub common: CommonBakeSettings, + pub high_poly: HighPolySettings, + pub cage: CageSettings, + pub skew: SkewSettings, + pub maps: MeshMapSettings, +} + +impl BakeSettings { + /// Whether a painted skew map steers the rays: it needs a separate high poly and a distance-based cage with averaged normals + pub fn skew_applies(&self) -> bool { + !self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals + } +} diff --git a/crates/core/src/bake/baked_map.rs b/crates/core/src/bake/baked_map.rs new file mode 100644 index 00000000..ed6e695d --- /dev/null +++ b/crates/core/src/bake/baked_map.rs @@ -0,0 +1,82 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum BakedMap { + Normal, + WorldNormal, + Id, + AmbientOcclusion, + Curvature, + Position, + Thickness, + Height, + /// World-space direction of least occlusion (packed like the world-space normal) + BentNormal, + /// High-poly coverage times vertex and material alpha + Opacity, +} + +impl BakedMap { + pub const ALL: [BakedMap; 10] = [ + BakedMap::Normal, + BakedMap::WorldNormal, + BakedMap::Id, + BakedMap::AmbientOcclusion, + BakedMap::Curvature, + BakedMap::Position, + BakedMap::Thickness, + BakedMap::Height, + BakedMap::BentNormal, + BakedMap::Opacity, + ]; + + /// Mesh-map identifier shared with MaterialCraft + pub fn id(self) -> &'static str { + match self { + BakedMap::Normal => "normal", + BakedMap::WorldNormal => "worldNormal", + BakedMap::Id => "id", + BakedMap::AmbientOcclusion => "ambientOcclusion", + BakedMap::Curvature => "curvature", + BakedMap::Position => "position", + BakedMap::Thickness => "thickness", + BakedMap::Height => "height", + BakedMap::BentNormal => "bentNormal", + BakedMap::Opacity => "opacity", + } + } + + /// Components stored (3 for vector maps, 1 for scalar maps) + pub fn components(self) -> usize { + match self { + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Id | BakedMap::Position | BakedMap::BentNormal => 3, + _ => 1, + } + } + + /// Value where nothing was baked (uncovered texels, missing maps) + pub fn neutral(self) -> [f32; 3] { + match self { + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::BentNormal => [0.5, 0.5, 1.0], + BakedMap::AmbientOcclusion | BakedMap::Thickness => [1.0; 3], + BakedMap::Curvature | BakedMap::Height => [0.5; 3], + BakedMap::Id | BakedMap::Position | BakedMap::Opacity => [0.0; 3], + } + } + + pub fn parse(identifier: &str) -> Option { + match identifier { + "normal" => Some(BakedMap::Normal), + "worldNormal" => Some(BakedMap::WorldNormal), + "id" => Some(BakedMap::Id), + "ambientOcclusion" => Some(BakedMap::AmbientOcclusion), + "curvature" => Some(BakedMap::Curvature), + "position" => Some(BakedMap::Position), + "thickness" => Some(BakedMap::Thickness), + "height" => Some(BakedMap::Height), + "bentNormal" => Some(BakedMap::BentNormal), + "opacity" => Some(BakedMap::Opacity), + _ => None, + } + } +} diff --git a/crates/core/src/bake/bent_normal_settings.rs b/crates/core/src/bake/bent_normal_settings.rs new file mode 100644 index 00000000..dcc03cda --- /dev/null +++ b/crates/core/src/bake/bent_normal_settings.rs @@ -0,0 +1,10 @@ +use super::{BackfaceMode, RaySettings, SelfOcclusion}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BentNormalSettings { + pub rays: RaySettings, + pub ignore_backface: BackfaceMode, + pub self_occlusion: SelfOcclusion, +} diff --git a/crates/core/src/bake/cage_settings.rs b/crates/core/src/bake/cage_settings.rs new file mode 100644 index 00000000..13b18929 --- /dev/null +++ b/crates/core/src/bake/cage_settings.rs @@ -0,0 +1,19 @@ +use super::CageType; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct CageSettings { + pub kind: CageType, + /// Distance-based cage offsets (slider range 0..=0.05) + pub max_frontal: f32, + pub max_rear: f32, + pub relative_to_bounding_box: bool, + pub average_normals: bool, +} + +impl Default for CageSettings { + fn default() -> Self { + Self { kind: CageType::DistanceBased, max_frontal: 0.01, max_rear: 0.01, relative_to_bounding_box: true, average_normals: true } + } +} diff --git a/crates/core/src/bake/cage_type.rs b/crates/core/src/bake/cage_type.rs new file mode 100644 index 00000000..1985055f --- /dev/null +++ b/crates/core/src/bake/cage_type.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CageType { + #[default] + DistanceBased, + CustomFile, +} diff --git a/crates/core/src/bake/common_bake_settings.rs b/crates/core/src/bake/common_bake_settings.rs new file mode 100644 index 00000000..3f743fff --- /dev/null +++ b/crates/core/src/bake/common_bake_settings.rs @@ -0,0 +1,34 @@ +use super::{BakeAntialiasing, BakeResolution}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct CommonBakeSettings { + pub is_enabled: bool, + pub resolution: BakeResolution, + /// None locks both axes to the same resolution + pub resolution_height: Option, + pub antialiasing: BakeAntialiasing, + /// Padding width in pixels (0..=128) + pub dilation: u32, + pub apply_diffusion: bool, +} + +impl Default for CommonBakeSettings { + fn default() -> Self { + Self { + is_enabled: true, + resolution: BakeResolution::R2048, + resolution_height: None, + antialiasing: BakeAntialiasing::None, + dilation: 1, + apply_diffusion: true, + } + } +} + +impl CommonBakeSettings { + pub fn output_size(&self) -> (u32, u32) { + (self.resolution.pixels(), self.resolution_height.unwrap_or(self.resolution).pixels()) + } +} diff --git a/crates/core/src/bake/curvature_method.rs b/crates/core/src/bake/curvature_method.rs new file mode 100644 index 00000000..32ac645b --- /dev/null +++ b/crates/core/src/bake/curvature_method.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CurvatureMethod { + NormalMap, + #[default] + Mesh, +} diff --git a/crates/core/src/bake/curvature_settings.rs b/crates/core/src/bake/curvature_settings.rs new file mode 100644 index 00000000..66b4e732 --- /dev/null +++ b/crates/core/src/bake/curvature_settings.rs @@ -0,0 +1,10 @@ +use super::{CurvatureMethod, MeshCurvatureSettings, NormalMapCurvatureSettings}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct CurvatureSettings { + pub method: CurvatureMethod, + pub normal_map: NormalMapCurvatureSettings, + pub mesh: MeshCurvatureSettings, +} diff --git a/crates/core/src/bake/ground_plane_settings.rs b/crates/core/src/bake/ground_plane_settings.rs new file mode 100644 index 00000000..077c9bfd --- /dev/null +++ b/crates/core/src/bake/ground_plane_settings.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct GroundPlaneSettings { + pub enabled: bool, + /// Offset in mesh units (0..=100) + pub offset: f32, +} diff --git a/crates/core/src/bake/height_normalization.rs b/crates/core/src/bake/height_normalization.rs new file mode 100644 index 00000000..84113725 --- /dev/null +++ b/crates/core/src/bake/height_normalization.rs @@ -0,0 +1,10 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum HeightNormalization { + RelativeToRayDistances, + #[default] + RelativeToLowMesh, + RelativeToMinMax, + Manual, +} diff --git a/crates/core/src/bake/height_settings.rs b/crates/core/src/bake/height_settings.rs new file mode 100644 index 00000000..4200acf5 --- /dev/null +++ b/crates/core/src/bake/height_settings.rs @@ -0,0 +1,15 @@ +use super::HeightNormalization; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct HeightSettings { + pub normalization: HeightNormalization, + pub scaling_divisor: f32, +} + +impl Default for HeightSettings { + fn default() -> Self { + Self { normalization: HeightNormalization::RelativeToLowMesh, scaling_divisor: 1.0 } + } +} diff --git a/crates/core/src/bake/high_poly_settings.rs b/crates/core/src/bake/high_poly_settings.rs new file mode 100644 index 00000000..5c27f5d1 --- /dev/null +++ b/crates/core/src/bake/high_poly_settings.rs @@ -0,0 +1,26 @@ +use super::MeshMatchMode; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct HighPolySettings { + pub use_low_as_high: bool, + pub ignore_backface: bool, + pub match_mode: MeshMatchMode, + pub low_suffix: String, + pub high_suffix: String, + pub ignore_backface_suffix: String, +} + +impl Default for HighPolySettings { + fn default() -> Self { + Self { + use_low_as_high: false, + ignore_backface: true, + match_mode: MeshMatchMode::Always, + low_suffix: "_low".into(), + high_suffix: "_high".into(), + ignore_backface_suffix: "_ignorebf".into(), + } + } +} diff --git a/crates/core/src/bake/id_color_generator.rs b/crates/core/src/bake/id_color_generator.rs new file mode 100644 index 00000000..33b279d7 --- /dev/null +++ b/crates/core/src/bake/id_color_generator.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum IdColorGenerator { + Random, + #[default] + HueShift, + Grayscale, +} diff --git a/crates/core/src/bake/id_color_source.rs b/crates/core/src/bake/id_color_source.rs new file mode 100644 index 00000000..6551f5fc --- /dev/null +++ b/crates/core/src/bake/id_color_source.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum IdColorSource { + VertexColor, + #[default] + MaterialColor, + FileId, + MeshId, + Submesh, +} diff --git a/crates/core/src/bake/id_settings.rs b/crates/core/src/bake/id_settings.rs new file mode 100644 index 00000000..3a7f20d4 --- /dev/null +++ b/crates/core/src/bake/id_settings.rs @@ -0,0 +1,9 @@ +use super::{IdColorGenerator, IdColorSource}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct IdSettings { + pub source: IdColorSource, + pub generator: IdColorGenerator, +} diff --git a/crates/core/src/bake/map_settings.rs b/crates/core/src/bake/map_settings.rs new file mode 100644 index 00000000..47849b6e --- /dev/null +++ b/crates/core/src/bake/map_settings.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; + +/// One map's enablement and typed parameters +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct MapSettings { + pub is_enabled: bool, + pub parameters: T, +} + +impl Default for MapSettings { + fn default() -> Self { + Self { is_enabled: true, parameters: T::default() } + } +} + +impl MapSettings { + pub fn disabled() -> Self { + Self { is_enabled: false, ..Self::default() } + } +} diff --git a/crates/core/src/bake/mesh_curvature_settings.rs b/crates/core/src/bake/mesh_curvature_settings.rs new file mode 100644 index 00000000..55860ecb --- /dev/null +++ b/crates/core/src/bake/mesh_curvature_settings.rs @@ -0,0 +1,30 @@ +use super::SelfOcclusion; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MeshCurvatureSettings { + pub rays: u32, + /// Radius (0.00001..=10 relative to bounds, 0.00001..=1 in mesh units) + pub sampling_radius: f32, + pub relative_to_bounding_box: bool, + pub self_intersection: SelfOcclusion, + pub auto_tonemapping: bool, + /// Value bounds (-10..=10) + pub value_min: f32, + pub value_max: f32, +} + +impl Default for MeshCurvatureSettings { + fn default() -> Self { + Self { + rays: 32, + sampling_radius: 0.001, + relative_to_bounding_box: true, + self_intersection: SelfOcclusion::Always, + auto_tonemapping: true, + value_min: -1.0, + value_max: 1.0, + } + } +} diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs new file mode 100644 index 00000000..c0a38673 --- /dev/null +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -0,0 +1,83 @@ +use super::{ + AmbientOcclusionSettings, BakedMap, BentNormalSettings, CurvatureSettings, HeightSettings, IdSettings, MapSettings, PositionSettings, ThicknessSettings, +}; +use serde::{Deserialize, Serialize}; + +/// Per-map configuration; enabled outputs are derived from these flags +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MeshMapSettings { + pub normal: MapSettings, + pub world_normal: MapSettings, + pub id: MapSettings, + pub ao: MapSettings, + pub curvature: MapSettings, + pub position: MapSettings, + pub thickness: MapSettings, + pub height: MapSettings, + pub bent_normal: MapSettings, + pub opacity: MapSettings, +} + +impl Default for MeshMapSettings { + fn default() -> Self { + Self { + normal: MapSettings::default(), + world_normal: MapSettings::default(), + id: MapSettings::default(), + ao: MapSettings::default(), + curvature: MapSettings::default(), + position: MapSettings::default(), + thickness: MapSettings::default(), + height: MapSettings::disabled(), + bent_normal: MapSettings::disabled(), + opacity: MapSettings::disabled(), + } + } +} + +impl MeshMapSettings { + pub fn is_enabled(&self, map: BakedMap) -> bool { + match map { + BakedMap::Normal => self.normal.is_enabled, + BakedMap::WorldNormal => self.world_normal.is_enabled, + BakedMap::Id => self.id.is_enabled, + BakedMap::AmbientOcclusion => self.ao.is_enabled, + BakedMap::Curvature => self.curvature.is_enabled, + BakedMap::Position => self.position.is_enabled, + BakedMap::Thickness => self.thickness.is_enabled, + BakedMap::Height => self.height.is_enabled, + BakedMap::BentNormal => self.bent_normal.is_enabled, + BakedMap::Opacity => self.opacity.is_enabled, + } + } + + pub fn set_enabled(&mut self, map: BakedMap, is_enabled: bool) { + let enabled = match map { + BakedMap::Normal => &mut self.normal.is_enabled, + BakedMap::WorldNormal => &mut self.world_normal.is_enabled, + BakedMap::Id => &mut self.id.is_enabled, + BakedMap::AmbientOcclusion => &mut self.ao.is_enabled, + BakedMap::Curvature => &mut self.curvature.is_enabled, + BakedMap::Position => &mut self.position.is_enabled, + BakedMap::Thickness => &mut self.thickness.is_enabled, + BakedMap::Height => &mut self.height.is_enabled, + BakedMap::BentNormal => &mut self.bent_normal.is_enabled, + BakedMap::Opacity => &mut self.opacity.is_enabled, + }; + *enabled = is_enabled; + } + + pub fn enabled(&self) -> impl Iterator { + BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) + } + + pub fn select(&mut self, maps: impl IntoIterator) { + for map in BakedMap::ALL { + self.set_enabled(map, false); + } + for map in maps { + self.set_enabled(map, true); + } + } +} diff --git a/crates/core/src/bake/mesh_match_mode.rs b/crates/core/src/bake/mesh_match_mode.rs new file mode 100644 index 00000000..7030f640 --- /dev/null +++ b/crates/core/src/bake/mesh_match_mode.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum MeshMatchMode { + #[default] + Always, + ByMeshName, +} diff --git a/crates/core/src/bake/normal_map_curvature_settings.rs b/crates/core/src/bake/normal_map_curvature_settings.rs new file mode 100644 index 00000000..cb31b904 --- /dev/null +++ b/crates/core/src/bake/normal_map_curvature_settings.rs @@ -0,0 +1,15 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct NormalMapCurvatureSettings { + pub details: f32, + pub enable_seams: bool, + pub seams_intensity: f32, +} + +impl Default for NormalMapCurvatureSettings { + fn default() -> Self { + Self { details: 0.5, enable_seams: true, seams_intensity: 1.0 } + } +} diff --git a/crates/core/src/bake/position_axis.rs b/crates/core/src/bake/position_axis.rs new file mode 100644 index 00000000..0507e902 --- /dev/null +++ b/crates/core/src/bake/position_axis.rs @@ -0,0 +1,10 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PositionAxis { + #[default] + All, + X, + Y, + Z, +} diff --git a/crates/core/src/bake/position_mode.rs b/crates/core/src/bake/position_mode.rs new file mode 100644 index 00000000..dbba5e73 --- /dev/null +++ b/crates/core/src/bake/position_mode.rs @@ -0,0 +1,13 @@ +use serde::{Deserialize, Serialize}; + +/// Position map normalization +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum PositionMode { + /// Each axis spans the bounding box (0..1 per axis) + BoundingBox, + /// One scale for every axis: the largest extent around the box centre (keeps proportions) + #[default] + BoundingSphere, + /// Keep mesh coordinates without normalization + None, +} diff --git a/crates/core/src/bake/position_normalization_scale.rs b/crates/core/src/bake/position_normalization_scale.rs new file mode 100644 index 00000000..ef51c8c3 --- /dev/null +++ b/crates/core/src/bake/position_normalization_scale.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PositionNormalizationScale { + PerMaterial, + #[default] + FullScene, +} diff --git a/crates/core/src/bake/position_settings.rs b/crates/core/src/bake/position_settings.rs new file mode 100644 index 00000000..9fe62110 --- /dev/null +++ b/crates/core/src/bake/position_settings.rs @@ -0,0 +1,10 @@ +use super::{PositionAxis, PositionMode, PositionNormalizationScale}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PositionSettings { + pub axis: PositionAxis, + pub normalization: PositionMode, + pub scale: PositionNormalizationScale, +} diff --git a/crates/core/src/bake/ray_distribution.rs b/crates/core/src/bake/ray_distribution.rs new file mode 100644 index 00000000..4d38a287 --- /dev/null +++ b/crates/core/src/bake/ray_distribution.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +/// How secondary rays spread over their cone +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum RayDistribution { + /// Cosine-weighted: more rays near the normal + #[default] + Cosine, + /// Uniform over the cone's solid angle + Uniform, +} diff --git a/crates/core/src/bake/ray_settings.rs b/crates/core/src/bake/ray_settings.rs new file mode 100644 index 00000000..5aa76651 --- /dev/null +++ b/crates/core/src/bake/ray_settings.rs @@ -0,0 +1,24 @@ +use super::RayDistribution; +use serde::{Deserialize, Serialize}; + +/// Secondary-ray parameters of one map (ambient occlusion, thickness, bent normals) +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct RaySettings { + /// Rays per sample (settings range 1..=256) + pub rays: u32, + /// Minimum distance in the same units as max_distance (0.00001..=1) + pub min_distance: f32, + /// Maximum distance: 0.00001..=1 relative to the bounding box, or 0.00001..=10 in mesh units + pub max_distance: f32, + pub relative_to_bounding_box: bool, + /// Full cone angle around the normal in degrees (180 = the whole hemisphere) + pub spread: f32, + pub distribution: RayDistribution, +} + +impl Default for RaySettings { + fn default() -> Self { + RaySettings { rays: 64, min_distance: 0.00001, max_distance: 1.0, relative_to_bounding_box: true, spread: 180.0, distribution: RayDistribution::Cosine } + } +} diff --git a/crates/core/src/bake/self_occlusion.rs b/crates/core/src/bake/self_occlusion.rs new file mode 100644 index 00000000..a48f592d --- /dev/null +++ b/crates/core/src/bake/self_occlusion.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +/// Mesh filtering for occlusion, thickness and curvature rays +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum SelfOcclusion { + /// Every part occludes every other + #[default] + Always, + /// Only parts with the same mesh name (suffixes removed) occlude each other + SameMeshName, +} diff --git a/crates/core/src/bake/skew_correction_method.rs b/crates/core/src/bake/skew_correction_method.rs new file mode 100644 index 00000000..82e0a41e --- /dev/null +++ b/crates/core/src/bake/skew_correction_method.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SkewCorrectionMethod { + #[default] + MeshNormalsBased, + FaceNormalsBased, +} diff --git a/crates/core/src/bake/skew_settings.rs b/crates/core/src/bake/skew_settings.rs new file mode 100644 index 00000000..8a42b0fc --- /dev/null +++ b/crates/core/src/bake/skew_settings.rs @@ -0,0 +1,20 @@ +use super::SkewCorrectionMethod; +use serde::{Deserialize, Serialize}; + +/// Skew controls independent of the painted pixel asset +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SkewSettings { + pub method: SkewCorrectionMethod, + pub edge_protection: bool, + /// Edge protection distance (0..=1), retained while protection is disabled + pub edge_distance: f32, + /// Edge protection contrast (0..=1) + pub edge_contrast: f32, +} + +impl Default for SkewSettings { + fn default() -> Self { + Self { method: SkewCorrectionMethod::MeshNormalsBased, edge_protection: false, edge_distance: 0.15, edge_contrast: 0.5 } + } +} diff --git a/crates/core/src/bake/thickness_normalization.rs b/crates/core/src/bake/thickness_normalization.rs new file mode 100644 index 00000000..1a01a86e --- /dev/null +++ b/crates/core/src/bake/thickness_normalization.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ThicknessNormalization { + RelativeToRayDistances, + #[default] + RelativeToMinMax, + None, +} diff --git a/crates/core/src/bake/thickness_settings.rs b/crates/core/src/bake/thickness_settings.rs new file mode 100644 index 00000000..659391a2 --- /dev/null +++ b/crates/core/src/bake/thickness_settings.rs @@ -0,0 +1,20 @@ +use super::{RaySettings, SelfOcclusion, ThicknessNormalization}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ThicknessSettings { + pub rays: RaySettings, + pub self_occlusion: SelfOcclusion, + pub normalization: ThicknessNormalization, +} + +impl Default for ThicknessSettings { + fn default() -> Self { + Self { + rays: RaySettings { max_distance: 0.1, ..RaySettings::default() }, + self_occlusion: SelfOcclusion::Always, + normalization: ThicknessNormalization::RelativeToMinMax, + } + } +} 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..0e05255b 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,7 +4,19 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::{BlendMode, Channel, ChannelKind, lum}; +use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; + +mod curvature_detail; +mod curvature_mode; +mod generator_global; +mod output_resolution; +mod resolution_mode; + +pub use curvature_detail::CurvatureDetail; +pub use curvature_mode::CurvatureMode; +pub use generator_global::GeneratorGlobal; +pub use output_resolution::OutputResolution; +pub use resolution_mode::ResolutionMode; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -520,6 +532,17 @@ impl GeneratorKind { GeneratorKind::Direction => "Light / direction", } } + + /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. + pub fn inputs(self) -> &'static [BakedMap] { + match self { + GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature], + GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], + GeneratorKind::ThinAreas => &[BakedMap::Thickness], + GeneratorKind::Position | GeneratorKind::Direction => &[], + } + } + pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s)) @@ -537,20 +560,74 @@ pub struct Generator { pub noise_amount: f32, pub noise_scale: f32, pub seed: u32, + /// Added to the finished mask value and clamped to 0..1 (−1..1; 0 = unchanged). + #[serde(default)] + pub offset: f32, /// 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, + /// Blur, balance and contrast of the finished value (neutral for generators saved before they existed). + #[serde(default, skip_serializing_if = "GeneratorGlobal::is_neutral")] + pub global: GeneratorGlobal, + /// The resolution the generator is computed at (the texture set's for generators saved before it existed). + #[serde(default, skip_serializing_if = "OutputResolution::is_default")] + pub resolution: OutputResolution, + /// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub inputs: BTreeMap, } impl Generator { + /// The softest a ramp gets, so its threshold never divides by zero. + pub const MIN_SOFTNESS: f32 = 1e-3; + /// The most noise a generator mixes in, and the range of its noise scale. + pub const MAX_NOISE_AMOUNT: f32 = 2.0; + pub const MIN_NOISE_SCALE: f32 = 0.01; + pub const MAX_NOISE_SCALE: f32 = 1000.0; + 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, + offset: 0.0, + direction: [0.0, 1.0, 0.0], + invert: false, + detail, + global: GeneratorGlobal::default(), + resolution: OutputResolution::default(), + inputs: BTreeMap::new(), + } + } + + /// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over + /// `softness`, inverted if asked, then shifted by `offset` (a non-finite offset counts as 0). + pub fn shape(&self, s: f32) -> f32 { + let th = 1.0 - self.level.clamp(0.0, 1.0); + let soft = self.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); + let v = if self.invert { 1.0 - v } else { v }; + let offset = if self.offset.is_finite() { self.offset } else { 0.0 }; + (v + offset).clamp(0.0, 1.0) } } @@ -1008,14 +1085,46 @@ impl EffectKind { matches!(self, EffectKind::Paint | EffectKind::Path(_)) } - /// Anchor points read by this effect's sources. + /// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point. fn reads_anchor(&self) -> bool { match self { EffectKind::Fill { source, .. } => source.anchor().is_some(), - EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()), + EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()), + EffectKind::Generator(generator) => generator.inputs.values().any(|source| source.anchor().is_some()), _ => false, } } + + /// The anchor points this effect's sources read, with the channel each reads. + pub fn anchors_read(&self) -> Vec<(LayerId, Channel)> { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Material(fill) => fill.sources.values().collect(), + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources + .into_iter() + .filter_map(|source| match source { + Source::Anchor { anchor, channel } => Some((*anchor, *channel)), + _ => None, + }) + .collect() + } + + /// The image resources this effect's sources read (a fill, material or generator input). + pub fn images_read(&self) -> impl Iterator { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Material(fill) => fill.sources.values().collect(), + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources.into_iter().filter_map(|source| match source { + Source::Image { name, .. } => Some(name.as_str()), + _ => None, + }) + } } impl Layer { @@ -1050,6 +1159,66 @@ impl Effect { mod tests { use super::*; + #[test] + fn material_effect_images_are_reported_as_used() { + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::image("material.png")); + let effect = EffectKind::Material(fill); + + assert_eq!(effect.images_read().collect::>(), vec!["material.png"]); + } + + #[test] + fn generator_offset_shifts_the_mask_value() { + let mut g = Generator::new(GeneratorKind::Position); + let base = g.shape(0.2); + assert!(base < 0.5); + g.offset = 0.3; + assert!((g.shape(0.2) - (base + 0.3)).abs() < 1e-6, "the offset is added"); + g.offset = 1.0; + assert_eq!(g.shape(0.2), 1.0, "and the result is clamped"); + g.offset = -1.0; + assert_eq!(g.shape(0.9), 0.0); + } + + #[test] + fn generator_non_finite_offset_counts_as_zero() { + let mut g = Generator::new(GeneratorKind::Position); + let base: Vec = [0.0, 0.2, 0.5, 0.9].iter().map(|&s| g.shape(s)).collect(); + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + g.offset = bad; + let got: Vec = [0.0, 0.2, 0.5, 0.9].iter().map(|&s| g.shape(s)).collect(); + assert_eq!(got, base, "offset {bad} behaves like 0"); + } + } + + #[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 generators_saved_before_the_new_settings_load_and_save_unchanged() { + let saved = serde_json::to_value(Generator::new(GeneratorKind::Dirt)).unwrap(); + for field in ["global", "resolution", "inputs"] { + assert!(saved.get(field).is_none(), "a default `{field}` is not written, so saved files stay as they were"); + } + + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert!(loaded.global.is_neutral()); + + let mut blurred = Generator::new(GeneratorKind::Dirt); + blurred.global.blur = 0.5; + let round_trip: Generator = serde_json::from_value(serde_json::to_value(&blurred).unwrap()).unwrap(); + assert_eq!(round_trip, blurred); + } + #[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/layer/generator_global.rs b/crates/core/src/layer/generator_global.rs new file mode 100644 index 00000000..15349e0d --- /dev/null +++ b/crates/core/src/layer/generator_global.rs @@ -0,0 +1,96 @@ +use serde::{Deserialize, Serialize}; + +/// Adjustments every generator applies to its finished value: a blur, then balance and contrast. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct GeneratorGlobal { + /// Blur of the generated value (0..1 of [`GeneratorGlobal::MAX_BLUR`]). + pub blur: f32, + /// Shifts the value darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged. + pub balance: f32, + /// Narrows the ramp around its middle (0 unchanged, 1 a hard step). + pub contrast: f32, +} + +impl GeneratorGlobal { + /// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub const MAX_BLUR: f32 = 64.0; + /// Narrower than this, the balanced range is a hard step. + pub const MIN_RANGE: f32 = 1e-6; + /// The texels per side the blur radius is measured at (2K). + pub const BLUR_RESOLUTION: f32 = 2048.0; + + pub fn is_neutral(&self) -> bool { + *self == GeneratorGlobal::default() + } + + /// The blur as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub fn blur_radius(&self) -> f32 { + self.blur.clamp(0.0, 1.0) * GeneratorGlobal::MAX_BLUR + } + + /// The blur as a radius in texels at `resolution` texels per side. + pub fn blur_radius_at(&self, resolution: u32) -> f32 { + self.blur_radius() * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION + } + + /// `value` after balance and contrast: balance picks the input range stretched to 0..1, contrast narrows it around its middle. + pub fn apply(&self, value: f32) -> f32 { + if self.balance == 0.5 && self.contrast == 0.0 { + return value; + } + let balance = self.balance.clamp(0.0, 1.0); + let (low, high) = ((1.0 - 2.0 * balance).max(0.0), (2.0 - 2.0 * balance).min(1.0)); + let middle = (low + high) * 0.5; + let keep = 1.0 - self.contrast.clamp(0.0, 1.0); + let (low, high) = (middle - (middle - low) * keep, middle + (high - middle) * keep); + if high - low < GeneratorGlobal::MIN_RANGE { + return if value >= middle { 1.0 } else { 0.0 }; + } + ((value - low) / (high - low)).clamp(0.0, 1.0) + } +} + +impl Default for GeneratorGlobal { + fn default() -> Self { + GeneratorGlobal { blur: 0.0, balance: 0.5, contrast: 0.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn neutral_settings_leave_the_value_unchanged() { + let global = GeneratorGlobal::default(); + for value in [0.0, 0.1, 0.5, 0.93, 1.0] { + assert_eq!(global.apply(value), value); + } + } + + #[test] + fn balance_darkens_below_the_middle_and_brightens_above() { + let darker = GeneratorGlobal { balance: 0.25, ..GeneratorGlobal::default() }; + assert_eq!(darker.apply(0.4), 0.0, "the lower half goes black"); + assert!((darker.apply(0.75) - 0.5).abs() < 1e-6, "the upper half stretches over the whole range"); + + let brighter = GeneratorGlobal { balance: 0.75, ..GeneratorGlobal::default() }; + assert!((brighter.apply(0.25) - 0.5).abs() < 1e-6); + assert_eq!(brighter.apply(0.6), 1.0, "the upper half goes white"); + + assert_eq!(GeneratorGlobal { balance: 0.0, ..GeneratorGlobal::default() }.apply(0.99), 0.0); + assert_eq!(GeneratorGlobal { balance: 1.0, ..GeneratorGlobal::default() }.apply(0.01), 1.0); + } + + #[test] + fn full_contrast_is_a_step_at_the_middle_of_the_balanced_range() { + let step = GeneratorGlobal { contrast: 1.0, ..GeneratorGlobal::default() }; + assert_eq!(step.apply(0.49), 0.0); + assert_eq!(step.apply(0.51), 1.0); + + let half = GeneratorGlobal { contrast: 0.5, ..GeneratorGlobal::default() }; + assert_eq!(half.apply(0.25), 0.0); + assert!((half.apply(0.5) - 0.5).abs() < 1e-6); + assert_eq!(half.apply(0.75), 1.0); + } +} diff --git a/crates/core/src/layer/output_resolution.rs b/crates/core/src/layer/output_resolution.rs new file mode 100644 index 00000000..c0e5173c --- /dev/null +++ b/crates/core/src/layer/output_resolution.rs @@ -0,0 +1,120 @@ +use serde::{Deserialize, Serialize}; + +use super::resolution_mode::ResolutionMode; + +/// The resolution a generator computes its output at, before it is sampled onto the texture set. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputResolution { + pub mode: ResolutionMode, + /// Texels per side for [`ResolutionMode::Custom`]. + pub custom: u32, + /// Power of two applied to the base size (−3 = 1/8 … 3 = ×8; 0 = the same as the context). + pub factor: i8, +} + +impl OutputResolution { + /// The factors the reference app offers: 1/8 to ×8. + pub const FACTORS: std::ops::RangeInclusive = -3..=3; + /// The sizes offered for [`ResolutionMode::Custom`]. + pub const CUSTOM_SIZES: [u32; 6] = [128, 256, 512, 1024, 2048, 4096]; + /// The largest output, the largest texture set resolution. + pub const MAX_SIZE: u32 = 8192; + /// The coarsest output: one value per this many texels of the context per side (a compositing tile). + pub const MAX_CELL: u32 = 64; + + pub fn is_default(&self) -> bool { + *self == OutputResolution::default() + } + + /// Whether some UV tile can get a coarser output than its own resolution (a custom size, the set's size or a factor below 1). + pub fn can_reduce(&self) -> bool { + matches!(self.mode, ResolutionMode::Custom | ResolutionMode::TextureSet) || self.factor < 0 + } + + /// The largest cell a UV tile of up to `uv_tile` texels per side can get, whatever its texture set's resolution. + pub fn largest_cell(&self, uv_tile: u32) -> u32 { + if self.mode == ResolutionMode::TextureSet { OutputResolution::MAX_CELL } else { self.cell(uv_tile, uv_tile) } + } + + /// Texels per side of the output for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`. + pub fn output_size(&self, uv_tile: u32, texture_set: u32) -> u32 { + let base = match self.mode { + ResolutionMode::Auto | ResolutionMode::UvTile => uv_tile, + ResolutionMode::TextureSet => texture_set, + ResolutionMode::Custom => self.custom, + }; + let factor = self.factor.clamp(*OutputResolution::FACTORS.start(), *OutputResolution::FACTORS.end()); + let scaled = if factor >= 0 { base.saturating_mul(1 << factor) } else { base >> -factor }; + + // Hostile tile sizes can make the minimum exceed the supported maximum + let minimum = (uv_tile / OutputResolution::MAX_CELL).clamp(1, OutputResolution::MAX_SIZE); + scaled.clamp(minimum, OutputResolution::MAX_SIZE) + } + + /// How many texels of the UV tile one output texel covers per side (1 when the output is as fine or finer). + pub fn cell(&self, uv_tile: u32, texture_set: u32) -> u32 { + (uv_tile / self.output_size(uv_tile, texture_set)).max(1) + } +} + +impl Default for OutputResolution { + fn default() -> Self { + OutputResolution { mode: ResolutionMode::Auto, custom: 2048, factor: 0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_follows_the_uv_tile() { + let resolution = OutputResolution::default(); + assert_eq!(resolution.output_size(1024, 2048), 1024); + assert_eq!(resolution.cell(1024, 2048), 1); + assert!(!resolution.can_reduce()); + } + + #[test] + fn the_texture_set_mode_reads_the_set_not_the_uv_tile() { + let resolution = OutputResolution { mode: ResolutionMode::TextureSet, factor: -1, ..OutputResolution::default() }; + assert_eq!(resolution.output_size(512, 2048), 1024, "half the set's 2048"); + assert_eq!(resolution.cell(512, 2048), 1, "finer than the 512 tile: one texel per texel"); + } + + #[test] + fn factors_and_custom_sizes_scale_the_output() { + let eighth = OutputResolution { factor: -3, ..OutputResolution::default() }; + assert_eq!((eighth.output_size(2048, 2048), eighth.cell(2048, 2048)), (256, 8)); + + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 512, factor: 1 }; + assert_eq!((custom.output_size(2048, 2048), custom.cell(2048, 2048)), (1024, 2)); + + let finer = OutputResolution { factor: 3, ..OutputResolution::default() }; + assert_eq!((finer.output_size(2048, 2048), finer.cell(2048, 2048)), (8192, 1), "a finer output than the tile keeps one texel per texel"); + } + + #[test] + fn the_largest_cell_covers_any_texture_set() { + let set = OutputResolution { mode: ResolutionMode::TextureSet, ..OutputResolution::default() }; + assert!(set.can_reduce(), "a UV tile larger than its set gets the set's coarser size"); + assert_eq!(set.largest_cell(2048), OutputResolution::MAX_CELL); + assert_eq!(OutputResolution { factor: -2, ..OutputResolution::default() }.largest_cell(2048), 4); + } + + #[test] + fn hostile_sizes_stay_within_the_largest_output_and_the_coarsest_cell() { + let huge = OutputResolution { mode: ResolutionMode::Custom, custom: u32::MAX, factor: i8::MAX }; + assert_eq!(huge.output_size(2048, 2048), OutputResolution::MAX_SIZE); + + let tiny = OutputResolution { mode: ResolutionMode::Custom, custom: 1, factor: -3 }; + assert_eq!(tiny.cell(4096, 4096), OutputResolution::MAX_CELL); + } + + #[test] + fn hostile_uv_tile_size_does_not_panic() { + let resolution = OutputResolution::default(); + + assert_eq!(resolution.output_size(u32::MAX, 2048), OutputResolution::MAX_SIZE); + } +} diff --git a/crates/core/src/layer/resolution_mode.rs b/crates/core/src/layer/resolution_mode.rs new file mode 100644 index 00000000..ffd6a140 --- /dev/null +++ b/crates/core/src/layer/resolution_mode.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +/// What a generator's output resolution is based on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ResolutionMode { + /// The context: the resolution of the UV tile it is computed for. + Auto, + /// The texture set's resolution. + TextureSet, + /// The UV tile's resolution. + UvTile, + /// A size of its own. + Custom, +} + +impl ResolutionMode { + pub const ALL: [ResolutionMode; 4] = [ResolutionMode::Auto, ResolutionMode::TextureSet, ResolutionMode::UvTile, ResolutionMode::Custom]; + + pub fn label(self) -> &'static str { + match self { + ResolutionMode::Auto => "Auto", + ResolutionMode::TextureSet => "Texture set", + ResolutionMode::UvTile => "UV tile", + ResolutionMode::Custom => "Custom", + } + } + + pub fn parse(name: &str) -> Option { + let norm = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + ResolutionMode::ALL.into_iter().find(|mode| norm(&format!("{mode:?}")) == norm(name) || norm(mode.label()) == norm(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 80f1cafe..4a17e89e 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -7,21 +7,30 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake; pub mod blend; +mod block_scales; pub mod channel; pub mod layer; pub mod project; +pub use bake::{ + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, + BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, + HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, + NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, + SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, +}; 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, GeneratorGlobal, GeneratorKind, HeightMask, + Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, OutputResolution, PathShape, Procedural, ProceduralKind, + Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ - AoMixing, BakeMatch, BakeSettings, BakedMap, BlockScales, Camera, DepthOfField, DirectionMode, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, - MIN_RESOLUTION, NormalFormat, NormalMixing, PositionMode, Project, RayDistribution, RaySettings, SelfOcclusion, TextureSet, TileGrid, ToneMapping, - UDIM_RANGE, udim_at, + AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, + TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; #[derive(Debug, thiserror::Error, Clone, PartialEq)] diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index c144ec98..3fe26e04 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -1,14 +1,14 @@ -//! The project: texture sets, their layer stacks, and project-wide settings. +//! The project: texture sets, their layer stacks, and project-wide settings use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +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). +/// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -18,273 +18,6 @@ pub enum NormalFormat { DirectX, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub enum BakedMap { - Normal, - WorldNormal, - Id, - AmbientOcclusion, - Curvature, - Position, - Thickness, - Height, - /// World-space direction of least occlusion (packed like the world-space normal). - BentNormal, - /// 1 where the high poly covers the low poly (times the high poly's vertex alpha). - Opacity, - /// The high poly's vertex colors. - ColorMap, - /// Facing ratio towards [`BakeSettings::direction`] (0.5 = perpendicular). - WorldDirection, -} - -impl BakedMap { - pub const ALL: [BakedMap; 12] = [ - BakedMap::Normal, - BakedMap::WorldNormal, - BakedMap::Id, - BakedMap::AmbientOcclusion, - BakedMap::Curvature, - BakedMap::Position, - BakedMap::Thickness, - BakedMap::Height, - BakedMap::BentNormal, - BakedMap::Opacity, - BakedMap::ColorMap, - BakedMap::WorldDirection, - ]; - pub fn label(self) -> &'static str { - match self { - BakedMap::Normal => "Normal", - BakedMap::WorldNormal => "World space normal", - BakedMap::Id => "ID", - BakedMap::AmbientOcclusion => "Ambient occlusion", - BakedMap::Curvature => "Curvature", - BakedMap::Position => "Position", - BakedMap::Thickness => "Thickness", - BakedMap::Height => "Height", - BakedMap::BentNormal => "Bent normals", - BakedMap::Opacity => "Opacity", - BakedMap::ColorMap => "Color map", - BakedMap::WorldDirection => "World space direction", - } - } - pub fn id(self) -> &'static str { - match self { - BakedMap::Normal => "normal_base", - BakedMap::WorldNormal => "world_space_normals", - BakedMap::Id => "id", - BakedMap::AmbientOcclusion => "ambient_occlusion", - BakedMap::Curvature => "curvature", - BakedMap::Position => "position", - BakedMap::Thickness => "thickness", - BakedMap::Height => "height", - BakedMap::BentNormal => "bent_normals", - BakedMap::Opacity => "opacity", - BakedMap::ColorMap => "color_map", - BakedMap::WorldDirection => "world_space_direction", - } - } - /// The identifier shared with MaterialCraft (graph inputs fed from this map). - pub fn interop_id(self) -> &'static str { - match self { - BakedMap::Normal => "normal", - BakedMap::WorldNormal => "worldNormal", - BakedMap::Id => "id", - BakedMap::AmbientOcclusion => "ambientOcclusion", - BakedMap::Curvature => "curvature", - BakedMap::Position => "position", - BakedMap::Thickness => "thickness", - BakedMap::Height => "height", - BakedMap::BentNormal => "bentNormal", - BakedMap::Opacity => "opacity", - BakedMap::ColorMap => "colorMap", - BakedMap::WorldDirection => "worldDirection", - } - } - /// The map a MaterialCraft graph input `identifier` reads: its shared or own id, ignoring - /// case and underscores (`ambient_occlusion` = `ambientOcclusion`). - pub fn for_input(identifier: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace(['_', '-', ' '], ""); - let want = norm(identifier); - BakedMap::ALL.into_iter().find(|m| norm(m.interop_id()) == want || norm(m.id()) == want) - } - /// Components stored (3 for vector maps, 1 for scalar maps). - pub fn components(self) -> usize { - match self { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Id | BakedMap::Position | BakedMap::BentNormal | BakedMap::ColorMap => 3, - _ => 1, - } - } - /// Value where nothing was baked (uncovered texels, missing maps). - pub fn neutral(self) -> [f32; 3] { - match self { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::BentNormal => [0.5, 0.5, 1.0], - BakedMap::AmbientOcclusion | BakedMap::Thickness => [1.0; 3], - BakedMap::Curvature | BakedMap::Height | BakedMap::WorldDirection => [0.5; 3], - BakedMap::Id | BakedMap::Position | BakedMap::Opacity | BakedMap::ColorMap => [0.0; 3], - } - } - pub fn parse(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], ""); - BakedMap::ALL.into_iter().find(|m| norm(m.label()) == norm(s) || norm(m.id()) == norm(s) || norm(&format!("{m:?}")) == norm(s)) - } -} - -/// How low-poly parts find their high-poly counterparts (the bake "Match" option). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum BakeMatch { - /// Every low-poly part sees every high-poly part. - #[default] - Always, - /// A low-poly part sees only high-poly parts of the same name once the suffixes are removed - /// (`wheel_low` ↔ `wheel_high`). - ByMeshName, -} - -/// How secondary rays spread over their cone. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum RayDistribution { - /// Cosine-weighted: more rays near the normal. - #[default] - Cosine, - /// Uniform over the cone's solid angle. - Uniform, -} - -/// Which geometry occludes ambient occlusion and bent-normal rays. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum SelfOcclusion { - /// Every part occludes every other. - #[default] - Always, - /// Only parts with the same mesh name (suffixes removed) occlude each other. - SameMeshName, -} - -/// Position map normalization. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum PositionMode { - /// Each axis spans the bounding box (0..1 per axis). - #[default] - BoundingBox, - /// One scale for every axis: the bounding sphere around the box centre (keeps proportions). - BoundingSphere, -} - -/// World space direction map encoding. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum DirectionMode { - /// −1..1 to 0..1: mid grey where the surface is perpendicular to the direction. - #[default] - Signed, - /// 0..1: black where the surface is perpendicular or faces away. - Positive, -} - -/// Secondary-ray parameters of one map (ambient occlusion, thickness, bent normals). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct RaySettings { - /// Rays per sample. - pub rays: u32, - /// Max ray length relative to the bounding-box diagonal. - pub max_distance: f32, - /// Full cone angle around the normal in degrees (180 = the whole hemisphere). - pub spread: f32, - pub distribution: RayDistribution, -} - -impl Default for RaySettings { - fn default() -> Self { - RaySettings { rays: 32, max_distance: 0.25, spread: 180.0, distribution: RayDistribution::Cosine } - } -} - -/// Bake parameters (the common parameters plus the per-map parameters). Fields missing -/// from older projects take their defaults. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct BakeSettings { - /// Included by "Bake selected textures". - pub enabled: bool, - pub resolution: u32, - /// Supersampling per axis: 1 (none), 2, 4 or 8. - pub antialiasing: u32, - pub dilation: u32, - /// Ambient occlusion rays. - pub ao: RaySettings, - /// Ambient occlusion and bent-normal rays ignore surfaces they hit from behind. - pub ao_ignore_backface: bool, - pub ao_self_occlusion: SelfOcclusion, - /// Thickness rays (into the surface). - pub thickness: RaySettings, - /// Bent-normal rays (they follow the ambient occlusion's occluder rules). - pub bent_normal: RaySettings, - /// Curvature strength. - pub curvature_strength: f32, - /// Curvature from the baked normal map instead of the mesh. - pub curvature_from_normal: bool, - /// Sampling radius of curvature from the normal map, in texels (0: by resolution). - pub curvature_radius: u32, - pub position_mode: PositionMode, - /// World-space direction of the "World space direction" map. - pub direction: [f32; 3], - pub direction_mode: DirectionMode, - pub maps: BTreeSet, - /// Bake from the low poly itself ("Use low poly mesh as high poly"). - pub use_low_as_high: bool, - /// Ray start distance in front of the low poly, relative to the bbox diagonal. - pub max_frontal: f32, - pub max_rear: f32, - /// Cast rays along normals averaged over hard edges (no gaps at split normals). - pub average_normals: bool, - pub matching: BakeMatch, - pub low_suffix: String, - pub high_suffix: String, -} - -impl Default for BakeSettings { - fn default() -> Self { - BakeSettings { - enabled: true, - resolution: 1024, - antialiasing: 1, - dilation: 16, - ao: RaySettings::default(), - ao_ignore_backface: false, - ao_self_occlusion: SelfOcclusion::Always, - // Thickness is hit distance / max distance: long rays turn thin parts almost black. - thickness: RaySettings { max_distance: 0.1, ..RaySettings::default() }, - bent_normal: RaySettings::default(), - curvature_strength: 1.0, - curvature_from_normal: false, - curvature_radius: 0, - position_mode: PositionMode::BoundingBox, - direction: [0.0, 1.0, 0.0], - direction_mode: DirectionMode::Signed, - maps: [ - BakedMap::Normal, - BakedMap::WorldNormal, - BakedMap::Id, - BakedMap::AmbientOcclusion, - BakedMap::Curvature, - BakedMap::Position, - BakedMap::Thickness, - ] - .into_iter() - .collect(), - use_low_as_high: true, - max_frontal: 0.01, - max_rear: 0.01, - average_normals: true, - matching: BakeMatch::Always, - low_suffix: "_low".into(), - high_suffix: "_high".into(), - } - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum NormalMixing { #[default] @@ -330,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")] @@ -399,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 @@ -443,6 +160,7 @@ impl TextureSet { baked: BTreeSet::new(), visible: true, uv_tiles: Vec::new(), + bake_excluded_tiles: BTreeSet::new(), tile_resolutions: BTreeMap::new(), } } @@ -452,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 { @@ -673,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, @@ -690,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(), @@ -1027,34 +755,21 @@ mod tests { } #[test] - fn per_map_bake_settings_round_trip_and_old_projects_load() { - let mut p = project(); - let b = &mut p.texture_sets[0].bake; - b.ao = RaySettings { rays: 96, max_distance: 0.4, spread: 120.0, distribution: RayDistribution::Uniform }; - b.ao_ignore_backface = true; - b.ao_self_occlusion = SelfOcclusion::SameMeshName; - b.thickness.spread = 60.0; - b.bent_normal.rays = 8; - b.curvature_radius = 3; - b.position_mode = PositionMode::BoundingSphere; - b.direction_mode = DirectionMode::Positive; - let json = serde_json::to_string(&p).unwrap(); - assert_eq!(serde_json::from_str::(&json).unwrap(), p); - // Settings saved before per-map rays (one shared ray count) load with the defaults. - let mut v: serde_json::Value = serde_json::from_str(&json).unwrap(); - let old = v["texture_sets"][0]["bake"].as_object_mut().unwrap(); - for k in ["ao", "ao_ignore_backface", "ao_self_occlusion", "thickness", "bent_normal", "curvature_radius", "position_mode", "direction_mode"] { - old.remove(k); - } - old.insert("rays".into(), 64.into()); - old.insert("max_distance".into(), 0.3.into()); - let back: Project = serde_json::from_value(v).unwrap(); - let d = BakeSettings::default(); - let b = &back.texture_sets[0].bake; - assert_eq!( - (b.ao, b.thickness, b.bent_normal, b.ao_self_occlusion, b.position_mode), - (d.ao, d.thickness, d.bent_normal, d.ao_self_occlusion, d.position_mode) - ); + fn per_map_bake_settings_round_trip() { + use crate::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; + + let mut project = project(); + let settings = &mut project.texture_sets[0].bake; + settings.maps.ao.parameters.rays = + RaySettings { rays: 96, max_distance: 0.4, spread: 120.0, distribution: RayDistribution::Uniform, ..RaySettings::default() }; + settings.maps.ao.parameters.ignore_backface = BackfaceMode::Always; + settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + settings.maps.thickness.parameters.rays.spread = 60.0; + settings.maps.bent_normal.parameters.rays.rays = 8; + settings.maps.position.parameters.normalization = PositionMode::BoundingSphere; + + let json = serde_json::to_string(&project).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), project); } #[test] diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs new file mode 100644 index 00000000..800efd98 --- /dev/null +++ b/crates/core/tests/bake_settings.rs @@ -0,0 +1,192 @@ +#![recursion_limit = "256"] + +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; +use texturecraft_core::{self as bake, BakedMap, Project, TextureSet}; + +#[test] +fn reference_defaults_cover_common_and_per_map_settings() { + let rays = json!({ + "rays": 64, "min_distance": 0.00001, "max_distance": 1.0, + "relative_to_bounding_box": true, "spread": 180.0, "distribution": "Cosine" + }); + let mut thickness_rays = rays.clone(); + thickness_rays["max_distance"] = json!(0.1); + let mut expected = json!({ + "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 1, "apply_diffusion": true}, + "high_poly": {"match_mode": "Always", "use_low_as_high": false, "ignore_backface": true, "low_suffix": "_low", "high_suffix": "_high", "ignore_backface_suffix": "_ignorebf"}, + "cage": {"kind": "DistanceBased", "max_frontal": 0.01, "max_rear": 0.01, "relative_to_bounding_box": true, "average_normals": true}, + "skew": {"method": "MeshNormalsBased", "edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5}, + "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": "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} + }, + "position": {"axis": "All", "normalization": "BoundingSphere", "scale": "FullScene"}, + "thickness": {"rays": thickness_rays, "self_occlusion": "Always", "normalization": "RelativeToMinMax"}, + "height": {"normalization": "RelativeToLowMesh", "scaling_divisor": 1.0}, + "bent_normal": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always"} + }); + + let mut maps = serde_json::Map::new(); + for key in ["id", "ao", "curvature", "position", "thickness", "height", "bent_normal"] { + let parameters = expected.as_object_mut().unwrap().remove(key).unwrap(); + maps.insert(key.into(), json!({"is_enabled": !["height", "bent_normal"].contains(&key), "parameters": parameters})); + } + for key in ["normal", "world_normal", "opacity"] { + maps.insert(key.into(), json!({"is_enabled": key != "opacity", "parameters": null})); + } + expected["maps"] = Value::Object(maps); + + // Normalize the expected JSON floats to f32 before comparing every value + let decoded: bake::BakeSettings = serde_json::from_value(expected.clone()).unwrap(); + assert_eq!(bake::BakeSettings::default(), decoded); + assert_eq!(serde_json::from_str::("{}").unwrap(), decoded); + assert_eq!(decoded.common.output_size(), (2048, 2048)); + + fn assert_shape(actual: &Value, expected: &Value) { + if let (Some(actual), Some(expected)) = (actual.as_object(), expected.as_object()) { + assert_eq!(actual.keys().collect::>(), expected.keys().collect::>()); + for (key, expected) in expected { + assert_shape(&actual[key], expected); + } + } + } + + 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); + } +} + +fn assert_choices(choices: &[T]) { + for choice in choices { + let encoded = serde_json::to_value(choice).unwrap(); + assert!(encoded.is_string()); + assert_eq!(serde_json::from_value::(encoded).unwrap(), *choice); + } + + for invalid in [json!(true), json!(false), json!(1), json!(3), json!("invalid")] { + assert!(serde_json::from_value::(invalid).is_err()); + } +} + +#[test] +fn all_dropdowns_store_enum_choices() { + assert_choices(&[bake::MeshMatchMode::Always, bake::MeshMatchMode::ByMeshName]); + assert_choices(&[bake::SkewCorrectionMethod::MeshNormalsBased, bake::SkewCorrectionMethod::FaceNormalsBased]); + assert_choices(&bake::BakeResolution::ALL); + assert_choices(&bake::BakeAntialiasing::ALL); + assert_choices(&[bake::CageType::DistanceBased, bake::CageType::CustomFile]); + assert_choices(&[bake::CurvatureMethod::NormalMap, bake::CurvatureMethod::Mesh]); + assert_choices(&[ + bake::IdColorSource::VertexColor, + bake::IdColorSource::MaterialColor, + bake::IdColorSource::FileId, + bake::IdColorSource::MeshId, + bake::IdColorSource::Submesh, + ]); + assert_choices(&[bake::IdColorGenerator::Random, bake::IdColorGenerator::HueShift, bake::IdColorGenerator::Grayscale]); + assert_choices(&[bake::RayDistribution::Uniform, bake::RayDistribution::Cosine]); + assert_choices(&[bake::BackfaceMode::Never, bake::BackfaceMode::Always, bake::BackfaceMode::ByMeshName]); + assert_choices(&[bake::SelfOcclusion::Always, bake::SelfOcclusion::SameMeshName]); + assert_choices(&[bake::AmbientOcclusionAttenuation::None, bake::AmbientOcclusionAttenuation::Smooth, bake::AmbientOcclusionAttenuation::Linear]); + assert_choices(&[bake::PositionAxis::All, bake::PositionAxis::X, bake::PositionAxis::Y, bake::PositionAxis::Z]); + assert_choices(&[bake::PositionMode::BoundingBox, bake::PositionMode::BoundingSphere, bake::PositionMode::None]); + assert_choices(&[bake::PositionNormalizationScale::PerMaterial, bake::PositionNormalizationScale::FullScene]); + assert_choices(&[bake::ThicknessNormalization::RelativeToRayDistances, bake::ThicknessNormalization::RelativeToMinMax, bake::ThicknessNormalization::None]); + assert_choices(&[ + bake::HeightNormalization::RelativeToRayDistances, + bake::HeightNormalization::RelativeToLowMesh, + bake::HeightNormalization::RelativeToMinMax, + bake::HeightNormalization::Manual, + ]); +} + +#[test] +fn components_keep_their_own_defaults() { + let settings: bake::BakeSettings = serde_json::from_value(json!({ + "common": {}, "cage": {}, "high_poly": {}, "skew": {}, + "maps": { + "ao": {"is_enabled": true, "parameters": {"ground_plane": {}}}, + "curvature": {"is_enabled": true, "parameters": {"normal_map": {}, "mesh": {}}} + } + })) + .unwrap(); + assert_eq!(settings, bake::BakeSettings::default()); + assert_eq!(settings.maps.thickness.parameters.rays.max_distance, 0.1); +} + +#[test] +fn nested_settings_round_trip_per_texture_set() { + let mut settings = bake::BakeSettings::default(); + settings.common.resolution = bake::BakeResolution::R16; + settings.common.resolution_height = Some(bake::BakeResolution::R8192); + settings.common.antialiasing = bake::BakeAntialiasing::Subsampling8x8; + settings.common.apply_diffusion = false; + settings.high_poly.ignore_backface_suffix = "_two_sided".into(); + settings.cage.kind = bake::CageType::CustomFile; + settings.skew.edge_protection = true; + settings.maps.id.parameters.source = bake::IdColorSource::Submesh; + settings.maps.id.parameters.generator = bake::IdColorGenerator::Grayscale; + settings.maps.ao.parameters.ignore_backface = bake::BackfaceMode::ByMeshName; + settings.maps.ao.parameters.ground_plane = bake::GroundPlaneSettings { enabled: true, offset: 5.0 }; + settings.maps.curvature.parameters.method = bake::CurvatureMethod::Mesh; + settings.maps.curvature.parameters.normal_map.details = 0.25; + settings.maps.curvature.parameters.mesh.sampling_radius = 0.25; + settings.maps.curvature.parameters.mesh.auto_tonemapping = false; + settings.maps.position.parameters.axis = bake::PositionAxis::Z; + settings.maps.position.parameters.normalization = bake::PositionMode::None; + settings.maps.thickness.parameters.normalization = bake::ThicknessNormalization::None; + settings.maps.height.parameters.normalization = bake::HeightNormalization::Manual; + settings.maps.height.parameters.scaling_divisor = 2.0; + settings.maps.bent_normal.parameters.ignore_backface = bake::BackfaceMode::ByMeshName; + + let mut project = Project::new("Bake options", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, 128)); + project.texture_sets.push(TextureSet::new("B", 1, 128)); + project.texture_sets[0].bake = settings; + + let reloaded: Project = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap(); + assert_eq!(project, reloaded); + assert_eq!(reloaded.texture_sets[0].bake.common.output_size(), (16, 8192)); + assert_eq!(reloaded.texture_sets[1].bake, bake::BakeSettings::default()); +} + +#[test] +fn malformed_settings_are_rejected() { + for invalid in [ + json!({"maps": {"ao": {"is_enabled": "yes", "parameters": {}}}}), + json!({"maps": {"ao": {"is_enabled": true, "parameters": {"rays": {"min_distance": "bad"}}}}}), + json!({"common": {"resolution_height": -1}}), + json!({"maps": {"curvature": {"is_enabled": true, "parameters": {"method": true}}}}), + Value::Null, + ] { + assert!(serde_json::from_value::(invalid).is_err()); + } +} + +#[test] +fn map_enablement_is_owned_by_each_map() { + let mut settings = bake::BakeSettings::default(); + settings.maps.ao.parameters.rays.rays = 23; + settings.maps.ao.is_enabled = false; + settings.maps.height.is_enabled = true; + assert!(!settings.maps.enabled().any(|map| map == BakedMap::AmbientOcclusion)); + assert!(settings.maps.enabled().any(|map| map == BakedMap::Height)); + + let encoded = serde_json::to_value(&settings).unwrap(); + assert_eq!(encoded["maps"]["ao"]["is_enabled"], false); + assert!(encoded.get("selection").is_none()); + let mut reloaded: bake::BakeSettings = serde_json::from_value(encoded).unwrap(); + assert_eq!(reloaded, settings); + + reloaded.maps.select([BakedMap::AmbientOcclusion]); + assert_eq!(reloaded.maps.enabled().collect::>(), [BakedMap::AmbientOcclusion]); + assert!(reloaded.maps.ao.is_enabled); + assert_eq!(reloaded.maps.ao.parameters.rays.rays, 23); +} diff --git a/crates/engine/src/auto_rebake.rs b/crates/engine/src/auto_rebake.rs deleted file mode 100644 index 8c37a83b..00000000 --- a/crates/engine/src/auto_rebake.rs +++ /dev/null @@ -1,209 +0,0 @@ -//! Auto-rebake: one mesh map that bakes itself again when what it was baked from changes. -//! -//! The map is chosen with `bake.autoRebake`. From then on, [`Session::auto_rebake_due`] names the -//! texture sets whose bake inputs (the set's bake settings except the list of maps, the low poly, -//! the high polys, the cage and the skew map) differ from those of their last bake of that map. -//! The apps poll it each frame and bake the due sets in the background; `bake.autoRebake.run` -//! does the same thing once, blocking, for agents and scripts. -//! -//! A set only takes part once it has the map baked at its current output size: Auto-rebake -//! keeps a bake up to date, it doesn't start one, and it never leaves a set's maps at two sizes. -//! The choice isn't part of the project. - -use std::collections::BTreeMap; -use std::collections::hash_map::DefaultHasher; -use std::hash::{Hash, Hasher}; -use std::sync::{Arc, Weak}; - -use serde_json::{Value, json}; -use texturecraft_bake::Progress; -use texturecraft_core::BakedMap; - -use crate::bake_cmds::BakeTask; -use crate::commands::{CommandSpec, always, bad, boolp}; -use crate::{Result, Session, cmd}; - -/// Which map rebakes itself, and what each texture set was last baked from. -#[derive(Clone, Debug, Default)] -pub struct AutoRebake { - pub map: Option, - /// Fingerprint of each set's bake inputs when it last baked [`AutoRebake::map`]. - seen: BTreeMap, - /// Fingerprint taken when a set's bake started, kept when that bake finishes. - pending: BTreeMap, - /// What each map image in use was baked from. Undo and redo bring back an older image; its own - /// entry says its inputs no longer match. Weak, so a freed image doesn't linger and its - /// address can't be taken by a new one. - origin: Vec<(Weak>, u64)>, -} - -impl AutoRebake { - fn remember(&mut self, image: &Arc>, key: u64) { - self.origin.retain(|(w, _)| w.strong_count() > 0); - self.origin.retain(|(w, _)| !std::ptr::eq(w.as_ptr(), Arc::as_ptr(image))); - self.origin.push((Arc::downgrade(image), key)); - } - - fn origin_of(&self, image: &Arc>) -> Option { - self.origin.iter().find(|(w, _)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(image))).map(|(_, k)| *k) - } -} - -pub fn specs() -> Vec { - vec![ - cmd!( - "bake.autoRebake", - "Auto-rebake", - [], - None, - "{map?: map id (e.g. \"normal_base\", \"height\") to keep up to date, or null / off: true to turn it off; no params: just report} → {map, due: [texture sets that need a rebake]}", - always, - auto_rebake - ), - cmd!( - "bake.autoRebake.run", - "Run Auto-rebake", - [], - None, - "{cpu?: true (skip the GPU)} → {rebaked: [texture sets]}: bakes the Auto-rebake map of every set whose bake inputs changed since it was last baked, now", - always, - auto_rebake_run - ), - ] -} - -impl Session { - /// A fingerprint of everything a bake of texture set `ts` is made from, except which maps it - /// makes. - pub fn bake_inputs_key(&self, ts: usize) -> Option { - let set = self.doc.project.texture_sets.get(ts)?; - let mut settings = set.bake.clone(); - settings.maps.clear(); - settings.enabled = true; - let mut h = DefaultHasher::new(); - serde_json::to_string(&settings).ok()?.hash(&mut h); - (Arc::as_ptr(&self.mesh) as usize).hash(&mut h); - for m in &self.bake_meshes.high { - (Arc::as_ptr(&m.mesh) as usize).hash(&mut h); - } - self.bake_meshes.cage.as_ref().map(|c| Arc::as_ptr(&c.mesh) as usize).hash(&mut h); - (self.bake_meshes.skew.is_some(), self.bake_meshes.skew_rev).hash(&mut h); - Some(h.finish()) - } - - /// Texture sets whose Auto-rebake map is out of date. A set seen for the first time (a project - /// just opened, a bake from before Auto-rebake was on) is taken as up to date. - pub fn auto_rebake_due(&mut self) -> Vec { - let Some(map) = self.auto_rebake.map else { return Vec::new() }; - let mut due = Vec::new(); - for ts in 0..self.doc.project.texture_sets.len() { - let Some(set) = self.doc.project.texture_sets.get(ts).filter(|t| t.bake.enabled) else { continue }; - let columns = set.tile_grid().map_or(1, |g| g.cols); - let baked = self.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map) && b.resolution == set.bake.resolution.saturating_mul(columns)); - let Some(key) = self.bake_inputs_key(ts).filter(|_| baked) else { continue }; - let image = self.doc.baked.get(&ts).and_then(|b| b.maps.get(&map)).cloned(); - // An image whose inputs are known is judged by them (this is what undo is caught by); - // one not seen before is taken as up to date, like a project just opened. - match (image.as_ref().and_then(|i| self.auto_rebake.origin_of(i)), self.auto_rebake.seen.get(&ts)) { - (Some(made_from), _) if made_from != key => due.push(ts), - (Some(_), _) => {} - (None, Some(seen)) if *seen != key => due.push(ts), - (None, Some(_)) => {} - (None, None) => { - self.auto_rebake.seen.insert(ts, key); - if let Some(image) = &image { - self.auto_rebake.remember(image, key); - } - } - } - } - due - } - - /// Call right before building the bake task of `ts`: remembers what it is baked from, so a - /// finished bake of the Auto-rebake map marks the set up to date (and a change made while it - /// ran still triggers another). - pub fn begin_bake(&mut self, ts: usize) { - if let Some(key) = self.bake_inputs_key(ts) { - self.auto_rebake.pending.insert(ts, key); - } - } - - /// The bake task of `ts` restricted to one map (Auto-rebake's: the other maps stay as they are). - pub fn bake_task_for(&self, ts: usize, only: Option) -> Result { - let mut task = self.bake_task(ts)?; - if let Some(m) = only { - task.settings.maps = std::iter::once(m).collect(); - } - Ok(task) - } - - /// Records a finished bake: when it made the Auto-rebake map, the set is up to date. - pub(crate) fn note_baked(&mut self, ts: usize, mut made: impl Iterator) { - let key = self.auto_rebake.pending.remove(&ts); - if let (Some(key), Some(map)) = (key, self.auto_rebake.map) - && made.any(|m| m == map) - { - self.auto_rebake.seen.insert(ts, key); - if let Some(image) = self.doc.baked.get(&ts).and_then(|b| b.maps.get(&map)).cloned() { - self.auto_rebake.remember(&image, key); - } - } - } - - /// Records bakes of `sets` that were cancelled, failed or never started: Auto-rebake leaves - /// those sets alone until their bake inputs change again, instead of retrying every frame. - pub fn bake_abandoned(&mut self, sets: impl IntoIterator) { - for ts in sets { - if let Some(key) = self.auto_rebake.pending.remove(&ts).or_else(|| self.bake_inputs_key(ts)) { - self.auto_rebake.seen.insert(ts, key); - // The map as it stands is left alone for these inputs. - let image = self.auto_rebake.map.and_then(|m| self.doc.baked.get(&ts)?.maps.get(&m).cloned()); - if let Some(image) = image { - self.auto_rebake.remember(&image, key); - } - } - } - } - - /// Bakes every due set's Auto-rebake map now (blocking); returns the sets. - pub fn auto_rebake_now(&mut self, cpu: bool) -> Result> { - let due = self.auto_rebake_due(); - let map = self.auto_rebake.map; - for &ts in &due { - self.begin_bake(ts); - let mut task = self.bake_task_for(ts, map)?; - if cpu { - task.tracer = None; - } - let out = task.run(&Progress::new())?; - self.apply_bake(ts, out)?; - } - Ok(due) - } -} - -fn state(s: &mut Session) -> Value { - json!({ "map": s.auto_rebake.map.map(BakedMap::id), "due": s.auto_rebake_due() }) -} - -fn auto_rebake(s: &mut Session, p: &Value) -> Result { - if boolp(p, "off") == Some(true) || p.get("map").is_some_and(Value::is_null) { - s.auto_rebake = AutoRebake::default(); - } else if let Some(id) = p.get("map") { - let map = id.as_str().and_then(BakedMap::parse).ok_or_else(|| bad("bake.autoRebake", format!("unknown mesh map {id}")))?; - if s.auto_rebake.map != Some(map) { - s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() }; - } - } - Ok(state(s)) -} - -fn auto_rebake_run(s: &mut Session, p: &Value) -> Result { - if s.auto_rebake.map.is_none() { - return Err(bad("bake.autoRebake.run", "no Auto-rebake map is set; run bake.autoRebake {map} first")); - } - let rebaked = s.auto_rebake_now(boolp(p, "cpu") == Some(true))?; - s.update(); - Ok(json!({ "rebaked": rebaked })) -} 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..be6eef7c --- /dev/null +++ b/crates/engine/src/bake/bake_cage_inputs.rs @@ -0,0 +1,55 @@ +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()) + } + + /// Whether this set uses the session's shared low mesh + pub fn uses_mesh(&self, mesh: &Arc) -> bool { + Arc::ptr_eq(&self.mesh, mesh) + } + + /// Build a cage from edges shared across sets using the same low mesh + pub fn cage_shell_with_edges(&self, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result { + CageShell::new_with_edges(&self.request(), wire_edges, missing_seam_edges) + } + + /// 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_checks.rs b/crates/engine/src/bake/bake_checks.rs new file mode 100644 index 00000000..3ea93729 --- /dev/null +++ b/crates/engine/src/bake/bake_checks.rs @@ -0,0 +1,109 @@ +//! What can spoil a texture set's bake, checked before it runs: overlapping UVs and parts "By Mesh Name" leaves unpaired + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_bake::NamePair; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::{Mesh, SubMesh, UvGBuffer, glam::Vec2}; + +use crate::{Result, Session}; + +/// Side of the UV raster the overlap check counts texels on, per UV tile (as mesh import does) +const OVERLAP_CHECK_RESOLUTION: u32 = 512; + +/// The only material of the UV-only mesh the overlap check builds per UV tile +const BLOCK_MATERIAL: usize = 0; + +impl Session { + /// About the share (0..1) of texture set `texture_set`'s UV layout the bake sees covered more than once, over the UV tiles it bakes: a texel under three triangles counts twice + pub fn bake_uv_overlap(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + let mesh = self.bake_mesh(texture_set)?; + let (overlaps, covered) = match set.tile_grid() { + Some(grid) => { + let baked_blocks: BTreeSet<(u32, u32)> = + set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid.block(*tile)).collect(); + let blocks = triangles_by_block(&mesh, set.material, (grid.cols, grid.rows), &baked_blocks); + blocks + .values() + .map(|block| overlap_counts(block, BLOCK_MATERIAL)) + .fold((0, 0), |(overlaps, covered), (block_overlaps, block_covered)| (overlaps + block_overlaps, covered + block_covered)) + } + None => overlap_counts(&mesh, set.material), + }; + + Ok(if covered == 0 { 0.0 } else { (overlaps as f32 / covered as f32).min(1.0) }) + } + + /// How texture set `texture_set`'s low-poly parts pair with the high-poly parts ([`NamePair::list`]); `None` unless it bakes from a high poly "By Mesh Name" + pub fn bake_name_pairs(&self, texture_set: usize) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let settings = &set.bake.high_poly; + let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); + + Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings))) + } + + /// The high-poly parts none of `texture_sets` bakes from, by name: a set matching "Always" bakes from every part, one matching "By Mesh Name" only from the parts its names pair with + pub fn bake_unpaired_high_parts(&self, texture_sets: &[usize]) -> Result> { + let (mut paired, mut unpaired) = (BTreeSet::new(), BTreeSet::new()); + for &texture_set in texture_sets { + let settings = &self.doc.project.texture_set(texture_set)?.bake.high_poly; + if !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always { + return Ok(Vec::new()); + } + + for pair in self.bake_name_pairs(texture_set)?.unwrap_or_default() { + match pair { + NamePair { low: Some(_), high: Some(high) } => paired.insert(high), + NamePair { low: None, high: Some(high) } => unpaired.insert(high), + _ => false, + }; + } + } + + Ok(unpaired.difference(&paired).cloned().collect()) + } +} + +/// Texels covered more than once and texels covered, rasterizing material `material`'s UVs over 0..1 +fn overlap_counts(mesh: &Mesh, material: usize) -> (usize, usize) { + let gbuffer = UvGBuffer::new(mesh, material, OVERLAP_CHECK_RESOLUTION, OVERLAP_CHECK_RESOLUTION); + (gbuffer.overlaps as usize, gbuffer.covered_count()) +} + +/// Material `material`'s triangles sorted into the `baked_blocks` of a `grid` (columns, rows) atlas their UVs reach, one UV-only mesh per block with the block's UVs over 0..1: a single pass, however many blocks +fn triangles_by_block(mesh: &Mesh, material: usize, grid: (u32, u32), baked_blocks: &BTreeSet<(u32, u32)>) -> BTreeMap<(u32, u32), Mesh> { + let scale = Vec2::new(grid.0 as f32, grid.1 as f32); + let mut blocks: BTreeMap<(u32, u32), Mesh> = BTreeMap::new(); + for triangle in mesh.triangles_of(material) { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(first_uv), Some(second_uv), Some(third_uv)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { continue }; + let uvs = [*first_uv * scale, *second_uv * scale, *third_uv * scale]; + + // Every block the triangle's UV bounds touch, so a triangle across a border counts in both + let (uv_min, uv_max) = uvs.iter().fold((Vec2::INFINITY, Vec2::NEG_INFINITY), |(uv_min, uv_max), uv| (uv_min.min(*uv), uv_max.max(*uv))); + + // Capped at the grid: a stray huge UV must not walk billions of blocks + let columns = uv_min.x.floor().max(0.0) as u32..=((uv_max.x.ceil() as u32).saturating_sub(1)).min(grid.0 - 1); + let rows = uv_min.y.floor().max(0.0) as u32..=((uv_max.y.ceil() as u32).saturating_sub(1)).min(grid.1 - 1); + for column in columns { + for row in rows.clone() { + if !baked_blocks.contains(&(column, row)) { + continue; + } + + let block = blocks.entry((column, row)).or_insert_with(|| Mesh { materials: vec![String::new()], ..Mesh::default() }); + let offset = Vec2::new(column as f32, row as f32); + block.indices.extend(block.uvs.len() as u32..block.uvs.len() as u32 + 3); + block.uvs.extend(uvs.iter().map(|uv| *uv - offset)); + } + } + } + + for block in blocks.values_mut() { + block.submeshes = vec![SubMesh { name: String::new(), material: BLOCK_MATERIAL, start: 0, count: block.indices.len() as u32 }]; + } + + blocks +} diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs new file mode 100644 index 00000000..0d4d5ffe --- /dev/null +++ b/crates/engine/src/bake/bake_mesh.rs @@ -0,0 +1,12 @@ +use std::sync::Arc; +use texturecraft_geom::{BaseColor, Mesh}; + +/// A mesh file the baker reads (high poly or cage): its name, original bytes (saved in the +/// project), parsed mesh and its materials' base colors (high polys). +#[derive(Clone, Debug)] +pub struct BakeMesh { + pub name: String, + pub bytes: Arc>, + pub mesh: Arc, + pub base_color: Vec>>, +} diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs new file mode 100644 index 00000000..da0e4a97 --- /dev/null +++ b/crates/engine/src/bake/bake_meshes.rs @@ -0,0 +1,34 @@ +use super::{BakeMesh, MergedHigh}; +use std::sync::{Arc, OnceLock}; +use texturecraft_geom::{Bvh, Mesh}; + +/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the +/// undo history. +#[derive(Clone, Debug, Default)] +pub struct BakeMeshes { + pub(crate) low_base_color: OnceLock>, + pub high: Vec, + pub cage: Option, + /// Every high poly appended into one mesh (rebuilt when the list changes). + pub(crate) merged: Option, +} + +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()); + for (file_index, source) in self.high.iter().enumerate() { + file_ids.extend(std::iter::repeat_n(file_index as u32, source.mesh.submeshes.len())); + mesh.append(&source.mesh); + base_color.extend(source.base_color.iter().cloned().chain(std::iter::repeat(None)).take(source.mesh.materials.len())); + } + let bvh = Bvh::new(&mesh); + MergedHigh { file_ids: Arc::new(file_ids), mesh: Arc::new(mesh), bvh: Arc::new(bvh), base_color: Arc::new(base_color) } + }); + } +} diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs new file mode 100644 index 00000000..24629b56 --- /dev/null +++ b/crates/engine/src/bake/bake_task.rs @@ -0,0 +1,216 @@ +use super::{MergedHigh, StreamedBake, StreamedMap}; +use crate::{EngineError, Result}; +use std::sync::Arc; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakeSettings, BakedMap}; +use texturecraft_geom::{Bvh, Mesh}; + +/// A self-contained bake task that can run on another thread. +pub struct BakeTask { + pub low_base_color: super::MaterialColors, + pub ts: usize, + pub mesh: Arc, + pub bvh: Arc, + pub material: usize, + pub settings: BakeSettings, + /// The merged high polys, unless the set bakes from the low poly. + pub high: Option, + pub cage: Option>, + pub skew: Option>, + 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>, +} + +impl BakeTask { + /// The maps this task makes, in the order [`BakeTask::run_streaming`] finishes them + pub fn maps(&self) -> Vec { + self.settings.maps.enabled().collect() + } + + /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded, + /// and return all of them together. Each map is a bake of its own, so with a high poly + /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several + /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s. + /// The handed-over buffers are the returned ones too (no copy is made), so a preview that + /// keeps them costs no second set of maps. A cancel or an error leaves the maps already + /// handed over whole. + pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result { + let maps = self.maps(); + let total = maps.len(); + let mut combined: Option = None; + + for (index, map) in maps.iter().copied().enumerate() { + let mut settings = self.settings.clone(); + settings.maps.select([map]); + let mut output = self.run_with(&settings, progress)?; + let Some(data) = output.maps.remove(&map) else { continue }; + if combined.is_none() { + // Retain unchecked maps once, using the full selection rather than this one-map pass. + super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?; + } + + let data = Arc::new(data); + on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() }); + match &mut combined { + Some(combined) => { + combined.maps.insert(map, data); + } + None => { + // A resized partial bake also returns unchecked maps that must survive application + let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); + retained.insert(map, data); + combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer }); + } + } + } + + match combined { + Some(output) => Ok(output), + None => { + let output = self.run(progress)?; + Ok(StreamedBake { + resolution: output.resolution, + height: output.height, + maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), + tracer: output.tracer, + }) + } + } + } + + pub fn run(&self, progress: &Progress) -> Result { + let mut output = self.run_with(&self.settings, progress)?; + super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?; + Ok(output) + } + + fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result { + let high = + self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color }); + let request = BakeRequest { + low_base_color: &self.low_base_color, + mesh: &self.mesh, + bvh: &self.bvh, + material: self.material, + settings, + high, + cage: self.cage.as_deref(), + skew: self.skew.as_deref(), + cage_paint: self.cage_paint.as_deref(), + tiles: self.tiles, + }; + + 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) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Session, execute}; + use serde_json::json; + use texturecraft_geom::primitives; + + const PREVIOUS_MAPS: [BakedMap; 3] = [BakedMap::Normal, BakedMap::AmbientOcclusion, BakedMap::Height]; + const SELECTED_MAPS: [BakedMap; 2] = [BakedMap::AmbientOcclusion, BakedMap::Height]; + + fn partial_task(selected: &[BakedMap], resized: bool, excluded: bool) -> BakeTask { + let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 64, "rays": 2})).unwrap(); + if excluded { + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + } + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + task.settings.maps.select(selected.iter().copied()); + let (width, height) = if resized { (64, 32) } else { (128, 64) }; + task.previous_maps = BakedMaps { + resolution: width, + maps: PREVIOUS_MAPS.into_iter().map(|map| (map, Arc::new(vec![0.25; width as usize * height * map.components()]))).collect(), + }; + task + } + + #[test] + fn streaming_allocates_only_truly_unchecked_resized_maps_once() { + for (selected, resized, excluded) in [ + (SELECTED_MAPS.as_slice(), true, true), + (PREVIOUS_MAPS.as_slice(), true, true), + (SELECTED_MAPS.as_slice(), false, true), + (SELECTED_MAPS.as_slice(), true, false), + ] { + let task = partial_task(selected, resized, excluded); + let whole = task.run(&Progress::new()).unwrap(); + super::super::preserve_tiles::take_retained_allocations(); + let mut allocations = Vec::new(); + let mut handed_over = Vec::new(); + let output = task + .run_streaming(&Progress::new(), &mut |map| { + allocations.extend(super::super::preserve_tiles::take_retained_allocations()); + assert!(allocations.iter().all(|map| !selected.contains(map)), "maps scheduled to bake must never allocate retained buffers"); + handed_over.push(map); + }) + .unwrap(); + allocations.extend(super::super::preserve_tiles::take_retained_allocations()); + let expected: Vec<_> = PREVIOUS_MAPS.into_iter().filter(|map| resized && excluded && !selected.contains(map)).collect(); + assert_eq!(allocations, expected, "each truly unchecked resized map must allocate exactly once"); + assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in &whole.maps { + assert_eq!(*output.maps[map], *pixels, "{map:?} must preserve the ordinary bake's pixels"); + } + for map in handed_over { + assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]), "streaming must keep sharing the baked buffer"); + } + } + } + + #[test] + fn cancelling_a_partial_stream_does_not_resample_future_maps() { + let task = partial_task(&SELECTED_MAPS, true, true); + let whole = task.run(&Progress::new()).unwrap(); + super::super::preserve_tiles::take_retained_allocations(); + let progress = Progress::new(); + let mut handed_over = Vec::new(); + let result = task.run_streaming(&progress, &mut |map| { + handed_over.push(map); + progress.cancel(); + }); + assert!(result.is_err()); + assert_eq!(handed_over.len(), 1); + for map in handed_over { + assert_eq!(*map.data, whole.maps[&map.map], "cancellation leaves the handed-over map whole"); + } + assert_eq!(super::super::preserve_tiles::take_retained_allocations(), [BakedMap::Normal]); + } + + #[test] + fn an_empty_streaming_selection_keeps_the_ordinary_bake_behavior() { + let task = partial_task(&[], true, true); + super::super::preserve_tiles::take_retained_allocations(); + let whole = task.run(&Progress::new()); + let expected_allocations = super::super::preserve_tiles::take_retained_allocations(); + let output = task.run_streaming(&Progress::new(), &mut |_| panic!("an empty selection must not stream a map")); + assert_eq!(super::super::preserve_tiles::take_retained_allocations(), expected_allocations); + match (whole, output) { + (Ok(whole), Ok(output)) => { + assert_eq!((output.resolution, output.height), (whole.resolution, whole.height)); + assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in whole.maps { + assert_eq!(*output.maps[&map], pixels); + } + } + (Err(whole), Err(output)) => assert_eq!(whole.to_string(), output.to_string()), + _ => panic!("empty streaming and ordinary bakes must agree"), + } + } +} 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..c9663ac1 --- /dev/null +++ b/crates/engine/src/bake/high_poly_missed.rs @@ -0,0 +1,34 @@ +use rayon::prelude::*; +use texturecraft_bake::HighPolyReach; + +/// The value [`high_poly_missed`] gives a vertex that `only_set` doesn't own, which the 3D view leaves out +pub const HIDDEN_HIGH_POLY_VERTEX: f32 = -1.0; + +/// Per vertex of the validated high poly: 1.0 if its owning set's bake misses it at that set's (max frontal, max rear), 0.0 if reached or unknown, [`HIDDEN_HIGH_POLY_VERTEX`] if `only_set` doesn't own it +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| { + if only_set.is_some_and(|only| !owns(reach, only, vertex)) { + return HIDDEN_HIGH_POLY_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() +} + +/// Whether texture set `texture_set`'s reach claims high-poly vertex `vertex` +fn owns(reach: &[Option], texture_set: usize, vertex: usize) -> bool { + reach.get(texture_set).and_then(Option::as_ref).and_then(|set| set.vertices.get(vertex)).is_some_and(Option::is_some) +} 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/merged_high.rs b/crates/engine/src/bake/merged_high.rs new file mode 100644 index 00000000..317bb592 --- /dev/null +++ b/crates/engine/src/bake/merged_high.rs @@ -0,0 +1,11 @@ +use std::sync::Arc; +use texturecraft_geom::{Bvh, Mesh}; + +/// Every high poly appended into one mesh, its BVH and per-material base colors. +#[derive(Clone, Debug)] +pub struct MergedHigh { + pub file_ids: Arc>, + pub mesh: Arc, + pub bvh: Arc, + pub base_color: super::MaterialColors, +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs new file mode 100644 index 00000000..f8826b44 --- /dev/null +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -0,0 +1,725 @@ +//! Mesh-map baking commands (the "Bake Mesh Maps" window): bake settings, the +//! 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, StreamedBake}; +use serde_json::{Value, json}; +use texturecraft_bake::tracing::Tracer; +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(super) fn specs() -> Vec { + vec![ + cmd!( + "bake.run", + "Bake mesh maps", + ["Mode"], + None, + "{ts?: index|[indices]|\"all\"|\"selected\", cpu?: true (skip the GPU), ...any bake.settings parameter} → {baked, tracer: [where each set's rays ran]}", + always, + bake_run + ), + cmd!( + "bake.settings", + "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, 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 + ), + cmd!( + "bake.highPoly.add", + "Add high definition mesh", + [], + None, + "{path} — a mesh file (glb, gltf, fbx, dae, usd, usda, usdc, usdz, abc, obj, ply, stl; base color textures from glTF, embedded FBX media, usdz packages and image files next to a .gltf or USD layer supply opacity)", + always, + high_add + ), + cmd!("bake.highPoly.remove", "Remove high definition mesh", [], None, "{index? | name? | all?: true}", always, high_remove), + cmd!("bake.highPoly.list", "List high definition meshes", [], None, "{}", always, |s, _| Ok(meshes_json(s))), + cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set), + cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| { + s.bake_meshes.cage = None; + s.modified = true; + Ok(meshes_json(s)) + }), + ] +} + +/// A mesh file as saved in a project: (file name, bytes). +type MeshFile = (String, Vec); + +static GPU_TRACER: OnceLock> = OnceLock::new(); + +/// Cast bake rays with `tracer` (the apps install the render crate's GPU baker at start-up); +/// the first call wins. +pub fn install_gpu_tracer(tracer: Arc) { + let _ = GPU_TRACER.set(tracer); +} + +/// A mesh file name made unique among `taken` (and safe as a project file entry). +fn unique_name(file_name: &str, taken: &[&str]) -> String { + let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh"); + let base = texturecraft_formats::sanitize_resource_name(leaf); + let mut name = base.clone(); + let mut n = 2; + while taken.contains(&name.as_str()) { + name = format!("{n}_{base}"); + n += 1; + } + name +} + +fn parse_mesh(file_name: &str, bytes: Vec) -> Result { + let h = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; + let base_color = h.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); + Ok(BakeMesh { name: file_name.to_string(), bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color }) +} + +impl Session { + 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()) { + self.bake_meshes + .low_base_color + .get_or_init(|| match &self.mesh_source { + Some((extension, bytes)) => texturecraft_formats::import_high_poly_bytes(&format!("mesh.{extension}"), bytes) + .map(|imported| Arc::new(imported.base_color.into_iter().map(|color| color.map(Arc::new)).collect())) + .map_err(|error| error.to_string()), + None => Ok(Arc::new(Vec::new())), + }) + .clone() + .map_err(EngineError::Other)? + } else { + Arc::new(Vec::new()) + }; + + 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: texture_set, + mesh: self.bake_mesh(texture_set)?, + bvh: self.bvh.clone(), + material: set.material, + settings: set.bake.clone(), + high, + cage, + 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 steers = has_high && (target != BakePaintTarget::Skew || set.bake.skew_applies()); + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| steers); + 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 + pub(super) 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(); + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?; + self.log.push(format!("Baked texture set {texture_set} ({tracer})")); + Ok(()) + } + + /// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the + /// preview that showed them holds the same ones) + pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { + let tracer = output.tracer.clone(); + self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?; + self.log.push(format!("Baked texture set {texture_set} ({tracer})")); + Ok(()) + } + + fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); + self.store_bake_maps(texture_set, output.resolution, output.height, maps) + } + + fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap>>) -> Result<()> { + let entry = self.doc.baked.entry(texture_set).or_default(); + if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) { + entry.maps.clear(); + } + + entry.resolution = resolution; + entry.maps.extend(maps); + self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); + Ok(()) + } + + /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. + pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { + let mut task = self.bake_task(ts)?; + if cpu { + task.tracer = None; + } + let out = task.run(&Progress::new())?; + let tracer = out.tracer.clone(); + self.apply_bake(ts, out)?; + Ok(tracer) + } + + /// Add a high-definition mesh from file bytes (the web picker, the desktop dialog and + /// `bake.highPoly.add`); every texture set then bakes from the high polys. Returns its name. + pub fn add_high_poly_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + let mut m = parse_mesh(file_name, bytes)?; + let taken: Vec<&str> = self.bake_meshes.high.iter().map(|h| h.name.as_str()).collect(); + m.name = unique_name(file_name, &taken); + let textures = m.base_color.iter().flatten().filter(|c| !c.texels.is_empty()).count(); + self.log.push(format!("High poly {}: {} triangles, {textures} base color textures", m.name, m.mesh.triangle_count())); + let name = m.name.clone(); + self.bake_meshes.high.push(m); + self.bake_meshes.rebuild(); + for set in &mut self.doc.project.texture_sets { + set.bake.high_poly.use_low_as_high = false; + } + self.modified = true; + Ok(name) + } + + /// Remove high-definition mesh `index`. + pub fn remove_high_poly(&mut self, index: usize) -> Result { + if index >= self.bake_meshes.high.len() { + return Err(EngineError::Other(format!("no high poly mesh {index}"))); + } + let removed = self.bake_meshes.high.remove(index); + self.bake_meshes.rebuild(); + self.modified = true; + Ok(removed) + } + + /// Use a cage mesh (same triangles as the low poly) from file bytes. + pub fn set_cage_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + let mut m = parse_mesh(file_name, bytes)?; + if m.mesh.triangle_count() != self.mesh.triangle_count() { + return Err(EngineError::Other(format!( + "the cage has {} triangles but the low poly has {}; export the cage from the low poly", + m.mesh.triangle_count(), + self.mesh.triangle_count() + ))); + } + m.name = unique_name(file_name, &[]); + m.base_color.clear(); + let name = m.name.clone(); + self.bake_meshes.cage = Some(m); + self.modified = true; + Ok(name) + } + + /// Add mesh file `f` as a high-definition mesh, or set it as the cage, logging what it could + /// not fold in. Replies like `bake.highPoly.add` / `bake.cage.set`: `{name, meshes}`. + pub fn add_bake_mesh(&mut self, f: texturecraft_formats::MeshFile, cage: bool) -> Result { + let name = if cage { self.set_cage_bytes(&f.name, f.bytes)? } else { self.add_high_poly_bytes(&f.name, f.bytes)? }; + self.log.extend(f.warnings); + Ok(json!({ "name": name, "meshes": meshes_json(self) })) + } + + /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped. + pub(crate) fn load_bake_meshes(&mut self, high: Vec, cage: Option) { + for (name, bytes) in high { + match parse_mesh(&name, bytes) { + Ok(m) => self.bake_meshes.high.push(m), + Err(e) => self.log.push(format!("skipped high poly mesh: {e}")), + } + } + self.bake_meshes.rebuild(); + if let Some((name, bytes)) = cage + && let Err(e) = self.set_cage_bytes(&name, bytes) + { + self.log.push(format!("skipped cage mesh: {e}")); + } + } + + pub(crate) fn load_bake_paint(&mut self, maps: BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData>) { + for (key, data) in maps { + if key.0 >= self.doc.project.texture_sets.len() { + self.log.push(format!("skipped bake paint map for missing texture set {}", key.0)); + continue; + } + let map = BakePaintMap { width: data.width, height: data.height, values: data.values }; + match map.validate() { + Ok(()) => { + self.doc.bake_paint.insert(key, Arc::new(map)); + } + Err(error) => self.log.push(format!("skipped bake paint map: {error}")), + } + } + } + + pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> { + self.doc + .bake_paint + .iter() + .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() })) + .collect() + } + + /// The bake meshes for a project file: (high polys, cage). + pub(crate) fn saved_bake_meshes(&self) -> (Vec, Option) { + let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone()); + (self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry)) + } +} + +/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`). +pub fn meshes_json(s: &Session) -> Value { + let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::>() }); + let painted = |target| s.doc.bake_paint.get(&(s.ts(), target)).map(|map| json!({ "width": map.width, "height": map.height })); + json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| { + let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0 }; + json!({"textureSet": texture_set, "target": target, "width": map.width, "height": map.height, "paintedTexels": map.values.iter().filter(|value| **value != default).count()}) + }).collect::>() }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn read_mesh_file(cmd: &str, p: &Value) -> Result { + let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?; + crate::file_cmds::read_mesh(cmd, path) +} + +#[cfg(target_arch = "wasm32")] +fn read_mesh_file(_: &str, _: &Value) -> Result { + Err(EngineError::Other("file paths are not available in the browser; use the bake panel's file picker".into())) +} + +fn high_add(s: &mut Session, p: &Value) -> Result { + s.add_bake_mesh(read_mesh_file("bake.highPoly.add", p)?, false) +} + +fn high_remove(s: &mut Session, p: &Value) -> Result { + if boolp(p, "all") == Some(true) { + s.bake_meshes.high.clear(); + s.bake_meshes.rebuild(); + s.modified = true; + return Ok(meshes_json(s)); + } + let index = match (u64p(p, "index"), strp(p, "name")) { + (Some(i), _) => usize::try_from(i).unwrap_or(usize::MAX), + (None, Some(n)) => s.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, + (None, None) => return Err(bad("bake.highPoly.remove", "`index`, `name` or `all` is required")), + }; + s.remove_high_poly(index)?; + Ok(meshes_json(s)) +} + +fn cage_set(s: &mut Session, p: &Value) -> Result { + s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true) +} + +/// Texture sets named by `ts` (default: the active one). +fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { + let n = s.set_count(); + let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}"))); + match p.get("ts") { + Some(Value::String(a)) if a == "all" => Ok((0..n).collect()), + Some(Value::String(a)) if a == "selected" => { + Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.common.is_enabled)).collect()) + } + Some(Value::Array(a)) => a.iter().map(one).collect(), + Some(v) => Ok(vec![one(v)?]), + None => Ok(vec![s.ts()]), + } +} + +/// Parameters shared by the current bake command and UI +pub fn settings_params(settings: &BakeSettings) -> Value { + let mut ao = rays_params(&settings.maps.ao.parameters.rays); + ao["ignoreBackface"] = match settings.maps.ao.parameters.ignore_backface { + BackfaceMode::Never => "never", + BackfaceMode::Always => "always", + BackfaceMode::ByMeshName => "byMeshName", + } + .into(); + ao["selfOcclusion"] = match settings.maps.ao.parameters.self_occlusion { + SelfOcclusion::Always => "always", + SelfOcclusion::SameMeshName => "sameMeshName", + } + .into(); + + json!({ + "resolution": settings.common.resolution.pixels(), + "antialiasing": settings.common.antialiasing.samples_per_axis(), + "dilation": settings.common.dilation, + "ao": ao, + "thickness": rays_params(&settings.maps.thickness.parameters.rays), + "bentNormal": rays_params(&settings.maps.bent_normal.parameters.rays), + "curvatureMethod": match settings.maps.curvature.parameters.method { CurvatureMethod::NormalMap => "normalMap", CurvatureMethod::Mesh => "mesh" }, + "positionMode": match settings.maps.position.parameters.normalization { PositionMode::BoundingBox => "boundingBox", PositionMode::BoundingSphere => "boundingSphere", PositionMode::None => "none" }, + "maps": settings.maps.enabled().map(|m| m.id()).collect::>(), + "enabled": settings.common.is_enabled, + "useLowAsHigh": settings.high_poly.use_low_as_high, + "maxFrontal": settings.cage.max_frontal, + "maxRear": settings.cage.max_rear, + "averageNormals": settings.cage.average_normals, + "lowSuffix": settings.high_poly.low_suffix, + "highSuffix": settings.high_poly.high_suffix, + }) +} + +/// Apply only the bake parameters supplied by the caller +fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> { + // Preserve the legacy flat-parameter limits for existing callers + const MAX_DILATION_PIXELS: u32 = 256; + const MAX_SUFFIX_CHARS: usize = 64; + + if let Some(model) = params.get("model") { + let replacement: BakeSettings = serde_json::from_value(model.clone()).map_err(|error| bad(command, error.to_string()))?; + validate_model_settings(&replacement, command)?; + let is_enabled = settings.common.is_enabled; + *settings = replacement; + if boolp(params, "preserveEnabled") == Some(true) { + settings.common.is_enabled = is_enabled; + } + } + + 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() + .and_then(BakeResolution::from_pixels) + .ok_or_else(|| bad(command, "resolution must be a power of two from 16 to 8192"))?; + } + + if let Some(antialiasing) = u64p(params, "antialiasing") { + settings.common.antialiasing = u32::try_from(antialiasing) + .ok() + .and_then(BakeAntialiasing::from_samples_per_axis) + .ok_or_else(|| bad(command, "antialiasing must be 1, 2, 4 or 8"))?; + } + + if let Some(dilation) = u64p(params, "dilation") { + settings.common.dilation = dilation.min(u64::from(MAX_DILATION_PIXELS)) as u32; + } + + // Per-map values override the shared ray settings + for ray_settings in [&mut settings.maps.ao.parameters.rays, &mut settings.maps.thickness.parameters.rays, &mut settings.maps.bent_normal.parameters.rays] { + apply_rays(ray_settings, params, command)?; + } + + for (key, ray_settings) in [ + ("ao", &mut settings.maps.ao.parameters.rays), + ("thickness", &mut settings.maps.thickness.parameters.rays), + ("bentNormal", &mut settings.maps.bent_normal.parameters.rays), + ] { + if let Some(map_params) = params.get(key) { + apply_rays(ray_settings, map_params, command)?; + } + } + + if let Some(ao) = params.get("ao") { + if let Some(value) = ao.get("ignoreBackface") { + let mode = value.as_str().ok_or_else(|| bad(command, "ignoreBackface must be never, always or byMeshName"))?; + settings.maps.ao.parameters.ignore_backface = match mode { + "never" => BackfaceMode::Never, + "always" => BackfaceMode::Always, + "byMeshName" => BackfaceMode::ByMeshName, + _ => return Err(bad(command, "ignoreBackface must be never, always or byMeshName")), + }; + } + + if let Some(self_occlusion) = strp(ao, "selfOcclusion") { + settings.maps.ao.parameters.self_occlusion = match self_occlusion { + "always" => SelfOcclusion::Always, + "sameMeshName" => SelfOcclusion::SameMeshName, + _ => return Err(bad(command, "selfOcclusion must be always or sameMeshName")), + }; + } + } + + if let Some(position_mode) = strp(params, "positionMode") { + settings.maps.position.parameters.normalization = match position_mode { + "boundingBox" => PositionMode::BoundingBox, + "boundingSphere" => PositionMode::BoundingSphere, + "none" => PositionMode::None, + _ => return Err(bad(command, "positionMode must be boundingBox, boundingSphere or none")), + }; + } + + if let Some(value) = params.get("curvatureMethod") { + let method = value.as_str().ok_or_else(|| bad(command, "curvatureMethod must be normalMap or mesh"))?; + settings.maps.curvature.parameters.method = match method { + "normalMap" => CurvatureMethod::NormalMap, + "mesh" => CurvatureMethod::Mesh, + _ => return Err(bad(command, "curvatureMethod must be normalMap or mesh")), + }; + } + + for (key, setting, minimum, maximum) in [("maxFrontal", &mut settings.cage.max_frontal, 0.0, 1.0), ("maxRear", &mut settings.cage.max_rear, 0.0, 1.0)] { + if let Some(value) = f32p(params, key).filter(|value| value.is_finite()) { + *setting = value.clamp(minimum, maximum); + } + } + + for (key, setting) in [ + ("enabled", &mut settings.common.is_enabled), + ("useLowAsHigh", &mut settings.high_poly.use_low_as_high), + ("averageNormals", &mut settings.cage.average_normals), + ] { + if let Some(value) = boolp(params, key) { + *setting = value; + } + } + + if let Some(maps) = params.get("maps").and_then(Value::as_array) { + let selected = maps + .iter() + .map(|map| map.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(command, format!("unknown mesh map {map}")))) + .collect::>>()?; + settings.maps.select(selected); + } + + for (key, setting) in [("lowSuffix", &mut settings.high_poly.low_suffix), ("highSuffix", &mut settings.high_poly.high_suffix)] { + if let Some(suffix) = strp(params, key) { + *setting = suffix.chars().take(MAX_SUFFIX_CHARS).collect(); + } + } + + Ok(()) +} + +fn validate_model_settings(settings: &BakeSettings, command: &str) -> Result<()> { + let range = |name: &str, value: f32, minimum: f32, maximum: f32| { + if value.is_finite() && (minimum..=maximum).contains(&value) { Ok(()) } else { Err(bad(command, format!("{name} must be in {minimum}..={maximum}"))) } + }; + if settings.common.dilation > 128 { + return Err(bad(command, "dilation must be at most 128")); + } + for rays in [&settings.maps.ao.parameters.rays, &settings.maps.thickness.parameters.rays, &settings.maps.bent_normal.parameters.rays] { + if !(1..=256).contains(&rays.rays) { + return Err(bad(command, "secondary rays must be in 1..=256")); + } + range("minimum occluder distance", rays.min_distance, 0.00001, 1.0)?; + range("maximum occluder distance", rays.max_distance, 0.00001, if rays.relative_to_bounding_box { 1.0 } else { 10.0 })?; + range("spread angle", rays.spread, 0.0, 180.0)?; + if rays.min_distance > rays.max_distance { + return Err(bad(command, "minimum occluder distance must not exceed maximum distance")); + } + } + let curvature = &settings.maps.curvature.parameters; + if !(1..=256).contains(&curvature.mesh.rays) { + return Err(bad(command, "curvature rays must be in 1..=256")); + } + if !curvature.mesh.auto_tonemapping && curvature.mesh.value_min >= curvature.mesh.value_max { + return Err(bad(command, "curvature minimum must be below maximum")); + } + range("sampling radius", curvature.mesh.sampling_radius, 0.00001, if curvature.mesh.relative_to_bounding_box { 10.0 } else { 1.0 })?; + for (name, value, minimum, maximum) in [ + ("frontal distance", settings.cage.max_frontal, 0.0, 0.05), + ("rear distance", settings.cage.max_rear, 0.0, 0.05), + ("edge distance", settings.skew.edge_distance, 0.0, 1.0), + ("edge contrast", settings.skew.edge_contrast, 0.0, 1.0), + ("ground plane offset", settings.maps.ao.parameters.ground_plane.offset, 0.0, 100.0), + ("curvature details", curvature.normal_map.details, 0.0, 1.0), + ("seams intensity", curvature.normal_map.seams_intensity, 0.0, 1.0), + ("value bounds minimum", curvature.mesh.value_min, -10.0, 10.0), + ("value bounds maximum", curvature.mesh.value_max, -10.0, 10.0), + ("height scaling divisor", settings.maps.height.parameters.scaling_divisor, 0.00001, 100.0), + ] { + range(name, value, minimum, maximum)?; + } + Ok(()) +} + +/// Ray settings supported by the current bake command +fn rays_params(settings: &RaySettings) -> Value { + json!({ + "rays": settings.rays, + "maxDistance": settings.max_distance, + "spread": settings.spread, + "distribution": match settings.distribution { + RayDistribution::Cosine => "cosine", + RayDistribution::Uniform => "uniform", + }, + }) +} + +/// Apply only the ray parameters supplied by the caller +fn apply_rays(settings: &mut RaySettings, params: &Value, command: &str) -> Result<()> { + if let Some(count) = u64p(params, "rays") { + settings.rays = count.clamp(1, u64::from(MAX_RAYS)) as u32; + } + + for (key, setting, minimum, maximum) in [("maxDistance", &mut settings.max_distance, 0.001, 10.0), ("spread", &mut settings.spread, 0.0, 180.0)] { + if let Some(value) = f32p(params, key).filter(|value| value.is_finite()) { + *setting = value.clamp(minimum, maximum); + } + } + + if let Some(distribution) = strp(params, "distribution") { + settings.distribution = match distribution { + "cosine" => RayDistribution::Cosine, + "uniform" => RayDistribution::Uniform, + _ => return Err(bad(command, "distribution must be cosine or uniform")), + }; + } + + Ok(()) +} + +fn updated_settings(session: &Session, params: &Value, command: &str) -> Result> { + sets_param(session, command, params)? + .into_iter() + .map(|index| { + let mut settings = session.doc.project.texture_set(index)?.bake.clone(); + apply_settings(&mut settings, params, command)?; + Ok((index, settings)) + }) + .collect() +} + +fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { + let next = updated_settings(session, params, command)?; + let sets = next.iter().map(|(index, _)| *index).collect(); + if next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)) { + session.edit("Bake Settings", |session| { + for (index, settings) in next { + session.doc.project.texture_set_mut(index)?.bake = settings; + } + Ok(()) + })?; + } + Ok(sets) +} + +fn settings(session: &mut Session, params: &Value) -> Result { + let sets = set_settings(session, params, "bake.settings")?; + let result: Vec = sets + .iter() + .filter_map(|set_index| { + session + .doc + .project + .texture_sets + .get(*set_index) + .map(|texture_set| json!({ "ts": set_index, "settings": settings_params(&texture_set.bake), "model": &texture_set.bake })) + }) + .collect(); + + Ok(json!(result)) +} + +fn bake_run(session: &mut Session, params: &Value) -> Result { + 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()); + for (index, settings) in next { + session.doc.project.texture_set_mut(index)?.bake = settings; + let mut task = session.bake_task(index)?; + if cpu { + task.tracer = None; + } + let output = task.run(&Progress::new())?; + tracers.push(output.tracer.clone()); + session.store_bake(index, output)?; + } + Ok(tracers) + })?; + for (index, tracer) in sets.iter().zip(&tracers) { + session.log.push(format!("Baked texture set {index} ({tracer})")); + } + session.update(); + Ok(json!({ "baked": sets, "tracer": tracers })) +} diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs new file mode 100644 index 00000000..bfe9b22c --- /dev/null +++ b/crates/engine/src/bake/mod.rs @@ -0,0 +1,40 @@ +//! Baking tasks, commands, settings helpers, and the mesh-map baking API + +mod bake_cage_inputs; +mod bake_checks; +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 streamed_bake; +mod streamed_map; +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::{HIDDEN_HIGH_POLY_VERTEX, 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 streamed_bake::StreamedBake; +pub use streamed_map::StreamedMap; +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_command.rs b/crates/engine/src/bake/paint_command.rs new file mode 100644 index 00000000..1bbe2580 --- /dev/null +++ b/crates/engine/src/bake/paint_command.rs @@ -0,0 +1,147 @@ +use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; +use crate::{Result, Session, cmd}; +use serde_json::Value; +use std::sync::Arc; +use texturecraft_bake::BakePaintMap; +use texturecraft_core::BakePaintTarget; +use texturecraft_geom::glam::Vec2; + +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, + parameters, + BakePaintTarget::Skew + )), + cmd!( + "bake.skew.paint", + "Paint Skew Correction", + [], + None, + "{ts?, points: [[u,v],...], radius?: 0.03, value?: 1, hardness?: 0.5, strength?: 1, size?: 1024, continue?: false}", + always, + |session, parameters| paint(session, parameters, BakePaintTarget::Skew) + ), + cmd!("bake.skew.clear", "Remove Skew Correction", [], None, "{ts?}", always, |session, parameters| clear(session, parameters, BakePaintTarget::Skew)), + cmd!( + "bake.cage.paint", + "Paint Cage", + [], + None, + "{ts?, points: [[u,v],...], radius?: 0.03, value?: 1 (frontal distance multiplier, 0..1), hardness?: 0.5, strength?: 1, size?: 1024, continue?: false}", + always, + |session, parameters| paint(session, parameters, BakePaintTarget::Cage) + ), + cmd!("bake.cage.reset", "Reset Painted Cage", [], None, "{ts?}", always, |session, parameters| clear(session, parameters, BakePaintTarget::Cage)), + ] +} + +fn texture_set(session: &Session, parameters: &Value) -> Result { + let index = match parameters.get("ts") { + None => session.ts(), + Some(value) => value.as_u64().and_then(|value| usize::try_from(value).ok()).ok_or_else(|| bad("bake.paint", "ts must be a texture set index"))?, + }; + session.doc.project.texture_set(index)?; + Ok(index) +} + +fn number(parameters: &Value, name: &str, default: f32, minimum: f32, maximum: f32) -> Result { + if parameters.get(name).is_none() { + return Ok(default); + } + f32p(parameters, name) + .filter(|value| (minimum..=maximum).contains(value)) + .ok_or_else(|| bad("bake.paint", format!("{name} must be in {minimum}..={maximum}"))) +} + +fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { + let texture_set = texture_set(session, parameters)?; + let map = match strp(parameters, "path") { + Some(path) => load_image(path)?, + None => BakePaintMap::constant(number(parameters, "value", 1.0, 0.0, 1.0)?), + }; + map.validate().map_err(|error| bad("bake.paint", error.to_string()))?; + session.edit("Set Bake Paint Map", |session| { + session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); + Ok(()) + })?; + Ok(super::meshes_json(session)) +} + +fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { + let texture_set = texture_set(session, parameters)?; + if session.doc.bake_paint.contains_key(&(texture_set, target)) { + session.edit("Clear Bake Paint Map", |session| { + session.doc.bake_paint.remove(&(texture_set, target)); + Ok(()) + })?; + } + Ok(super::meshes_json(session)) +} + +fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { + const MAX_POINTS: usize = 100_000; + let texture_set = texture_set(session, parameters)?; + let points = parameters + .get("points") + .and_then(Value::as_array) + .filter(|points| !points.is_empty() && points.len() <= MAX_POINTS) + .ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?; + let points = points + .iter() + .map(|point| { + let coordinate = |index| point.get(index).and_then(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()); + match (coordinate(0), coordinate(1)) { + (Some(u), Some(v)) => Ok(Vec2::new(u, v)), + _ => Err(bad("bake.paint", "each point must contain two finite UV coordinates")), + } + }) + .collect::>>()?; + let value = number(parameters, "value", 1.0, 0.0, 1.0)?; + let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?; + let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; + let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; + let size = match parameters.get("size") { + None => 1024, + Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?, + }; + if !(16..=4096).contains(&size) { + return Err(bad("bake.paint", "size must be between 16 and 4096")); + } + let default = match target { + BakePaintTarget::Cage => 1.0, + BakePaintTarget::Skew => 0.0, + }; + let label = match target { + BakePaintTarget::Cage => "Paint Cage", + BakePaintTarget::Skew => "Paint Skew Correction", + }; + session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| { + let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default))); + if map.values.len() == 1 { + *map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?); + } + Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string())) + })?; + Ok(super::meshes_json(session)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn load_image(path: &str) -> Result { + let length = std::fs::metadata(path).map_err(|error| bad("bake.paint", error.to_string()))?.len(); + if length > 256 << 20 { + return Err(bad("bake.paint", "image exceeds 256 MiB")); + } + let bytes = std::fs::read(path).map_err(|error| bad("bake.paint", error.to_string()))?; + let image = texturecraft_formats::decode_image_within(&bytes, texturecraft_bake::MAX_TEXELS).map_err(|error| bad("bake.paint", error.to_string()))?; + Ok(BakePaintMap { + width: image.width, + height: image.height, + values: image.rgba.iter().map(|pixel| ((pixel[0] + pixel[1] + pixel[2]) / 3.0).clamp(0.0, 1.0)).collect(), + }) +} + +#[cfg(target_arch = "wasm32")] +fn load_image(_: &str) -> Result { + Err(bad("bake.paint", "file paths are unavailable in the browser")) +} diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs new file mode 100644 index 00000000..f44a09a4 --- /dev/null +++ b/crates/engine/src/bake/preserve_tiles.rs @@ -0,0 +1,78 @@ +use texturecraft_bake::BakeOutput; +use texturecraft_compose::BakedMaps; +use texturecraft_core::BakedMap; + +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; + } + } + } + } + } + + Ok(()) +} + +/// Retain only maps outside the full task selection, once per completed atlas. +/// A one-map streaming pass must not resample maps that are still scheduled to bake. +pub(super) fn restore_unchecked(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], selected: &[BakedMap]) -> Result<()> { + if excluded_tiles.is_empty() { + return Ok(()); + } + let size = (output.resolution, output.height); + for map in previous.maps.keys() { + if selected.contains(map) || 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())))?; + #[cfg(test)] + RETAINED_ALLOCATIONS.with(|allocations| allocations.borrow_mut().push(*map)); + 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(()) +} + +// Restoration is sequential on the calling thread. Record successful retained-buffer allocations +// only in unit tests, without a global allocator or interference from parallel test threads. +#[cfg(test)] +std::thread_local! { + static RETAINED_ALLOCATIONS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +pub(super) fn take_retained_allocations() -> Vec { + RETAINED_ALLOCATIONS.with(|allocations| std::mem::take(&mut *allocations.borrow_mut())) +} diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs new file mode 100644 index 00000000..55aecbca --- /dev/null +++ b/crates/engine/src/bake/streamed_bake.rs @@ -0,0 +1,14 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use texturecraft_core::BakedMap; + +/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them, +/// so the preview and the document hold one buffer per map, never two +#[derive(Clone, Debug)] +pub struct StreamedBake { + pub resolution: u32, + pub height: u32, + pub maps: BTreeMap>>, + pub tracer: String, +} diff --git a/crates/engine/src/bake/streamed_map.rs b/crates/engine/src/bake/streamed_map.rs new file mode 100644 index 00000000..33781099 --- /dev/null +++ b/crates/engine/src/bake/streamed_map.rs @@ -0,0 +1,17 @@ +use std::sync::Arc; + +use texturecraft_core::BakedMap; + +/// One finished map of a streamed bake (see [`crate::BakeTask::run_streaming`]). +#[derive(Clone, Debug)] +pub struct StreamedMap { + pub map: BakedMap, + /// Position among the maps this bake makes, from 0, and how many there are. + pub index: usize, + pub total: usize, + /// Width and height in texels. + pub resolution: u32, + pub height: u32, + /// Row-major, `map.components()` floats per texel, padded. + pub data: Arc>, +} 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/bake_cmds.rs b/crates/engine/src/bake_cmds.rs deleted file mode 100644 index 6bd3ea67..00000000 --- a/crates/engine/src/bake_cmds.rs +++ /dev/null @@ -1,681 +0,0 @@ -//! Mesh-map baking commands (the "Bake Mesh Maps" window): bake settings, the -//! 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 std::collections::BTreeSet; -use std::sync::{Arc, OnceLock}; - -use serde_json::{Value, json}; -use texturecraft_bake::rays::Tracer; -use texturecraft_bake::{BakeOutput, BakeRequest, HighPoly, MAX_RAYS, Progress, SkewMap, bake, bake_on}; -use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; -use texturecraft_geom::{BaseColor, Bvh, Mesh}; - -use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; -use crate::{EngineError, Result, Session, cmd}; - -pub fn specs() -> Vec { - vec![ - cmd!( - "bake.run", - "Bake mesh maps", - ["Mode"], - None, - "{ts?: index|[indices]|\"all\"|\"selected\", cpu?: true (skip the GPU), ...any bake.settings parameter} → {baked, tracer: [where each set's rays ran]}", - always, - bake_run - ), - cmd!( - "bake.settings", - "Bake settings", - [], - None, - "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureStrength?, curvatureFromNormal?, curvatureRadius?: texels (0 = auto), positionMode?: boundingBox|boundingSphere, direction?: [x,y,z], directionMode?: signed|positive, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, matching?: always|byMeshName, lowSuffix?, highSuffix?}", - always, - settings - ), - cmd!( - "bake.highPoly.add", - "Add high definition mesh", - [], - None, - "{path} — a mesh file (glb, gltf, fbx, dae, usd, usda, usdc, usdz, abc, obj, ply, stl; base color textures from glTF, embedded FBX media, usdz packages and image files next to a .gltf or USD layer feed the color map)", - always, - high_add - ), - cmd!("bake.highPoly.remove", "Remove high definition mesh", [], None, "{index? | name? | all?: true}", always, high_remove), - cmd!("bake.highPoly.list", "List high definition meshes", [], None, "{}", always, |s, _| Ok(meshes_json(s))), - cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set), - cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| { - s.bake_meshes.cage = None; - s.modified = true; - Ok(meshes_json(s)) - }), - cmd!( - "bake.skew.set", - "Set skew correction", - [], - None, - "{value?: 0..1 (a constant map, default 1) | path: a greyscale image over the UV atlas (white turns the rays onto the base normal, black keeps the cage's averaged direction), edgeDistance?: fraction of the mesh diagonal over which hard edges hold the correction back (default 0), edgeContrast?: falloff exponent (default 1), base?: mesh|triangle (default mesh)} → {skew}. Applies to the transfer rays of a bake from the built-in distance cage; a cage mesh ignores it", - always, - skew_set - ), - cmd!( - "bake.skew.paint", - "Paint skew correction", - [], - None, - "{points: [[u, v], ...] (atlas uv, a stroke), radius?: uv units (default 0.03), value?: 0..1 (1 turns rays onto the base normal, 0 erases; default 1), hardness?: 0..1 (default 0.5), strength?: 0..1 per dab (default 1), size?: px of a new or constant map (default 1024, 16..4096)} → {skew}. Paints into the skew map; a missing or constant map is first widened to `size`", - always, - skew_paint - ), - cmd!("bake.skew.clear", "Remove skew correction", [], None, "{}", always, |s, _| { - s.bake_meshes.skew = None; - s.bake_meshes.skew_rev += 1; - s.modified = true; - Ok(meshes_json(s)) - }), - ] -} - -/// A mesh file as saved in a project: (file name, bytes). -type MeshFile = (String, Vec); - -/// A mesh file the baker reads (high poly or cage): its name, original bytes (saved in the -/// project), parsed mesh and its materials' base colors (high polys). -#[derive(Clone, Debug)] -pub struct BakeMesh { - pub name: String, - pub bytes: Arc>, - pub mesh: Arc, - pub base_color: Vec>>, -} - -/// Every high poly appended into one mesh, its BVH and per-material base colors. -#[derive(Clone, Debug)] -pub struct MergedHigh { - pub mesh: Arc, - pub bvh: Arc, - pub base_color: Arc>>>, -} - -static GPU_TRACER: OnceLock> = OnceLock::new(); - -/// Cast bake rays with `tracer` (the apps install the render crate's GPU baker at start-up); -/// the first call wins. -pub fn install_gpu_tracer(tracer: Arc) { - let _ = GPU_TRACER.set(tracer); -} - -/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the -/// undo history. -#[derive(Clone, Debug, Default)] -pub struct BakeMeshes { - pub high: Vec, - pub cage: Option, - /// Skew correction of the transfer rays (saved in the project as `skew.bin`). - pub skew: Option>, - /// Counts changes to `skew`, so a view knows when to redraw it. - pub skew_rev: u64, - /// Every high poly appended into one mesh (rebuilt when the list changes). - merged: Option, -} - -impl BakeMeshes { - // shortcut: the merged copy doubles high-poly memory; build the BVH over the parts in place if - // multi-million-triangle sets run out of memory. - fn rebuild(&mut self) { - self.merged = (!self.high.is_empty()).then(|| { - let (mut all, mut base_color) = (Mesh::default(), Vec::new()); - for h in &self.high { - all.append(&h.mesh); - base_color.extend(h.base_color.iter().cloned().chain(std::iter::repeat(None)).take(h.mesh.materials.len())); - } - let bvh = Bvh::new(&all); - MergedHigh { mesh: Arc::new(all), bvh: Arc::new(bvh), base_color: Arc::new(base_color) } - }); - } -} - -/// A self-contained bake task that can run on another thread. -pub struct BakeTask { - pub ts: usize, - pub mesh: Arc, - pub bvh: Arc, - pub material: usize, - pub settings: BakeSettings, - /// The merged high polys, unless the set bakes from the low poly. - pub high: Option, - pub cage: Option>, - pub skew: Option>, - /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. - pub tiles: (u32, u32), - /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). - pub tracer: Option>, -} - -impl BakeTask { - pub fn run(&self, progress: &Progress) -> Result { - let high = self.high.as_ref().map(|h| HighPoly { mesh: &h.mesh, bvh: &h.bvh, base_color: &h.base_color }); - let req = BakeRequest { - mesh: &self.mesh, - bvh: &self.bvh, - material: self.material, - settings: &self.settings, - high, - cage: self.cage.as_deref(), - skew: self.skew.as_deref(), - tiles: self.tiles, - }; - match &self.tracer { - Some(t) => bake_on(&req, progress, t.as_ref()), - None => bake(&req, progress), - } - .map_err(|e| EngineError::Other(format!("bake failed: {e}"))) - } -} - -/// A mesh file name made unique among `taken` (and safe as a project file entry). -fn unique_name(file_name: &str, taken: &[&str]) -> String { - let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh"); - let base = texturecraft_formats::sanitize_resource_name(leaf); - let mut name = base.clone(); - let mut n = 2; - while taken.contains(&name.as_str()) { - name = format!("{n}_{base}"); - n += 1; - } - name -} - -fn parse_mesh(file_name: &str, bytes: Vec) -> Result { - let h = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; - let base_color = h.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); - Ok(BakeMesh { name: file_name.to_string(), bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color }) -} - -impl Session { - pub fn bake_task(&self, ts: usize) -> Result { - let set = self.doc.project.texture_set(ts)?; - let high = if set.bake.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; - let cage = high.as_ref().and(self.bake_meshes.cage.as_ref()).map(|c| c.mesh.clone()); - let skew = high.as_ref().and(self.bake_meshes.skew.clone()); - let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); - let tracer = GPU_TRACER.get().cloned(); - Ok(BakeTask { ts, mesh: self.mesh.clone(), bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), high, cage, skew, tiles, tracer }) - } - - /// Store a finished bake (one undo step). - pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> { - self.log.push(format!("Baked texture set {ts} ({})", out.tracer)); - let made: Vec = out.maps.keys().copied().collect(); - self.edit("Bake mesh maps", |s| { - let maps: BTreeSet = out.maps.keys().copied().collect(); - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = out.resolution; - for (m, data) in out.maps { - entry.maps.insert(m, Arc::new(data)); - } - s.doc.project.texture_set_mut(ts)?.baked.extend(maps); - Ok(()) - })?; - self.note_baked(ts, made.into_iter()); - Ok(()) - } - - /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. - pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { - self.begin_bake(ts); - let mut task = self.bake_task(ts)?; - if cpu { - task.tracer = None; - } - let out = task.run(&Progress::new())?; - let tracer = out.tracer.clone(); - self.apply_bake(ts, out)?; - Ok(tracer) - } - - /// Add a high-definition mesh from file bytes (the web picker, the desktop dialog and - /// `bake.highPoly.add`); every texture set then bakes from the high polys. Returns its name. - pub fn add_high_poly_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - let mut m = parse_mesh(file_name, bytes)?; - let taken: Vec<&str> = self.bake_meshes.high.iter().map(|h| h.name.as_str()).collect(); - m.name = unique_name(file_name, &taken); - let textures = m.base_color.iter().flatten().filter(|c| !c.texels.is_empty()).count(); - self.log.push(format!("High poly {}: {} triangles, {textures} base color textures", m.name, m.mesh.triangle_count())); - let name = m.name.clone(); - self.bake_meshes.high.push(m); - self.bake_meshes.rebuild(); - for set in &mut self.doc.project.texture_sets { - set.bake.use_low_as_high = false; - } - self.modified = true; - Ok(name) - } - - /// Remove high-definition mesh `index`. - pub fn remove_high_poly(&mut self, index: usize) -> Result { - if index >= self.bake_meshes.high.len() { - return Err(EngineError::Other(format!("no high poly mesh {index}"))); - } - let removed = self.bake_meshes.high.remove(index); - self.bake_meshes.rebuild(); - self.modified = true; - Ok(removed) - } - - /// Use a cage mesh (same triangles as the low poly) from file bytes. - pub fn set_cage_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - let mut m = parse_mesh(file_name, bytes)?; - if m.mesh.triangle_count() != self.mesh.triangle_count() { - return Err(EngineError::Other(format!( - "the cage has {} triangles but the low poly has {}; export the cage from the low poly", - m.mesh.triangle_count(), - self.mesh.triangle_count() - ))); - } - m.name = unique_name(file_name, &[]); - m.base_color.clear(); - let name = m.name.clone(); - self.bake_meshes.cage = Some(m); - self.modified = true; - Ok(name) - } - - /// Add mesh file `f` as a high-definition mesh, or set it as the cage, logging what it could - /// not fold in. Replies like `bake.highPoly.add` / `bake.cage.set`: `{name, meshes}`. - pub fn add_bake_mesh(&mut self, f: texturecraft_formats::MeshFile, cage: bool) -> Result { - let name = if cage { self.set_cage_bytes(&f.name, f.bytes)? } else { self.add_high_poly_bytes(&f.name, f.bytes)? }; - self.log.extend(f.warnings); - Ok(json!({ "name": name, "meshes": meshes_json(self) })) - } - - /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped. - pub(crate) fn load_bake_meshes(&mut self, high: Vec, cage: Option) { - for (name, bytes) in high { - match parse_mesh(&name, bytes) { - Ok(m) => self.bake_meshes.high.push(m), - Err(e) => self.log.push(format!("skipped high poly mesh: {e}")), - } - } - self.bake_meshes.rebuild(); - if let Some((name, bytes)) = cage - && let Err(e) = self.set_cage_bytes(&name, bytes) - { - self.log.push(format!("skipped cage mesh: {e}")); - } - } - - /// The skew map of a project file, if it passes the baker's checks. - pub(crate) fn load_skew(&mut self, skew: Option) { - let Some(k) = skew else { return }; - let map = SkewMap { - width: k.width, - height: k.height, - values: k.values, - edge_distance: k.edge_distance, - edge_contrast: k.edge_contrast, - per_triangle: k.per_triangle, - }; - match map.validate() { - Ok(()) => { - self.bake_meshes.skew = Some(Arc::new(map)); - self.bake_meshes.skew_rev += 1; - } - Err(e) => self.log.push(format!("skipped skew map: {e}")), - } - } - - /// The skew map for a project file. - pub(crate) fn saved_skew(&self) -> Option { - let k = self.bake_meshes.skew.as_ref()?; - Some(texturecraft_formats::SkewData { - width: k.width, - height: k.height, - values: k.values.clone(), - edge_distance: k.edge_distance, - edge_contrast: k.edge_contrast, - per_triangle: k.per_triangle, - }) - } - - /// The bake meshes for a project file: (high polys, cage). - pub(crate) fn saved_bake_meshes(&self) -> (Vec, Option) { - let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone()); - (self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry)) - } -} - -/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`). -pub fn meshes_json(s: &Session) -> Value { - let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::>() }); - let skew = s.bake_meshes.skew.as_ref().map(|k| { - json!({ "width": k.width, "height": k.height, "edgeDistance": k.edge_distance, "edgeContrast": k.edge_contrast, "base": if k.per_triangle { "triangle" } else { "mesh" } }) - }); - json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": skew }) -} - -#[cfg(not(target_arch = "wasm32"))] -fn read_mesh_file(cmd: &str, p: &Value) -> Result { - let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?; - crate::file_cmds::read_mesh(cmd, path) -} - -#[cfg(target_arch = "wasm32")] -fn read_mesh_file(_: &str, _: &Value) -> Result { - Err(EngineError::Other("file paths are not available in the browser; use the bake panel's file picker".into())) -} - -fn high_add(s: &mut Session, p: &Value) -> Result { - s.add_bake_mesh(read_mesh_file("bake.highPoly.add", p)?, false) -} - -fn high_remove(s: &mut Session, p: &Value) -> Result { - if boolp(p, "all") == Some(true) { - s.bake_meshes.high.clear(); - s.bake_meshes.rebuild(); - s.modified = true; - return Ok(meshes_json(s)); - } - let index = match (u64p(p, "index"), strp(p, "name")) { - (Some(i), _) => usize::try_from(i).unwrap_or(usize::MAX), - (None, Some(n)) => s.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, - (None, None) => return Err(bad("bake.highPoly.remove", "`index`, `name` or `all` is required")), - }; - s.remove_high_poly(index)?; - Ok(meshes_json(s)) -} - -/// The greyscale skew map of an image file (the mean of its colour channels, as stored). -#[cfg(not(target_arch = "wasm32"))] -fn skew_image(path: &str) -> Result<(u32, u32, Vec)> { - const MAX_BYTES: u64 = 256 << 20; - let cmd = "bake.skew.set"; - let len = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?.len(); - if len > MAX_BYTES { - return Err(bad(cmd, format!("{path} is over 256 MiB"))); - } - let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; - // The size is checked from the header, before the pixels are decoded. - let img = texturecraft_formats::decode_image_within(&bytes, texturecraft_bake::MAX_TEXELS).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - Ok((img.width, img.height, img.rgba.iter().map(|p| (p[0] + p[1] + p[2]) / 3.0).collect())) -} - -#[cfg(target_arch = "wasm32")] -fn skew_image(_: &str) -> Result<(u32, u32, Vec)> { - Err(EngineError::Other("file paths are not available in the browser".into())) -} - -fn skew_set(s: &mut Session, p: &Value) -> Result { - let cmd = "bake.skew.set"; - let mut map = match strp(p, "path") { - Some(path) => { - let (width, height, values) = skew_image(path)?; - SkewMap { width, height, values: values.into_iter().map(|v| v.clamp(0.0, 1.0)).collect(), ..SkewMap::constant(0.0) } - } - None => SkewMap::constant(f32p(p, "value").unwrap_or(1.0).clamp(0.0, 1.0)), - }; - map.edge_distance = f32p(p, "edgeDistance").unwrap_or(0.0); - map.edge_contrast = f32p(p, "edgeContrast").unwrap_or(1.0); - map.per_triangle = match strp(p, "base") { - None | Some("mesh") => false, - Some("triangle") => true, - Some(other) => return Err(bad(cmd, format!("unknown base `{other}`"))), - }; - map.validate().map_err(|e| bad(cmd, e.to_string()))?; - s.bake_meshes.skew = Some(Arc::new(map)); - s.bake_meshes.skew_rev += 1; - s.modified = true; - Ok(meshes_json(s)) -} - -fn cage_set(s: &mut Session, p: &Value) -> Result { - s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true) -} - -/// Texture sets named by `ts` (default: the active one). -fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { - let n = s.set_count(); - let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}"))); - match p.get("ts") { - Some(Value::String(a)) if a == "all" => Ok((0..n).collect()), - Some(Value::String(a)) if a == "selected" => Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.enabled)).collect()), - Some(Value::Array(a)) => a.iter().map(one).collect(), - Some(v) => Ok(vec![one(v)?]), - None => Ok(vec![s.ts()]), - } -} - -/// `b` as `bake.settings` parameters (what the command returns and the UI sends back). -pub fn settings_params(b: &BakeSettings) -> Value { - let mut ao = rays_params(&b.ao); - ao["ignoreBackface"] = b.ao_ignore_backface.into(); - ao["selfOcclusion"] = SELF_OCCLUSION.name(b.ao_self_occlusion).into(); - json!({ - "resolution": b.resolution, - "antialiasing": b.antialiasing, - "dilation": b.dilation, - "ao": ao, - "thickness": rays_params(&b.thickness), - "bentNormal": rays_params(&b.bent_normal), - "curvatureStrength": b.curvature_strength, - "curvatureFromNormal": b.curvature_from_normal, - "curvatureRadius": b.curvature_radius, - "positionMode": POSITION_MODE.name(b.position_mode), - "direction": b.direction, - "directionMode": DIRECTION_MODE.name(b.direction_mode), - "maps": b.maps.iter().map(|m| m.id()).collect::>(), - "enabled": b.enabled, - "useLowAsHigh": b.use_low_as_high, - "maxFrontal": b.max_frontal, - "maxRear": b.max_rear, - "averageNormals": b.average_normals, - "matching": match b.matching { BakeMatch::Always => "always", BakeMatch::ByMeshName => "byMeshName" }, - "lowSuffix": b.low_suffix, - "highSuffix": b.high_suffix, - }) -} - -/// Apply the `bake.settings` parameters present in `p` to `b`. -fn apply_settings(b: &mut BakeSettings, p: &Value, cmd: &str) -> Result<()> { - if let Some(r) = u64p(p, "resolution") { - b.resolution = crate::session::check_resolution(u32::try_from(r).unwrap_or(0))?; - } - if let Some(a) = u64p(p, "antialiasing") { - if ![1, 2, 4, 8].contains(&a) { - return Err(bad(cmd, "antialiasing must be 1, 2, 4 or 8")); - } - b.antialiasing = a as u32; - } - if let Some(d) = u64p(p, "dilation") { - b.dilation = d.min(256) as u32; - } - // `rays` / `maxDistance` set every ray map; the per-map objects override. - for r in [&mut b.ao, &mut b.thickness, &mut b.bent_normal] { - apply_rays(r, p, cmd)?; - } - for (k, r) in [("ao", &mut b.ao), ("thickness", &mut b.thickness), ("bentNormal", &mut b.bent_normal)] { - if let Some(o) = p.get(k) { - apply_rays(r, o, cmd)?; - } - } - if let Some(ao) = p.get("ao") { - if let Some(v) = boolp(ao, "ignoreBackface") { - b.ao_ignore_backface = v; - } - if let Some(v) = strp(ao, "selfOcclusion") { - b.ao_self_occlusion = SELF_OCCLUSION.parse(cmd, "selfOcclusion", v)?; - } - } - if let Some(v) = strp(p, "positionMode") { - b.position_mode = POSITION_MODE.parse(cmd, "positionMode", v)?; - } - if let Some(v) = strp(p, "directionMode") { - b.direction_mode = DIRECTION_MODE.parse(cmd, "directionMode", v)?; - } - if let Some(r) = u64p(p, "curvatureRadius") { - b.curvature_radius = r.min(64) as u32; - } - for (k, slot, lo, hi) in - [("curvatureStrength", &mut b.curvature_strength, 0.0, 16.0), ("maxFrontal", &mut b.max_frontal, 0.0, 1.0), ("maxRear", &mut b.max_rear, 0.0, 1.0)] - { - if let Some(v) = f32p(p, k).filter(|v| v.is_finite()) { - *slot = v.clamp(lo, hi); - } - } - for (k, slot) in [ - ("curvatureFromNormal", &mut b.curvature_from_normal), - ("enabled", &mut b.enabled), - ("useLowAsHigh", &mut b.use_low_as_high), - ("averageNormals", &mut b.average_normals), - ] { - if let Some(v) = boolp(p, k) { - *slot = v; - } - } - if let Some(d) = p.get("direction") { - let v: Vec = d.as_array().into_iter().flatten().filter_map(Value::as_f64).map(|x| x as f32).collect(); - match v[..] { - [x, y, z] if [x, y, z].iter().all(|c| c.is_finite()) && [x, y, z] != [0.0; 3] => b.direction = [x, y, z], - _ => return Err(bad(cmd, "`direction` must be three finite numbers, not all zero")), - } - } - if let Some(a) = p.get("maps").and_then(Value::as_array) { - b.maps = a.iter().map(|v| v.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(cmd, format!("unknown mesh map {v}")))).collect::>()?; - } - match strp(p, "matching") { - Some("always") => b.matching = BakeMatch::Always, - Some("byMeshName") | Some("byName") => b.matching = BakeMatch::ByMeshName, - Some(o) => return Err(bad(cmd, format!("unknown matching `{o}` (always|byMeshName)"))), - None => {} - } - for (k, slot) in [("lowSuffix", &mut b.low_suffix), ("highSuffix", &mut b.high_suffix)] { - if let Some(v) = strp(p, k) { - *slot = v.chars().take(64).collect(); - } - } - Ok(()) -} - -/// Parameter names of a settings enum. -struct Names(&'static [(&'static str, T)]); - -impl Names { - fn name(&self, v: T) -> &'static str { - self.0.iter().find(|(_, x)| *x == v).map_or("", |(n, _)| n) - } - - fn parse(&self, cmd: &str, key: &str, s: &str) -> Result { - let all = || self.0.iter().map(|(n, _)| *n).collect::>().join("|"); - self.0.iter().find(|(n, _)| *n == s).map(|(_, v)| *v).ok_or_else(|| bad(cmd, format!("unknown {key} `{s}` ({})", all()))) - } -} - -const SELF_OCCLUSION: Names = Names(&[("always", SelfOcclusion::Always), ("sameMeshName", SelfOcclusion::SameMeshName)]); -const DISTRIBUTION: Names = Names(&[("cosine", RayDistribution::Cosine), ("uniform", RayDistribution::Uniform)]); -const POSITION_MODE: Names = Names(&[("boundingBox", PositionMode::BoundingBox), ("boundingSphere", PositionMode::BoundingSphere)]); -const DIRECTION_MODE: Names = Names(&[("signed", DirectionMode::Signed), ("positive", DirectionMode::Positive)]); - -/// `r` as `bake.settings` parameters. -fn rays_params(r: &RaySettings) -> Value { - json!({ "rays": r.rays, "maxDistance": r.max_distance, "spread": r.spread, "distribution": DISTRIBUTION.name(r.distribution) }) -} - -/// Apply the ray parameters present in `p` (`rays`, `maxDistance`, `spread`, `distribution`). -fn apply_rays(r: &mut RaySettings, p: &Value, cmd: &str) -> Result<()> { - if let Some(n) = u64p(p, "rays") { - r.rays = n.clamp(1, u64::from(MAX_RAYS)) as u32; - } - for (k, slot, lo, hi) in [("maxDistance", &mut r.max_distance, 0.001, 10.0), ("spread", &mut r.spread, 0.0, 180.0)] { - if let Some(v) = f32p(p, k).filter(|v| v.is_finite()) { - *slot = v.clamp(lo, hi); - } - } - if let Some(v) = strp(p, "distribution") { - r.distribution = DISTRIBUTION.parse(cmd, "distribution", v)?; - } - Ok(()) -} - -/// Validate and apply the settings parameters to every set first, so a bad parameter changes -/// nothing. -fn set_settings(s: &mut Session, p: &Value, cmd: &str) -> Result> { - let sets = sets_param(s, cmd, p)?; - let mut next = Vec::with_capacity(sets.len()); - for &ts in &sets { - let mut b = s.doc.project.texture_set(ts)?.bake.clone(); - apply_settings(&mut b, p, cmd)?; - next.push((ts, b)); - } - for (ts, b) in next { - let set = s.doc.project.texture_set_mut(ts)?; - if set.bake != b { - set.bake = b; - s.modified = true; - } - } - Ok(sets) -} - -fn settings(s: &mut Session, p: &Value) -> Result { - let sets = set_settings(s, p, "bake.settings")?; - let out: Vec = - sets.iter().filter_map(|t| s.doc.project.texture_sets.get(*t).map(|set| json!({ "ts": t, "settings": settings_params(&set.bake) }))).collect(); - Ok(json!(out)) -} - -fn bake_run(s: &mut Session, p: &Value) -> Result { - let sets = set_settings(s, p, "bake.run")?; - let cpu = boolp(p, "cpu") == Some(true); - let tracer = sets.iter().map(|&ts| s.bake_now(ts, cpu)).collect::>>()?; - s.update(); - Ok(json!({ "baked": sets, "tracer": tracer })) -} - -fn skew_paint(s: &mut Session, p: &Value) -> Result { - use texturecraft_geom::glam::Vec2; - let cmd = "bake.skew.paint"; - const MAX_POINTS: usize = 100_000; - let points: Vec = p - .get("points") - .and_then(Value::as_array) - .ok_or_else(|| bad(cmd, "`points` is required: [[u, v], ...]"))? - .iter() - .map(|q| match (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) { - (Some(u), Some(v)) => Ok(Vec2::new(u as f32, v as f32)), - _ => Err(bad(cmd, "each point is [u, v]")), - }) - .collect::>()?; - if points.is_empty() || points.len() > MAX_POINTS { - return Err(bad(cmd, format!("give 1 to {MAX_POINTS} points"))); - } - let size = p.get("size").and_then(Value::as_u64).unwrap_or(1024); - if !(16..=4096).contains(&size) { - return Err(bad(cmd, "`size` is 16 to 4096")); - } - let (value, radius) = (f32p(p, "value").unwrap_or(1.0), f32p(p, "radius").unwrap_or(0.03)); - if !(radius.is_finite() && radius > 0.0 && radius <= 1.0) { - return Err(bad(cmd, "`radius` is above 0 and at most 1 (uv units)")); - } - let (hardness, strength) = (f32p(p, "hardness").unwrap_or(0.5), f32p(p, "strength").unwrap_or(1.0)); - let stroke = |m: &mut SkewMap| m.paint(&points, radius, value, hardness, strength).map_err(|e| bad(cmd, e.to_string())); - match s.bake_meshes.skew.as_mut() { - // In place: the map is copied only while a running bake still holds it, and `paint` - // refuses a stroke before it changes a texel. - Some(k) if k.values.len() > 1 => stroke(Arc::make_mut(k))?, - // A constant map has no resolution to paint at: widen it, keeping its value everywhere. - k => { - let mut map = match k { - Some(k) => k.resized(size as u32, size as u32), - None => SkewMap::constant(0.0).resized(size as u32, size as u32), - } - .map_err(|e| bad(cmd, e.to_string()))?; - stroke(&mut map)?; - s.bake_meshes.skew = Some(Arc::new(map)); - } - } - s.bake_meshes.skew_rev += 1; - s.modified = true; - Ok(meshes_json(s)) -} diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs new file mode 100644 index 00000000..878fb276 --- /dev/null +++ b/crates/engine/src/bake_preview.rs @@ -0,0 +1,236 @@ +//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon +//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in +//! the document: nothing enters the undo history until a texture set's bake is applied +//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already +//! applied keep their results and undo steps. The preview shows one map at a time, raw on the +//! model; maps and texture sets not baked yet show their neutral value. + +mod preview_set; +mod preview_show; +mod stage; + +pub use preview_set::PreviewSet; +pub use preview_show::PreviewShow; +pub use stage::Stage; + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_compose::BakedMaps; +use texturecraft_core::BakedMap; + +use crate::bake::StreamedMap; +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::session::ViewMode; +use crate::{Result, Session, cmd}; + +/// What painting says while a bake preview shows (the app translates it). +pub const PAINTING_PAUSED: &str = "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish."; + +pub fn specs() -> Vec { + vec![cmd!( + "bake.preview", + "Bake preview", + [], + None, + "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)", + always, + preview + )] +} + +#[derive(Clone, Debug)] +pub struct BakePreview { + /// The view mode to put back when the preview ends. + pub restore: ViewMode, + pub show: PreviewShow, + pub sets: BTreeMap, + /// The texture set being baked. + pub current: Option, + /// The last map that finished. + pub newest: Option, +} + +impl BakePreview { + /// The map the view shows, None for the material. + pub fn shown(&self) -> Option { + match self.show { + PreviewShow::Material => None, + PreviewShow::Pin(map) => Some(map), + PreviewShow::Follow => self + .newest + .or_else(|| self.current_set().and_then(|set| set.order.first().copied())) + .or_else(|| self.sets.values().find_map(|set| set.order.first().copied())), + } + } + + pub fn current_set(&self) -> Option<&PreviewSet> { + self.sets.get(&self.current?) + } + + /// The map being baked now (None between sets and once the set's maps are all in). + pub fn stage(&self) -> Option { + let texture_set = self.current?; + let set = self.sets.get(&texture_set)?; + let done = set.baked.maps.len(); + Some(Stage { texture_set, map: *set.order.get(done)?, position: done + 1, total: set.order.len() }) + } +} + +impl Session { + /// Start a preview from each selected texture set's enabled maps, in the same order as + /// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before + /// changing the preview or view mode. This reads settings without preparing bake geometry. + pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> { + let orders = sets + .iter() + .map(|&texture_set| { + let set = self.doc.project.texture_set(texture_set)?; + Ok((texture_set, set.bake.maps.enabled().collect())) + }) + .collect::>>()?; + + self.bake_preview_begin(orders); + Ok(()) + } + + /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view + /// follows the newest map and every set shows neutral values until its maps arrive. The + /// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is + /// discarded so a later pointer release cannot commit paint during the preview. + pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec)>) { + self.cancel_stroke(); + + let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore); + let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect(); + + self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None }); + self.bake_preview_refresh(); + } + + /// The texture set whose maps stream in now. + pub fn bake_preview_set_current(&mut self, texture_set: usize) { + if let Some(preview) = &mut self.bake_preview { + preview.current = Some(texture_set); + } + + self.bake_preview_refresh(); + } + + /// Install one finished map of set `texture_set`. Returns false when no preview shows. + pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool { + let Some(preview) = &mut self.bake_preview else { return false }; + + let set = preview.sets.entry(texture_set).or_default(); + + // A new bake of the set starts from nothing (the baker never repeats a map) + if streamed.index == 0 { + set.baked = BakedMaps::default(); + } + + set.baked.resolution = streamed.resolution; + set.baked.maps.insert(streamed.map, streamed.data); + preview.newest = Some(streamed.map); + self.bake_preview_refresh(); + true + } + + /// Choose what the view shows (Follow, a pinned map or the material). + pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> { + let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) }; + + preview.show = show; + self.bake_preview_refresh(); + Ok(()) + } + + /// The user picked a view mode during a bake: a mesh map pins it, any other mode shows + /// the material and is what comes back when the bake ends. + pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) { + let Some(preview) = &mut self.bake_preview else { return }; + + match view { + ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map), + other => { + preview.show = PreviewShow::Material; + preview.restore = other; + } + } + + self.bake_preview_refresh(); + if !matches!(view, ViewMode::MeshMap(_)) { + self.view = view; + } + } + + /// Drop the displayed maps and restore the previous view mode. This does not stop a + /// worker or undo any applied results; the UI also uses it when leaving Bake mode. + pub fn bake_preview_end(&mut self) { + if let Some(preview) = self.bake_preview.take() { + self.view = preview.restore; + self.revision = self.revision.wrapping_add(1); + } + } + + pub fn bake_preview_active(&self) -> bool { + self.bake_preview.is_some() + } + + /// The streamed maps of set `texture_set` while a preview shows (empty for a set not baked + /// yet: neutral values), None when the document's baked maps are what shows. + pub fn bake_preview_baked(&self, texture_set: usize) -> Option<&BakedMaps> { + self.bake_preview.as_ref()?.sets.get(&texture_set).map(|set| &set.baked) + } + + /// Why painting is not possible now, when a bake preview shows. + pub fn painting_blocked(&self) -> Option<&'static str> { + self.bake_preview.as_ref().map(|_| PAINTING_PAUSED) + } + + fn bake_preview_refresh(&mut self) { + let Some(preview) = &self.bake_preview else { return }; + + self.view = match preview.shown() { + Some(map) => ViewMode::MeshMap(map), + None => ViewMode::Material, + }; + self.revision = self.revision.wrapping_add(1); + } +} + +/// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`. +pub fn preview_json(session: &Session) -> Value { + let Some(preview) = &session.bake_preview else { return json!({ "active": false }) }; + + let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total })); + let sets: Vec = preview + .sets + .iter() + .map(|(texture_set, set)| { + json!({ + "set": texture_set, + "order": set.order.iter().map(|map| map.id()).collect::>(), + "done": set.baked.maps.keys().map(|map| map.id()).collect::>(), + }) + }) + .collect(); + + json!({ + "active": true, + "show": preview.show.id(), + "shown": preview.shown().map(|map| map.id()), + "newest": preview.newest.map(|map| map.id()), + "restore": preview.restore.label(), + "stage": stage, + "sets": sets, + }) +} + +fn preview(session: &mut Session, params: &Value) -> Result { + if let Some(show) = strp(params, "show") { + let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:")))?; + session.bake_preview_show(show)?; + } + + Ok(preview_json(session)) +} diff --git a/crates/engine/src/bake_preview/preview_set.rs b/crates/engine/src/bake_preview/preview_set.rs new file mode 100644 index 00000000..e1eabef8 --- /dev/null +++ b/crates/engine/src/bake_preview/preview_set.rs @@ -0,0 +1,10 @@ +use texturecraft_compose::BakedMaps; +use texturecraft_core::BakedMap; + +/// The maps of one texture set streamed so far. +#[derive(Clone, Debug, Default)] +pub struct PreviewSet { + pub baked: BakedMaps, + /// The maps this set's bake makes, in the order they arrive. + pub order: Vec, +} diff --git a/crates/engine/src/bake_preview/preview_show.rs b/crates/engine/src/bake_preview/preview_show.rs new file mode 100644 index 00000000..28a13614 --- /dev/null +++ b/crates/engine/src/bake_preview/preview_show.rs @@ -0,0 +1,30 @@ +use texturecraft_core::BakedMap; + +/// What the 3D view shows while a bake runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewShow { + /// The newest finished map (the first one, still neutral, before any is done). + Follow, + /// One map, pinned: neutral until it is baked. + Pin(BakedMap), + /// The lit material. + Material, +} + +impl PreviewShow { + pub fn id(self) -> String { + match self { + PreviewShow::Follow => "follow".into(), + PreviewShow::Pin(map) => format!("map:{}", map.id()), + PreviewShow::Material => "material".into(), + } + } + + pub fn parse(text: &str) -> Option { + match text { + "follow" => Some(PreviewShow::Follow), + "material" => Some(PreviewShow::Material), + _ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin), + } + } +} diff --git a/crates/engine/src/bake_preview/stage.rs b/crates/engine/src/bake_preview/stage.rs new file mode 100644 index 00000000..d1513ae2 --- /dev/null +++ b/crates/engine/src/bake_preview/stage.rs @@ -0,0 +1,11 @@ +use texturecraft_core::BakedMap; + +/// The map a bake is working on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stage { + pub texture_set: usize, + pub map: BakedMap, + /// 1-based position among the set's maps, and how many there are. + pub position: usize, + pub total: usize, +} diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 0ebfa070..2a83b3e1 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -3,7 +3,9 @@ use serde_json::{Value, json}; use texturecraft_paint::BrushSettings; -use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of}; +#[cfg(not(target_arch = "wasm32"))] +use texturecraft_paint::presets::with_stroke_of; +use texturecraft_paint::presets::{PRESETS, find_preset}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::tool_cmds::brush_json; 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 c5fb7134..a03a58a9 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use texturecraft_core::{BlendMode, Channel, NormalFormat}; +use texturecraft_geom::glam::Vec3; use crate::{EngineError, Result, Session}; @@ -56,6 +57,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 +67,12 @@ 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::auto_rebake::specs()); - v.extend(crate::bake_cmds::specs()); + v.extend(crate::bake::specs()); + v.extend(crate::bake_preview::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); @@ -133,6 +136,14 @@ pub(crate) fn u64p(p: &Value, key: &str) -> Option { p.get(key).and_then(|v| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64))) } +/// A `[x, y, z]` param of finite numbers +pub(crate) fn vec3(params: &Value, key: &str) -> Option { + let [x, y, z] = params.get(key)?.as_array()?.as_slice() else { return None }; + let vector = Vec3::new(x.as_f64()? as f32, y.as_f64()? as f32, z.as_f64()? as f32); + + vector.is_finite().then_some(vector) +} + pub(crate) fn boolp(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_bool) } @@ -184,16 +195,26 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result Option<[f32; 3]> { - color_of(p.get(key)?) +pub(crate) fn color_param(cmd: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")"))), + } } /// A color value (see [`color_param`]). pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { match v { Value::Array(a) if a.len() >= 3 => { - let v: Vec = a.iter().take(3).map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - if v.iter().all(|x| x.is_finite()) { Some([v[0], v[1], v[2]]) } else { None } + let mut out = [0.0f32; 3]; + for (i, x) in a.iter().take(3).enumerate() { + let f = x.as_f64()? as f32; + if !f.is_finite() { + return None; + } + out[i] = f; + } + Some(out) } Value::Number(n) => n.as_f64().map(|v| [v as f32; 3]).filter(|v| v[0].is_finite()), Value::String(s) => { @@ -207,3 +228,51 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { _ => None, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn color_param_accepts_valid_forms() { + let p = json!({ + "hex": "#336699", + "hex_plain": "336699", + "rgb": [0.2, 0.4, 0.6], + "grey": 0.5, + }); + assert!(color_param("cmd", &p, "hex").unwrap().is_some()); + assert!(color_param("cmd", &p, "hex_plain").unwrap().is_some()); + assert_eq!(color_param("cmd", &p, "rgb").unwrap(), Some([0.2, 0.4, 0.6])); + assert_eq!(color_param("cmd", &p, "grey").unwrap(), Some([0.5, 0.5, 0.5])); + assert_eq!(color_param("cmd", &p, "missing").unwrap(), None); + assert_eq!(color_param("cmd", &json!({"c": null}), "c").unwrap(), None); + } + + #[test] + fn color_param_rejects_invalid_forms() { + let bad_cases = [ + ("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ]; + for (input, expected_err) in bad_cases { + let p = json!({ "color": input }); + let err = color_param("test.cmd", &p, "color").unwrap_err(); + assert_eq!(err.to_string(), format!("`test.cmd`: {expected_err}")); + } + + let bad_array = json!({ "color": ["a", "b", "c"] }); + assert!(color_param("test.cmd", &bad_array, "color").is_err()); + + let short_array = json!({ "color": [0.5, 0.5] }); + assert!(color_param("test.cmd", &short_array, "color").is_err()); + + let overflow_array = json!({ "color": [1e40, 0.0, 0.0] }); + assert!(color_param("test.cmd", &overflow_array, "color").is_err()); + + let overflow_scalar = json!({ "color": 1e40 }); + assert!(color_param("test.cmd", &overflow_scalar, "color").is_err()); + } +} diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index e937b6f5..f1cecf11 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -2,12 +2,12 @@ //! (a decal fill with a planar projection), as a fill layer with a decal projection. use serde_json::{Value, json}; -use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source}; +use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source}; use texturecraft_geom::glam::{Vec2, Vec3}; -use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp}; +use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p, vec3}; use crate::tool_cmds::viewport_of; -use crate::{Result, Session, cmd}; +use crate::{Result, Session, StackTarget, cmd}; pub fn specs() -> Vec { vec![ @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", + "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,60 +25,58 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), ] } -/// A `[x, y, z]` param of finite numbers. -fn vec3(p: &Value, key: &str) -> Option { - let a = p.get(key)?.as_array()?; - let v: Vec = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - match v.as_slice() { - [x, y, z] => Some(Vec3::new(*x, *y, *z)), - _ => None, +/// Resolve a viewport hit or explicit world position, using `texture_set` for explicit positions. +/// Returns None when placement is optional and no position or viewport point is given. +fn placement(session: &Session, command: &str, params: &Value, texture_set: usize, optional: bool) -> Result> { + if let Some(position) = vec3(params, "position") { + let normal = vec3(params, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(command, "`position` needs a non-zero `normal`"))?; + return Ok(Some((position, normal, texture_set))); } -} -/// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view -/// center by default) or `position` + `normal`. None when `optional` and neither is given. -fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result> { - if let Some(pos) = vec3(p, "position") { - let n = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?; - return Ok(Some((pos, n))); - } - let vp = viewport_of(s, p); - let at = match (f32p(p, "x"), f32p(p, "y")) { + let viewport = viewport_of(session, params); + let point = match (f32p(params, "x"), f32p(params, "y")) { (Some(x), Some(y)) => Vec2::new(x, y), _ if optional => return Ok(None), - _ => vp * 0.5, + _ => viewport * 0.5, }; - let hit = s.pick(at, vp).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?; - if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) { - return Err(bad(cmd, "that surface belongs to another texture set")); - } - Ok(Some((hit.pos, hit.nrm))) + let hit = session.pick(point, viewport).ok_or_else(|| bad(command, "nothing under that point: place the decal on the mesh"))?; + let hit_set = session.texture_set_of_material(hit.material).ok_or_else(|| bad(command, "that surface has no texture set"))?; + Ok(Some((hit.pos, hit.nrm, hit_set))) } +/// A new decal's height, relative to the mesh diagonal +const DEFAULT_HEIGHT: f32 = 0.25; + +/// The smallest decal side or depth, relative to the mesh diagonal +const MIN_SIZE: f32 = 1e-4; + +/// The largest decal side or depth, relative to the mesh diagonal +const MAX_SIZE: f32 = 10.0; + /// The mesh's diagonal (decal sizes are relative to it). fn mesh_size(s: &Session) -> f32 { let (lo, hi) = s.mesh.bounds(); (hi - lo).length().max(1e-3) } -/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`). -fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> { - let v = p.get("size")?; - let size = match v.as_array() { - Some(a) => [a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32], +/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits +fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { + let value = p.get("size")?; + let size = match value.as_array() { + Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32], None => { - let h = v.as_f64()? as f32; - [h * aspect, h] + let height = value.as_f64()? as f32; + [height * aspect, height] } }; - size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0))) + size.iter().all(|side| side.is_finite()).then(|| size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE))) } /// The decal's up direction: `up` when given, else the camera's (decals are placed upright on @@ -96,11 +94,25 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { fn add(s: &mut Session, p: &Value) -> Result { let cmd = "layer.add.decal"; let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string(); - let img = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; - let aspect = img.width as f32 / img.height.max(1) as f32; - let (center, normal) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?; - let diag = mesh_size(s); - let size = size_param(p, aspect, diag).unwrap_or([diag * 0.25 * aspect, diag * 0.25]); + let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; + let aspect = resource.width as f32 / resource.height.max(1) as f32; + let (center, normal, ts) = placement(s, cmd, p, s.ts(), false)?.ok_or_else(|| bad(cmd, "no placement"))?; + + // None: the image masks a new fill layer + let target = match strp(p, "channel") { + Some("mask") => None, + _ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)), + }; + let set_channels = s.doc.project.texture_set(ts)?.channel_list(); + if let Some(channel) = target + && !set_channels.contains(&channel) + { + return Err(bad(cmd, format!("the texture set has no {} channel", channel.label()))); + } + + let mesh_diagonal = mesh_size(s); + let default_height = mesh_diagonal * DEFAULT_HEIGHT; + let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); let decal = Decal { center: center.to_array(), normal: normal.to_array(), @@ -108,68 +120,139 @@ fn add(s: &mut Session, p: &Value) -> Result { size, rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), offset: [0.0; 2], - depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |d| d.clamp(diag * 1e-4, diag * 10.0)), + // By default it reaches half its larger side into the surface + depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), }; - let ts = s.ts(); - let base = - strp(p, "name").map(str::to_string).unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|n| n.to_str()).unwrap_or("Decal").to_string()); + + // A decal dropped on another texture set goes there and selects it, as a dropped material does + if ts != s.ts() { + crate::set_cmds::select_set(s, ts)?; + } + + let base = strp(p, "name") + .map(str::to_string) + .unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string()); let name = s.doc.project.next_layer_name(ts, &base); - let id = s.edit("Add decal", |s| { + let (id, mask_effect) = s.edit("Add decal", |s| { let id = s.doc.project.alloc_id(); + let Some(channel) = target else { + let effect_id = s.doc.project.alloc_id(); + let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) })); + layer.mask = Some(mask); + crate::layer_cmds::insert_selected(s, layer)?; + s.target = StackTarget::Effect(effect_id); + return Ok((id, Some(effect_id))); + }; + let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() }; - fill.sources.insert(Channel::BaseColor, Source::image(image.clone())); - crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor])) + fill.sources.insert(channel, Source::image(image.clone())); + crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; + Ok((id, None)) })?; - Ok(json!({ "layer": id.0, "decal": decal })) + Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) })) } -/// The decal of fill layer `id`. -fn decal_of(s: &Session, cmd: &str, id: LayerId) -> Result { +/// The decal of fill layer `id`, or of mask fill effect `effect` when given +fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option) -> Result { + if let Some(effect) = effect { + return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), + _ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")), + }; + } + match &s.doc.project.layer(id)?.kind { - LayerKind::Fill(Fill { projection: Projection::Decal(d), .. }) => Ok(*d), + LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), _ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")), } } -fn set(s: &mut Session, p: &Value) -> Result { - let cmd = "layer.decal.set"; - let id = s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|l| l.id).ok_or_else(|| bad(cmd, "no layer"))?; - let mut d = decal_of(s, cmd, id)?; - let diag = mesh_size(s); - if let Some((center, normal)) = placement(s, cmd, p, true)? { - (d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); - } - if p.get("up").is_some() { - d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array(); - } - if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) { - d.size = size; - } - if let Some(r) = f32p(p, "rotation") { - d.rotation = r.rem_euclid(360.0); - } - if let Some(o) = p.get("offset").and_then(Value::as_array) { - let v: Vec = o.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - let [x, y] = v.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) }; - d.offset = [x.clamp(-diag, diag), y.clamp(-diag, diag)]; - } - if let Some(v) = f32p(p, "depth") { - d.depth = v.clamp(diag * 1e-4, diag * 10.0); - } - let image = strp(p, "image").map(str::to_string); - if let Some(name) = &image - && !s.doc.resources.contains_key(name) +fn set(session: &mut Session, params: &Value) -> Result { + let command = "layer.decal.set"; + let effect = u64p(params, "effect").map(LayerId); + let layer_id = match effect { + Some(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(command, format!("no effect {}", effect.0)))?, + None => session.doc.project.content_layer(layer_param(session, command, params)?).map(|layer| layer.id).ok_or_else(|| bad(command, "no layer"))?, + }; + if let (Some(effect), Some(layer)) = (effect, u64p(params, "layer")) + && layer != layer_id.0 { - return Err(bad(cmd, format!("no image resource `{name}`"))); + return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0))); } - s.edit("Edit decal", |s| { - if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind { - f.projection = Projection::Decal(d); - if let Some(name) = image { - f.sources.insert(Channel::BaseColor, Source::image(name)); + + let mut decal = decal_of(session, command, layer_id, effect)?; + let texture_set = + session.doc.project.locate(layer_id).map(|(texture_set, _, _)| texture_set).ok_or_else(|| bad(command, "the decal has no texture set"))?; + let mesh_diagonal = mesh_size(session); + if let Some((center, normal, hit_set)) = placement(session, command, params, texture_set, true)? { + // Selecting another set must not let this decal leave its layer's stack + if hit_set != texture_set { + return Err(bad(command, "that surface belongs to another texture set")); + } + + (decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); + } + if params.get("up").is_some() { + decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array(); + } + if let Some(size) = size_param(params, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) { + decal.size = size; + } + if let Some(rotation) = f32p(params, "rotation") { + decal.rotation = rotation.rem_euclid(360.0); + } + if let Some(offset) = params.get("offset").and_then(Value::as_array) { + let values: Vec = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect(); + let [right, up] = values.as_slice() else { return Err(bad(command, "`offset` must be [right, up]")) }; + + decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)]; + } + if let Some(depth) = f32p(params, "depth") { + decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); + } + + let image = strp(params, "image").map(str::to_string); + if let Some(name) = &image + && !session.doc.resources.contains_key(name) + { + return Err(bad(command, format!("no image resource `{name}`"))); + } + + session.edit("Edit decal", |session| { + if let Some(effect) = effect { + if let Some(EffectKind::Fill { source, projection }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { + *projection = Projection::Decal(decal); + if let Some(image) = image { + *source = Source::image(image); + } + } + } else if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind { + fill.projection = Projection::Decal(decal); + + // The new image goes where the decal's image is (the channel it was placed in) + let placed = fill.sources.values().find_map(|source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }); + match (image, placed) { + (Some(image), Some(placed)) => { + for source in fill.sources.values_mut() { + if let Source::Image { name, .. } = source + && *name == placed + { + name.clone_from(&image); + } + } + } + (Some(image), None) => { + fill.sources.insert(Channel::BaseColor, Source::image(image)); + } + (None, _) => {} } } Ok(()) })?; - Ok(json!({ "layer": id.0, "decal": d })) + Ok(json!({ "layer": layer_id.0, "decal": decal })) } diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 36aa5f3a..5aedd49b 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -2,7 +2,7 @@ //! clipboard: it holds a layer or an effect. use serde_json::{Value, json}; -use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; +use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground}; use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::layer_ops::{empty_texel, fit}; @@ -55,26 +55,29 @@ fn cut(s: &mut Session, p: &Value) -> Result { Ok(json!({ "cut": eid })) } -fn paste(s: &mut Session, p: &Value) -> Result { +fn paste(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.paste"; - let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let layer = layer_param(s, CMD, p)?; - // The selected effect's stack, or the content or mask the selection targets. - let selected = match s.target { - StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x), + let (copied, copied_id) = session.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let effect = copied.project.effect(copied_id).map(|(_, effect)| effect.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let layer = layer_param(session, CMD, params)?; + + // The selected effect's stack, or the content or mask the selection targets + let selected = match session.target { + StackTarget::Effect(selected) if session.selected_layer() == Some(layer) => Some(selected), _ => None, }; - let in_content = |s: &Session, x: LayerId| { - s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x)) + let in_content = |session: &Session, effect_id: LayerId| { + let owner = session.doc.project.effect(effect_id).and_then(|(owner, _)| session.doc.project.layers.get(&owner)); + owner.is_some_and(|owner| owner.content_effects.iter().any(|effect| effect.id == effect_id)) }; - let asked = strp(p, "target").is_some(); + let asked = strp(params, "target").is_some(); let content = match selected { - _ if asked => content_target(p, CMD)?, - Some(x) => in_content(s, x), - None => s.target == StackTarget::Content && s.selected_layer() == Some(layer), + _ if asked => content_target(params, CMD)?, + Some(selected) => in_content(session, selected), + None => session.target == StackTarget::Content && session.selected_layer() == Some(layer), }; - // Effects that fit one stack only go there, unless another was asked for. + + // Effects that fit one stack only go there, unless another was asked for let content = match effect.kind.content_only() { Some(only) if only != content && asked => { return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); @@ -82,46 +85,54 @@ fn paste(s: &mut Session, p: &Value) -> Result { Some(only) => only, None => content, }; - // An instance's content and (unless it has its own) mask belong to its source. - let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) }; - let owner_layer = s.doc.project.layer(owner)?; + + // An instance's content and (unless it has its own) mask belong to its source + let owner = if content { session.doc.project.content_layer(layer).map_or(layer, |source| source.id) } else { session.doc.project.mask_owner(layer) }; + let owner_layer = session.doc.project.layer(owner)?; if content && owner_layer.is_group() { return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name))); } - // A fill reading an anchor point needs one below its new layer. - if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { - anchor_source(s, CMD, owner, *anchor, *channel)?; + + // Each anchor point the effect reads must be below its new layer + for (anchor, channel) in effect.kind.anchors_read() { + anchor_source(session, CMD, owner, anchor, channel)?; } - let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; - let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; - let new = s.edit("Paste effect", |s| { - let new = s.doc.project.alloc_id(); - let l = s.doc.project.layer_mut(owner)?; - let list = if content { - &mut l.content_effects + + let (set, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; + let (size, channels) = session.doc.project.texture_set(set).map(|texture_set| (texture_set.size(), texture_set.channel_list()))?; + + let pasted = session.edit("Paste effect", |session| { + let pasted = session.doc.project.alloc_id(); + let owner_layer = session.doc.project.layer_mut(owner)?; + let stack = if content { + &mut owner_layer.content_effects } else { - let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; - &mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects + let background = + if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; + &mut owner_layer.mask.get_or_insert_with(|| Mask::new(background)).effects }; - let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1); - list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() }); - // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's). - if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) { - s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0])); + let index = selected.and_then(|selected| stack.iter().position(|effect| effect.id == selected)).map_or(stack.len(), |position| position + 1); + stack.insert(index, texturecraft_core::Effect { id: pasted, ..effect.clone() }); + + // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's) + if let Some(image) = copied.pixels.masks.get(&copied_id).filter(|_| !content) { + session.doc.pixels.masks.insert(pasted, fit(image, size, &[0, 0])); } - for c in channels.iter().copied().filter(|_| content) { - if let Some(img) = src.pixels.layer(eid, c) { - s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); + for channel in channels.iter().copied().filter(|_| content) { + if let Some(image) = copied.pixels.layer(copied_id, channel) { + session.doc.pixels.layers.insert((pasted, channel), fit(image, size, &empty_texel(channel))); } } - // The target belongs to the active set's selection: a paste into another set leaves it. - if let Some((lts, _, _)) = s.doc.project.locate(layer) { - s.selected.insert(lts, layer); - if lts == s.ts() { - s.target = StackTarget::Effect(new); + + // The target belongs to the active set's selection: a paste into another set leaves it + if let Some((layer_set, _, _)) = session.doc.project.locate(layer) { + session.selected.insert(layer_set, layer); + if layer_set == session.ts() { + session.target = StackTarget::Effect(pasted); } } - Ok(new) + Ok(pasted) })?; - Ok(json!({ "effect": new.0 })) + + Ok(json!({ "effect": pasted.0 })) } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 78916328..e4d17f53 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -3,8 +3,8 @@ use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] -use texturecraft_core::PROJECT_EXT; -use texturecraft_core::{NormalFormat, Project, TextureSet}; +use texturecraft_core::{NormalFormat, PROJECT_EXT}; +use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; @@ -37,6 +37,15 @@ pub fn specs() -> Vec { always, reimport ), + cmd!( + "file.changeMesh", + "Change mesh", + [], + None, + "{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index", + always, + change_mesh + ), cmd!( "file.exportTextures", "Export textures", @@ -132,7 +141,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()), }) @@ -174,20 +183,25 @@ impl Session { (Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh, (None, None) => return Err(EngineError::Other("the project has no mesh".into())), }; + check_materials(&pf.project, &mesh)?; let source = pf.mesh.clone(); let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect(); - let mut s = Session::new(Document { project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; + let mut s = + Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; + s.sync_images(); s.load_bake_meshes(pf.high_poly, pf.cage); - s.load_skew(pf.skew); + s.load_bake_paint(pf.bake_paint); + s.log.extend(pf.warnings); + Ok(s) } /// The project as a `ProjectFile` (for saving). pub fn project_file(&self) -> ProjectFile { let mut pixels = self.doc.pixels.clone(); - // Drop pixel images whose size no longer matches their texture set (never unloadable). + // Drop pixel images whose size no longer matches their texture set let size_of = |id: texturecraft_core::LayerId| { self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| { self.doc @@ -200,6 +214,7 @@ impl Session { }; pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height()))); pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); + let (high_poly, cage) = self.saved_bake_meshes(); ProjectFile { project: self.doc.project.clone(), @@ -208,9 +223,10 @@ impl Session { mesh: self.mesh_source.clone(), high_poly, cage, - skew: self.saved_skew(), + bake_paint: self.saved_bake_paint(), thumbnail: None, resources: self.doc.resources.iter().map(|(k, v)| (k.clone(), v.as_ref().clone())).collect(), + warnings: Vec::new(), } } @@ -324,6 +340,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 { @@ -342,6 +363,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) } @@ -360,8 +382,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")?; @@ -370,6 +394,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); @@ -407,14 +432,38 @@ 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"))] +fn change_mesh(s: &mut Session, p: &Value) -> Result { + let path = native::path_param(p, "path", "file.changeMesh")?; + let file = native::read_mesh("file.changeMesh", path)?; + let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?; + // Only after the swap succeeded: Reimport mesh and Save keep following the new file. + 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 @@ -441,6 +490,21 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.sync_images(); + // The high polys and the skew map stay. The cage is sampled by triangle index and + // barycentrics, so it stays only for an identical mesh; the low poly's base colours are + // read again from the new mesh. + next.bake_meshes = self.bake_meshes.clone(); + next.bake_meshes.low_base_color = Default::default(); + if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { + next.bake_meshes.cage = None; + next.log.push("the cage mesh was dropped: the low-poly mesh changed".into()); + } + if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { + next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into()); + } + 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 }))) @@ -589,6 +653,8 @@ use unsupported as save_copy; #[cfg(target_arch = "wasm32")] use unsupported as reimport; #[cfg(target_arch = "wasm32")] +use unsupported as change_mesh; +#[cfg(target_arch = "wasm32")] use unsupported as export_textures; #[cfg(target_arch = "wasm32")] use unsupported as export_mesh; @@ -603,6 +669,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(); @@ -679,6 +798,82 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A project built on one mesh moves to another mesh file with its layers intact, even when + /// it carries its own copy of the mesh (a plain reimport would only re-read that copy). + #[test] + fn change_mesh_swaps_the_mesh_and_keeps_the_layers() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let quad = dir.join("quad.obj"); + std::fs::write(&quad, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n").unwrap(); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layers = s.doc.project.layers.len(); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap(); + assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use"); + assert_eq!(s.doc.project.mesh_file, "tri.obj"); + assert_eq!(s.doc.project.layers.len(), layers, "the layers stay"); + std::fs::remove_dir_all(&dir).ok(); + } + + /// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B, + /// not A. A failed change leaves the remembered path alone. + #[test] + fn change_mesh_remembers_the_new_file_for_reimport() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"); + let (a, b) = (dir.join("a.obj"), dir.join("b.obj")); + std::fs::write(&a, obj(1.0)).unwrap(); + std::fs::write(&b, obj(2.0)).unwrap(); + let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap(); + let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap(); + // A failed change (unreadable file) keeps A. + let missing = dir.join("missing.obj"); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err()); + assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str())); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert_eq!(width(&s), 2.0); + let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered"); + assert_ne!(a_abs, b_abs); + // The remembered path survives save and reopen. + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str())); + // Edit B, then Reimport from the remembered path: B's edits arrive, not A. + std::fs::write(&b, obj(3.0)).unwrap(); + let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap(); + crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap(); + assert_eq!(width(&reopened), 3.0); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.obj"); + std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + // Same triangle count, other vertices. + let b = dir.join("b.obj"); + std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); + let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.bake_meshes.cage = Some(cage); + let _ = s.bake_meshes.low_base_color.set(Err("old".into())); + // The same mesh again keeps the cage but not the cached colours. + crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_some()); + assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { // A GLB quad whose mesh and node have no name: its one part is named after the file. 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..1e7c2b69 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 } } @@ -239,8 +253,8 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { } Filter::ColorBalance { shadows, midtones, highlights } => { for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] { - if p.get(key).is_some() { - let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; + if let Some(val) = p.get(key).filter(|v| !v.is_null()) { + let v = color_of(val).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; *slot = v.map(|x| x.clamp(-1.0, 1.0)); } } @@ -291,8 +305,7 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { } Filter::ReplaceColor { from, to, tolerance, softness } => { for (key, slot) in [("from", from), ("to", to)] { - if p.get(key).is_some() { - let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")")))?; + if let Some(v) = color_param(cmd, p, key)? { *slot = v.map(|x| x.clamp(0.0, 1.0)); } } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 228d37e1..a1140aa1 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,56 @@ 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: global adjustments, then its resolution, replaced inputs and curvature detail 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, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast }); + if !generator.resolution.is_default() { + out["resolution"] = + json!({ "mode": format!("{:?}", generator.resolution.mode), "custom": generator.resolution.custom, "factor": generator.resolution.factor }); + } + if !generator.inputs.is_empty() { + out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::>().into(); + } + 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 { @@ -94,7 +112,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { v["geometryMask"] = json!(parts); } if matches!(l.kind, LayerKind::Paint) { - // Sorted: the store is a hash map, and inspect output must be stable. + // Sort the hash map entries for stable inspection output let mut painted: Vec<(&str, usize)> = s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect(); painted.sort_unstable(); @@ -129,26 +147,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,13 +187,14 @@ 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) }, "layers": stack(s, ts), "tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) }, "view": s.view.label(), + "bakePreview": crate::bake_preview::preview_json(s), "camera": crate::view_cmds::camera_json(s), "display": s.doc.project.display, "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 747d7da1..5d5fc104 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -71,9 +71,9 @@ fn add_paint(s: &mut Session, p: &Value) -> Result { } /// A uniform fill from the `color`, `roughness`, `metallic`, `height` and `opacity` params. -pub(crate) fn fill_from(p: &Value) -> Fill { +pub(crate) fn fill_from(cmd: &str, p: &Value) -> Result { let mut fill = Fill::default(); - if let Some(c) = color_param(p, "color") { + if let Some(c) = color_param(cmd, p, "color")? { fill.sources.insert(Channel::BaseColor, Source::Uniform(c)); } for (key, ch) in [("roughness", Channel::Roughness), ("metallic", Channel::Metallic), ("height", Channel::Height), ("opacity", Channel::Opacity)] { @@ -81,13 +81,13 @@ pub(crate) fn fill_from(p: &Value) -> Fill { fill.sources.insert(ch, Source::Uniform([v; 3])); } } - fill + Ok(fill) } fn add_fill(s: &mut Session, p: &Value) -> Result { let ts = s.ts(); let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Fill layer")); - let fill = fill_from(p); + let fill = fill_from("layer.add.fill", p)?; let id = s.edit("Add fill layer", |s| { let id = s.doc.project.alloc_id(); insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &channels_of(s))) @@ -168,6 +168,12 @@ fn group(s: &mut Session, p: &Value) -> Result { fn select(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.select", p)?; let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?; + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + } + s.active_set = ts; s.selected.insert(ts, id); s.target = match p.get("target") { @@ -184,6 +190,7 @@ fn select(s: &mut Session, p: &Value) -> Result { }, None => StackTarget::Content, }; + s.revision = s.revision.wrapping_add(1); Ok(json!({ "layer": id.0, "textureSet": ts })) } @@ -309,6 +316,10 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { let solo = boolp(p, "solo") == Some(true); let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; let normal_format = normal_format_param("layer.fill.set", p)?; + let low = color_param("layer.fill.set", p, "low")?.unwrap_or([0.0; 3]); + let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]); + let color = color_param("layer.fill.set", p, "color")?; + let value = color_param("layer.fill.set", p, "value")?; let source = if let Some(kind) = strp(p, "procedural") { let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; let mut pr = Procedural::new(kind); @@ -325,8 +336,8 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { pr.balance = v.clamp(-1.0, 1.0); } pr.invert = boolp(p, "invert").unwrap_or(false); - Some(Source::Procedural { pattern: pr, low: color_param(p, "low").unwrap_or([0.0; 3]), high: color_param(p, "high").unwrap_or([1.0; 3]) }) - } else if let Some(c) = color_param(p, "color").or_else(|| color_param(p, "value")) { + Some(Source::Procedural { pattern: pr, low, high }) + } else if let Some(c) = color.or(value) { Some(Source::Uniform(c)) } else if let Some(name) = strp(p, "image") { Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() }) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ec99643f..8a5b3df0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,14 +8,17 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod auto_rebake; -pub mod bake_cmds; +pub mod bake; +pub mod bake_preview; 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; @@ -23,13 +26,22 @@ 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; +mod path_draft; pub mod path_tool; -// Mesh reimport reads files: native only. +mod polygon_fill; +mod polygon_fill_drag; +// Mesh reimport reads files on native targets only #[cfg(not(target_arch = "wasm32"))] mod preserve; pub mod preset_cmds; @@ -42,18 +54,24 @@ pub mod set_cmds; pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; +pub mod thumbs; +mod tool_availability; pub mod tool_cmds; +mod triangle_partition; +mod uv_stroke_state; pub mod uv_tile_cmds; pub mod view_cmds; -pub use bake_cmds::{BakeMesh, BakeMeshes, BakeTask}; +pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; +pub use bake_preview::{BakePreview, PreviewShow}; 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/link_cmds.rs b/crates/engine/src/link_cmds.rs index ddd7bfd5..3a77ae50 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -8,7 +8,9 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use texturecraft_core::{BakedMap, Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source}; -use texturecraft_formats::mcmat::{MCMAT_EXT, MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat}; +#[cfg(not(target_arch = "wasm32"))] +use texturecraft_formats::mcmat::MCMAT_EXT; +use texturecraft_formats::mcmat::{MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat}; use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp}; use crate::materials::Place; @@ -54,7 +56,7 @@ pub fn specs() -> Vec { "Save MaterialCraft package", [], None, - "{layer?, path} — writes the MaterialCraft package (.mcraft) behind a material layer, to open in MaterialCraft", + "{layer?, path} — writes the MaterialCraft source (.mcraft or .sbs) behind a material layer", has_layer, save_source ), @@ -176,7 +178,9 @@ fn save_source(s: &mut Session, p: &Value) -> Result { const CMD: &str = "material.link.saveSource"; let id = layer_param(s, CMD, p)?; let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; - let path = if path.to_ascii_lowercase().ends_with(&format!(".{MCRAFT_EXT}")) { path.to_string() } else { format!("{path}.{MCRAFT_EXT}") }; + let link = link_of(s, CMD, id)?; + let ext = source_extension(&link.package); + let path = if path.to_ascii_lowercase().ends_with(&format!(".{ext}")) { path.to_string() } else { format!("{path}.{ext}") }; let bytes = s.link_package(id)?; texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad(CMD, e.to_string()))?; Ok(json!({"path": path})) @@ -193,6 +197,10 @@ fn save_source(_: &mut Session, _: &Value) -> Result { pub struct LinkJob { pub layer: LayerId, pub package: Arc>, + /// The source package extension (`mcraft` or `sbs`). + pub source_ext: &'static str, + /// The named graph in a linked material; direct package imports use its default. + pub graph: Option, /// Pixels across (the texture set's resolution). pub size: u32, /// Every parameter's value, by id, in MaterialCraft's typed form. @@ -224,7 +232,7 @@ fn quiet(program: &std::path::Path) -> std::process::Command { c } -/// Open `package` (a `.mcraft` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this +/// Open `package` (a `.mcraft` or `.sbs` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this /// program, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { @@ -234,11 +242,21 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Source file extensions are chosen from the linked resource name, never an untrusted path. +pub fn source_extension(name: &str) -> &'static str { + if name.to_ascii_lowercase().ends_with(".sbs") { "sbs" } else { MCRAFT_EXT } +} + impl LinkJob { /// Cook through `materialcraft-cli` (`$MATERIALCRAFT_CLI`, next to this program, or on /// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K). #[cfg(not(target_arch = "wasm32"))] pub fn run(&self) -> Result> { + self.run_with_cli(&materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI")) + } + + #[cfg(not(target_arch = "wasm32"))] + fn run_with_cli(&self, cli: &std::path::Path) -> Result> { let other = |e: String| EngineError::Other(e); let n = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("texturecraft-link-{}-{n}", std::process::id())); @@ -250,15 +268,27 @@ impl LinkJob { std::fs::write(&p, bytes).map_err(|e| other(format!("{name}: {e}")))?; utf8(&p) }; - let src = write("source.mcraft", &self.package)?; + let ext = if self.source_ext == "sbs" { "sbs" } else { MCRAFT_EXT }; + let src = write(&format!("source.{ext}"), &self.package)?; let mut inputs = Map::new(); for (i, (id, png)) in self.inputs.iter().enumerate() { inputs.insert(id.clone(), json!(write(&format!("input{i}.png"), png)?)); } let out = dir.join(format!("out.{MCMAT_EXT}")); let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs}); - let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"); - let run = quiet(&cli).arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()).output().map_err(|e| { + let mut command = quiet(cli); + if let Some(graph) = &self.graph { + // Opening the source starts on its first graph; select the graph saved in the link. + let script = json!({"open": src, "steps": [ + {"id": "graph.open", "params": {"graph": graph}}, + {"id": "file.exportMaterial", "params": params}, + ]}); + let script_path = write("cook.json", script.to_string().as_bytes())?; + command.arg("batch").arg(script_path); + } else { + command.arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()); + } + let run = command.output().map_err(|e| { other(format!( "MaterialCraft's command line ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT_CLI", cli.display() @@ -299,7 +329,15 @@ impl Session { let bytes = if is_mcraft(bytes) { let ts = self.ts(); let size = self.doc.project.texture_set(ts)?.resolution; - let job = LinkJob { layer: LayerId(0), package: Arc::new(bytes.to_vec()), size, values: Map::new(), inputs: Vec::new() }; + let job = LinkJob { + layer: LayerId(0), + package: Arc::new(bytes.to_vec()), + source_ext: MCRAFT_EXT, + graph: None, + size, + values: Map::new(), + inputs: Vec::new(), + }; cooked = job.run()?; cooked.as_slice() } else { @@ -314,7 +352,7 @@ impl Session { let (id, names) = self.edit(&label, |s| { let ts = s.ts(); let stem = texturecraft_formats::sanitize_resource_name(&m.manifest.name); - let package = unique(s, &format!("{stem}.{MCRAFT_EXT}")); + let package = unique(s, &format!("{stem}.{}", source_extension(&m.manifest.source))); s.doc.resources.insert(package.clone(), Arc::new(m.source.clone())); let link = MaterialLink { name: m.manifest.name.clone(), @@ -343,7 +381,7 @@ impl Session { Ok(id) } - /// The `.mcraft` package behind linked layer `id`. + /// The source package behind linked layer `id`. pub fn link_package(&self, id: LayerId) -> Result>> { let link = link_of(self, "material.link", id)?; self.doc.resources.get(&link.package).cloned().ok_or_else(|| EngineError::Other(format!("the package of {} is missing", link.name))) @@ -354,62 +392,80 @@ impl Session { Ok(link_of(self, "material.link", id)?.params.iter().map(|p| (p.id.clone(), p.value.clone())).collect()) } - /// The re-cook of linked layer `id` with `overrides` over its values, at its texture set's - /// resolution, with the set's baked mesh maps for matching graph inputs. + /// Prepare a re-cook with current parameter values and matching baked mesh maps pub fn link_job(&self, id: LayerId, overrides: &Map) -> Result { let link = link_of(self, "material.link", id)?; - let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("layer {} is not in a stack", id.0)))?; + let (texture_set, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("layer {} is not in a stack", id.0)))?; let mut values = self.link_values(id)?; values.extend(overrides.clone()); + let mut inputs = Vec::new(); - if let Some(baked) = self.doc.baked.get(&ts) { - for ident in &link.inputs { - let Some((m, data)) = BakedMap::for_input(ident).and_then(|m| Some((m, baked.maps.get(&m)?))) else { continue }; - let png = texturecraft_formats::mcmat::mesh_map_png(baked.resolution, m.components(), data).map_err(|e| EngineError::Other(e.to_string()))?; - inputs.push((ident.clone(), png)); + if let Some(baked) = self.doc.baked.get(&texture_set) { + for identifier in &link.inputs { + let Some((map, data)) = BakedMap::parse(identifier).and_then(|map| Some((map, baked.maps.get(&map)?))) else { continue }; + + let png = texturecraft_formats::mcmat::mesh_map_png(baked.resolution, map.components(), data) + .map_err(|error| EngineError::Other(error.to_string()))?; + inputs.push((identifier.clone(), png)); } } - // shortcut: one cook per texture set at its base resolution; UDIM tiles share it. - let size = self.doc.project.texture_set(ts)?.resolution; - Ok(LinkJob { layer: id, package: self.link_package(id)?, size, values, inputs }) + + // UDIM tiles share one cook at the texture set's base resolution + let size = self.doc.project.texture_set(texture_set)?.resolution; + Ok(LinkJob { + layer: id, + package: self.link_package(id)?, + source_ext: source_extension(&link.package), + graph: Some(link.graph.clone()), + size, + values, + inputs, + }) } /// Swap in maps a [`LinkJob`] cooked (`.mcmat` bytes) and the values they were cooked with. /// With `merge`, this folds into the previous undo step when that was an edit of the same kind /// (a parameter set while the cook ran). pub fn apply_link_cook(&mut self, id: LayerId, bytes: &[u8], merge: bool) -> Result<()> { - let m = read_mcmat(bytes).map_err(|e| EngineError::Other(e.to_string()))?; - let maps = decoded_maps(&m)?; - let names = self.edit_merging(EDIT, merge, |s| { - let LayerKind::Fill(mut fill) = s.doc.project.layer(id)?.kind.clone() else { + let material = read_mcmat(bytes).map_err(|error| EngineError::Other(error.to_string()))?; + let maps = decoded_maps(&material)?; + + let names = self.edit_merging(EDIT, merge, |session| { + let LayerKind::Fill(mut fill) = session.doc.project.layer(id)?.kind.clone() else { return Err(EngineError::Other(format!("layer {} is not a fill", id.0))); }; + let link = fill.link.as_mut().ok_or_else(|| EngineError::Other(format!("layer {} is not a MaterialCraft material", id.0)))?; - for p in &mut link.params { - if let Some(cooked) = m.manifest.parameters.iter().find(|c| c.id == p.id) { - p.value = cooked.value.clone(); + for parameter in &mut link.params { + if let Some(cooked) = material.manifest.parameters.iter().find(|candidate| candidate.id == parameter.id) { + parameter.value = cooked.value.clone(); } } - link.size = m.manifest.size[0]; + link.size = material.manifest.size[0]; let stem = texturecraft_formats::sanitize_resource_name(&link.name); - let old: Vec = - fill.sources.values().filter_map(|src| if let Source::Image { name, .. } = src { Some(name.clone()) } else { None }).collect(); - let names = put_maps(s, &stem, &maps, &mut fill); - s.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill); - // Old maps go unless another layer (a duplicate) still shows them. - let mut used = Vec::new(); - for set in 0..s.doc.project.texture_sets.len() { - for root in s.doc.project.texture_sets.get(set).map(|t| t.stack.clone()).unwrap_or_default() { - crate::material_lib::images_used(&s.doc.project, root, &mut used, 0); + let old_names: Vec = + fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect(); + let names = put_maps(session, &stem, &maps, &mut fill); + session.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill); + + // Duplicated layers may still use the earlier maps + let mut used_names = Vec::new(); + for set in 0..session.doc.project.texture_sets.len() { + for root in session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.clone()).unwrap_or_default() { + crate::material_lib::images_used(&session.doc.project, root, &mut used_names, 0); } } - for name in old.iter().filter(|n| !used.contains(n)) { - s.doc.resources.remove(name); + for name in old_names.iter().filter(|name| !used_names.contains(name)) { + session.doc.resources.remove(name); } + Ok(names) })?; - self.sync_images(); + + // Reuse the validated maps before synchronization considers decoding missing images self.cache_decoded(names, maps); + self.sync_images(); + Ok(()) } @@ -444,3 +500,54 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec, texturecraft } names } + +#[cfg(all(test, unix))] +mod subprocess_tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn cook_uses_the_saved_graph_and_source_type_without_global_environment() { + let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("texturecraft-cook-test-{}-{id}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cli = dir.join("materialcraft-cli"); + let script = r#"#!/bin/sh +set -eu +case "$1" in + batch) + grep -F '"graph":"Second"' "$2" >/dev/null + grep -F '"id":"file.exportMaterial"' "$2" >/dev/null + test -f "$(dirname "$2")/source.sbs" + test -f "$(dirname "$2")/input0.png" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + run) + test "$(basename "$2")" = "source.mcraft" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + *) exit 1 ;; +esac +"#; + std::fs::write(&cli, script).unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::write(dir.join("result.mcmat"), b"cooked").unwrap(); + let mut job = LinkJob { + layer: LayerId(1), + package: Arc::new(b"source".to_vec()), + source_ext: "sbs", + graph: Some("Second".into()), + size: 64, + values: Map::new(), + inputs: vec![("curvature".into(), b"png".to_vec())], + }; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = None; + job.source_ext = "mcraft"; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = Some("wrong".into()); + assert!(job.run_with_cli(&cli).is_err()); + assert!(job.run_with_cli(&dir.join("missing")).is_err()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..c0887849 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, + BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, + MaskBackground, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, 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?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), 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), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), 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 ), @@ -141,7 +141,7 @@ fn add_mask(s: &mut Session, p: &Value, bg: MaskBackground) -> Result { } fn add_color_mask(s: &mut Session, p: &Value) -> Result { - let color = color_param(p, "color").unwrap_or([1.0, 0.0, 0.0]); + let color = color_param("mask.add.colorSelection", p, "color")?.unwrap_or([1.0, 0.0, 0.0]); let tolerance = f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0); with_mask(s, p, "mask.add.colorSelection", "Add mask with color selection", |s, id| { let eid = s.doc.project.alloc_id(); @@ -242,7 +242,7 @@ fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) - let label = format!("Add {}", kind.name().to_ascii_lowercase()); let eid = with_mask(s, p, "effect.add", &label, |s, id| { let eid = s.doc.project.alloc_id(); - // An instance's content and (unless it has its own) mask belong to its source. + // An instance's content and inherited mask belong to its source let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) }; let l = s.doc.project.layer_mut(id)?; let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; @@ -285,7 +285,7 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { let blend = blend_param("effect.add.fill", p, "blend")?.unwrap_or(BlendMode::Normal); let id = layer_param(s, "effect.add.fill", p)?; if content_target(p, "effect.add.fill")? { - let mut fill = crate::layer_cmds::fill_from(p); + let mut fill = crate::layer_cmds::fill_from("effect.add.fill", p)?; if fill.sources.is_empty() { fill.sources = s.doc.project.layer(id)?.channels.keys().map(|c| (*c, Source::uniform_of(*c))).collect(); } @@ -314,39 +314,128 @@ 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, Generator::MAX_NOISE_AMOUNT); } - if let Some(v) = f32p(p, "noiseScale") { - g.noise_scale = v.clamp(0.01, 1000.0); + if let Some(offset) = f32p(params, "offset") { + generator.offset = offset.clamp(-1.0, 1.0); } - if let Some(v) = u64p(p, "seed") { - g.seed = v as u32; + if let Some(noise_scale) = f32p(params, "noiseScale") { + generator.noise_scale = noise_scale.clamp(Generator::MIN_NOISE_SCALE, Generator::MAX_NOISE_SCALE); } - if let Some(v) = boolp(p, "invert") { - g.invert = v; + if let Some(seed) = u64p(params, "seed") { + generator.seed = seed as u32; } - if let Some(d) = color_param(p, "direction") { - g.direction = d; + if let Some(invert) = boolp(params, "invert") { + generator.invert = invert; } + if let Some(direction) = color_param(command, params, "direction")? { + generator.direction = direction; + } + if let Some(blur) = f32p(params, "blur") { + generator.global.blur = blur.clamp(0.0, 1.0); + } + if let Some(balance) = f32p(params, "balance") { + generator.global.balance = balance.clamp(0.0, 1.0); + } + if let Some(contrast) = f32p(params, "contrast") { + generator.global.contrast = contrast.clamp(0.0, 1.0); + } + if let Some(value) = params.get("resolution") { + let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; + generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; + } + if let Some(custom) = u64p(params, "customResolution") { + generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; + } + if let Some(factor) = params.get("resolutionFactor") { + let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; + generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; + } + + // 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) +} + +/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. +fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { + const CMD: &str = "effect.set"; + let Some(name) = params.get("input") else { return Ok(None) }; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?; + let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?; + + let image = strp(params, "inputImage"); + let value = f32p(params, "inputValue"); + let anchor = u64p(params, "inputAnchor"); + let baked = boolp(params, "inputBaked") == Some(true); + let source = match (image, value, anchor, baked) { + (Some(image), None, None, false) => { + if !session.images.contains_key(image) { + return Err(bad(CMD, format!("no image resource `{image}`"))); + } + Some(Source::Image { name: image.to_string(), normal_format: Default::default() }) + } + (None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])), + (None, None, Some(anchor), false) => { + let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height); + Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?) + } + (None, None, None, true) => None, + _ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")), + }; + Ok(Some((map, source))) +} + +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 +502,111 @@ 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")?; + let generator_kind = params + .get("generator") + .map(|value| { + let name = value.as_str().ok_or_else(|| bad(CMD, "`generator` must be a string"))?; + GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`"))) + }) + .transpose()?; + + // `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; + + // `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back + let input = match session.doc.project.effect(effect) { + Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => generator_input_param(session, owner, params)?, + _ => None, + }; + + // 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")?, - EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") - && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) + if let Some(name) = name_param(params) { + edited.name = name.to_string(); + } + + match &mut edited.kind { + EffectKind::Generator(generator) => { + if let Some(kind) = generator_kind + && kind != generator.kind { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + generator.kind = kind; + generator.detail = Generator::new(kind).detail; + generator.inputs.retain(|map, _| kind.inputs().contains(map)); + } + generator_from(CMD, params, generator)?; + if let Some((map, source)) = input { + if !generator.kind.inputs().contains(&map) { + return Err(bad(CMD, format!("this generator has no `{}` input", map.id()))); + } + match source { + Some(source) => generator.inputs.insert(map, source), + None => generator.inputs.remove(&map), + }; } } - EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), + 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(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(params, "value") + && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) + { + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); + } + } + 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 +616,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_lib.rs b/crates/engine/src/material_lib.rs index 8a59b186..8c5c819f 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use texturecraft_compose::PixelStore; -use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet}; use crate::commands::{CommandSpec, always, has_layer}; use crate::materials::Place; @@ -36,27 +36,26 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and fill effects). -pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec, depth: usize) { +/// Image resources a layer subtree uses (fill sources and mask or content effects). +pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; } - let Some(l) = p.layers.get(&id) else { return }; - if let LayerKind::Fill(f) = &l.kind { - for s in f.sources.values() { - if let Source::Image { name, .. } = s { + let Some(layer) = project.layers.get(&id) else { return }; + + if let LayerKind::Fill(fill) = &layer.kind { + for source in fill.sources.values() { + if let Source::Image { name, .. } = source { out.push(name.clone()); } } - out.extend(f.link.as_ref().map(|link| link.package.clone())); + out.extend(fill.link.as_ref().map(|link| link.package.clone())); } - for e in l.mask.iter().flat_map(|m| m.effects.iter()) { - if let EffectKind::Fill { source: Source::Image { name, .. }, .. } = &e.kind { - out.push(name.clone()); - } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { + out.extend(effect.kind.images_read().map(str::to_string)); } - for c in l.children() { - images_used(p, *c, out, depth + 1); + for child in layer.children() { + images_used(project, *child, out, depth + 1); } } @@ -71,7 +70,7 @@ impl Session { set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); project.texture_sets.push(set); - let mut mini = Document { project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }; + let mut mini = Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }; let new = crate::layer_ops::copy_tree(&self.doc, id, &mut mini, 0, None, false, 0)?; if let Ok(l) = mini.project.layer_mut(new) { l.name = name.to_string(); @@ -86,9 +85,10 @@ impl Session { mesh: None, high_poly: Vec::new(), cage: None, - skew: None, + bake_paint: BTreeMap::new(), thumbnail: None, resources, + warnings: Vec::new(), }; texturecraft_formats::save_project_bytes(&pf).map_err(fe) } @@ -112,7 +112,7 @@ impl Session { .and_then(|t| t.stack.last().copied()) .ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?; let resources: BTreeMap>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); - let src = Document { project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: resources.clone() }; + let src = Document { bake_paint: BTreeMap::new(), project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: resources.clone() }; let id = self.edit("Add smart material", |s| { for (k, v) in &resources { s.doc.resources.entry(k.clone()).or_insert_with(|| v.clone()); 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/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 06c5ba75..68792d5c 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -14,7 +14,9 @@ use serde_json::{Value, json}; use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source}; use texturecraft_formats::materialx_read::{Material, Value as Mtlx}; -use crate::commands::{CommandSpec, always, bad, strp}; +use crate::commands::{CommandSpec, always}; +#[cfg(not(target_arch = "wasm32"))] +use crate::commands::{bad, strp}; use crate::{EngineError, Result, Session, cmd}; pub fn specs() -> Vec { diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 3f3a414e..4524b361 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Use image as mesh map", [], None, - "{ts?, map: mesh map id (normal_base, ambient_occlusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format. A UV-tiled set takes one image per tile, named alike with the tile number (`image: \"ao.1001.png\"` finds ao.1002.png…)", + "{ts?, map: mesh map id (normal, ambientOcclusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format. A UV-tiled set takes one image per tile, named alike with the tile number (`image: \"ao.1001.png\"` finds ao.1002.png…)", always, set ), @@ -38,52 +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 => (set.bake.resolution.saturating_mul(cols), set.bake.resolution.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(); @@ -118,7 +157,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { - return Err(bad(CMD, format!("texture set {ts} has no {} map", map.label()))); + return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id()))); } s.edit("Clear mesh map", |s| { if let Some(b) = s.doc.baked.get_mut(&ts) { 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..5d5bfbf4 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -1,5 +1,5 @@ //! Interactive painting on the session: strokes (begin / continue / end / cancel), polygon fill -//! and the color picker. The UI, CLI and agents all go through these. +//! and the material picker. The UI, CLI and agents all go through these. use std::collections::{BTreeMap, BTreeSet}; @@ -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 { @@ -135,6 +155,7 @@ impl Session { /// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh /// (the Clone tool's destination anchor). fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option) -> Result<()> { + self.refuse_while_baking()?; let tool = self.tool.tool; let erase = tool == Tool::Eraser; let quick_mask = self.quick_mask.editing; @@ -224,7 +245,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, @@ -276,9 +297,18 @@ impl Session { Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile }) } + /// Painting is paused while a bake preview shows the baked maps instead of the material. + pub(crate) fn refuse_while_baking(&self) -> Result<()> { + match self.painting_blocked() { + Some(why) => Err(EngineError::Other(why.into())), + None => Ok(()), + } + } + /// Start a stroke at `screen` (viewport pixels). Returns false when the cursor misses the /// mesh (the stroke starts anyway and resumes when the cursor enters the mesh). pub fn begin_stroke(&mut self, screen: Vec2, viewport: Vec2, pressure: f32) -> Result { + self.refuse_while_baking()?; self.cancel_stroke(); match self.tool.tool { Tool::PolygonFill => return self.polygon_fill(screen, viewport).map(|_| true), @@ -291,12 +321,16 @@ 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.refuse_while_baking()?; 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 +338,47 @@ 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 radius = settings.uv_stamp_radius(pressure); + 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 +513,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,77 +526,49 @@ 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 self.paint_fill(ts, canvas); + } + + // 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)) + } + + /// 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(()); } - 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(()) - }) - } - /// 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 - } + 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. + /// Material 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 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); - let mut out = BTreeMap::new(); - for c in cache.composite.channels.keys() { - let v = cache.composite.value(*c, x, y); - self.tool.values.insert(*c, v); - out.insert(*c, v); + let texture_set = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); + let cache = self.caches.get(texture_set).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + + let (width, height) = (cache.size.0 as f32, cache.size.1 as f32); + let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32); + + let mut picked = BTreeMap::new(); + for channel in cache.composite.channels.keys() { + let value = cache.composite.value(*channel, x, y); + self.tool.values.insert(*channel, value); + picked.insert(*channel, value); } - Ok(out) + Ok(picked) } /// The stroke canvas alpha of the active stroke (for overlays and tests). @@ -617,34 +615,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/path_draft.rs b/crates/engine/src/path_draft.rs new file mode 100644 index 00000000..6322a7dc --- /dev/null +++ b/crates/engine/src/path_draft.rs @@ -0,0 +1,13 @@ +//! A new Path tool path previewed in the document before it is applied + +use serde_json::Value; + +use crate::Document; + +/// A new path previewed in the document before it is applied +pub(crate) struct PathDraft { + /// The document before the preview + pub(crate) base: Document, + /// What painting the preview last reported (the commit's report when nothing changed since) + pub(crate) painted: Value, +} diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 150a103e..745e3197 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -7,56 +7,108 @@ //! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_compose::{PaintTarget, PixelStore}; +use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape}; +use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; -use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; +use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; +use crate::path_draft::PathDraft; use crate::session::{StackTarget, Tool}; use crate::tool_cmds::{points_param, set_tool, viewport_of}; -use crate::{EngineError, Result, Session, cmd}; +use crate::{Document, EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// The undo step that adds a new path +pub(crate) const NEW_PATH_LABEL: &str = "Path"; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; +/// A stored path's viewport is clamped to this range (pixels per side) before painting from it +const MIN_PAINT_VIEWPORT_PX: f32 = 16.0; +const MAX_PAINT_VIEWPORT_PX: f32 = 16384.0; +/// Sampling step of a 3D path's curve on the mesh for the views, in its paint viewport pixels +const SURFACE_STEP_PX: f32 = 4.0; const MIN_PROJECTIVE_W: f32 = 1e-6; +// Match the minimum world-space scale used by brush stamps +const MIN_BRUSH_SCALE: f32 = 1e-4; // Allow ray hits to differ slightly from transformed texel positions const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001; -/// The curve being edited with the Path tool. +/// The curve being edited with the Path tool #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PathState { - /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view). + /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view) pub points: Vec, - /// The points are texture coordinates (placed in the 2D view). + /// The points are texture coordinates (placed in the 2D view) pub uv: bool, - /// The curve loops back to its first point. + /// The curve loops back to its first point pub closed: bool, - /// A closed path fills its interior instead of stroking the curve. + /// A closed path fills its interior instead of stroking the curve pub fill: bool, - /// The stored path being edited: (path sublayer, index). Changes repaint it live. + /// The stored path being edited: (path sublayer, index). Changes repaint it live #[serde(default)] pub editing: Option<(LayerId, usize)>, - /// This edit has already repainted: later changes join its undo step, not an earlier edit's. + /// This edit has already repainted: later changes join its undo step, not an earlier edit's #[serde(default)] pub edited: bool, + /// The selected control point (drawn in the accent color; Backspace or Remove point removes it) + #[serde(default)] + pub selected: Option, } impl PathState { /// Append a control point; a point placed in the other view starts a new path. - pub fn push(&mut self, p: Vec3, uv: bool) { + pub fn push(&mut self, point: Vec3, uv: bool) { if uv != self.uv { self.points.clear(); self.uv = uv; } if self.points.len() < MAX_PATH_POINTS { - self.points.push(p); + self.points.push(point); + } + } + + /// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't + pub fn insert(&mut self, at: usize, point: Vec3) -> Option { + if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS { + return None; + } + + self.points.insert(at, point); + self.selected = Some(at); + self.selected + } + + /// The same curve (points, open or closed, filled, view) as `other` + fn same_curve(&self, other: &PathState) -> bool { + (&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv) + } + + /// Empty the tool for the next path: no points, open, nothing selected or edited + pub fn clear(&mut self) { + self.points.clear(); + self.closed = false; + self.selected = None; + self.editing = None; + self.edited = false; + } + + /// Remove the selected control point, or the last one when none is selected + pub fn remove_selected(&mut self) { + let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1)); + if let Some(i) = at { + self.points.remove(i); + } + if self.closed && self.points.len() < 3 { + self.closed = false; } } } @@ -116,31 +168,35 @@ pub fn specs() -> Vec { ] } +/// Set the curve from command parameters, then preview or commit it in the supplied viewport fn path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "tool.path"; if s.tool.tool != Tool::Path { set_tool(s, Tool::Path)?; } - let vp = viewport_of(s, p); + + let viewport = viewport_of(s, p); if boolp(p, "clear") == Some(true) { - s.tool.path.points.clear(); - s.tool.path.editing = None; + s.cancel_path(); } + let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) { - (Some(pts), _) => Some(( - pts.iter() + (Some(pixels), _) => Some(( + pixels + .iter() .enumerate() - .map(|(i, q)| s.pick(*q, vp).map(|h| h.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) + .map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) .collect::>>()?, false, )), - (None, Some(pts)) => Some((pts.iter().map(|q| q.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), + (None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), (None, None) => None, }; if let Some((points, uv)) = placed { if points.len() > MAX_PATH_POINTS { return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points"))); } + s.tool.path.points = points; s.tool.path.uv = uv; } @@ -151,19 +207,21 @@ fn path(s: &mut Session, p: &Value) -> Result { s.tool.path.fill = v; } s.revision = s.revision.wrapping_add(1); + let committed = if boolp(p, "commit") == Some(true) { - let r = s.commit_path(vp)?; + let report = s.commit_path(viewport)?; s.update(); - r + report } else { - if s.path_live()? { + if s.path_live_in_view(viewport)? { s.update(); } Value::Null }; - let st = &s.tool.path; - let editing = st.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); - Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "editing": editing, "committed": committed })) + + let path = &s.tool.path; + let editing = path.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); + Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed })) } /// The `effect` and `index` params naming a stored path, with the path. @@ -177,20 +235,25 @@ fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathSh Ok((eid, i, shape)) } +/// Finish any draft and load a stored path's geometry and paint settings for live editing fn edit_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.edit"; let (eid, index, shape) = path_ref(s, CMD, p)?; let paint = read_paint(&shape)?; + + s.finish_path()?; set_tool(s, Tool::Path)?; s.tool.brush = paint.brush; s.tool.values = paint.values; s.tool.enabled = paint.enabled; s.tool.mask_value = paint.mask_value; s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) }; + s.path_steps = Default::default(); s.target = StackTarget::Effect(eid); Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() })) } +/// Remove one stored curve and repaint its sublayer as an atomic document edit fn remove_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.remove"; let (eid, index, _) = path_ref(s, CMD, p)?; @@ -216,10 +279,46 @@ fn read_paint(shape: &PathShape) -> Result { Ok(paint) } -/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]). +/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); - PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, editing: None, edited: false } + PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() } +} + +/// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation) +fn changed_tiles(before: &PixelStore, after: &PixelStore, eid: LayerId) -> BTreeSet<(u32, u32)> { + let (before_images, after_images) = (sublayer_images(before, eid), sublayer_images(after, eid)); + let channels: BTreeSet> = before_images.keys().chain(after_images.keys()).copied().collect(); + + let mut tiles = BTreeSet::new(); + for channel in channels { + let (before_image, after_image) = (before_images.get(&channel), after_images.get(&channel)); + let Some(image) = before_image.or(after_image) else { continue }; + for ty in 0..image.tiles_y() { + for tx in 0..image.tiles_x() { + let same = match (before_image.and_then(|i| i.tile_handle(tx, ty)), after_image.and_then(|i| i.tile_handle(tx, ty))) { + (None, None) => true, + (Some(before_tile), Some(after_tile)) => Arc::ptr_eq(before_tile, after_tile), + _ => false, + }; + if !same { + tiles.insert((tx, ty)); + } + } + } + } + tiles +} + +/// Sublayer `eid`'s images by channel (None: its mask image) +fn sublayer_images(pixels: &PixelStore, eid: LayerId) -> BTreeMap, &TileImage> { + let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, channel), image)| (Some(*channel), image)); + layers.chain(pixels.masks.get(&eid).map(|mask| (None, mask))).collect() +} + +/// The camera and viewport a stored path paints through (the views draw its curve the same way) +fn paint_view(shape: &PathShape, paint: &PathPaint) -> (OrbitCamera, Vec2) { + (paint.camera, Vec2::from_array(shape.viewport).max(Vec2::splat(MIN_PAINT_VIEWPORT_PX)).min(Vec2::splat(MAX_PAINT_VIEWPORT_PX))) } /// NDC (y up) to viewport pixels (origin top-left). @@ -235,10 +334,16 @@ impl Session { if path.uv { return path.points.iter().map(|p| Some(p.truncate())).collect(); } + let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect() } + /// The stored paths of path sublayer `eid` as Path tool states, for the views to draw + pub fn stored_path_states(&self, eid: LayerId) -> Vec { + self.paths(eid).unwrap_or_default().iter().map(state_of).collect() + } + /// The stored paths of path sublayer `eid` (None if it isn't one). pub fn paths(&self, eid: LayerId) -> Option<&[PathShape]> { match self.doc.project.effect(eid) { @@ -261,89 +366,419 @@ impl Session { } } - /// Store the Path tool's curve (a new path in the selected path sublayer, or in a new one; - /// or the path being edited) and repaint the sublayer, as one undo step. Clears the tool. + /// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool pub fn commit_path(&mut self, viewport: Vec2) -> Result { + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + + if let Some((effect, index)) = self.tool.path.editing + && self.paths(effect).and_then(|paths| paths.get(index)).is_some_and(|stored| self.same_as_stored(stored)) + { + // Camera navigation alone must not replace the pixels the user just previewed + let mut report = match self.path_draft.take() { + Some(draft) => { + self.push_step(NEW_PATH_LABEL, draft.base, false); + draft.painted + } + None => json!({}), + }; + report["effect"] = json!(effect.0); + report["index"] = json!(index); + self.target = StackTarget::Effect(effect); + self.cancel_path(); + return Ok(report); + } + + if let Some(draft) = self.path_draft.take() { + // Changed settings paint again from the document before the preview + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + self.tool.path.editing = None; + } + let shape = self.path_shape(self.camera, viewport); let editing = self.tool.path.editing; - let label = editing.map_or("Path".to_string(), |(_, i)| format!("Edit path {}", i + 1)); - let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| { - let (eid, index) = match editing { + let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1)); + let report = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |session| { + let (effect_id, index) = match editing { Some(at) => at, - None => (s.path_effect()?, usize::MAX), + None => (session.path_effect()?, usize::MAX), }; - s.put_path(eid, index, shape) + session.put_path(effect_id, index, shape) })?; - if let Some(eid) = out.get("effect").and_then(Value::as_u64) { - self.target = StackTarget::Effect(LayerId(eid)); + + if let Some(effect_id) = report.get("effect").and_then(Value::as_u64) { + self.target = StackTarget::Effect(LayerId(effect_id)); } - self.tool.path.points.clear(); - self.tool.path.editing = None; - Ok(out) + self.tool.path.clear(); + + Ok(report) } - /// While a stored path is edited, repaint its sublayer when the tool's points, brush or - /// material changed (orbiting or resizing the view alone doesn't), merged into one undo - /// step. Cheap when nothing changed; the UI calls it every frame. Returns whether it - /// repainted. + /// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame pub fn path_live(&mut self) -> Result { - let Some((eid, index)) = self.tool.path.editing else { return Ok(false) }; - let Some(stored) = self.paths(eid).and_then(|v| v.get(index)).cloned() else { - self.stop_path_edit(); + self.path_live_in_view(self.viewport) + } + + /// Compare curve and typed paint settings through the stored camera and viewport + fn same_as_stored(&self, stored: &PathShape) -> bool { + // JSON round trips can change float representation without changing the paint settings + read_paint(stored).is_ok_and(|paint| { + let current = self.path_shape(paint.camera, Vec2::from_array(stored.viewport)); + (¤t.points, current.uv, current.closed, current.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) + && read_paint(¤t).is_ok_and(|current_paint| current_paint == paint) + }) + } + + /// Preview a command's points in its supplied viewport, or the UI's current viewport + fn path_live_in_view(&mut self, viewport: Vec2) -> Result { + if self.quick_mask.editing { return Ok(false); + } + + let stored = match self.tool.path.editing { + Some((effect_id, index)) => match self.paths(effect_id).and_then(|paths| paths.get(index)).cloned() { + Some(shape) => Some((effect_id, index, shape)), + None => { + self.stop_path_edit(); + return Ok(false); + } + }, + None => None, }; + + if self.tool.tool != Tool::Path || self.stroke.is_some() { + return Ok(false); + } + + if self.tool.path.points.is_empty() { + if let Some((effect, index, _)) = stored { + if self.path_draft.is_some() { + self.cancel_path(); + } else { + self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |session| { + if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) { + paths.remove(index); + } + session.render_paths(effect, index) + })?; + self.cancel_path(); + } + return Ok(true); + } + return Ok(false); + } + let path = &self.tool.path; - if self.tool.tool != Tool::Path || self.stroke.is_some() || path.points.is_empty() || (path.closed && path.fill && path.points.len() < 3) { + if path.closed && path.fill && path.points.len() < 3 { return Ok(false); } - // Typed comparison: the stored settings went through JSON (f64), maybe a save and load. - let unchanged = read_paint(&stored).is_ok_and(|p| { - let now = self.path_shape(p.camera, Vec2::from_array(stored.viewport)); - (&now.points, now.uv, now.closed, now.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) && read_paint(&now).is_ok_and(|n| n == p) - }); - if unchanged { + + let Some((eid, index, stored)) = stored else { return self.start_path_draft(viewport) }; + + if self.same_as_stored(&stored) { return Ok(false); } - let shape = self.path_shape(self.camera, self.viewport); - self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |s| s.put_path(eid, index, shape))?; - self.tool.path.edited = true; + + let shape = self.path_shape(self.camera, viewport); + let (painted, before) = self.repaint_path(eid, index, shape)?; + match &mut self.path_draft { + Some(draft) => draft.painted = painted, + None => { + // The path's own repaint keeps its point changes undoable, unlike other steps + let steps = std::mem::take(&mut self.path_steps); + self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited); + self.path_steps = steps; + self.tool.path.edited = true; + } + } Ok(true) } - /// Stop editing a stored path (its changes are already applied) and clear the tool. - pub fn stop_path_edit(&mut self) { - if self.tool.path.editing.take().is_some() { - self.tool.path.points.clear(); + /// Paint a new path's first preview where [`Session::commit_path`] would add it, keeping the document before it for apply and cancel + fn start_path_draft(&mut self, viewport: Vec2) -> Result { + let base = self.doc.clone(); + let shape = self.path_shape(self.camera, viewport); + let placed = self.path_effect().and_then(|eid| { + let index = self.paths(eid).map_or(0, <[_]>::len); + self.put_path(eid, index, shape).map(|painted| ((eid, index), painted)) + }); + match placed { + Ok((at, painted)) => { + // Placing a path is a new action: what was undone before can't be redone over it + self.redo.clear(); + self.tool.path.editing = Some(at); + self.changed_without_history(&base); + self.path_draft = Some(PathDraft { base, painted }); + Ok(true) + } + Err(e) => { + self.doc = base; + Err(e) + } } } - /// The selected path sublayer, or a new one on the selected layer's content or mask - /// (whichever is selected). + /// Remember the curve before a point change from a view, so undo steps back through those changes while the path is edited + pub fn path_checkpoint(&mut self) { + if !self.path_steps.0.last().is_some_and(|s| s.same_curve(&self.tool.path)) { + self.path_steps.0.push(self.tool.path.clone()); + // Each snapshot can contain thousands of points; bound point history like document history + let excess = self.path_steps.0.len().saturating_sub(crate::session::MAX_HISTORY); + self.path_steps.0.drain(..excess); + self.path_steps.1.clear(); + } + } + + /// Select a point without changing its geometry or clearing redo + pub fn select_path_point(&mut self, index: usize) { + self.tool.path.selected = (index < self.tool.path.points.len()).then_some(index); + } + + /// Append and select a point, checkpointing the curve before it changes + pub fn append_path_point(&mut self, point: Vec3, uv: bool) -> Option { + if !point.is_finite() || (self.tool.path.uv == uv && self.tool.path.points.len() >= MAX_PATH_POINTS) { + return None; + } + + // A click in the other view must not replace a committed path's coordinate space + if self.tool.path.editing.is_some() && self.path_draft.is_none() && self.tool.path.uv != uv { + return None; + } + + self.path_checkpoint(); + self.tool.path.push(point, uv); + self.tool.path.selected = self.tool.path.points.len().checked_sub(1); + self.tool.path.selected + } + + /// Insert and select a point as one undoable point edit + pub fn insert_path_point(&mut self, index: usize, point: Vec3) -> Option { + if !point.is_finite() || index > self.tool.path.points.len() || self.tool.path.points.len() >= MAX_PATH_POINTS { + return None; + } + + self.path_checkpoint(); + self.tool.path.insert(index, point) + } + + /// Move a point, checkpointing only the first actual movement in a drag + pub fn move_path_point(&mut self, index: usize, point: Vec3, begin_drag: bool) -> bool { + if !point.is_finite() || self.tool.path.points.get(index).is_none_or(|current| *current == point) { + return false; + } + + if begin_drag { + self.path_checkpoint(); + } + if let Some(current) = self.tool.path.points.get_mut(index) { + *current = point; + } + true + } + + /// Remove the selected point, or the last one, as one undoable point edit + pub fn remove_selected_path_point(&mut self) { + if self.tool.path.points.is_empty() { + return; + } + + self.path_checkpoint(); + self.tool.path.remove_selected(); + } + + /// Change whether the path loops back to its first point, with point undo + pub fn set_path_closed(&mut self, closed: bool) { + if self.tool.path.closed != closed { + self.path_checkpoint(); + self.tool.path.closed = closed; + } + } + + /// Change whether a closed path fills its interior, with point undo + pub fn set_path_fill(&mut self, fill: bool) { + if self.tool.path.fill != fill { + self.path_checkpoint(); + self.tool.path.fill = fill; + } + } + + /// Whether [`Session::step_path`] would undo (`back`) or redo a point change + pub(crate) fn path_step_pending(&self, back: bool) -> bool { + let steps = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) + } + + /// Undo calls needed to move back through document history, including pending path operations. + /// With zero document steps, only an uncommitted draft is canceled; stored edits stay applied. + pub fn history_undo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 && self.path_draft.is_none() { + return 0; + } + + let (point_steps, clears_path) = self.path_steps_before_document(true); + let cancel_draft = self.path_draft.is_some() && !clears_path; + document_steps.saturating_add(point_steps).saturating_add(usize::from(cancel_draft)) + } + + /// Redo calls needed to move forward through document history, including pending point edits. + /// Unlike undo, document redo cancels any remaining draft in the same call. + pub fn history_redo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 { + return 0; + } + + document_steps.saturating_add(self.path_steps_before_document(false).0) + } + + /// Count pending point steps and whether their last step clears the path + fn path_steps_before_document(&self, back: bool) -> (usize, bool) { + if self.tool.tool != Tool::Path { + return (0, false); + } + + let states = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let mut steps = 0usize; + let mut current = &self.tool.path; + for state in states.iter().rev() { + if state.same_curve(current) { + continue; + } + + steps = steps.saturating_add(1); + + // Restoring an empty curve cancels the draft and clears point history in the same step + if state.points.is_empty() { + return (steps, true); + } + + current = state; + } + + (steps, false) + } + + /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history + pub(crate) fn step_path(&mut self, back: bool) -> Result { + if self.tool.tool != Tool::Path { + return Ok(false); + } + + // Skip no-change checkpoints without consuming history until the repaint succeeds + let from = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) }; + + // Returning false here would let undo/redo consume document history instead. + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + + let path = &mut self.tool.path; + let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() }); + if let Err(error) = self.path_live() { + self.tool.path = previous; + return Err(error); + } + + if self.tool.path.points.is_empty() { + self.stop_path_edit(); + } else { + let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; + from.truncate(index); + to.push(previous); + } + Ok(true) + } + + /// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes + pub fn finish_path(&mut self) -> Result<()> { + if self.path_draft.is_some() { + let viewport = self.viewport; + self.commit_path(viewport)?; + } + self.stop_path_edit(); + Ok(()) + } + + /// Cancel the Path tool's path: a new one's preview is removed, a stored one keeps its applied changes + pub fn cancel_path(&mut self) { + self.stop_path_edit(); + self.tool.path.clear(); + } + + /// Stop editing a stored path (its changes are already applied) and clear the tool; a new path's preview is removed + pub fn stop_path_edit(&mut self) { + if let Some(draft) = self.path_draft.take() { + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + } + if self.tool.path.editing.is_some() { + self.tool.path.clear(); + } + self.path_steps = Default::default(); + } + + /// The selected path sublayer, or a new one on the selected paint layer's content or mask fn path_effect(&mut self) -> Result { - let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?; - let p = &self.doc.project; + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + + let selected = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?; + let project = &self.doc.project; let mask = match self.target { - StackTarget::Effect(e) => match p.effect(e) { - Some((_, x)) if matches!(x.kind, EffectKind::Path(_)) => return Ok(e), - Some((owner, _)) => !p.layer(owner)?.content_effects.iter().any(|x| x.id == e), + StackTarget::Effect(effect) => match project.effect(effect) { + // Paths saved in a fill layer before paths there were removed stay editable + Some((_, found)) if matches!(found.kind, EffectKind::Path(_)) => return Ok(effect), + Some((owner, _)) => !project.layer(owner)?.content_effects.iter().any(|candidate| candidate.id == effect), None => false, }, StackTarget::Mask => true, StackTarget::Content => false, }; - // An instance's content and (unless it has its own) mask belong to its source. - let owner = if mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) }; - let eid = self.doc.project.alloc_id(); - let l = self.doc.project.layer_mut(owner)?; - let e = Effect::new(eid, EffectKind::Path(Vec::new())); + + // An instance's content and (unless it has its own) mask belong to its source + let owner = if mask { project.mask_owner(selected) } else { project.content_layer(selected).map_or(selected, |layer| layer.id) }; + let path_id = self.doc.project.alloc_id(); + let layer = self.doc.project.layer_mut(owner)?; + let path = Effect::new(path_id, EffectKind::Path(Vec::new())); if mask { - l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(e); - } else if l.is_group() { - return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", l.name))); + layer.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(path); + } else if layer.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", layer.name))); + } else if matches!(layer.kind, LayerKind::Paint) { + layer.content_effects.push(path); } else { - l.content_effects.push(e); + return Err(EngineError::Other(format!("\"{}\" is not a paint layer: add the path to a paint layer or a mask", layer.name))); } - Ok(eid) + Ok(path_id) + } + + /// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before + fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> { + let before = self.doc.clone(); + let painted = match self.put_path(eid, index, shape) { + Ok(v) => v, + Err(e) => { + self.doc = before; + return Err(e); + } + }; + + // Paths paint into the active set; a sublayer in another set recomposites in full + let project = &self.doc.project; + let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts); + if set == Some(self.ts()) { + // Content or mask, the sublayer's owner decides which sets redraw + let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid); + self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles); + } else { + self.invalidate_changed(&before); + } + self.revision = self.revision.wrapping_add(1); + self.modified = true; + Ok((painted, before)) } /// Replace path `index` of sublayer `eid` (append when out of range) and repaint the @@ -421,13 +856,41 @@ impl Session { fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; + let (camera, viewport) = paint_view(shape, &paint); self.tool.brush = paint.brush; self.tool.values = paint.values; self.tool.enabled = paint.enabled; self.tool.mask_value = paint.mask_value; - self.camera = paint.camera; + self.camera = camera; self.tool.path = state_of(shape); - self.paint_path(Vec2::from_array(shape.viewport).max(Vec2::splat(16.0)).min(Vec2::splat(16384.0))) + self.paint_path(viewport) + } + + /// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh) + pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec>> { + let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); + let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::>>() else { + return Vec::new(); + }; + + let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport }; + spline_segments(&screen, closed, SURFACE_STEP_PX) + .into_iter() + .zip(&screen) + .map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect()) + .collect() + } + + /// [`Session::path_surface`] of a stored 3D path through the camera and viewport it paints with + pub fn stored_path_surface(&self, eid: LayerId, index: usize) -> Option>>> { + let shape = self.paths(eid)?.get(index)?; + if shape.uv { + return None; + } + + let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?); + let path = state_of(shape); + Some(self.path_surface(&path.points, path.closed, camera, viewport)) } /// Paint the Path tool's curve with the current brush (or fill it when closed and filled) @@ -452,74 +915,101 @@ impl Session { }) } - /// Fill the inside of `poly`: viewport pixels over the visible surface, or texture - /// coordinates. Returns the touched tiles. - fn lasso_fill(&mut self, poly: Vec, uv: bool, viewport: Vec2) -> Result { - let ts = self.ts(); - let (gbuf, mut canvas) = self.fill_canvas(ts)?; - let w = gbuf.width.max(1); + /// Fill the inside of `polygon` (viewport pixels over the visible surface, or texture coordinates); returns the touched tiles + fn lasso_fill(&mut self, polygon: Vec, uv: bool, viewport: Vec2) -> Result { + let texture_set = self.ts(); + let (uv_buffer, mut canvas) = self.fill_canvas(texture_set)?; + let width = uv_buffer.width.max(1); + if uv { - let lasso = Lasso::new(poly.iter().map(|p| *p * Vec2::new(w as f32, gbuf.height as f32)).collect()); - fill_coverage(&mut canvas, &gbuf, |i, _| lasso.coverage(Vec2::new((i as u32 % w) as f32 + 0.5, (i as u32 / w) as f32 + 0.5))); + let lasso = Lasso::new(polygon.iter().map(|point| *point * Vec2::new(width as f32, uv_buffer.height as f32)).collect()); + fill_coverage(&mut canvas, &uv_buffer, |texel, _| { + lasso.coverage(Vec2::new((texel as u32 % width) as f32 + 0.5, (texel as u32 / width) as f32 + 0.5)) + }); } else { - let lasso = Lasso::new(poly); - let view_proj = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0)); - let inv = view_proj.inverse(); - let (cull, mesh, bvh) = (self.tool.brush.backface_culling, &self.mesh, &self.bvh); + let lasso = Lasso::new(polygon); + let view_projection = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0)); + let inverse_view_projection = view_projection.inverse(); + let (mesh, bvh) = (&self.mesh, &self.bvh); + let brush = self.tool.brush.sanitized(); // A visible source inside the lasso can paint each symmetry copy - let (lo, hi) = mesh.bounds(); - let center = (lo + hi) * 0.5; - let inverses: Vec<_> = self.tool.brush.sanitized().symmetry.transforms().iter().map(|m| m.inverse()).collect(); + let (bounds_min, bounds_max) = mesh.bounds(); + let symmetry = brush.symmetry; + let symmetry_origin = symmetry.origin((bounds_min + bounds_max) * 0.5); + let inverses: Vec<_> = symmetry.transforms().iter().map(|transform| transform.inverse()).collect(); - fill_coverage(&mut canvas, &gbuf, |i, _| { - let Some(s) = gbuf.surface(mesh, i) else { return 0.0 }; + // Copies can leave the source surface, within the same depth allowed for brush stamps + let copy_depth = brush.size * (bounds_max - bounds_min).length().max(MIN_BRUSH_SCALE) * brush.depth; + let eye = self.camera.eye(); + let camera_distance = self.camera.distance.max(MIN_BRUSH_SCALE); + + // Bound the search using the farthest bounding-box corner; acceptance still uses the actual hit + let max_copy_depth = + if brush.screen_space { copy_depth * (bounds_min - eye).abs().max((bounds_max - eye).abs()).length() / camera_distance } else { copy_depth }; + + fill_coverage(&mut canvas, &uv_buffer, |texel, _| { + let Some(surface) = uv_buffer.surface(mesh, texel) else { return 0.0 }; let mut best = 0.0f32; - for m in &inverses { - let pos = center + *m * (s.pos - center); - let c = view_proj * pos.extend(1.0); - if c.w <= MIN_PROJECTIVE_W { + for inverse in &inverses { + let position = symmetry_origin + *inverse * (surface.pos - symmetry_origin); + let clip = view_projection * position.extend(1.0); + if clip.w <= MIN_PROJECTIVE_W { continue; } - let ndc = Vec2::new(c.x, c.y) / c.w; - let a = lasso.coverage(to_pixels(ndc, viewport)); - if a <= best { + + let normalized_screen = Vec2::new(clip.x, clip.y) / clip.w; + let coverage = lasso.coverage(to_pixels(normalized_screen, viewport)); + if coverage <= best { continue; } // Use the source surface normal; a copy may face away from the camera - let o = inv * ndc.extend(0.0).extend(1.0); - let origin = o.truncate() / o.w; - let to = pos - origin; - let d = to.length(); - let Some(dir) = to.try_normalize() else { continue }; - let Some(hit) = - bvh.closest(origin, dir, d * (1.0 + RAY_HIT_RELATIVE_TOLERANCE)).filter(|hit| hit.t >= d * (1.0 - RAY_HIT_RELATIVE_TOLERANCE)) - else { - continue; + let near_clip = inverse_view_projection * normalized_screen.extend(0.0).extend(1.0); + let origin = near_clip.truncate() / near_clip.w; + let to_surface = position - origin; + let distance = to_surface.length(); + let Some(direction) = to_surface.try_normalize() else { continue }; + let is_copy = *inverse != Mat3::IDENTITY; + let max_distance = distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE); + let search_depth = if is_copy { max_copy_depth } else { 0.0 }; + let Some(hit) = bvh.closest(origin, direction, max_distance + search_depth) else { continue }; + + // Keep identity copies exact and reject occluders beyond the bounded displacement + let off_surface = if !is_copy { + 0.0 + } else if brush.screen_space { + copy_depth * (origin + direction * hit.t).distance(eye) / camera_distance + } else { + copy_depth }; - - let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue }; - - if cull && source.nrm.dot(dir) >= 0.0 { + if hit.t < distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE) - off_surface || hit.t > max_distance + off_surface { continue; } - best = a; + let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue }; + + if brush.backface_culling && source.nrm.dot(direction) >= 0.0 { + continue; + } + + best = coverage; } best }); } + let tiles = canvas.dirty.len(); - self.commit_fill("Path fill", ts, &canvas)?; + self.commit_fill("Path fill", texture_set, &canvas)?; Ok(tiles) } } #[cfg(test)] mod tests { + use super::*; use serde_json::json; use crate::{Session, execute}; @@ -556,4 +1046,117 @@ mod tests { assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); } + + #[test] + fn point_insertion_and_removal_respect_boundaries() { + let mut path = PathState { points: vec![Vec3::ZERO, Vec3::X], ..Default::default() }; + + assert_eq!(path.insert(2, Vec3::Y), Some(2)); + assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X, Vec3::Y]); + assert_eq!(path.insert(4, Vec3::Z), None); + path.closed = true; + path.selected = Some(usize::MAX); + path.remove_selected(); + assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X]); + assert!(!path.closed); + path.remove_selected(); + path.remove_selected(); + path.remove_selected(); + assert!(path.points.is_empty()); + assert_eq!(path.selected, None); + + path.points = vec![Vec3::ZERO; MAX_PATH_POINTS]; + assert_eq!(path.insert(MAX_PATH_POINTS, Vec3::X), None); + assert_eq!(path.points.len(), MAX_PATH_POINTS); + } + + #[test] + fn changed_tiles_include_mask_and_channel_creation_and_deletion() { + let effect = LayerId(7); + let mut before = PixelStore::default(); + let mut image = TileImage::new(192, 128, 1); + image.tile_mut(0, 0, &[1]).unwrap(); + before.masks.insert(effect, image.clone()); + before.layers.insert((effect, Channel::Roughness), image.clone()); + let mut after = before.clone(); + after.masks.get_mut(&effect).unwrap().set_tile(0, 0, None); + after.masks.get_mut(&effect).unwrap().tile_mut(2, 1, &[1]).unwrap(); + after.layers.remove(&(effect, Channel::Roughness)); + image.set_tile(0, 0, None); + image.tile_mut(1, 0, &[1]).unwrap(); + after.layers.insert((effect, Channel::Metallic), image); + + assert_eq!(changed_tiles(&before, &before.clone(), effect), BTreeSet::new()); + assert_eq!(changed_tiles(&before, &after, effect), BTreeSet::from([(0, 0), (1, 0), (2, 1)])); + assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new()); + } + + #[test] + fn quick_mask_preserves_pending_path_undo_and_redo() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + session.path_checkpoint(); + session.tool.path.points[0].y = 0.3; + session.path_live().unwrap(); + for back in [true, false] { + let curve = session.tool.path.clone(); + let steps = (session.path_steps.0.len(), session.path_steps.1.len()); + let history = (session.history_labels(), session.redo_labels()); + let pixels = session.doc.pixels.clone(); + session.quick_mask.editing = true; + assert!(if back { session.undo() } else { session.redo() }.is_err()); + assert!(curve.same_curve(&session.tool.path)); + assert_eq!(steps, (session.path_steps.0.len(), session.path_steps.1.len())); + assert_eq!(history, (session.history_labels(), session.redo_labels())); + assert_eq!(format!("{:?}", pixels), format!("{:?}", session.doc.pixels)); + session.quick_mask.editing = false; + if back { session.undo() } else { session.redo() }.unwrap(); + } + } + + #[test] + fn point_checkpoints_skip_noops_and_bound_retained_points() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap(); + session.tool.tool = Tool::Path; + session.tool.path.points = vec![Vec3::ZERO; MAX_PATH_POINTS]; + session.path_checkpoint(); + assert!(!session.path_step_pending(true)); + assert!(!session.step_path(true).unwrap()); + + for index in 0..crate::session::MAX_HISTORY + 10 { + session.path_checkpoint(); + session.tool.path.points[0].x = index as f32 + 1.0; + } + + assert_eq!(session.path_steps.0.len(), crate::session::MAX_HISTORY); + assert_eq!(session.path_steps.0.iter().map(|state| state.points.len()).sum::(), crate::session::MAX_HISTORY * MAX_PATH_POINTS); + session.path_checkpoint(); + assert!(session.step_path(true).unwrap(), "a no-change checkpoint does not consume an undo"); + assert_eq!(session.tool.path.points[0].x, (crate::session::MAX_HISTORY + 9) as f32); + } + + #[test] + fn stored_surface_uses_bounded_viewports_and_skips_uv_paths() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let StackTarget::Effect(effect) = session.target else { panic!("path sublayer") }; + assert!(session.stored_path_surface(effect, 0).is_none()); + let shape = session.paths(effect).unwrap()[0].clone(); + let paint = read_paint(&shape).unwrap(); + let mut shape = shape; + shape.viewport = [-1.0, f32::MAX]; + assert_eq!(paint_view(&shape, &paint).1, Vec2::new(MIN_PAINT_VIEWPORT_PX, MAX_PAINT_VIEWPORT_PX)); + + let points = [Vec3::new(-0.2, 0.0, 1.0), Vec3::new(0.0, 0.2, 1.0), Vec3::new(0.2, 0.0, 1.0)]; + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + let surface = session.path_surface(&points, true, session.camera, Vec2::splat(400.0)); + assert_eq!(surface.len(), 3); + let first = surface.first().unwrap().first().unwrap().unwrap(); + let last = surface.last().unwrap().last().unwrap().unwrap(); + assert!(first.distance(last) < 1e-5, "the closed curve returns to its starting surface point"); + let off_mesh = session.path_surface(&[Vec3::new(10.0, 0.0, 0.0), Vec3::new(11.0, 0.0, 0.0)], false, session.camera, Vec2::splat(400.0)); + assert!(!off_mesh.is_empty()); + assert!(off_mesh.iter().flatten().all(Option::is_none)); + } } diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs new file mode 100644 index 00000000..af93f71c --- /dev/null +++ b/crates/engine/src/polygon_fill.rs @@ -0,0 +1,614 @@ +//! 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 { + self.refuse_while_baking()?; + 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 { + self.refuse_while_baking()?; + 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 { + self.refuse_while_baking()?; + + // 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.refuse_while_baking()?; + + 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 { + self.refuse_while_baking()?; + 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/preserve.rs b/crates/engine/src/preserve.rs index 38544edc..d68f20bc 100644 --- a/crates/engine/src/preserve.rs +++ b/crates/engine/src/preserve.rs @@ -16,8 +16,14 @@ use crate::Session; const REACH: f32 = 0.05; /// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s -/// document) from `old`'s UV layout. Returns how many texels found the old surface. +/// document) from `old`'s UV layout. Returns how many texels found the old surface; +/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the +/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already +/// sit where they belong, however far the mesh moved. pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { + if same_layout(&old.mesh, &next.mesh) { + return 0; + } let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius()); let mut found = 0; for ts in 0..next.set_count() { @@ -52,7 +58,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { ((tx, ty), src) }) .collect(); - found += table.values().flatten().filter(|p| p[0].is_finite()).count(); + let matched = table.values().flatten().filter(|p| p[0].is_finite()).count(); + found += matched; + // No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is. + if matched == 0 { + continue; + } let map = |x: f32, y: f32| { let (xi, yi) = (x as u32, y as u32); table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1])) @@ -63,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { found } +/// Same index buffer, same UVs per vertex and the same material ranges. +fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool { + let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::>(); + a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b) +} + #[cfg(test)] mod tests { use super::*; @@ -104,4 +121,50 @@ mod tests { } assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong"); } + + #[test] + fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..64 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout + // shortcut is not taken): nothing of the old surface is within reach. + let mut mesh = (*s.mesh).clone(); + for p in &mut mesh.positions { + p.x += 100.0; + } + for uv in &mut mesh.uvs { + *uv = Vec2::new(1.0 - uv.x, uv.y); + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there"); + } + + #[test] + fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..128 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // Slid along its own surface by a fraction of the plane: half of it still overlaps the old one. + let mut mesh = (*s.mesh).clone(); + let shift = mesh.radius() * 0.5; + for p in &mut mesh.positions { + p.x += shift; + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + for x in 0..128 { + assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved"); + assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint"); + } + } } 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/project_cmds.rs b/crates/engine/src/project_cmds.rs index 4bea6deb..b3a753ff 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -2,6 +2,7 @@ use serde_json::{Value, json}; use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakeResolution, CurvatureMethod}; use texturecraft_geom::primitives; use crate::commands::{CommandSpec, always, bad, boolp, strp, u64p}; @@ -56,31 +57,37 @@ fn material(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": l.0 })) } -/// The sample project: the material ball, baked, with smart materials on both texture sets. +/// A baked material ball with smart materials on both texture sets pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result { - let mut s = Session::new_project("Material Ball", primitives::material_ball(), "builtin:material_ball", None, resolution)?; - for ts in 0..s.set_count() { - let set = s.doc.project.texture_set_mut(ts)?; - set.bake.resolution = bake_resolution; - for r in [&mut set.bake.ao, &mut set.bake.thickness, &mut set.bake.bent_normal] { - r.rays = 24; + let mut session = Session::new_project("Material Ball", primitives::material_ball(), "builtin:material_ball", None, resolution)?; + for set_index in 0..session.set_count() { + let set = session.doc.project.texture_set_mut(set_index)?; + set.bake.common.resolution = BakeResolution::from_pixels(bake_resolution).ok_or_else(|| bad("project.sample", "invalid bake resolution"))?; + + // Mesh curvature gives the procedural sample visible edge wear + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + for ray_settings in + [&mut set.bake.maps.ao.parameters.rays, &mut set.bake.maps.thickness.parameters.rays, &mut set.bake.maps.bent_normal.parameters.rays] + { + ray_settings.rays = 24; } - s.bake_now(ts, false)?; + session.bake_now(set_index, false)?; } - s.active_set = 1; - crate::materials::apply(&mut s, "iron_rusted")?; - s.active_set = 0; - crate::materials::apply(&mut s, "steel_painted_worn")?; - // Ready to paint: an empty paint layer on top of each stack, selected (the smart material - // fully covers the bottom layer, so strokes there would stay hidden). - for ts in (0..s.set_count()).rev() { - s.active_set = ts; - s.selected.remove(&ts); - crate::execute(&mut s, "layer.add.paint", &Value::Null)?; + session.active_set = 1; + crate::materials::apply(&mut session, "iron_rusted")?; + session.active_set = 0; + crate::materials::apply(&mut session, "steel_painted_worn")?; + + // Paint above the smart material so new strokes remain visible + for set_index in (0..session.set_count()).rev() { + session.active_set = set_index; + session.selected.remove(&set_index); + crate::execute(&mut session, "layer.add.paint", &Value::Null)?; } - s.undo.clear(); - s.modified = false; - Ok(s) + session.undo.clear(); + session.modified = false; + Ok(session) } fn sample(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 304ab3c9..cfb0175c 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -35,44 +35,53 @@ pub fn specs() -> Vec { "Edit quick mask", ["Viewport"], Some("U"), - "{editing?: bool} — toggles when omitted; editing enables the mask", - always, + "{editing?: bool} — toggles when omitted; needs the quick mask enabled", + mask_enabled, edit ), - cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", always, invert), + cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", mask_enabled, invert), ] } -fn state(s: &Session) -> Value { - let q = &s.quick_mask; +fn mask_enabled(session: &Session) -> std::result::Result<(), String> { + if session.quick_mask.enabled { Ok(()) } else { Err("enable the quick mask first".into()) } +} + +fn state(session: &Session) -> Value { + let mask = &session.quick_mask; json!({ - "enabled": q.enabled, "editing": q.editing, "inverted": q.inverted, - "paintedTiles": q.masks.get(&s.ts()).map(TileImage::allocated_count).unwrap_or(0), + "enabled": mask.enabled, "editing": mask.editing, "inverted": mask.inverted, + "paintedTiles": mask.masks.get(&session.ts()).map(TileImage::allocated_count).unwrap_or(0), }) } -fn changed(s: &mut Session) -> Result { - s.quick_mask.revision = s.quick_mask.revision.wrapping_add(1); - s.revision = s.revision.wrapping_add(1); - Ok(state(s)) +fn changed(session: &mut Session) -> Result { + session.quick_mask.revision = session.quick_mask.revision.wrapping_add(1); + session.revision = session.revision.wrapping_add(1); + Ok(state(session)) } -fn enable(s: &mut Session, p: &Value) -> Result { - s.quick_mask.enabled = boolp(p, "enabled").unwrap_or(!s.quick_mask.enabled); - changed(s) +fn enable(session: &mut Session, params: &Value) -> Result { + let enabled = boolp(params, "enabled").unwrap_or(!session.quick_mask.enabled); + if !enabled && session.quick_mask.editing { + session.cancel_stroke(); + session.quick_mask.editing = false; + } + + session.quick_mask.enabled = enabled; + changed(session) } -fn edit(s: &mut Session, p: &Value) -> Result { - s.cancel_stroke(); - let q = &mut s.quick_mask; - q.editing = boolp(p, "editing").unwrap_or(!q.editing); - q.enabled |= q.editing; - changed(s) +fn edit(session: &mut Session, params: &Value) -> Result { + session.cancel_stroke(); + let quick_mask = &mut session.quick_mask; + quick_mask.editing = boolp(params, "editing").unwrap_or(!quick_mask.editing); + changed(session) } -fn invert(s: &mut Session, _: &Value) -> Result { - s.quick_mask.inverted = !s.quick_mask.inverted; - changed(s) +fn invert(session: &mut Session, _: &Value) -> Result { + session.quick_mask.inverted = !session.quick_mask.inverted; + changed(session) } impl Session { @@ -105,34 +114,37 @@ impl Session { /// Includes the stroke in progress. pub fn quick_mask_rgba(&self, ts: usize, size: u32) -> Option> { let cache = self.caches.get(ts)?; - let (w, h) = cache.size; - let size = size.clamp(1, w.max(h)); + let (width, height) = cache.size; + let size = size.clamp(1, width.max(height)); let mask = self.quick_mask_image(ts, cache.size); let live = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_none()).map(|s| (&s.canvas.alpha, s.stroke.settings.opacity, s.erase)); let base = cache.composite.channels.get(&Channel::BaseColor); - let lut = srgb_lut(); + let srgb = srgb_lut(); let inverted = self.quick_mask.inverted; let mut out = vec![255u8; size as usize * size as usize * 4]; + out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| { - let ty = (y as u64 * u64::from(h) / u64::from(size)) as u32; - for (x, px) in row.chunks_exact_mut(4).enumerate() { - let tx = (x as u64 * u64::from(w) / u64::from(size)) as u32; - let mut m = from_u16(mask.get(tx, ty)[0]); + let ty = (y as u64 * u64::from(height) / u64::from(size)) as u32; + for (x, pixel) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let tx = (x as u64 * u64::from(width) / u64::from(size)) as u32; + let mut coverage = from_u16(mask.get(tx, ty)[0]); if let Some((alpha, opacity, erase)) = live { - let a = from_u16(alpha.get(tx, ty)[0]) * opacity; - m = if erase { m * (1.0 - a) } else { a + m * (1.0 - a) }; + let stroke_coverage = from_u16(alpha.get(tx, ty)[0]) * opacity; + coverage = if erase { coverage * (1.0 - stroke_coverage) } else { stroke_coverage + coverage * (1.0 - stroke_coverage) }; } - let blocked = if inverted { m } else { 1.0 - m }; + + let blocked = if inverted { coverage } else { 1.0 - coverage }; let raw = base.map(|b| b.get(tx, ty)).unwrap_or([32768; 4]); - let t = 0.55 * blocked; + let tint_amount = 0.55 * blocked; for (k, tint) in [0.9, 0.1, 0.15].into_iter().enumerate() { - let c = f32::from(lut.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0; - if let Some(slot) = px.get_mut(k) { - *slot = ((c + (tint - c) * t).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let color = f32::from(srgb.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0; + if let Some(slot) = pixel.get_mut(k) { + *slot = ((color + (tint - color) * tint_amount).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } } } }); + Some(out) } } diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 87f6d50f..2c973280 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Add fill layer from image", [], None, - "{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}", + "{name (exact resource name with extension or unique stem), channel?: baseColor, projection?: uv|triplanar|planar, scale?}", always, add_image_fill ), @@ -36,47 +36,49 @@ 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", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) + } + + /// 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 leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); + + let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; + let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); let mut name = base.clone(); - let mut n = 2; + let mut duplicate_index = 2; while self.doc.resources.contains_key(&name) { - name = format!("{n}_{base}"); - n += 1; + name = format!("{duplicate_index}_{base}"); + duplicate_index += 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) } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). pub fn sync_images(&mut self) { - let keep: Vec = self.doc.resources.keys().cloned().collect(); - self.images.retain(|k, _| keep.contains(k)); - // Linked materials' packages are resources too, not images. - let missing: Vec<(String, Arc>)> = self - .doc - .resources - .iter() - .filter(|(k, _)| !self.images.contains_key(*k) && !k.ends_with(&format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT))) - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); - for (k, bytes) in missing { - match texturecraft_formats::decode_image(&bytes) { - Ok(d) => { - self.images.insert(k, decoded(d)); + self.images.retain(|name, _| self.doc.resources.contains_key(name)); + + // Linked material packages are resources but cannot be decoded as images + let package_suffix = format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT); + for (name, bytes) in &self.doc.resources { + if self.images.contains_key(name) || name.ends_with(&package_suffix) { + continue; + } + + match texturecraft_formats::decode_image(bytes) { + Ok(image) => { + self.images.insert(name.clone(), decoded(image)); } - Err(e) => self.log.push(format!("resource {k}: {e}")), + Err(error) => self.log.push(format!("resource {name}: {error}")), } } } @@ -98,15 +100,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())) @@ -147,11 +178,35 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { Ok(json!({ "removed": unused })) } -fn add_image_fill(s: &mut Session, p: &Value) -> Result { - let name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?.to_string(); - if !s.doc.resources.contains_key(&name) { - return Err(bad("layer.add.image", format!("no resource `{name}`"))); +#[cfg(not(target_arch = "wasm32"))] +const IMPORT_HINT: &str = "resource.import"; +#[cfg(target_arch = "wasm32")] +const IMPORT_HINT: &str = "File > Import resources"; + +/// Resolve an image resource by exact name or unique file stem. +fn resolve_resource_name(s: &Session, name: &str) -> Result { + if s.images.contains_key(name) { + return Ok(name.to_string()); } + let matches: Vec<&String> = s.images.keys().filter(|k| std::path::Path::new(k).file_stem().and_then(|stem| stem.to_str()) == Some(name)).collect(); + match matches.as_slice() { + [single] => Ok((*single).clone()), + [] => { + let available: Vec<&str> = s.images.keys().map(String::as_str).collect(); + let hint = + if available.is_empty() { format!(" (no resources imported: use {IMPORT_HINT})") } else { format!(" (available: {})", available.join(", ")) }; + Err(bad("layer.add.image", format!("no resource `{name}`{hint}"))) + } + multiple => { + let matches_str = multiple.iter().map(|m| format!("`{m}`")).collect::>().join(", "); + Err(bad("layer.add.image", format!("ambiguous resource `{name}` matches {matches_str}: give the full name with extension"))) + } + } +} + +fn add_image_fill(s: &mut Session, p: &Value) -> Result { + let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?; + let name = resolve_resource_name(s, raw_name)?; let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor); let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?; let ts = s.ts(); @@ -165,3 +220,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 cda91902..ed60718f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -13,6 +13,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. @@ -26,6 +27,7 @@ pub struct Document { pub project: Project, pub pixels: PixelStore, pub baked: BTreeMap, + pub bake_paint: BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc>, /// Imported image resources by name: original file bytes. pub resources: BTreeMap>>, } @@ -109,7 +111,7 @@ impl Tool { Tool::PolygonFill => "Polygon fill", Tool::Smudge => "Smudge", Tool::Clone => "Clone", - Tool::ColorPicker => "Color picker", + Tool::ColorPicker => "Material picker", Tool::Path => "Path", Tool::GeometryMask => "Geometry mask", } @@ -154,22 +156,13 @@ impl ViewMode { match self { ViewMode::Material => "Material".into(), ViewMode::Channel(c) => c.label().into(), - ViewMode::MeshMap(m) => m.label().into(), + ViewMode::MeshMap(m) => m.id().into(), ViewMode::UvChecker => "UV checker".into(), ViewMode::Mask(_) => "Layer mask".into(), } } } -/// 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 { @@ -211,6 +204,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, @@ -232,6 +231,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 { @@ -261,6 +264,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, @@ -292,8 +297,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, @@ -315,6 +320,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, @@ -322,8 +330,6 @@ pub struct Session { pub mesh_source: Option<(String, Vec)>, /// High-definition meshes and cage for baking (saved inside the project). pub bake_meshes: crate::BakeMeshes, - /// The map that bakes itself again when its inputs change (not saved). - pub auto_rebake: crate::auto_rebake::AutoRebake, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -337,6 +343,8 @@ pub struct Session { pub target: StackTarget, pub camera: OrbitCamera, pub view: ViewMode, + /// The live bake preview while the app bakes (see [`crate::bake_preview`]). + pub bake_preview: Option, /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, @@ -350,6 +358,10 @@ pub struct Session { pub(crate) painting_paths: bool, /// Pixels of the paths below the one being edited, so live edits skip repainting them. pub(crate) path_cache: Option, + /// A new path's live preview: the path becomes an undo step only when it is applied + pub(crate) path_draft: Option, + /// Point changes of the path being edited: (earlier states for undo, undone states for redo) + pub(crate) path_steps: (Vec, Vec), pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -359,6 +371,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). @@ -366,8 +380,7 @@ pub struct Session { } impl Session { - /// A session for `project` on `mesh` (texture sets must reference mesh materials). The - /// UVs of UV-tiled sets are mapped into their tile atlas (see [`Session::source_mesh`]). + /// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`]) pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec)>) -> Result { mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?; let source = Arc::new(mesh); @@ -381,12 +394,12 @@ impl Session { Ok(Session { doc, mesh_id: next_mesh_id(), + project_id: next_mesh_id(), source, mesh, bvh: Arc::new(bvh), mesh_source, bake_meshes: Default::default(), - auto_rebake: Default::default(), caches, undo: Vec::new(), redo: Vec::new(), @@ -397,6 +410,7 @@ impl Session { target: StackTarget::Content, camera, view: ViewMode::Material, + bake_preview: None, viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, @@ -404,11 +418,14 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_draft: None, + path_steps: Default::default(), path: None, modified: false, revision: 1, log: Vec::new(), depth_cache: None, + polygon_fill_drag: None, export_presets: Default::default(), templates: Default::default(), }) @@ -453,7 +470,11 @@ impl Session { ts.stack.push(id); project.texture_sets.push(ts); } - let mut s = Session::new(Document { project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, mesh, mesh_source)?; + let mut s = Session::new( + Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, + mesh, + mesh_source, + )?; s.log.extend(log); Ok(s) } @@ -489,22 +510,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) } } } @@ -513,55 +536,120 @@ impl Session { self.record(label, before, false); } - /// A change from `before` to the current document: a new undo step `label`, or with - /// `merge` part of the previous one when it has the same label. + /// A change from `before`: a new undo step `label`, or with `merge` part of the previous one when it has the same label fn record(&mut self, label: &str, before: Document, merge: bool) { + self.invalidate_changed(&before); + self.push_step(label, before, merge); + } + + /// [`Session::record`] for a change whose tiles the caller already marked for recompositing + pub(crate) fn push_step(&mut self, label: &str, before: Document, merge: bool) { + // Another change during a new path's preview makes the path its own step first + if !self.painting_paths + && let Some(draft) = self.path_draft.take() + { + self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base)); + } + + // Point changes of an edited path undo only until another step lands + if !self.painting_paths { + self.path_steps = Default::default(); + } + self.modified = true; self.revision = self.revision.wrapping_add(1); - self.invalidate_changed(&before); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { self.undo.push((label.to_string(), before)); - if self.undo.len() > MAX_HISTORY { - self.undo.remove(0); - } } + let over = self.undo.len().saturating_sub(MAX_HISTORY); + self.undo.drain(..over); self.redo.clear(); } - /// Mark dirty every texture set whose composite differs between `other` and the current + /// A change from `other` to the current document that is not an undo step (a path preview) + pub(crate) fn changed_without_history(&mut self, other: &Document) { + self.modified = true; + self.revision = self.revision.wrapping_add(1); + self.invalidate_changed(other); + } + + /// Mark dirty every texture set whose composite differs between the previous and current /// document (after an edit, undo or redo). - fn invalidate_changed(&mut self, other: &Document) { - self.follow_uv_layouts(&other.project); + pub(crate) fn invalidate_changed(&mut self, previous_document: &Document) { + self.follow_uv_layouts(&previous_document.project); self.sync_caches(); - let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); - let all = resources(other) != resources(&self.doc); - let (empty, images) = (BakedMaps::default(), Default::default()); - let key = |d: &Document, ts: usize| { - let stack = d.project.texture_sets.get(ts).map(|s| s.stack.as_slice()).unwrap_or_default(); - StackKey::new(&d.project, &d.pixels, d.baked.get(&ts).unwrap_or(&empty), &images, ts, stack) + + // Removed or replaced resources may change any set's rendered content + let removed_or_replaced_resource = + previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); + let added_resource_names: BTreeSet<_> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).collect(); + let uses_added_resource = |texture_set_index: usize| { + use texturecraft_core::{EffectKind, Fill, Source}; + + let uses_source = |source: &Source| matches!(source, Source::Image { name, .. } if added_resource_names.contains(name)); + let uses_fill = + |fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package)); + let project = &self.doc.project; + !added_resource_names.is_empty() + && project.texture_sets.get(texture_set_index).is_some_and(|set| { + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) + || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind { + EffectKind::Fill { source, .. } => uses_source(source), + EffectKind::Material(fill) => uses_fill(fill), + EffectKind::Generator(generator) => generator.inputs.values().any(uses_source), + _ => false, + }) + }) + }) }; - for ts in 0..self.caches.len() { - let Some(c) = self.caches.get_mut(ts) else { continue }; - if all { - c.invalidate_all(); + let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default()); + let stack_key = |document: &Document, texture_set_index: usize| { + let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default(); + StackKey::new( + &document.project, + &document.pixels, + document.baked.get(&texture_set_index).unwrap_or(&empty_baked_maps), + &empty_images, + texture_set_index, + stack, + ) + }; + for texture_set_index in 0..self.caches.len() { + let before = stack_key(previous_document, texture_set_index); + let after = stack_key(&self.doc, texture_set_index); + let resource_changed = removed_or_replaced_resource || uses_added_resource(texture_set_index); + let Some(cache) = self.caches.get_mut(texture_set_index) else { + continue; + }; + + if resource_changed { + cache.invalidate_all(); continue; } - let (before, after) = (key(other, ts), key(&self.doc, ts)); + if before == after { continue; } - // Only painted pixels changed and nothing reads across tiles: the tiles whose pixels - // differ are the tiles to recomposite. Anything else recomposites the whole set. - let tiles = match (&before, &after) { - (Some(a), Some(b)) if !stack_reads_neighbours(&self.doc.project, ts) && !stack_reads_neighbours(&other.project, ts) => a.changed_tiles(b), + + // Neighbourhood readers require a full recomposite after painted pixels change + let changed_tiles = match (&before, &after) { + (Some(before), Some(after)) + if !stack_reads_neighbours(&self.doc.project, texture_set_index) + && !stack_reads_neighbours(&previous_document.project, texture_set_index) => + { + before.changed_tiles(after) + } _ => None, }; - match tiles { - Some(tiles) => { - let covered: BTreeSet<(u32, u32)> = c.covered_tiles.iter().copied().collect(); - c.dirty.extend(tiles.into_iter().filter(|t| covered.contains(t))); + match changed_tiles { + Some(changed_tiles) => { + // covered_tiles is emitted in row order + cache + .dirty + .extend(changed_tiles.into_iter().filter(|tile| cache.covered_tiles.binary_search_by_key(&(tile.1, tile.0), |&(x, y)| (y, x)).is_ok())); } - None => c.invalidate_all(), + None => cache.invalidate_all(), } } } @@ -621,18 +709,32 @@ impl Session { } } + /// Whether a point edit, an uncommitted path preview, or a document edit can be undone pub fn can_undo(&self) -> bool { - !self.undo.is_empty() + !self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true) } + + /// Whether a point edit or document edit can be restored pub fn can_redo(&self) -> bool { - !self.redo.is_empty() + !self.redo.is_empty() || self.path_step_pending(false) } + + /// Label of the next undo action, giving an active path's point edits and preview priority pub fn undo_label(&self) -> Option<&str> { + if self.path_draft.is_some() || self.path_step_pending(true) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.undo.last().map(|(l, _)| l.as_str()) } + + /// Label of the next redo action, giving an active path's point history priority pub fn redo_label(&self) -> Option<&str> { + if self.path_step_pending(false) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.redo.last().map(|(l, _)| l.as_str()) } + /// The undone steps, the next one to redo first. pub fn redo_labels(&self) -> Vec { self.redo.iter().rev().map(|(l, _)| l.clone()).collect() @@ -641,26 +743,49 @@ impl Session { self.undo.iter().map(|(l, _)| l.clone()).collect() } + /// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order 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(); + + // While a path is edited, undo steps back through its point changes first + if self.step_path(true)? { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // A path being placed isn't a step yet: undo removes it + if self.path_draft.is_some() { + self.stop_path_edit(); + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + 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) } + /// Restore a point edit and its pixels before considering document redo 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(); + + if self.step_path(false)? { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + 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) } @@ -669,7 +794,8 @@ impl Session { self.modified = true; self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); - // An undone add or duplicate takes the selected effect away: select the stack it was in. + + // An undone add or duplicate takes the selected effect away if let StackTarget::Effect(e) = self.target && self.doc.project.effect(e).is_none() { @@ -677,6 +803,10 @@ impl Session { let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); self.target = if content { StackTarget::Content } else { StackTarget::Mask }; } + let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some()); + if self.target == StackTarget::Mask && !has_mask { + self.target = StackTarget::Content; + } } // ----------------------------------------------------------------------------------------- @@ -696,22 +826,24 @@ impl Session { /// of a finite budget, after the dirty ones. pub fn update_for(&mut self, budget_ms: f64, clock: impl Fn() -> f64) -> bool { let start = clock(); - let first = if budget_ms.is_finite() { rayon::current_num_threads().clamp(1, CHUNK) } else { CHUNK }; - // The layer being edited: everything else is cached per tile. - let hot = self.stroke.as_ref().and_then(|s| s.target).map(|t| self.paint_owner(t)).or_else(|| self.selected_layer()); - let stroke_size = self.stroke.as_ref().and_then(|s| self.caches.get(s.ts)).map(|c| c.size); - let preview = self.stroke.as_ref().and_then(|s| { + let initial_chunk_size = if budget_ms.is_finite() { rayon::current_num_threads().clamp(1, CHUNK) } else { CHUNK }; + + // The layer being edited: everything else is cached per tile + let hot = self.stroke.as_ref().and_then(|stroke| stroke.target).map(|target| self.paint_owner(target)).or_else(|| self.selected_layer()); + let stroke_size = self.stroke.as_ref().and_then(|stroke| self.caches.get(stroke.ts)).map(|cache| cache.size); + let preview = self.stroke.as_ref().and_then(|stroke| { Some(StrokePreview { - target: s.target?, - alpha: s.canvas.alpha.clone(), - opacity: s.stroke.settings.opacity, - erase: s.erase, - values: s.values.clone(), + target: stroke.target?, + alpha: stroke.canvas.alpha.clone(), + opacity: stroke.stroke.settings.opacity, + erase: stroke.erase, + values: stroke.values.clone(), mask_value: self.tool.mask_value, - stencil: s.stencil.clone(), - carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(), + stencil: stroke.stencil.clone(), + carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(), }) }); + let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); let mut changed = false; @@ -719,24 +851,27 @@ impl Session { let Some(cache) = self.caches.get_mut(ts) else { continue }; cache.below.set_hot(hot); cache.below.pass = cache.dirty.len() + cache.settle.len(); - // Instances in sets of the stroke's size show the live stroke too. + + // Instances in sets of the stroke's size show the live stroke too let preview = preview.as_ref().filter(|_| Some(cache.size) == stroke_size); - // Start at the size that fit the budget last time: with a heavy stack (smart - // materials at 8K) one tile per thread alone would take several frames' budget. - let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { first }; + + // Reuse the last affordable chunk size for heavy stacks + let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { initial_chunk_size }; loop { if cache.dirty.is_empty() { if cache.settle.is_empty() || clock() - start >= budget_ms.min(SETTLE_BUDGET_MS) { break; } - // Small chunks: the settle slice of the budget is short. - cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(first))); + + // Small chunks: the settle slice of the budget is short + cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(initial_chunk_size))); } - let t0 = clock(); + let chunk_started = clock(); let tiles = next_chunk(&mut cache.dirty, chunk); - for t in &tiles { - cache.settle.remove(t); + for tile in &tiles { + cache.settle.remove(tile); } + let empty = BakedMaps::default(); let inputs = texturecraft_compose::Inputs { project: &self.doc.project, @@ -745,34 +880,44 @@ 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(), }; + + // Look ahead so sliced updates filter a run of tiles once + cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() }; texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); - // The composited tiles and the neighbours their padding reached change. + + // The composited tiles and the neighbours their padding reached change let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); cache.revision = cache.revision.wrapping_add(1); changed = true; + let now = clock(); - let left = budget_ms - (now - start); - // As many tiles as fit in what is left, at the pace of this chunk. - let per_tile = (now - t0) / tiles.len().max(1) as f64; - if budget_ms.is_finite() && per_tile > 0.0 { - // Never above one tile per thread: work can turn heavy from one frame to the next. - cache.chunk = ((budget_ms / per_tile) as usize).clamp(1, first); + let remaining_ms = budget_ms - (now - start); + + // Estimate how many tiles fit in the remaining frame budget + let ms_per_tile = (now - chunk_started) / tiles.len().max(1) as f64; + if budget_ms.is_finite() && ms_per_tile > 0.0 { + // Never above one tile per thread: work can turn heavy from one frame to the next + cache.chunk = ((budget_ms / ms_per_tile) as usize).clamp(1, initial_chunk_size); } - if left <= 0.0 { + if remaining_ms <= 0.0 { return changed; } - let fit = if per_tile > 0.0 { (left / per_tile) as usize } else { CHUNK }; - if fit == 0 { + + let fitting_tiles = if ms_per_tile > 0.0 { (remaining_ms / ms_per_tile) as usize } else { CHUNK }; + if fitting_tiles == 0 { return changed; } - chunk = fit.min(CHUNK); + + chunk = fitting_tiles.min(CHUNK); } } + changed } @@ -833,6 +978,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(), @@ -846,6 +992,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> { @@ -887,19 +1040,42 @@ pub const SETTLE_BUDGET_MS: f64 = 6.0; /// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters /// evaluate compact regions. -fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> { - if dirty.len() <= n { +fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> { + // A zero-sized request cannot select a pivot + if max_tiles == 0 { + return Vec::new(); + } + + if dirty.len() <= max_tiles { return std::mem::take(dirty).into_iter().collect(); } + let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect(); - tiles.sort_by_key(|&(x, y)| (y / 16, x / 16, y, x)); - tiles.truncate(n); - for t in &tiles { - dirty.remove(t); + + // Partition by block order so only the requested chunk needs sorting + tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); + tiles.truncate(max_tiles); + tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); + for tile in &tiles { + dirty.remove(tile); } + tiles } +/// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited. +const FILTER_AHEAD: usize = 64; + +/// The dirty tiles composited after `chunk` in its 16 × 16 tile blocks, in the order [`next_chunk`] takes them, at most [`FILTER_AHEAD`]. +fn tiles_ahead(dirty: &BTreeSet<(u32, u32)>, chunk: &[(u32, u32)]) -> Vec<(u32, u32)> { + let block = |&(x, y): &(u32, u32)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK); + let blocks: BTreeSet<(u32, u32)> = chunk.iter().map(block).collect(); + let mut ahead: Vec<(u32, u32)> = dirty.iter().copied().filter(|tile| blocks.contains(&block(tile))).collect(); + ahead.sort_by_key(|tile| (block(tile), tile.1, tile.0)); + ahead.truncate(FILTER_AHEAD); + ahead +} + /// Valid texture set resolutions: powers of two from 128 to 8192. pub fn check_resolution(r: u32) -> Result { if (128..=8192).contains(&r) && r.is_power_of_two() { diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 1d9cc7f0..a0bf6b6d 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -75,12 +75,27 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { } fn select(s: &mut Session, p: &Value) -> Result { - let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + let ts = u64p(p, "ts") + .map(|index| index as usize) + .filter(|index| *index < s.set_count()) + .ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + select_set(s, ts)?; + Ok(json!({ "ts": ts })) +} + +/// Make texture set `ts` the active one, on its content stack +pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> { s.cancel_stroke(); + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + } + s.active_set = ts; s.target = StackTarget::Content; s.revision = s.revision.wrapping_add(1); - Ok(json!({ "ts": ts })) + Ok(()) } fn resolution(s: &mut Session, p: &Value) -> Result { 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/text_cmds.rs b/crates/engine/src/text_cmds.rs index fbc4705b..5964813f 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -25,6 +25,7 @@ pub fn specs() -> Vec { /// Fonts bundled with the app (egui's), used when nothing is installed or in the browser. const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)]; /// Families tried, in order, when no font is asked for. +#[cfg(not(target_arch = "wasm32"))] const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"]; /// Largest font file read. #[cfg(not(target_arch = "wasm32"))] @@ -99,7 +100,7 @@ fn add_text(s: &mut Session, p: &Value) -> Result { let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?; let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0); let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?; - let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); + let rgb = color_param(cmd, p, "color")?.unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?; // The resource is named after the text (its first line, shortened) unless a name is given. let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect(); diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs new file mode 100644 index 00000000..6cd6e2a2 --- /dev/null +++ b/crates/engine/src/thumbs.rs @@ -0,0 +1,570 @@ +//! Asynchronous layer-panel thumbnails. +//! +//! The panel asks for small previews of layer contents, masks and effect stages +//! ([`ThumbTarget`]). The work never runs on the UI thread and never touches the main composite: +//! +//! * A **snapshot** ([`ThumbSnapshot`]) is an immutable copy of what the compositor reads (the +//! project, copy-on-write pixel tiles, baked maps, images and the mesh) plus a 64 px G-buffer. +//! It is rebuilt only when the document really changed, at most every [`DEBOUNCE`] seconds +//! (a slider drag renders at that pace, not once per frame). +//! * A **worker thread** evaluates one target at a time from a snapshot with +//! [`texturecraft_compose::thumb::render`]. On wasm32 (no threads) one job runs per +//! [`ThumbService::poll`] instead. +//! * Results are kept in a small LRU **cache** ([`CACHE_ENTRIES`]). A result computed from an +//! older snapshot than the current one is dropped, so a slow job can never overwrite a newer +//! thumbnail. An entry that is out of date keeps showing until its replacement arrives. +//! * Only targets requested during the current frame are rendered: a row that scrolled away +//! before its turn is dropped from the queue. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbTarget, thumb}; +use texturecraft_core::Project; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer}; + +use crate::Session; + +/// Thumbnails kept. +pub const CACHE_ENTRIES: usize = 96; +/// Seconds between checks for a changed document while it keeps changing. +pub const DEBOUNCE: f64 = 0.12; +/// Jobs handed to the worker at once (the rest wait here, where they can still be dropped). +const IN_FLIGHT: usize = 2; + +/// An immutable copy of everything the thumbnails of one texture set read. +pub struct ThumbSnapshot { + ts: usize, + mesh_id: u64, + project: Project, + pixels: PixelStore, + baked: BakedMaps, + images: ImageStore, + mesh: Arc, + gbuf: Arc, + bounds: (Vec3, Vec3), +} + +impl ThumbSnapshot { + /// Snapshot texture set `ts` of `s`, with the G-buffer from `gbufs` (built on a miss). + pub fn new(s: &Session, ts: usize, gbufs: &mut GbufCache) -> Option { + let material = s.doc.project.texture_set(ts).ok()?.material; + let gbuf = gbufs.get(&s.mesh, s.mesh_id, material); + Some(ThumbSnapshot { + ts, + mesh_id: s.mesh_id, + project: s.doc.project.clone(), + pixels: s.doc.pixels.clone(), + baked: s.doc.baked.get(&ts).cloned().unwrap_or_default(), + images: s.images.clone(), + mesh: s.mesh.clone(), + gbuf, + bounds: s.mesh.bounds(), + }) + } + + /// Whether `session` would give the same thumbnails as this snapshot. + fn matches(&self, session: &Session, texture_set: usize) -> bool { + let same_pixels = self.pixels.layers.len() == session.doc.pixels.layers.len() + && self.pixels.masks.len() == session.doc.pixels.masks.len() + && self.pixels.layers.iter().all(|(key, pixels)| session.doc.pixels.layers.get(key) == Some(pixels)) + && self.pixels.masks.iter().all(|(key, pixels)| session.doc.pixels.masks.get(key) == Some(pixels)); + let empty = BakedMaps::default(); + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + + // Copy-on-write maps change handles on edits; float equality would scan entire bakes + let same_baked = self.baked.resolution == baked.resolution + && self.baked.maps.len() == baked.maps.len() + && self.baked.maps.iter().all(|(map, pixels)| baked.maps.get(map).is_some_and(|current| Arc::ptr_eq(pixels, current))); + + self.ts == texture_set + && self.mesh_id == session.mesh_id + && self.project == session.doc.project + && same_pixels + && same_baked + && self.images.len() == session.images.len() + && self.images.iter().all(|(key, image)| session.images.get(key).is_some_and(|current| Arc::ptr_eq(current, image))) + } + + /// Render `target`: the work of one job. + pub fn render(&self, target: ThumbTarget) -> Option { + let inp = Inputs { + project: &self.project, + ts: self.ts, + mesh: &self.mesh, + gbuf: &self.gbuf, + pixels: &self.pixels, + baked: &self.baked, + block_scales: self.project.texture_set(self.ts).map(|set| set.block_scales()).unwrap_or_default(), + preview: None, + images: &self.images, + bounds: self.bounds, + }; + thumb::render(&inp, target) + } + + /// Whether the layer or effect `target` shows still exists in the snapshot's project. + fn has(&self, target: ThumbTarget) -> bool { + has_target(&self.project, target) + } +} + +fn has_target(p: &Project, target: ThumbTarget) -> bool { + match target { + ThumbTarget::Content { layer, .. } | ThumbTarget::Mask { layer } => p.layers.contains_key(&layer), + ThumbTarget::Stage { effect, .. } => p.effect(effect).is_some(), + } +} + +/// The 64 px G-buffers built so far, per mesh and material (rasterizing is the one part of a +/// snapshot that is not just copying handles). +#[derive(Default)] +pub struct GbufCache { + map: HashMap<(u64, usize), Arc>, +} + +impl GbufCache { + fn get(&mut self, mesh: &Mesh, mesh_id: u64, material: usize) -> Arc { + if self.map.len() > 16 { + self.map.clear(); + } + self.map.entry((mesh_id, material)).or_insert_with(|| Arc::new(UvGBuffer::new(mesh, material, THUMB_TEXELS, THUMB_TEXELS))).clone() + } +} + +struct Entry { + /// None: the target has nothing to show (a layer without that channel). + image: Option>, + /// Snapshot generation it was rendered from. + generation: u64, + /// Changes whenever `image` does (views key their GPU textures on it). + version: u64, + used: u64, +} + +/// What the panel draws for one target. +#[derive(Clone)] +pub struct ThumbView { + pub image: Option>, + /// Identifies `image`; changes when a new picture arrives. + pub version: u64, + /// A newer picture is on its way. + pub pending: bool, +} + +struct Job { + snapshot: Arc, + generation: u64, + target: ThumbTarget, +} + +struct Done { + generation: u64, + target: ThumbTarget, + image: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +struct Worker { + tx: std::sync::mpsc::Sender, + rx: std::sync::mpsc::Receiver, +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn_worker() -> Option { + let (tx, jobs) = std::sync::mpsc::channel::(); + let (done_tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("layer-thumbs".into()) + .spawn(move || { + while let Ok(job) = jobs.recv() { + let image = job.snapshot.render(job.target); + if done_tx.send(Done { generation: job.generation, target: job.target, image }).is_err() { + break; + } + } + }) + .ok()?; + Some(Worker { tx, rx }) +} + +/// The thumbnail cache and its worker. One lives in the UI; see the module documentation. +pub struct ThumbService { + snapshot: Option>, + /// Bumps whenever the snapshot's content changes; entries and jobs carry it. + generation: u64, + /// The session revision the snapshot was last compared with. + seen: Option, + last_check: f64, + cache: HashMap, + tick: u64, + versions: u64, + queue: VecDeque, + in_flight: HashSet<(u64, ThumbTarget)>, + wanted: HashSet, + gbufs: GbufCache, + #[cfg(not(target_arch = "wasm32"))] + worker: Option, + #[cfg(not(target_arch = "wasm32"))] + spawned: bool, + /// Jobs run inline (wasm32, or no worker thread could start). + inline: VecDeque, + /// Pictures computed (tests, benchmarks). + pub rendered: u64, +} + +impl Default for ThumbService { + fn default() -> Self { + ThumbService { + snapshot: None, + generation: 0, + seen: None, + last_check: f64::NEG_INFINITY, + cache: HashMap::new(), + tick: 0, + versions: 0, + queue: VecDeque::new(), + in_flight: HashSet::new(), + wanted: HashSet::new(), + gbufs: GbufCache::default(), + #[cfg(not(target_arch = "wasm32"))] + worker: None, + #[cfg(not(target_arch = "wasm32"))] + spawned: false, + inline: VecDeque::new(), + rendered: 0, + } + } +} + +impl ThumbService { + pub fn new() -> ThumbService { + ThumbService::default() + } + + /// Start of a frame: forget what the last frame asked for and notice document changes. + pub fn begin_frame(&mut self, session: &Session, now: f64) { + self.wanted.clear(); + let texture_set = session.ts(); + if self.seen == Some(session.revision) + && self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id) + { + return; + } + + // Compare at the debounce pace while the document keeps changing + if self.snapshot.is_some() && now - self.last_check < DEBOUNCE { + return; + } + + self.last_check = now; + if self.snapshot.as_ref().is_some_and(|snapshot| snapshot.matches(session, texture_set)) { + self.seen = Some(session.revision); + return; + } + + self.snapshot = ThumbSnapshot::new(session, texture_set, &mut self.gbufs).map(Arc::new); + self.seen = Some(session.revision); + self.generation = self.generation.wrapping_add(1); + + // Keep dispatched jobs counted until they finish, even when their snapshot is stale + self.queue.clear(); + for job in self.inline.drain(..) { + self.in_flight.remove(&(job.generation, job.target)); + } + + if let Some(snapshot) = &self.snapshot { + self.cache.retain(|target, _| snapshot.has(*target)); + } else { + self.cache.clear(); + } + } + + /// Whether the displayed pictures wait for a document comparison that is still debounced. + fn checked(&self, session: &Session) -> bool { + self.seen == Some(session.revision) + } + + /// The picture for `target` (call for the rows on screen only). Queues work when the + /// picture is missing or out of date. + pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView { + self.wanted.insert(target); + self.tick = self.tick.wrapping_add(1); + let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation); + let checked = self.checked(session); + if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) { + self.queue.push_back(target); + } + + match self.cache.get_mut(&target) { + Some(entry) => { + entry.used = self.tick; + ThumbView { image: entry.image.clone(), version: entry.version, pending: !(fresh && checked) } + } + None => ThumbView { image: None, version: 0, pending: true }, + } + } + + /// End of a frame: collect results, discard unrequested rows, and dispatch new work. + /// Returns whether another frame is needed, including to display newly collected pictures. + pub fn poll(&mut self, session: &Session) -> bool { + let changed = self.collect(); + self.queue.retain(|target| self.wanted.contains(target)); + self.dispatch(); + self.trim(); + + changed || !self.queue.is_empty() || !self.in_flight.is_empty() || !self.checked(session) + } + + fn dispatch(&mut self) { + let Some(snapshot) = self.snapshot.clone() else { return }; + + while self.in_flight.len() < IN_FLIGHT { + let Some(target) = self.queue.pop_front() else { break }; + let job = Job { snapshot: snapshot.clone(), generation: self.generation, target }; + self.in_flight.insert((job.generation, target)); + self.send(job); + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn send(&mut self, job: Job) { + if !self.spawned { + self.spawned = true; + self.worker = spawn_worker(); + } + + match &self.worker { + Some(worker) => { + if let Err(error) = worker.tx.send(job) { + // A stopped worker cannot complete any of its outstanding jobs + self.worker = None; + self.in_flight.clear(); + self.in_flight.insert((error.0.generation, error.0.target)); + self.inline.push_back(error.0); + } + } + None => self.inline.push_back(job), + } + } + + #[cfg(target_arch = "wasm32")] + fn send(&mut self, job: Job) { + self.inline.push_back(job); + } + + fn collect(&mut self) -> bool { + let mut completed = Vec::new(); + let mut changed = false; + #[cfg(not(target_arch = "wasm32"))] + if let Some(worker) = &self.worker { + loop { + match worker.rx.try_recv() { + Ok(result) => completed.push(result), + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + // Request another frame so wanted targets retry on the inline fallback + self.worker = None; + self.in_flight.clear(); + changed = true; + break; + } + } + } + } + + // Without a thread, bound each poll to one render + if let Some(job) = self.inline.pop_front() { + let image = job.snapshot.render(job.target); + completed.push(Done { generation: job.generation, target: job.target, image }); + } + + for result in completed { + self.rendered = self.rendered.wrapping_add(1); + self.in_flight.remove(&(result.generation, result.target)); + + // A picture of an older snapshot never replaces a newer one + if result.generation != self.generation { + continue; + } + + if !self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(result.target)) { + continue; + } + + self.versions = self.versions.wrapping_add(1); + let entry = Entry { image: result.image.map(Arc::new), generation: result.generation, version: self.versions, used: self.tick }; + self.cache.insert(result.target, entry); + changed = true; + } + + changed + } + + fn trim(&mut self) { + while self.cache.len() > CACHE_ENTRIES { + let Some(oldest) = self.cache.iter().filter(|(t, _)| !self.wanted.contains(t)).min_by_key(|(_, e)| e.used).map(|(t, _)| *t) else { break }; + self.cache.remove(&oldest); + } + } + + /// Entries held (tests). + pub fn cached(&self) -> usize { + self.cache.len() + } + + /// Whether `target` has a picture of the current snapshot (tests). + pub fn is_fresh(&self, target: ThumbTarget) -> bool { + self.cache.get(&target).is_some_and(|e| e.generation == self.generation) + } + + /// Whether any work is queued or running (tests). + pub fn busy(&self) -> bool { + !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use texturecraft_core::Channel; + use texturecraft_geom::primitives; + + fn test_session() -> crate::Result { + Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128) + } + + fn held_worker() -> (ThumbService, std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { + let (sender, jobs) = std::sync::mpsc::channel(); + let (results, receiver) = std::sync::mpsc::channel(); + let service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() }; + (service, jobs, results) + } + + #[test] + fn unchanged_baked_handles_match_even_with_non_finite_samples() { + let mut session = test_session().unwrap(); + let baked = session.doc.baked.entry(0).or_default(); + baked.resolution = 1; + baked.maps.insert(texturecraft_core::BakedMap::Height, Arc::new(vec![f32::NAN])); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + assert!(snapshot.matches(&session, 0), "unchanged shared data must not invalidate every frame"); + + let map = session.doc.baked.get_mut(&0).unwrap().maps.get_mut(&texturecraft_core::BakedMap::Height).unwrap(); + Arc::make_mut(map)[0] = 0.5; + assert!(!snapshot.matches(&session, 0), "a copy-on-write edit must invalidate the snapshot"); + } + + #[test] + #[ignore] + fn benchmark_unchanged_4k_baked_snapshot() { + let mut session = test_session().unwrap(); + let baked = session.doc.baked.entry(0).or_default(); + baked.resolution = 4096; + baked.maps.insert(texturecraft_core::BakedMap::Normal, Arc::new(vec![0.5; 4096 * 4096 * 3])); + baked.maps.insert(texturecraft_core::BakedMap::AmbientOcclusion, Arc::new(vec![0.5; 4096 * 4096])); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let start = std::time::Instant::now(); + + for _ in 0..20 { + assert!(std::hint::black_box(&snapshot).matches(std::hint::black_box(&session), 0)); + } + + eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed()); + } + + #[test] + fn collecting_the_last_result_requests_a_frame_to_display_it() { + let session = test_session().unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (mut service, jobs, results) = held_worker(); + service.begin_frame(&session, 0.0); + service.get(&session, target); + assert!(service.poll(&session)); + let job = jobs.try_recv().unwrap(); + results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap(); + + service.begin_frame(&session, 0.1); + assert!(service.get(&session, target).image.is_none()); + let repaint = service.poll(&session); + + assert!(service.is_fresh(target)); + assert!(repaint, "the frame drew before collecting the final thumbnail"); + service.begin_frame(&session, 0.2); + assert!(service.get(&session, target).image.is_some()); + assert!(!service.poll(&session), "an idle cache must stop repainting"); + } + + #[test] + fn a_stopped_worker_retries_visible_targets_inline() { + let session = test_session().unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (mut service, jobs, results) = held_worker(); + service.begin_frame(&session, 0.0); + service.get(&session, target); + service.poll(&session); + + // Simulate a worker that stops with a dispatched request still outstanding + drop(jobs); + drop(results); + for frame in 1..=4 { + service.begin_frame(&session, f64::from(frame)); + service.get(&session, target); + service.poll(&session); + } + + assert!(service.get(&session, target).image.is_some()); + assert!(!service.busy()); + } + + #[test] + fn edits_keep_worker_jobs_and_retained_snapshots_bounded() { + let mut session = test_session().unwrap(); + let layer = session.selected_layer().unwrap(); + let target = ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let (mut service, jobs, results) = held_worker(); + let mut snapshots = Vec::new(); + + // Hold the worker's receiver still while repeated edits each produce a new snapshot + for revision in 0..2_000 { + session.doc.pixels.layer_mut(layer, Channel::BaseColor, (128, 128)).set(0, 0, &[revision, 0, 0, u16::MAX]); + session.revision += 1; + service.begin_frame(&session, f64::from(revision)); + snapshots.push(Arc::downgrade(service.snapshot.as_ref().unwrap())); + service.get(&session, target); + service.poll(&session); + } + + let queued: Vec<_> = jobs.try_iter().collect(); + let retained = snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(); + let retained_pixel_bytes: usize = snapshots.iter().filter_map(std::sync::Weak::upgrade).map(|snapshot| snapshot.pixels.bytes()).sum(); + eprintln!("2,000 edits: {} queued jobs, {retained} live snapshots, {retained_pixel_bytes} retained pixel bytes", queued.len()); + assert!(queued.len() <= IN_FLIGHT, "{} queued jobs bypassed the worker limit", queued.len()); + assert!(retained <= IN_FLIGHT + 1, "{retained} document snapshots retained across edits"); + assert!(retained_pixel_bytes <= (IN_FLIGHT + 1) * texturecraft_texel::TILE_AREA * 4 * std::mem::size_of::()); + + // Finishing stale work frees a slot for the newest document, without caching old results + for job in queued { + results.send(Done { generation: job.generation, target: job.target, image: None }).unwrap(); + } + + assert_eq!(snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(), 1, "completed jobs release stale snapshots"); + assert!(service.poll(&session)); + assert!(!service.is_fresh(target)); + let latest = jobs.try_recv().unwrap(); + assert_eq!(latest.generation, service.generation); + results.send(Done { generation: latest.generation, target, image: latest.snapshot.render(target) }).unwrap(); + drop(latest); + assert!(service.poll(&session)); + assert!(service.is_fresh(target)); + + let image = Arc::downgrade(service.cache.get(&target).unwrap().image.as_ref().unwrap()); + drop(service); + + assert!(snapshots.iter().all(|snapshot| snapshot.upgrade().is_none()), "dropping the cache releases its last snapshot"); + assert!(image.upgrade().is_none(), "dropping the cache releases the rendered image"); + assert!(jobs.try_recv().is_err()); + } +} diff --git a/crates/engine/src/tool_availability.rs b/crates/engine/src/tool_availability.rs new file mode 100644 index 00000000..392388e3 --- /dev/null +++ b/crates/engine/src/tool_availability.rs @@ -0,0 +1,46 @@ +//! Which tools can act on the current selection: the tool shelf and its shortcuts grey the rest + +use texturecraft_core::{EffectKind, LayerKind}; + +use crate::{Session, StackTarget, Tool}; + +impl Session { + /// Whether `tool` can act on the selection (or on the quick mask while it is being edited) + pub fn tool_usable(&self, tool: Tool) -> bool { + match tool { + // The picker reads the composite under the cursor, whatever is selected + Tool::ColorPicker => return true, + Tool::GeometryMask => return self.selected_layer().is_some(), + _ => {} + } + + // Brushes paint the quick mask whatever is selected; paths can't edit it + if self.quick_mask.editing { + return tool != Tool::Path; + } + + let project = &self.doc.project; + let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false }; + + // Smudge and Clone read layer content, so they can't yet paint mask values + let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); + match self.target { + StackTarget::Content => matches!(layer.kind, LayerKind::Paint), + StackTarget::Mask => !reads_content, + StackTarget::Effect(effect) => { + let Some((owner, found)) = project.effect(effect) else { return false }; + let Some(owner_layer) = project.layers.get(&owner) else { return false }; + let in_content = owner_layer.content_effects.iter().any(|candidate| candidate.id == effect); + let in_fill_content = in_content && matches!(owner_layer.kind, LayerKind::Fill(_)); + + match found.kind { + // Paths saved in a fill layer before paths there were removed stay editable + EffectKind::Path(_) => tool == Tool::Path, + EffectKind::Paint if tool == Tool::Path => !in_fill_content, + EffectKind::Paint => in_content || !reads_content, + _ => false, + } + } + } + } +} diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..cecc8495 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -4,10 +4,12 @@ use serde_json::{Value, json}; use texturecraft_core::Channel; use texturecraft_geom::glam::Vec2; -use texturecraft_paint::{Alignment, BrushAlpha, alphas}; +use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas}; -use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; -use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; +use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_of, color_param, f32p, strp, vec3}; +use crate::fill_hit_test::FillHitTest; +use crate::fill_mode::FillMode; +use crate::session::{CloneFrom, CloneSource, StackTarget, Tool}; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { @@ -18,7 +20,7 @@ pub fn specs() -> Vec { cmd!("tool.polygonFill", "Polygon fill", ["Tools"], Some("4"), "{}", always, |s, _| set_tool(s, Tool::PolygonFill)), cmd!("tool.smudge", "Smudge", ["Tools"], Some("5"), "{}", always, |s, _| set_tool(s, Tool::Smudge)), cmd!("tool.clone", "Clone", ["Tools"], Some("6"), "{}", always, |s, _| set_tool(s, Tool::Clone)), - cmd!("tool.colorPicker", "Color picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)), + cmd!("tool.colorPicker", "Material picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)), cmd!( "tool.geometryMask", "Geometry mask", @@ -34,7 +36,7 @@ pub fn specs() -> Vec { "Brush settings", [], None, - "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", + "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", always, brush ), @@ -51,6 +53,15 @@ pub fn specs() -> Vec { always, material ), + cmd!( + "tool.swapMaskValue", + "Invert mask value", + ["Tools"], + Some("X"), + "{} — mask value becomes 1 − value: switch the brush between adding to and removing from the mask", + paints_mask, + swap_mask_value + ), cmd!( "tool.stencil", "Projection stencil", @@ -69,7 +80,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 +100,27 @@ 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 / material 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 { @@ -98,135 +129,171 @@ fn select(s: &mut Session, p: &Value) -> Result { set_tool(s, t) } -/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers. -fn brush(s: &mut Session, p: &Value) -> Result { - let b = &mut s.tool.brush; - let pct = |k: &str| f32p(p, k).map(|v| v / 100.0); - if let Some(v) = pct("size") { - b.size = v * 0.25; +/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers +fn brush(session: &mut Session, params: &Value) -> Result { + let mut settings = session.tool.brush.clone(); + let percent = |key: &str| f32p(params, key).map(|value| value / 100.0); + + if let Some(value) = percent("size") { + settings.size = value * 0.25; } - if let Some(v) = pct("minSize") { - b.min_size = v; + if let Some(value) = percent("minSize") { + settings.min_size = value; } - if let Some(v) = pct("flow") { - b.flow = v; + + if let Some(value) = percent("flow") { + settings.flow = value; } - if let Some(v) = pct("opacity") { - b.opacity = v; + if let Some(value) = percent("opacity") { + settings.opacity = value; } - if let Some(v) = pct("spacing") { - b.spacing = v; + if let Some(value) = percent("spacing") { + settings.spacing = value; } - if let Some(v) = pct("hardness") { - b.hardness = v; + if let Some(value) = percent("hardness") { + settings.hardness = value; } - if let Some(v) = f32p(p, "angle") { - b.angle = v; + + if let Some(value) = f32p(params, "angle") { + settings.angle = value; } - if let Some(v) = boolp(p, "followPath") { - b.follow_path = v; + if let Some(value) = boolp(params, "followPath") { + settings.follow_path = value; } - if let Some(a) = strp(p, "alignment") { - b.alignment = match a { + if let Some(alignment) = strp(params, "alignment") { + settings.alignment = match alignment { "camera" => Alignment::Camera, "tangent" | "uv" => Alignment::Tangent, other => return Err(bad("tool.brush", format!("unknown alignment `{other}`"))), }; } - if let Some(v) = f32p(p, "lazy") { - b.lazy = v; + + if let Some(value) = f32p(params, "lazy") { + settings.lazy = value; } - for (k, slot) in [("jitterSize", &mut b.jitter_size), ("jitterAngle", &mut b.jitter_angle), ("jitterFlow", &mut b.jitter_flow)] { - if let Some(v) = f32p(p, k) { - *slot = v / 100.0; + + for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] { + if let Some(value) = f32p(params, key) { + *slot = value / 100.0; } } - if let Some(v) = f32p(p, "jitterPosition") { - b.jitter_position = v / 100.0; + if let Some(value) = f32p(params, "jitterPosition") { + settings.jitter_position = value / 100.0; } - let alpha = p.get("alpha"); - if let Some(a) = strp(p, "alpha") { - b.alpha = BrushAlpha::parse(a).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{a}`")))?; - (b.alpha_image, b.alpha_library) = (None, None); - } else if let Some(name) = alpha.and_then(|a| a.get("image")).and_then(Value::as_str) { - if !s.images.contains_key(name) { + + let alpha = params.get("alpha"); + if let Some(alpha_name) = strp(params, "alpha") { + settings.alpha = BrushAlpha::parse(alpha_name).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{alpha_name}`")))?; + (settings.alpha_image, settings.alpha_library) = (None, None); + } else if let Some(name) = alpha.and_then(|alpha| alpha.get("image")).and_then(Value::as_str) { + if !session.images.contains_key(name) { return Err(bad("tool.brush", format!("no image resource `{name}` (import it first)"))); } - (b.alpha_image, b.alpha_library) = (Some(name.to_string()), None); - } else if let Some(id) = alpha.and_then(|a| a.get("library")).and_then(Value::as_str) { - let a = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?; - // Render it now rather than on the first stamp. - a.image(); - (b.alpha_image, b.alpha_library) = (None, Some(a.id.clone())); + + (settings.alpha_image, settings.alpha_library) = (Some(name.to_string()), None); + } else if let Some(id) = alpha.and_then(|alpha| alpha.get("library")).and_then(Value::as_str) { + let alpha = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?; + + // Render it now rather than on the first stamp + alpha.image(); + (settings.alpha_image, settings.alpha_library) = (None, Some(alpha.id.clone())); } - if let Some(v) = boolp(p, "backfaceCulling") { - b.backface_culling = v; + + if let Some(value) = boolp(params, "backfaceCulling") { + settings.backface_culling = value; } - for (k, slot) in [("symmetryX", &mut b.symmetry.x), ("symmetryY", &mut b.symmetry.y), ("symmetryZ", &mut b.symmetry.z)] { - if let Some(v) = boolp(p, k) { - *slot = v; + + if let Some(value) = boolp(params, "symmetryOn") { + settings.symmetry.enabled = value; + } + + for (key, slot) in [("symmetryX", &mut settings.symmetry.x), ("symmetryY", &mut settings.symmetry.y), ("symmetryZ", &mut settings.symmetry.z)] { + if let Some(value) = boolp(params, key) { + *slot = value; } } - if let Some(v) = f32p(p, "symmetryRadial") { - b.symmetry.radial = v.clamp(0.0, 32.0) as u8; + + if let Some(value) = f32p(params, "symmetryRadial") { + settings.symmetry.radial = value.clamp(0.0, f32::from(MAX_RADIAL_COPIES)) as u8; } - if let Some(a) = strp(p, "symmetryAxis") { - b.symmetry.axis = match a.to_ascii_lowercase().as_str() { + + if let Some(axis) = strp(params, "symmetryAxis") { + settings.symmetry.axis = match axis.to_ascii_lowercase().as_str() { "x" => 0, "y" => 1, "z" => 2, - _ => return Err(bad("tool.brush", format!("unknown symmetry axis `{a}` (x, y or z)"))), + _ => return Err(bad("tool.brush", format!("unknown symmetry axis `{axis}` (x, y or z)"))), }; } - if let Some(v) = boolp(p, "screenSpace") { - b.screen_space = v; + + if let Some(value) = f32p(params, "symmetryAngleSpan") { + settings.symmetry.angle_span = value; } - if let Some(q) = p.get("particles") { - let pt = &mut b.particles; - pt.enabled = boolp(q, "enabled").unwrap_or(pt.enabled); - pt.count = f32p(q, "count").map_or(pt.count, |v| v as u32); - pt.lifetime = f32p(q, "lifetime").map_or(pt.lifetime, |v| v as u32); - pt.gravity = f32p(q, "gravity").unwrap_or(pt.gravity); + + if params.get("symmetryOffset").is_some() { + settings.symmetry.offset = vec3(params, "symmetryOffset").ok_or_else(|| bad("tool.brush", "`symmetryOffset` must be [x, y, z]"))?.to_array(); } - *b = b.sanitized(); - if let Some(v) = f32p(p, "smudgeStrength") { - s.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0); + + if let Some(value) = boolp(params, "screenSpace") { + settings.screen_space = value; } - if let Some(v) = strp(p, "cloneSource") { - s.tool.clone_from = match v { + + if let Some(particle_params) = params.get("particles") { + let particles = &mut settings.particles; + particles.enabled = boolp(particle_params, "enabled").unwrap_or(particles.enabled); + particles.count = f32p(particle_params, "count").map_or(particles.count, |value| value as u32); + particles.lifetime = f32p(particle_params, "lifetime").map_or(particles.lifetime, |value| value as u32); + particles.gravity = f32p(particle_params, "gravity").unwrap_or(particles.gravity); + } + + let clone_from = if let Some(value) = strp(params, "cloneSource") { + match value { "composite" => CloneFrom::Composite, "layer" => CloneFrom::Layer, other => return Err(bad("tool.brush", format!("unknown clone source `{other}`: use composite or layer"))), - }; + } + } else { + session.tool.clone_from + }; + + session.tool.brush = settings.sanitized(); + session.tool.clone_from = clone_from; + if let Some(value) = f32p(params, "smudgeStrength") { + session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0); } - s.revision = s.revision.wrapping_add(1); - Ok(brush_json(s)) + + session.revision = session.revision.wrapping_add(1); + Ok(brush_json(session)) } -pub(crate) fn brush_json(s: &Session) -> Value { - let b = &s.tool.brush; +pub(crate) fn brush_json(session: &Session) -> Value { + let settings = &session.tool.brush; json!({ - "size": b.size / 0.25 * 100.0, "minSize": b.min_size * 100.0, "flow": b.flow * 100.0, "opacity": b.opacity * 100.0, - "spacing": b.spacing * 100.0, "hardness": b.hardness * 100.0, "angle": b.angle, "followPath": b.follow_path, - "alignment": format!("{:?}", b.alignment).to_lowercase(), "lazy": b.lazy, - "alpha": match (&b.alpha_image, &b.alpha_library) { + "size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0, + "spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path, + "alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy, + "alpha": match (&settings.alpha_image, &settings.alpha_library) { (Some(name), _) => json!({ "image": name }), (None, Some(id)) => json!({ "library": id }), - (None, None) => json!(b.alpha.label()), + (None, None) => json!(settings.alpha.label()), }, - "backfaceCulling": b.backface_culling, "symmetry": [b.symmetry.x, b.symmetry.y, b.symmetry.z], - "radialSymmetry": { "copies": b.symmetry.radial, "axis": (["x", "y", "z"].get(b.symmetry.axis as usize)) }, - "smudgeStrength": s.tool.smudge_strength * 100.0, "particles": b.particles, - "cloneSource": if s.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, + "backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], + "radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) }, + "symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span, + "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles, + "cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, }) } fn material(s: &mut Session, p: &Value) -> Result { + let channel = channel_param("tool.material", p, "channel")?; + let color = color_param("tool.material", p, "color")?; + let value = color_param("tool.material", p, "value")?; if let Some(v) = f32p(p, "maskValue") { s.tool.mask_value = v.clamp(0.0, 1.0); } - if let Some(c) = channel_param("tool.material", p, "channel")? { - if let Some(v) = color_param(p, "color").or_else(|| color_param(p, "value")) { + if let Some(c) = channel { + if let Some(v) = color.or(value) { let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) }; s.tool.values.insert(c, v); s.tool.enabled.insert(c); @@ -252,50 +319,77 @@ fn material(s: &mut Session, p: &Value) -> Result { })) } -fn stencil(s: &mut Session, p: &Value) -> Result { - if boolp(p, "clear") == Some(true) { - s.tool.stencil = None; +/// Whether strokes paint the selected layer's mask: the mask itself or one of its effects +fn paints_mask(session: &Session) -> std::result::Result<(), String> { + session.selected_layer().ok_or("no layer selected")?; + + let project = &session.doc.project; + let targets_mask = match session.target { + StackTarget::Content => false, + StackTarget::Mask => true, + StackTarget::Effect(effect_id) => project + .effect(effect_id) + .and_then(|(owner, _)| project.layers.get(&owner)) + .is_some_and(|owner_layer| !owner_layer.content_effects.iter().any(|effect| effect.id == effect_id)), + }; + + if targets_mask { Ok(()) } else { Err("select a mask to paint on".into()) } +} + +fn swap_mask_value(session: &mut Session, _: &Value) -> Result { + session.tool.mask_value = 1.0 - session.tool.mask_value; + session.revision = session.revision.wrapping_add(1); + + Ok(json!({ "maskValue": session.tool.mask_value })) +} + +fn stencil(session: &mut Session, params: &Value) -> Result { + if boolp(params, "clear") == Some(true) { + session.tool.stencil = None; return Ok(Value::Null); } - if let Some(name) = strp(p, "image") { - if !s.doc.resources.contains_key(name) { + + if let Some(name) = strp(params, "image") { + if !session.doc.resources.contains_key(name) { return Err(bad("tool.stencil", format!("no resource `{name}` (import it first)"))); } - let keep = s.tool.stencil.take(); - let mut st = crate::session::StencilState::new(name); - if let Some(k) = keep { - st = crate::session::StencilState { image: name.to_string(), ..k }; + + let previous_stencil = session.tool.stencil.take(); + let mut stencil_state = crate::session::StencilState::new(name); + if let Some(previous_stencil) = previous_stencil { + stencil_state = crate::session::StencilState { image: name.to_string(), ..previous_stencil }; } - s.tool.stencil = Some(st); + session.tool.stencil = Some(stencil_state); } - let st = s.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?; - if let Some(c) = color_param(p, "center").map(|c| [c[0], c[1]]).or_else(|| pair(p, "center")) { - st.center = c.map(|v| v.clamp(-4.0, 4.0)); + + let stencil_state = session.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?; + if let Some(center) = pair(params, "center").or_else(|| params.get("center").and_then(color_of).map(|color| [color[0], color[1]])) { + stencil_state.center = center.map(|value| value.clamp(-4.0, 4.0)); } - if let Some(v) = f32p(p, "scale") { - st.scale = v.clamp(0.01, 10.0); + if let Some(scale) = f32p(params, "scale") { + stencil_state.scale = scale.clamp(0.01, 10.0); } - if let Some(v) = f32p(p, "rotation") { - st.rotation = v.rem_euclid(360.0); + if let Some(rotation) = f32p(params, "rotation") { + stencil_state.rotation = rotation.rem_euclid(360.0); } - if let Some(v) = boolp(p, "tile") { - st.tile = v; + if let Some(tile) = boolp(params, "tile") { + stencil_state.tile = tile; } - if let Some(v) = f32p(p, "opacity") { - st.opacity = v.clamp(0.0, 1.0); + if let Some(opacity) = f32p(params, "opacity") { + stencil_state.opacity = opacity.clamp(0.0, 1.0); } - s.revision = s.revision.wrapping_add(1); - Ok(serde_json::to_value(&s.tool.stencil).unwrap_or(Value::Null)) + + session.revision = session.revision.wrapping_add(1); + Ok(serde_json::to_value(&session.tool.stencil).unwrap_or(Value::Null)) } /// A `[a, b]` param of two finite numbers. fn pair(p: &Value, key: &str) -> Option<[f32; 2]> { let a = p.get(key)?.as_array()?; - let v: Vec = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - match v.as_slice() { - [x, y] => Some([*x, *y]), - _ => None, - } + let [x, y] = a.as_slice() else { return None }; + let x = x.as_f64()? as f32; + let y = y.as_f64()? as f32; + (x.is_finite() && y.is_finite()).then_some([x, y]) } fn clone_source(s: &mut Session, p: &Value) -> Result { @@ -319,13 +413,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 +479,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 c6b49a7c..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,22 +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)); - if let Some(baked) = doc.baked.get(&ts) { - match remap_baked(baked, old, &new, &map) { - Some(b) => { - doc.baked.insert(ts, b); + + // 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 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); @@ -186,32 +202,68 @@ pub(crate) fn remap_image( /// Baked maps of layout `old` resampled (nearest texel) into layout `new` at the same density /// per UV tile; None when that is beyond what bakes may hold. -fn remap_baked(b: &BakedMaps, old: &TextureSet, new: &TextureSet, map: &(dyn Fn([f32; 2]) -> Option<[f32; 2]> + Sync)) -> Option { - let grid = |t: &TextureSet| t.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); - let ((ocols, _), (ncols, nrows)) = (grid(old), grid(new)); - let per_tile = b.resolution / ocols.max(1); - let (w, h) = (per_tile.checked_mul(ncols)?, per_tile.checked_mul(nrows)?); - if w == 0 || u64::from(w) * u64::from(h) > texturecraft_bake::MAX_TEXELS { - return None; - } - let mut out = BakedMaps { resolution: w, ..b.clone() }; - for (m, data) in &b.maps { - let (comps, ow, oh) = (m.components(), b.resolution as usize, b.height(*m) as usize); - let neutral = m.neutral(); - let mut texels = vec![0.0f32; w as usize * h as usize * comps]; - texels.par_chunks_mut(w as usize * comps).enumerate().for_each(|(y, row)| { - for (x, px) in row.chunks_mut(comps).enumerate() { - let src = map([(x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32]).and_then(|o| { - let (sx, sy) = (((o[0] * ow as f32) as usize).min(ow.saturating_sub(1)), ((o[1] * oh as f32) as usize).min(oh.saturating_sub(1))); - let i = (sy * ow + sx) * comps; - data.get(i..i + comps) +fn remap_baked(baked: &BakedMaps, old: &TextureSet, new: &TextureSet, map: &(dyn Fn([f32; 2]) -> Option<[f32; 2]> + Sync)) -> Option { + let first_map = baked.maps.keys().next()?; + let (width, height) = remapped_size((baked.resolution, baked.height(*first_map)), old, new)?; + let mut output = BakedMaps { resolution: width, ..BakedMaps::default() }; + for (kind, data) in &baked.maps { + let (component_count, old_width, old_height) = (kind.components(), baked.resolution as usize, baked.height(*kind) as usize); + let neutral = kind.neutral(); + let mut texels = vec![0.0f32; width as usize * height as usize * component_count]; + texels.par_chunks_mut(width as usize * component_count).enumerate().for_each(|(y, row)| { + for (x, pixel) in row.chunks_mut(component_count).enumerate() { + let source = map([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]).and_then(|uv| { + let source_x = ((uv[0] * old_width as f32) as usize).min(old_width.saturating_sub(1)); + let source_y = ((uv[1] * old_height as f32) as usize).min(old_height.saturating_sub(1)); + let offset = (source_y * old_width + source_x) * component_count; + data.get(offset..offset + component_count) }); - px.copy_from_slice(src.unwrap_or(&neutral[..comps])); + pixel.copy_from_slice(source.unwrap_or(&neutral[..component_count])); } }); - out.maps.insert(*m, Arc::new(texels)); + output.maps.insert(*kind, Arc::new(texels)); } - Some(out) + Some(output) +} + +fn remapped_size((width, height): (u32, u32), old: &TextureSet, new: &TextureSet) -> Option<(u32, u32)> { + let grid = |set: &TextureSet| set.tile_grid().map_or((1, 1), |grid| (grid.cols, grid.rows)); + let ((old_columns, old_rows), (new_columns, new_rows)) = (grid(old), grid(new)); + let width = (width / old_columns.max(1)).max(1).checked_mul(new_columns)?; + let height = (height / old_rows.max(1)).max(1).checked_mul(new_rows)?; + (u64::from(width) * u64::from(height) <= texturecraft_bake::MAX_TEXELS).then_some((width, height)) +} + +fn remap_bake_paint( + document: &mut Document, + texture_set: usize, + old: &TextureSet, + new: &TextureSet, + map: &(dyn Fn([f32; 2]) -> Option<[f32; 2]> + Sync), +) -> Result<()> { + use texturecraft_bake::BakePaintMap; + use texturecraft_core::BakePaintTarget; + for ((index, target), painted) in &mut document.bake_paint { + if *index != texture_set { + continue; + } + let (width, height) = remapped_size((painted.width, painted.height), old, new) + .ok_or_else(|| bad("textureSet.uvTiles", "painted bake maps would exceed the supported size"))?; + let empty = match target { + BakePaintTarget::Cage => 1.0, + BakePaintTarget::Skew => 0.0, + }; + let mut values = vec![empty; width as usize * height as usize]; + values.par_chunks_mut(width as usize).enumerate().for_each(|(y, row)| { + for (x, value) in row.iter_mut().enumerate() { + if let Some(uv) = map([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]) { + *value = painted.sample(texturecraft_geom::glam::Vec2::from_array(uv)); + } + } + }); + *painted = Arc::new(BakePaintMap { width, height, values }); + } + Ok(()) } #[cfg(test)] @@ -289,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(); @@ -397,3 +471,18 @@ mod tests { assert!(execute(&mut s, "textureSet.uvTiles", &json!({})).is_err()); } } + +#[test] +fn bake_maps_follow_uv_layout_without_losing_rectangular_dimensions() { + use texturecraft_core::{BakePaintTarget, BakedMap}; + let mut session = Session::new_project("UV", texturecraft_geom::primitives::builtin("udim_plane").unwrap(), "builtin:udim_plane", None, 256).unwrap(); + crate::execute(&mut session, "bake.settings", &json!({"model": {"common": {"resolution": "R64", "resolution_height": "R128"}}})).unwrap(); + crate::execute(&mut session, "bake.run", &json!({"maps": ["normal"]})).unwrap(); + crate::execute(&mut session, "bake.skew.paint", &json!({"points": [[0.125, 0.25]], "radius": 0.06, "size": 64})).unwrap(); + crate::execute(&mut session, "textureSet.uvTiles", &json!({"enabled": false})).unwrap(); + let baked = &session.doc.baked[&0]; + assert_eq!((baked.resolution, baked.height(BakedMap::Normal)), (64, 128)); + let painted = &session.doc.bake_paint[&(0, BakePaintTarget::Skew)]; + assert!(painted.sample(texturecraft_geom::glam::Vec2::new(0.25, 0.25)) > 0.9); + assert_eq!(painted.sample(texturecraft_geom::glam::Vec2::new(0.75, 0.75)), 0.0); +} diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index b39c876d..db03435c 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -88,7 +88,13 @@ fn frame(s: &mut Session, _: &Value) -> Result { } fn set_view(s: &mut Session, v: ViewMode) -> Result { - s.view = v; + if s.bake_preview.is_some() { + // During a bake the view follows the preview: a mesh map pins it, another mode comes back afterwards + s.bake_preview_user_view(v); + } else { + s.view = v; + } + let v = s.view; s.revision = s.revision.wrapping_add(1); Ok(json!({ "view": v.label() })) } @@ -205,6 +211,7 @@ fn display(s: &mut Session, p: &Value) -> Result { if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) { return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); } + let scatter_color = color_param("display.set", p, "scatterColor")?; let d = &mut s.doc.project.display; if let Some(e) = env { d.environment = e; @@ -230,7 +237,7 @@ fn display(s: &mut Session, p: &Value) -> Result { if let Some(t) = tm { d.tone_mapping = t; } - if let Some(c) = color_param(p, "scatterColor") { + if let Some(c) = scatter_color { d.scatter_color = c.map(|v| v.clamp(0.0, 1.0)); } if let Some(b) = boolp(p, "shadows") { diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs deleted file mode 100644 index e6a37275..00000000 --- a/crates/engine/tests/auto_rebake.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! Auto-rebake: one mesh map bakes itself again when its bake inputs change. - -use std::sync::Arc; - -use serde_json::{Value, json}; -use texturecraft_engine::core::BakedMap; -use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; - -/// A plane with a high poly just above it, baked once with height and opacity. -fn baked_session(tag: &str) -> (Session, std::path::PathBuf) { - let mesh = primitives::builtin("plane").unwrap(); - let mut obj = String::from("o Part_high\n"); - for p in &mesh.positions { - obj += &format!("v {} {} {}\n", p.x, p.y + 0.002, p.z); - } - for t in mesh.indices.chunks_exact(3) { - obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); - } - let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{tag}_{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("hp.obj"); - std::fs::write(&path, obj).unwrap(); - let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); - execute(&mut s, "bake.highPoly.add", &json!({ "path": path.display().to_string() })).unwrap(); - execute(&mut s, "bake.settings", &json!({ "resolution": 128, "dilation": 0, "maps": ["height", "opacity"] })).unwrap(); - execute(&mut s, "bake.run", &json!({ "cpu": true })).unwrap(); - (s, dir) -} - -fn due(s: &mut Session) -> Vec { - execute(s, "bake.autoRebake", &Value::Null).unwrap()["due"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() -} - -fn image(s: &Session, map: BakedMap) -> Arc> { - s.doc.baked[&0].maps[&map].clone() -} - -#[test] -fn a_changed_bake_input_rebakes_only_the_chosen_map() { - let (mut s, dir) = baked_session("rebake"); - // Off by default; nothing is due and the run command says what to do first. - assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], Value::Null); - assert!(execute(&mut s, "bake.autoRebake.run", &Value::Null).is_err()); - let r = execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert_eq!(r["map"], "height"); - assert!(due(&mut s).is_empty(), "turning it on takes the current bake as up to date"); - - // Which maps are ticked is not a bake input; a setting is. - execute(&mut s, "bake.settings", &json!({ "maps": ["height", "opacity", "ambient_occlusion"] })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2, "maps": ["height", "opacity"] })).unwrap(); - assert_eq!(due(&mut s), [0]); - - let (height, opacity) = (image(&s, BakedMap::Height), image(&s, BakedMap::Opacity)); - let r = execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - assert_eq!(r["rebaked"], json!([0])); - assert!(!Arc::ptr_eq(&height, &image(&s, BakedMap::Height)), "the Auto-rebake map was baked again"); - assert!(Arc::ptr_eq(&opacity, &image(&s, BakedMap::Opacity)), "the other maps were left alone"); - assert!(due(&mut s).is_empty(), "and the set is up to date"); - assert_eq!(execute(&mut s, "bake.autoRebake.run", &Value::Null).unwrap()["rebaked"], json!([])); - - // A manual bake of the map also counts; a changed high poly list is a change again. - execute(&mut s, "bake.settings", &json!({ "antialiasing": 2 })).unwrap(); - assert_eq!(due(&mut s), [0]); - s.begin_bake(0); - let out = s.bake_task_for(0, None).unwrap().run(&texturecraft_engine::bake::Progress::new()).unwrap(); - s.apply_bake(0, out).unwrap(); - assert!(due(&mut s).is_empty(), "a manual bake of the map marks it up to date"); - execute(&mut s, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); - assert_eq!(due(&mut s), [0]); - - // A different output size is left to a manual bake: the maps would end up at two sizes. - execute(&mut s, "bake.settings", &json!({ "resolution": 256 })).unwrap(); - assert!(due(&mut s).is_empty()); - - // Hostile input, and turning it off. - for bad in [json!({ "map": "nonsense" }), json!({ "map": 3 })] { - assert!(execute(&mut s, "bake.autoRebake", &bad).is_err(), "{bad}"); - } - assert_eq!(execute(&mut s, "bake.autoRebake", &json!({ "map": null })).unwrap()["map"], Value::Null); - assert!(due(&mut s).is_empty()); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_cancelled_or_failed_bake_is_not_queued_again_until_the_inputs_change() { - let (mut s, dir) = baked_session("cancel"); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2 })).unwrap(); - assert_eq!(due(&mut s), [0]); - - // What the app does: start the bake, cancel it, record the abandoned bake. - s.begin_bake(0); - let mut task = s.bake_task_for(0, Some(BakedMap::Height)).unwrap(); - task.tracer = None; - let progress = texturecraft_engine::bake::Progress::new(); - progress.cancel(); - assert!(task.run(&progress).is_err(), "a cancelled bake fails"); - s.bake_abandoned([0]); - assert!(due(&mut s).is_empty(), "not queued again on the next frame"); - - // The next change makes it due again; a bake that never started (queued behind a failed - // one) is recorded the same way. - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); - assert_eq!(due(&mut s), [0]); - s.bake_abandoned([0]); - assert!(due(&mut s).is_empty()); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_set_without_the_map_baked_is_left_alone() { - let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); - assert!(due(&mut s).is_empty(), "Auto-rebake keeps a bake up to date, it doesn't start one"); -} - -#[test] -fn undoing_a_rebake_brings_back_a_stale_map_and_it_is_due_again() { - let (mut s, dir) = baked_session("undo"); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2 })).unwrap(); - assert_eq!(due(&mut s), [0]); - execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - assert!(due(&mut s).is_empty()); - // Undo the bake: the older map is back, baked with the older settings, which no longer match. - let newer = image(&s, BakedMap::Height); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert!(!Arc::ptr_eq(&newer, &image(&s, BakedMap::Height)), "undo restored the older map"); - assert_eq!(due(&mut s), [0], "the restored map is out of date and rebakes"); - // Redo brings the newer map back, which does match. - execute(&mut s, "edit.redo", &Value::Null).unwrap(); - assert!(due(&mut s).is_empty(), "the newer map matches the current settings"); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn painting_or_clearing_the_skew_map_is_a_change() { - let (mut s, dir) = baked_session("skew"); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); - assert_eq!(due(&mut s), [0], "a skew map is a bake input"); - execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "size": 32 })).unwrap(); - assert_eq!(due(&mut s), [0], "so is a stroke painted into it"); - execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); - assert_eq!(due(&mut s), [0], "and so is taking it away"); - let _ = std::fs::remove_dir_all(dir); -} diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/bake.rs deleted file mode 100644 index 8f592937..00000000 --- a/crates/engine/tests/bake.rs +++ /dev/null @@ -1,457 +0,0 @@ -//! Bake commands: settings, high-definition meshes, cage, and project round trips. - -use serde_json::{Value, json}; -use texturecraft_engine::core::{BakeMatch, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; -use texturecraft_engine::geom::{Mesh, primitives}; -use texturecraft_engine::{Session, execute}; - -fn plane_session() -> Session { - let mesh = primitives::builtin("plane").unwrap(); - Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap() -} - -/// `mesh` as OBJ text, lifted by `dy`, keeping only vertices with x ≤ `max_x` (triangles that -/// lose a vertex are dropped), every vertex colored `rgb`. -fn obj(mesh: &Mesh, dy: f32, max_x: f32, rgb: [f32; 3]) -> String { - let mut s = String::from("o Part_high\n"); - for p in &mesh.positions { - s += &format!("v {} {} {} {} {} {}\n", p.x.min(max_x), p.y + dy, p.z, rgb[0], rgb[1], rgb[2]); - } - for t in mesh.indices.chunks_exact(3) { - s += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); - } - s -} - -fn temp_file(name: &str, text: &str) -> String { - let dir = std::env::temp_dir().join(format!("texturecraft-bake-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join(name); - std::fs::write(&path, text).unwrap(); - path.display().to_string() -} - -#[test] -fn high_poly_meshes_drive_the_bake_and_round_trip() { - let mut s = plane_session(); - let low = s.mesh.as_ref().clone(); - let (lo, hi) = low.bounds(); - let mid = (lo.x + hi.x) * 0.5; - // A red high poly over the left half of the plane, just above it. - let high = temp_file("hp_high.obj", &obj(&low, 0.002, mid, [1.0, 0.0, 0.0])); - let r = execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap(); - assert_eq!(r["name"], "hp_high.obj"); - assert!(s.doc.project.texture_sets.iter().all(|t| !t.bake.use_low_as_high), "adding a high poly bakes from it"); - let list = execute(&mut s, "bake.highPoly.list", &Value::Null).unwrap(); - assert_eq!(list["highPoly"][0]["parts"][0], "Part_high"); - assert!(execute(&mut s, "project.inspect", &Value::Null).unwrap()["bakeMeshes"]["highPoly"].as_array().is_some_and(|a| a.len() == 1)); - - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["opacity", "color_map"], "dilation": 0 })).unwrap(); - let baked = &s.doc.baked[&0]; - let opacity = &baked.maps[&BakedMap::Opacity]; - let covered = opacity.iter().filter(|v| **v > 0.99).count() as f32 / opacity.len() as f32; - assert!((covered - 0.5).abs() < 0.08, "the high poly covers half the plane: {covered}"); - let color = &baked.maps[&BakedMap::ColorMap]; - assert!(opacity.iter().zip(color.chunks(3)).filter(|(o, _)| **o > 0.99).all(|(_, c)| c == [1.0, 0.0, 0.0]), "red where covered"); - - // A cage must have the low poly's triangles. - let tri = temp_file("tri.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"); - assert!(execute(&mut s, "bake.cage.set", &json!({ "path": tri })).is_err()); - let cage = temp_file("cage.obj", &obj(&low, 0.05, f32::MAX, [1.0; 3])); - execute(&mut s, "bake.cage.set", &json!({ "path": cage })).unwrap(); - execute(&mut s, "bake.settings", &json!({ "matching": "byMeshName", "maxFrontal": 0.05 })).unwrap(); - - // Save and reopen: meshes, cage and settings come back. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - let names = |s: &Session| s.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect::>(); - assert_eq!(names(&back), names(&s)); - assert_eq!(back.bake_meshes.cage.as_ref().map(|c| c.name.as_str()), Some("cage.obj")); - assert_eq!(back.doc.project.texture_sets[0].bake, s.doc.project.texture_sets[0].bake); - assert_eq!(back.doc.project.texture_sets[0].bake.matching, BakeMatch::ByMeshName); - - execute(&mut s, "bake.highPoly.remove", &json!({ "name": "hp_high.obj" })).unwrap(); - assert!(s.bake_meshes.high.is_empty()); - execute(&mut s, "bake.cage.clear", &Value::Null).unwrap(); - assert!(s.bake_meshes.cage.is_none()); - // Without high polys the bake falls back to the low poly. - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"] })).unwrap(); - assert!(s.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|v| *v == 1.0)); - let _ = std::fs::remove_dir_all(std::path::Path::new(&high).parent().unwrap()); -} - -#[test] -fn malformed_high_poly_input_errors_cleanly() { - let mut s = plane_session(); - assert!(s.add_high_poly_bytes("bad.obj", b"this is not a mesh".to_vec()).is_err()); - assert!(s.add_high_poly_bytes("bad.glb", b"glTF\x02\0\0\0\xff\xff\xff\xff".to_vec()).is_err()); - assert!(s.add_high_poly_bytes("bad.xyz", vec![1, 2, 3]).is_err()); - assert!(s.set_cage_bytes("bad.stl", vec![0; 10]).is_err()); - assert!(execute(&mut s, "bake.highPoly.add", &json!({ "path": "/definitely/missing.obj" })).is_err()); - assert!(execute(&mut s, "bake.highPoly.remove", &json!({ "index": 3 })).is_err()); - assert!(execute(&mut s, "bake.highPoly.remove", &Value::Null).is_err()); - assert!(s.bake_meshes.high.is_empty() && s.bake_meshes.cage.is_none()); - assert!(s.doc.project.texture_sets.iter().all(|t| t.bake.use_low_as_high), "failed adds change nothing"); -} - -#[test] -fn bake_settings_apply_atomically() { - let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); - let r = - execute(&mut s, "bake.settings", &json!({ "ts": "all", "antialiasing": 4, "direction": [1, 0, 0], "maps": ["bent_normals", "World space direction"] })) - .unwrap(); - assert_eq!(r.as_array().map(Vec::len), Some(2)); - for t in &s.doc.project.texture_sets { - assert_eq!((t.bake.antialiasing, t.bake.direction), (4, [1.0, 0.0, 0.0])); - assert_eq!(t.bake.maps.iter().copied().collect::>(), [BakedMap::BentNormal, BakedMap::WorldDirection]); - } - let before = s.doc.project.texture_sets[0].bake.clone(); - for bad in [ - json!({ "rays": 4, "antialiasing": 3 }), - json!({ "maps": ["nope"] }), - json!({ "direction": [0, 0, 0] }), - json!({ "matching": "?" }), - json!({ "ts": [0, 9] }), - ] { - assert!(execute(&mut s, "bake.settings", &bad).is_err(), "{bad}"); - assert_eq!(s.doc.project.texture_sets[0].bake, before, "{bad} changed nothing"); - } - // "selected" = the sets checked for baking. - execute(&mut s, "bake.settings", &json!({ "ts": 1, "enabled": false })).unwrap(); - let r = execute(&mut s, "bake.settings", &json!({ "ts": "selected", "rays": 8 })).unwrap(); - assert_eq!(r[0]["ts"], 0); - assert_eq!(r.as_array().map(Vec::len), Some(1)); - // The returned parameters set the same settings again (what the UI sends back). - let mut copy = r[0]["settings"].clone(); - copy["ts"] = 1.into(); - execute(&mut s, "bake.settings", ©).unwrap(); - let (a, b) = (&s.doc.project.texture_sets[0].bake, &s.doc.project.texture_sets[1].bake); - assert_eq!(a, b); -} - -#[test] -fn per_map_ray_settings_round_trip() { - let mut s = plane_session(); - let p = json!({ - "ao": { "rays": 48, "maxDistance": 0.5, "spread": 90, "distribution": "uniform", "ignoreBackface": true, "selfOcclusion": "sameMeshName" }, - "thickness": { "rays": 12, "spread": 45 }, - "bentNormal": { "rays": 6, "maxDistance": 0.1 }, - "curvatureRadius": 3, - "positionMode": "boundingSphere", - "directionMode": "positive", - }); - let r = execute(&mut s, "bake.settings", &p).unwrap(); - let b = s.doc.project.texture_sets[0].bake.clone(); - assert_eq!(b.ao, RaySettings { rays: 48, max_distance: 0.5, spread: 90.0, distribution: RayDistribution::Uniform }); - assert!(b.ao_ignore_backface && b.ao_self_occlusion == SelfOcclusion::SameMeshName); - assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.1)); - assert_eq!((b.bent_normal.rays, b.bent_normal.max_distance, b.bent_normal.spread), (6, 0.1, 180.0)); - assert_eq!((b.curvature_radius, b.position_mode, b.direction_mode), (3, PositionMode::BoundingSphere, DirectionMode::Positive)); - assert_eq!(r[0]["settings"]["ao"]["selfOcclusion"], "sameMeshName"); - assert_eq!(r[0]["settings"]["thickness"]["distribution"], "cosine"); - // The project file keeps them. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.doc.project.texture_sets[0].bake, b); - // `rays` and `maxDistance` set every ray map; unknown names change nothing. - execute(&mut s, "bake.settings", &json!({ "rays": 16, "maxDistance": 0.2 })).unwrap(); - let b = s.doc.project.texture_sets[0].bake.clone(); - assert!([b.ao, b.thickness, b.bent_normal].iter().all(|r| r.rays == 16 && r.max_distance == 0.2)); - for bad in [ - json!({ "rays": 8, "ao": { "distribution": "gaussian" } }), - json!({ "ao": { "selfOcclusion": "never" } }), - json!({ "thickness": { "distribution": 3, "rays": 2 }, "positionMode": "uv" }), - json!({ "directionMode": "absolute" }), - ] { - assert!(execute(&mut s, "bake.settings", &bad).is_err(), "{bad}"); - assert_eq!(s.doc.project.texture_sets[0].bake, b, "{bad} changed nothing"); - } - // Forcing the CPU bakes there. - let r = execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["ambient_occlusion"], "cpu": true })).unwrap(); - assert_eq!(r["tracer"], json!(["CPU"])); -} - -/// A 4×4 PNG in quadrants: red, green / blue, mid grey (top row = v 0). -fn quadrants_png() -> Vec { - let quadrant = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [128, 128, 128, 255]]; - let img = image::RgbaImage::from_fn(4, 4, |x, y| image::Rgba(quadrant[(y / 2 * 2 + x / 2) as usize])); - let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - png -} - -/// The baked 128 px color map of set 0 shows [`quadrants_png`] on the plane. -fn assert_quadrants(s: &Session) { - let color = &s.doc.baked[&0].maps[&BakedMap::ColorMap]; - let at = |x: usize, y: usize| &color[(y * 128 + x) * 3..(y * 128 + x) * 3 + 3]; - let grey = 128.0 / 255.0; - for ((x, y), want) in [((32, 32), [1.0, 0.0, 0.0]), ((96, 32), [0.0, 1.0, 0.0]), ((32, 96), [0.0, 0.0, 1.0]), ((96, 96), [grey; 3])] { - assert!(at(x, y).iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "texel {x},{y}: {:?} vs {want:?}", at(x, y)); - } -} - -/// A GLB of `mesh` lifted by `dy`: one part `Part_high` whose material's base color is `png`. -fn textured_glb(mesh: &Mesh, dy: f32, png: &[u8]) -> Vec { - let mut bin = Vec::new(); - let mut view = |bytes: &[u8]| { - let offset = bin.len(); - bin.extend_from_slice(bytes); - bin.resize(bin.len().next_multiple_of(4), 0); - json!({ "buffer": 0, "byteOffset": offset, "byteLength": bytes.len() }) - }; - let floats = |v: Vec| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); - let views = [ - view(&floats(mesh.positions.iter().flat_map(|p| [p.x, p.y + dy, p.z]).collect())), - view(&floats(mesh.uvs.iter().flat_map(|uv| [uv.x, uv.y]).collect())), - view(&mesh.indices.iter().flat_map(|i| i.to_le_bytes()).collect::>()), - view(png), - ]; - let (lo, hi) = mesh.bounds(); - let doc = json!({ - "asset": { "version": "2.0" }, - "scene": 0, - "scenes": [{ "nodes": [0] }], - "nodes": [{ "name": "Part_high", "mesh": 0 }], - "meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "TEXCOORD_0": 1 }, "indices": 2, "material": 0 }] }], - "materials": [{ "name": "Painted", "pbrMetallicRoughness": { "baseColorTexture": { "index": 0 } } }], - "textures": [{ "source": 0 }], - "images": [{ "bufferView": 3, "mimeType": "image/png" }], - "buffers": [{ "byteLength": bin.len() }], - "bufferViews": views, - "accessors": [ - { "bufferView": 0, "componentType": 5126, "count": mesh.positions.len(), "type": "VEC3", "min": [lo.x, lo.y + dy, lo.z], "max": [hi.x, hi.y + dy, hi.z] }, - { "bufferView": 1, "componentType": 5126, "count": mesh.positions.len(), "type": "VEC2" }, - { "bufferView": 2, "componentType": 5125, "count": mesh.indices.len(), "type": "SCALAR" } - ] - }); - let mut text = serde_json::to_vec(&doc).unwrap(); - text.resize(text.len().next_multiple_of(4), b' '); - let mut glb = Vec::new(); - glb.extend_from_slice(b"glTF"); - glb.extend_from_slice(&2u32.to_le_bytes()); - glb.extend_from_slice(&((12 + 8 + text.len() + 8 + bin.len()) as u32).to_le_bytes()); - for (chunk, kind) in [(&text, b"JSON"), (&bin, b"BIN\0")] { - glb.extend_from_slice(&(chunk.len() as u32).to_le_bytes()); - glb.extend_from_slice(kind); - glb.extend_from_slice(chunk); - } - glb -} - -#[test] -fn color_map_samples_a_textured_gltf_high_poly() { - let mut s = plane_session(); - let low = s.mesh.as_ref().clone(); - let png = quadrants_png(); - s.add_high_poly_bytes("painted.glb", textured_glb(&low, 0.002, &png)).unwrap(); - assert!(s.log.iter().any(|l| l.contains("1 base color textures")), "{:?}", s.log); - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["color_map", "opacity"], "dilation": 0 })).unwrap(); - assert_quadrants(&s); - assert!(s.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|o| *o > 0.99), "the high poly covers the plane"); - // The textures come back with the project. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.high[0].base_color, s.bake_meshes.high[0].base_color); -} - -/// The color map reads a USDZ high poly's UsdPreviewSurface texture like a glTF one. -#[test] -fn color_map_samples_a_textured_usdz_high_poly() { - use texturecraft_engine::formats::{ExportedFile, UsdFormat, usd_bytes}; - let mut s = plane_session(); - let mut high = s.mesh.as_ref().clone(); - for p in &mut high.positions { - p.y += 0.002; - } - let png = quadrants_png(); - let texture = ExportedFile { name: "BaseColor.png".into(), bytes: png, width: 4, height: 4, warnings: vec![] }; - let usdz = usd_bytes(&high, "painted", &[vec![texture]], UsdFormat::Usdz).unwrap().bytes; - s.add_high_poly_bytes("painted.usdz", usdz).unwrap(); - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["color_map"], "dilation": 0 })).unwrap(); - assert_quadrants(&s); -} - -/// High polys whose textures are files next to them (a `.gltf` with its `.bin` and image, a loose -/// usda) are folded into one file on add, bake their color map, and come back with the project. -#[test] -fn color_map_samples_textures_next_to_a_high_poly() { - use texturecraft_engine::formats::{ExportedFile, UsdFormat, usd_bytes}; - let dir = std::env::temp_dir().join(format!("texturecraft-bake-external-{}", std::process::id())); - std::fs::create_dir_all(dir.join("tex")).unwrap(); - let low = plane_session().mesh.as_ref().clone(); - // The textured GLB taken apart: JSON, its .bin and the image as files. - let glb = textured_glb(&low, 0.002, &quadrants_png()); - let jlen = u32::from_le_bytes(glb[12..16].try_into().unwrap()) as usize; - let mut doc: Value = serde_json::from_slice(&glb[20..20 + jlen]).unwrap(); - doc["buffers"][0]["uri"] = "painted.bin".into(); - doc["images"] = json!([{ "uri": "tex/painted%20color.png" }]); - std::fs::write(dir.join("painted.bin"), &glb[20 + jlen + 8..]).unwrap(); - std::fs::write(dir.join("tex/painted color.png"), quadrants_png()).unwrap(); - std::fs::write(dir.join("painted.gltf"), serde_json::to_vec(&doc).unwrap()).unwrap(); - // The same high poly as a usda with its texture beside it. - let mut high = low.clone(); - for p in &mut high.positions { - p.y += 0.002; - } - let texture = ExportedFile { name: "BaseColor.png".into(), bytes: quadrants_png(), width: 4, height: 4, warnings: vec![] }; - let usda = usd_bytes(&high, "painted", &[vec![texture]], UsdFormat::Usda).unwrap(); - for (name, bytes) in &usda.textures { - std::fs::write(dir.join(name), bytes).unwrap(); - } - std::fs::write(dir.join("painted.usda"), &usda.bytes).unwrap(); - for (file, stored) in [("painted.gltf", "painted.gltf"), ("painted.usda", "painted.usdz")] { - let mut s = plane_session(); - let r = execute(&mut s, "bake.highPoly.add", &json!({ "path": dir.join(file).display().to_string() })).unwrap(); - assert_eq!(r["name"], stored); - assert!(s.log.iter().any(|l| l.contains("1 base color textures")), "{file}: {:?}", s.log); - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["color_map"], "dilation": 0 })).unwrap(); - assert_quadrants(&s); - // The project holds the folded file: the textures come back without the folder. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.high[0].base_color, s.bake_meshes.high[0].base_color, "{file}"); - } - // A missing image is named in the log; the high poly still loads, untextured. - std::fs::remove_file(dir.join("tex/painted color.png")).unwrap(); - let mut s = plane_session(); - execute(&mut s, "bake.highPoly.add", &json!({ "path": dir.join("painted.gltf").display().to_string() })).unwrap(); - assert!(s.log.iter().any(|l| l.contains("tex/painted color.png was not found")), "{:?}", s.log); - std::fs::remove_dir_all(&dir).unwrap(); -} - -/// A plane session whose vertex normals lean, with a high poly plane `dy` above it. -fn leaning_session(lean: bool) -> Session { - let mut mesh = primitives::builtin("plane").unwrap(); - if lean { - mesh.normals = vec![texturecraft_engine::geom::glam::Vec3::new(0.6, 0.8, 0.0); mesh.positions.len()]; - mesh.compute_tangents(); - } - let high_text = obj(&mesh, 0.1, f32::MAX, [1.0; 3]); - let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); - // A folder of its own per call: tests run in parallel, and another one removes the shared folder. - static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let call = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("texturecraft-lean-test-{}-{call}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let high = dir.join("high.obj"); - std::fs::write(&high, high_text).unwrap(); - execute(&mut s, "bake.highPoly.add", &json!({ "path": high.display().to_string() })).unwrap(); - // The mesh is parsed and kept on add, so the file can go. - let _ = std::fs::remove_dir_all(&dir); - execute( - &mut s, - "bake.settings", - &json!({ "resolution": 128, "dilation": 0, "maps": ["height"], "maxFrontal": 0.5, "maxRear": 0.2, "averageNormals": true }), - ) - .unwrap(); - s -} - -fn centre_height(s: &mut Session) -> f32 { - execute(s, "bake.run", &json!({ "cpu": true })).unwrap(); - s.doc.baked[&0].maps[&BakedMap::Height][64 * 128 + 64] -} - -#[test] -fn skew_correction_turns_the_transfer_rays_onto_the_base_normal() { - let flat = centre_height(&mut leaning_session(false)); - let mut s = leaning_session(true); - let leaning = centre_height(&mut s); - assert!((leaning - flat).abs() > 0.01, "leaning rays read a different height: {leaning} vs {flat}"); - - // Black changes nothing; white onto each triangle's flat normal matches the upright bake. - let r = execute(&mut s, "bake.skew.set", &json!({ "value": 0.0, "base": "triangle" })).unwrap(); - assert_eq!(r["skew"]["base"], "triangle"); - assert!((centre_height(&mut s) - leaning).abs() < 1e-6); - execute(&mut s, "bake.skew.set", &json!({ "value": 1.0, "base": "triangle", "edgeDistance": 0.1, "edgeContrast": 2.0 })).unwrap(); - assert_eq!(execute(&mut s, "bake.highPoly.list", &Value::Null).unwrap()["skew"]["edgeContrast"], 2.0); - assert!((centre_height(&mut s) - flat).abs() < 1e-3, "skew-corrected: {} vs upright {flat}", centre_height(&mut s)); - - // A greyscale image over the atlas: white everywhere is the same as value 1. - let dir = std::env::temp_dir().join(format!("texturecraft-skew-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let png = dir.join("skew.png"); - image::GrayImage::from_pixel(4, 4, image::Luma([255])).save(&png).unwrap(); - execute(&mut s, "bake.skew.set", &json!({ "path": png.display().to_string(), "base": "triangle" })).unwrap(); - assert_eq!(execute(&mut s, "bake.highPoly.list", &Value::Null).unwrap()["skew"]["width"], 4); - assert!((centre_height(&mut s) - flat).abs() < 1e-3); - - // Clearing restores the plain bake; hostile input is an error and leaves the state alone. - execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); - assert!((centre_height(&mut s) - leaning).abs() < 1e-6); - execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); - for bad in [ - json!({ "base": "sideways" }), - json!({ "edgeDistance": -1.0 }), - json!({ "edgeContrast": 0.0 }), - json!({ "path": dir.join("missing.png").display().to_string() }), - ] { - assert!(execute(&mut s, "bake.skew.set", &bad).is_err(), "{bad}"); - } - assert!(s.bake_meshes.skew.as_ref().is_some_and(|k| k.values == [0.5]), "a refused skew keeps the previous one"); - let _ = std::fs::remove_dir_all(&dir); -} - -#[test] -fn the_skew_map_is_saved_with_the_project() { - let mut s = leaning_session(false); - execute(&mut s, "bake.skew.set", &json!({ "value": 0.25, "edgeDistance": 0.1, "edgeContrast": 3.0, "base": "triangle" })).unwrap(); - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.skew, s.bake_meshes.skew); - // No skew: none comes back. - execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); - assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().bake_meshes.skew.is_none()); - // A map with a non-finite value is skipped with a log line, and the project still opens. - let mut pf = s.project_file(); - pf.skew = Some(texturecraft_formats::SkewData { width: 1, height: 1, values: vec![f32::NAN], edge_distance: 0.0, edge_contrast: 1.0, per_triangle: false }); - let opened = Session::from_project_file(pf).unwrap(); - assert!(opened.bake_meshes.skew.is_none() && opened.log.iter().any(|l| l.contains("skew")), "{:?}", opened.log); -} - -#[test] -fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() { - let mut s = leaning_session(true); - // Painting with no map makes a black one at `size` and puts the dab in it. - let r = execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 })).unwrap(); - assert_eq!(r["skew"]["width"], 64); - let map = s.bake_meshes.skew.clone().unwrap(); - assert!(map.values.iter().any(|v| *v > 0.99) && map.values.contains(&0.0)); - let rev = s.bake_meshes.skew_rev; - // Erasing with value 0 brings it back down; the size stays. - execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.2, "value": 0.0, "hardness": 1.0 })).unwrap(); - let after = s.bake_meshes.skew.clone().unwrap(); - assert_eq!(after.width, 64); - assert!(after.values.iter().all(|v| *v < 0.01) && s.bake_meshes.skew_rev > rev); - // A constant map is widened, keeping its value where nothing is painted. - execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); - execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.1, 0.1]], "radius": 0.05, "size": 32 })).unwrap(); - let wide = s.bake_meshes.skew.clone().unwrap(); - assert_eq!(wide.width, 32); - assert!((wide.values[wide.values.len() / 2] - 0.5).abs() < 1e-5, "{}", wide.values[wide.values.len() / 2]); - // Hostile input is an error and leaves the map alone. - let before = s.bake_meshes.skew.clone(); - for bad in [ - json!({}), - json!({ "points": [] }), - json!({ "points": [[0.5]] }), - json!({ "points": [["a", "b"]] }), - json!({ "points": [[0.5, 0.5]], "radius": 0.0 }), - json!({ "points": [[0.5, 0.5]], "radius": 5.0 }), - json!({ "points": [[0.5, 0.5]], "radius": -1.0 }), - json!({ "points": [[0.5, 0.5]], "size": 2 }), - json!({ "points": [[0.5, 0.5]], "size": 100000 }), - json!({ "points": [[0.0, 0.0], [1e9, 1e9]], "radius": 1e-4 }), - ] { - assert!(execute(&mut s, "bake.skew.paint", &bad).is_err(), "{bad}"); - } - assert_eq!(s.bake_meshes.skew, before); - // And the painted map is saved with the project. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.skew, s.bake_meshes.skew); -} - -#[test] -fn a_stroke_paints_the_skew_map_in_place() { - let mut s = plane_session(); - let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 }); - execute(&mut s, "bake.skew.paint", &stroke).unwrap(); - let first = s.bake_meshes.skew.as_ref().map(std::sync::Arc::as_ptr); - execute(&mut s, "bake.skew.paint", &stroke).unwrap(); - assert_eq!(s.bake_meshes.skew.as_ref().map(std::sync::Arc::as_ptr), first, "a stroke step doesn't copy the whole map"); -} diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs new file mode 100644 index 00000000..e8eb477b --- /dev/null +++ b/crates/engine/tests/bake_preview.rs @@ -0,0 +1,428 @@ +//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back, +//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it +//! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the +//! document share each map's buffer instead of holding two copies. + +use serde_json::{Value, json}; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeResolution, BakedMap, Channel}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::{BakeTask, PreviewShow, Session, ViewMode, execute}; + +const MAPS: [BakedMap; 4] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Height]; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.ao.parameters.rays.rays = 8; + texture_set.bake.maps.select(MAPS); + } + + session +} + +fn task(session: &Session) -> BakeTask { + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + task +} + +fn order(session: &Session) -> Vec { + task(session).maps() +} + +#[test] +fn streamed_maps_are_the_pixels_of_one_bake() { + let session = session(); + let task = task(&session); + let whole = task.run(&Progress::new()).unwrap(); + let mut streamed = Vec::new(); + + let combined = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap(); + + assert_eq!(streamed.iter().map(|map| map.map).collect::>(), order(&session)); + assert_eq!(streamed.iter().map(|map| (map.index, map.total)).collect::>(), (0..MAPS.len()).map(|index| (index, MAPS.len())).collect::>()); + assert_eq!((combined.resolution, combined.height), (whole.resolution, whole.height)); + assert_eq!(combined.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in &whole.maps { + assert!(*combined.maps[map] == *pixels, "{map:?} differs between a streamed and a single bake"); + } + for map in &streamed { + assert!(*map.data == whole.maps[&map.map], "{:?} handed over differs from the bake", map.map); + } +} + +#[test] +fn the_view_follows_each_map_and_the_previous_mode_comes_back() { + let mut session = session(); + session.view = ViewMode::Channel(Channel::Roughness); + let before = session.view; + let baked_before = session.doc.baked.get(&0).cloned(); + let maps = order(&session); + + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + + // Nothing is baked yet: the first map shows, neutral + assert_eq!(session.view, ViewMode::MeshMap(maps[0])); + assert!(session.bake_preview_baked(0).is_some_and(|baked| baked.maps.is_empty())); + + let task = task(&session); + let mut shown = Vec::new(); + let mut stages = Vec::new(); + let output = task + .run_streaming(&Progress::new(), &mut |map| { + session.bake_preview_map(0, map); + shown.push(session.view); + stages.push(session.bake_preview.as_ref().and_then(|preview| preview.stage()).map(|stage| (stage.position, stage.total))); + }) + .unwrap(); + + assert_eq!(shown, maps.iter().map(|map| ViewMode::MeshMap(*map)).collect::>(), "the view follows the newest map"); + assert_eq!(stages, [Some((2, 4)), Some((3, 4)), Some((4, 4)), None], "the stage names the next map"); + assert_eq!(session.doc.baked.get(&0).cloned(), baked_before, "the document is untouched until the bake is applied"); + let undo_before = session.undo_label().map(str::to_owned); + + session.apply_streamed_bake(0, output).unwrap(); + assert_ne!(session.undo_label().map(str::to_owned), undo_before, "applying the bake is one undo step"); + session.bake_preview_end(); + + assert_eq!(session.view, before, "the previous view mode is restored"); + assert!(!session.bake_preview_active()); + assert!(maps.iter().all(|map| session.doc.baked[&0].maps.contains_key(map))); +} + +#[test] +fn pinning_material_and_follow() { + let mut session = session(); + let maps = order(&session); + + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + let task = task(&session); + let mut count = 0; + + task.run_streaming(&Progress::new(), &mut |map| { + session.bake_preview_map(0, map); + count += 1; + match count { + // Pin the finished map: later maps do not take the view + 1 => session.bake_preview_show(PreviewShow::Pin(maps[0])).unwrap(), + 2 => { + assert_eq!(session.view, ViewMode::MeshMap(maps[0])); + session.bake_preview_show(PreviewShow::Material).unwrap(); + } + 3 => { + assert_eq!(session.view, ViewMode::Material); + session.bake_preview_show(PreviewShow::Follow).unwrap(); + assert_eq!(session.view, ViewMode::MeshMap(maps[2])); + } + _ => {} + } + }) + .unwrap(); + + // A mesh map picked in the viewport pins it; another mode is what comes back at the end + execute(&mut session, "viewport.view", &json!({ "mode": "map:height" })).unwrap(); + assert_eq!(session.bake_preview.as_ref().map(|preview| preview.show), Some(PreviewShow::Pin(BakedMap::Height))); + execute(&mut session, "viewport.view", &json!({ "mode": "uvChecker" })).unwrap(); + assert_eq!(session.view, ViewMode::UvChecker); + session.bake_preview_end(); + + assert_eq!(session.view, ViewMode::UvChecker); +} + +#[test] +fn unbaked_sets_show_neutral_and_the_control_command_reports() { + let mut session = session(); + assert_eq!(execute(&mut session, "bake.preview", &Value::Null).unwrap()["active"], false); + assert!(execute(&mut session, "bake.preview", &json!({ "show": "material" })).is_err(), "nothing to show when no bake runs"); + + session.bake_preview_begin(vec![(0, order(&session)), (1, order(&session))]); + session.bake_preview_set_current(0); + + assert!(session.bake_preview_baked(1).is_some_and(|baked| baked.maps.is_empty()), "a queued set has nothing yet"); + assert!(session.bake_preview_baked(7).is_none(), "a set outside the bake shows its document maps"); + let reply = execute(&mut session, "bake.preview", &json!({ "show": "map:ambientOcclusion" })).unwrap(); + + assert_eq!( + (reply["active"].clone(), reply["show"].clone(), reply["shown"].clone()), + (json!(true), json!("map:ambientOcclusion"), json!("ambientOcclusion")) + ); + assert!(execute(&mut session, "bake.preview", &json!({ "show": "nonsense" })).is_err()); + assert_eq!(texturecraft_engine::inspect::session(&session)["bakePreview"]["active"], true); +} + +#[test] +fn painting_is_refused_while_a_bake_shows() { + let mut session = session(); + session.bake_preview_begin(vec![(0, order(&session))]); + + let error = session.begin_stroke(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0), 1.0).unwrap_err().to_string(); + + assert_eq!(error, texturecraft_engine::bake_preview::PAINTING_PAUSED); + assert!(session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).is_err()); + assert!(session.polygon_fill(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0)).is_err()); + assert!(!session.stroke_active()); + session.bake_preview_end(); + assert!(session.painting_blocked().is_none()); +} + +#[test] +fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { + let mut session = session(); + let before = session.doc.baked.get(&0).cloned(); + let maps = order(&session); + let full = task(&session).run(&Progress::new()).unwrap(); + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + let progress = Progress::new(); + let task = task(&session); + + let result = task.run_streaming(&progress, &mut |map| { + if map.index == 1 { + progress.cancel(); + } + session.bake_preview_map(0, map); + }); + + assert!(result.is_err(), "a cancelled bake fails"); + + // The two maps that landed are whole and equal to a full bake's; the others are still neutral + let shown = session.bake_preview_baked(0).unwrap(); + assert_eq!(shown.maps.len(), 2); + for (map, data) in &shown.maps { + assert!(**data == full.maps[map], "{map:?}"); + } + + // What the app does on cancel: end the preview; the document keeps what it had + session.bake_preview_end(); + + assert_eq!(session.doc.baked.get(&0).cloned(), before); + assert!(session.bake_preview_baked(0).is_none()); +} + +#[test] +fn the_preview_and_the_applied_document_share_each_map_buffer() { + let mut session = session(); + let maps = order(&session); + + session.bake_preview_begin(vec![(0, maps)]); + session.bake_preview_set_current(0); + let mut handed_over = Vec::new(); + + let output = task(&session) + .run_streaming(&Progress::new(), &mut |map| { + handed_over.push((map.map, map.data.clone())); + session.bake_preview_map(0, map); + }) + .unwrap(); + + // Sharing the streamed buffers keeps preview memory independent of document ownership + for (map, data) in &handed_over { + assert!(std::sync::Arc::ptr_eq(data, &output.maps[map]), "{map:?} was copied on the way out of the bake"); + let shown = &session.bake_preview_baked(0).unwrap().maps[map]; + assert!(std::sync::Arc::ptr_eq(data, shown), "{map:?} is held twice by the preview"); + } + + // Applying the result must preserve sharing with the preview + session.apply_streamed_bake(0, output).unwrap(); + for (map, data) in &handed_over { + assert!(std::sync::Arc::ptr_eq(data, &session.doc.baked[&0].maps[map]), "{map:?} was copied into the document"); + } + session.bake_preview_end(); +} + +#[test] +fn cancelling_keeps_a_set_that_was_already_applied_as_one_undo_step() { + let mut session = session(); + let before = session.doc.baked.get(&0).cloned(); + let maps = order(&session); + + // A multi-set bake applies each set when it finishes; a later cancel does not undo it + session.bake_preview_begin(vec![(0, maps)]); + session.bake_preview_set_current(0); + let output = task(&session) + .run_streaming(&Progress::new(), &mut |map| { + session.bake_preview_map(0, map); + }) + .unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + session.bake_preview_end(); + + assert!(MAPS.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)), "the finished set stays baked after the cancel"); + session.undo().unwrap(); + assert_eq!(session.doc.baked.get(&0).cloned(), before, "applying the set was one undo step"); +} + +#[test] +fn a_resized_partial_streamed_bake_keeps_unchecked_maps() { + use std::sync::Arc; + use texturecraft_engine::compose::BakedMaps; + use texturecraft_engine::geom::primitives; + + let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + 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])), + (BakedMap::Height, Arc::new(vec![0.75; 64 * 32])), + ] + .into(), + }, + ); + execute(&mut session, "bake.settings", &json!({"resolution": 64, "maps": ["ambientOcclusion", "height"], "rays": 2})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let before = session.doc.baked.clone(); + let task = task(&session); + let whole = task.run(&Progress::new()).unwrap(); + let mut streamed = Vec::new(); + + let output = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap(); + + assert_eq!((output.resolution, output.height), (128, 64)); + assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in &whole.maps { + assert_eq!(*output.maps[map], *pixels, "{map:?} must match a whole bake, including retained pixels"); + } + assert_eq!(streamed.iter().map(|map| map.map).collect::>(), [BakedMap::AmbientOcclusion, BakedMap::Height]); + for map in &streamed { + assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map])); + } + + session.apply_streamed_bake(0, output).unwrap(); + + for (map, pixels) in &whole.maps { + assert_eq!(*session.doc.baked[&0].maps[map], *pixels); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked, before); +} + +#[test] +fn box_fills_are_refused_while_a_bake_shows() { + let mut session = session(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.polygonFill", &Value::Null).unwrap(); + session.bake_preview_begin(vec![(0, order(&session))]); + let before = texturecraft_engine::inspect::session(&session); + let viewport = Vec2::new(100.0, 100.0); + + for result in [ + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE), + session.drag_polygon_fill_box(Vec2::ZERO, viewport, viewport), + session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE), + session.polygon_fill_box(Vec2::ZERO, viewport, viewport), + execute(&mut session, "tool.click", &json!({"uv0": [0, 0], "uv1": [1, 1]})).map(|_| 0), + execute(&mut session, "tool.click", &json!({"x0": 0, "y0": 0, "x1": 100, "y1": 100})).map(|_| 0), + ] { + assert_eq!(result.unwrap_err().to_string(), texturecraft_engine::bake_preview::PAINTING_PAUSED); + } + + assert_eq!(session.end_polygon_fill_box(), 0); + assert_eq!(texturecraft_engine::inspect::session(&session), before); + session.bake_preview_end(); + assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0); +} + +#[test] +fn preview_order_matches_each_sets_bake_task() { + let mut session = session(); + session.doc.project.texture_sets[1].bake.maps.select([BakedMap::WorldNormal, BakedMap::Height]); + let expected: Vec<_> = [0, 1].into_iter().map(|texture_set| session.bake_task(texture_set).unwrap().maps()).collect(); + + session.bake_preview_begin_for(&[0, 1]).unwrap(); + + let preview = session.bake_preview.as_ref().unwrap(); + for (texture_set, maps) in expected.iter().enumerate() { + assert_eq!(&preview.sets[&texture_set].order, maps); + assert!(preview.sets[&texture_set].baked.maps.is_empty()); + } + assert_eq!(session.view, ViewMode::MeshMap(expected[0][0])); +} + +#[test] +fn invalid_preview_sets_preserve_the_existing_preview_and_view() { + let mut session = session(); + session.bake_preview_begin_for(&[0]).unwrap(); + session.bake_preview_set_current(0); + session.bake_preview_show(PreviewShow::Material).unwrap(); + let before = texturecraft_engine::bake_preview::preview_json(&session); + let view = session.view; + let revision = session.revision; + let invalid_set = session.set_count(); + let expected_error = session.doc.project.texture_set(invalid_set).unwrap_err().to_string(); + + let error = session.bake_preview_begin_for(&[1, invalid_set]).unwrap_err(); + + assert!(error.to_string().contains(&expected_error)); + assert_eq!(texturecraft_engine::bake_preview::preview_json(&session), before); + assert_eq!(session.view, view); + assert_eq!(session.revision, revision); +} + +#[test] +fn starting_a_bake_preview_discards_an_active_stroke() { + for (from_settings, paint_mask) in [(false, false), (true, false), (false, true), (true, true)] { + let mut session = session(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + if paint_mask { + session.target = texturecraft_engine::StackTarget::Mask; + } + + let before = session.doc.clone(); + let history = session.history_labels(); + let view = session.view; + session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + assert!(session.stroke_tiles() > 0, "the stroke must contain paint before the preview starts"); + + if from_settings { + session.bake_preview_begin_for(&[0]).unwrap(); + } else { + session.bake_preview_begin(vec![(0, order(&session))]); + } + let stroke_survived = session.stroke_active(); + session.continue_stroke_uv(Vec2::splat(0.6), 1.0); + session.end_stroke().unwrap(); + + assert_eq!(session.history_labels(), history, "releasing the pointer during a preview must not commit paint"); + assert!(!stroke_survived, "activation must cancel the stroke immediately"); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.doc.pixels.masks, before.pixels.masks); + assert!(session.bake_preview_active()); + session.bake_preview_end(); + + assert_eq!(session.view, view); + session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + session.end_stroke().unwrap(); + assert_eq!(session.history_labels().len(), history.len() + 1, "painting resumes after the preview ends"); + } +} + +#[test] +fn a_rejected_bake_preview_preserves_the_active_stroke() { + let mut session = session(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + let history_steps = session.history_labels().len(); + let view = session.view; + session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + let painted_tiles = session.stroke_tiles(); + assert!(painted_tiles > 0); + + let result = session.bake_preview_begin_for(&[0, session.set_count()]); + + assert!(result.is_err()); + assert!(!session.bake_preview_active()); + assert!(session.stroke_active()); + assert_eq!(session.stroke_tiles(), painted_tiles); + assert_eq!(session.view, view); + session.end_stroke().unwrap(); + + assert_eq!(session.history_labels().len(), history_steps + 1, "a rejected preview must not discard painting"); +} diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs new file mode 100644 index 00000000..acf54274 --- /dev/null +++ b/crates/engine/tests/it/bake.rs @@ -0,0 +1,677 @@ +//! Bake commands, mesh assets and project persistence + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BackfaceMode, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; +use texturecraft_engine::geom::{Mesh, primitives}; +use texturecraft_engine::{Session, execute}; + +fn plane_session() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap() +} + +/// `mesh` as OBJ text, shifted by `offset_y`, with x clamped to `max_x` and every vertex colored `rgb`. +fn obj(mesh: &Mesh, offset_y: f32, max_x: f32, rgb: [f32; 3]) -> String { + let mut text = String::from("o Part_high\n"); + for position in &mesh.positions { + text += &format!("v {} {} {} {} {} {}\n", position.x.min(max_x), position.y + offset_y, position.z, rgb[0], rgb[1], rgb[2]); + } + + for triangle in mesh.indices.as_chunks::<3>().0 { + text += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1); + } + + text +} + +fn temp_file(name: &str, text: &str) -> String { + let dir = std::env::temp_dir().join(format!("texturecraft-bake-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + path.display().to_string() +} + +#[test] +fn high_poly_meshes_drive_the_bake_and_round_trip() { + let mut session = plane_session(); + execute(&mut session, "bake.settings", &json!({ "ts": "all", "useLowAsHigh": true })).unwrap(); + + let low = session.mesh.as_ref().clone(); + let (lo, hi) = low.bounds(); + let midpoint_x = (lo.x + hi.x) * 0.5; + + // A red high poly over the left half of the plane, just above it + let high = temp_file("hp_high.obj", &obj(&low, 0.002, midpoint_x, [1.0, 0.0, 0.0])); + let result = execute(&mut session, "bake.highPoly.add", &json!({ "path": high })).unwrap(); + assert_eq!(result["name"], "hp_high.obj"); + assert!(session.doc.project.texture_sets.iter().all(|texture_set| !texture_set.bake.high_poly.use_low_as_high), "adding a high poly bakes from it"); + let list = execute(&mut session, "bake.highPoly.list", &Value::Null).unwrap(); + assert_eq!(list["highPoly"][0]["parts"][0], "Part_high"); + assert!(execute(&mut session, "project.inspect", &Value::Null).unwrap()["bakeMeshes"]["highPoly"].as_array().is_some_and(|a| a.len() == 1)); + + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + let baked = &session.doc.baked[&0]; + let opacity = &baked.maps[&BakedMap::Opacity]; + let covered = opacity.iter().filter(|v| **v > 0.99).count() as f32 / opacity.len() as f32; + assert!((covered - 0.5).abs() < 0.08, "the high poly covers half the plane: {covered}"); + + // A cage must have the low poly's triangles + let invalid_cage = temp_file("tri.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"); + assert!(execute(&mut session, "bake.cage.set", &json!({ "path": invalid_cage })).is_err()); + let cage = temp_file("cage.obj", &obj(&low, 0.05, f32::MAX, [1.0; 3])); + execute(&mut session, "bake.cage.set", &json!({ "path": cage })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "maxFrontal": 0.05 })).unwrap(); + + // Save and reopen: meshes, cage and settings come back + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + let names = |session: &Session| session.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect::>(); + assert_eq!(names(&reloaded), names(&session)); + assert_eq!(reloaded.bake_meshes.cage.as_ref().map(|c| c.name.as_str()), Some("cage.obj")); + assert_eq!(reloaded.doc.project.texture_sets[0].bake, session.doc.project.texture_sets[0].bake); + + execute(&mut session, "bake.highPoly.remove", &json!({ "name": "hp_high.obj" })).unwrap(); + assert!(session.bake_meshes.high.is_empty()); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + assert!(session.bake_meshes.cage.is_none()); + + // Without high polys the bake falls back to the low poly + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"] })).unwrap(); + assert!(session.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|v| *v == 1.0)); + let _ = std::fs::remove_dir_all(std::path::Path::new(&high).parent().unwrap()); +} + +#[test] +fn malformed_high_poly_input_errors_cleanly() { + let mut session = plane_session(); + execute(&mut session, "bake.settings", &json!({ "ts": "all", "useLowAsHigh": true })).unwrap(); + let before = session.doc.project.clone(); + + assert!(session.add_high_poly_bytes("bad.obj", b"this is not a mesh".to_vec()).is_err()); + assert!(session.add_high_poly_bytes("bad.glb", b"glTF\x02\0\0\0\xff\xff\xff\xff".to_vec()).is_err()); + assert!(session.add_high_poly_bytes("bad.xyz", vec![1, 2, 3]).is_err()); + assert!(session.set_cage_bytes("bad.stl", vec![0; 10]).is_err()); + assert!(execute(&mut session, "bake.highPoly.add", &json!({ "path": "/definitely/missing.obj" })).is_err()); + assert!(execute(&mut session, "bake.highPoly.remove", &json!({ "index": 3 })).is_err()); + assert!(execute(&mut session, "bake.highPoly.remove", &Value::Null).is_err()); + assert!(session.bake_meshes.high.is_empty() && session.bake_meshes.cage.is_none()); + assert_eq!(session.doc.project, before, "failed imports preserve project settings"); +} + +#[test] +fn bake_settings_apply_atomically() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let result = execute(&mut session, "bake.settings", &json!({ "ts": "all", "antialiasing": 4, "maps": ["bentNormal", "opacity"] })).unwrap(); + assert_eq!(result.as_array().map(Vec::len), Some(2)); + + for texture_set in &session.doc.project.texture_sets { + assert_eq!(texture_set.bake.common.antialiasing, texturecraft_core::BakeAntialiasing::Subsampling4x4); + assert_eq!(texture_set.bake.maps.enabled().collect::>(), [BakedMap::BentNormal, BakedMap::Opacity]); + } + + let before = session.doc.project.clone(); + + for bad in [ + json!({ "rays": 4, "antialiasing": 3 }), + json!({ "maps": ["nope"] }), + json!({ "ts": "all", "dilation": 8, "maps": ["color_map"] }), + json!({ "ts": "all", "dilation": 8, "maps": ["world_space_direction"] }), + json!({ "ts": [0, 9] }), + ] { + assert!(execute(&mut session, "bake.settings", &bad).is_err(), "{bad}"); + assert_eq!(session.doc.project, before, "{bad} changed nothing"); + } + + // "selected" = the sets checked for baking + execute(&mut session, "bake.settings", &json!({ "ts": 1, "enabled": false })).unwrap(); + let result = execute(&mut session, "bake.settings", &json!({ "ts": "selected", "rays": 8 })).unwrap(); + assert_eq!(result[0]["ts"], 0); + assert_eq!(result.as_array().map(Vec::len), Some(1)); + + // The returned parameters set the same settings again (what the UI sends back) + let mut copy = result[0]["settings"].clone(); + copy["ts"] = 1.into(); + execute(&mut session, "bake.settings", ©).unwrap(); + let first = &session.doc.project.texture_sets[0].bake; + let second = &session.doc.project.texture_sets[1].bake; + assert_eq!(first, second); +} + +#[test] +fn current_ui_parameters_preserve_nested_model_settings() { + let mut session = plane_session(); + let settings = &mut session.doc.project.texture_sets[0].bake; + settings.common.resolution_height = Some(texturecraft_core::BakeResolution::R1024); + settings.common.apply_diffusion = false; + settings.high_poly.ignore_backface_suffix = "_open".into(); + settings.cage.relative_to_bounding_box = false; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.maps.ao.parameters.ground_plane.offset = 3.0; + settings.maps.ao.parameters.rays.min_distance = 0.02; + settings.maps.curvature.parameters.mesh.sampling_radius = 0.25; + settings.maps.curvature.parameters.normal_map.details = 0.75; + settings.maps.height.parameters.scaling_divisor = 2.0; + + for (name, method) in [("normalMap", CurvatureMethod::NormalMap), ("mesh", CurvatureMethod::Mesh)] { + let result = execute(&mut session, "bake.settings", &json!({"curvatureMethod": name})).unwrap(); + let expected = session.doc.project.texture_sets[0].bake.clone(); + assert_eq!(expected.maps.curvature.parameters.method, method); + assert_eq!(result[0]["settings"]["curvatureMethod"], name); + + execute(&mut session, "bake.settings", &result[0]["settings"]).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].bake, expected); + + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.project.texture_sets[0].bake, expected); + } + + let expected = session.doc.project.clone(); + for method in [json!(true), json!(1), json!("invalid")] { + assert!(execute(&mut session, "bake.settings", &json!({"dilation": 8, "curvatureMethod": method})).is_err()); + assert_eq!(session.doc.project, expected); + } +} + +#[test] +fn complete_model_edits_round_trip_and_preserve_texture_set_selection() { + use texturecraft_core::{BakeResolution, HeightNormalization, IdColorGenerator, IdColorSource}; + + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + execute(&mut session, "bake.settings", &json!({"ts": 1, "enabled": false})).unwrap(); + let mut model = session.doc.project.texture_sets[0].bake.clone(); + model.common.resolution_height = Some(BakeResolution::R512); + model.common.apply_diffusion = false; + model.maps.id.parameters.source = IdColorSource::MeshId; + model.maps.id.parameters.generator = IdColorGenerator::Grayscale; + model.maps.ao.parameters.ground_plane.enabled = true; + model.maps.ao.parameters.ground_plane.offset = 3.25; + model.maps.height.is_enabled = true; + model.maps.height.parameters.normalization = HeightNormalization::Manual; + model.maps.height.parameters.scaling_divisor = 2.125; + + let result = execute(&mut session, "bake.settings", &json!({"ts": "all", "model": model, "preserveEnabled": true})).unwrap(); + assert_eq!(result[0]["model"], json!(model)); + assert!(session.modified); + assert_eq!(session.doc.project.texture_sets[0].bake, model); + model.common.is_enabled = false; + assert_eq!(session.doc.project.texture_sets[1].bake, model); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets, session.doc.project.texture_sets); +} + +#[test] +fn invalid_model_edits_leave_all_texture_sets_unchanged() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let before = session.doc.project.clone(); + let model = json!(before.texture_sets[0].bake); + for (path, invalid_value) in [ + ("/common/dilation", json!(129)), + ("/common/antialiasing", json!(true)), + ("/cage/max_frontal", json!(0.06)), + ("/skew/edge_distance", json!(-0.1)), + ("/maps/ao/parameters/rays/rays", json!(257)), + ("/maps/ao/parameters/rays/min_distance", json!(0)), + ("/maps/ao/parameters/rays/max_distance", json!(1.5)), + ("/maps/curvature/parameters/mesh/sampling_radius", json!(11)), + ("/maps/curvature/parameters/mesh/value_max", json!(11)), + ("/maps/height/parameters/normalization", json!(1)), + ("/maps/height/parameters/scaling_divisor", json!(0)), + ] { + let mut invalid = model.clone(); + *invalid.pointer_mut(path).unwrap() = invalid_value; + assert!(execute(&mut session, "bake.settings", &json!({"ts": "all", "model": invalid})).is_err(), "{path}"); + assert_eq!(session.doc.project, before, "{path}"); + } +} + +#[test] +fn per_map_ray_settings_round_trip() { + let mut session = plane_session(); + let params = json!({ + "ao": { "rays": 48, "maxDistance": 0.5, "spread": 90, "distribution": "uniform", "ignoreBackface": "always", "selfOcclusion": "sameMeshName" }, + "thickness": { "rays": 12, "spread": 45 }, + "bentNormal": { "rays": 6, "maxDistance": 0.1 }, + "positionMode": "boundingSphere", + }); + let result = execute(&mut session, "bake.settings", ¶ms).unwrap(); + let settings = session.doc.project.texture_sets[0].bake.clone(); + assert_eq!( + settings.maps.ao.parameters.rays, + RaySettings { rays: 48, max_distance: 0.5, spread: 90.0, distribution: RayDistribution::Uniform, ..RaySettings::default() } + ); + assert_eq!(settings.maps.ao.parameters.ignore_backface, BackfaceMode::Always); + assert_eq!(settings.maps.ao.parameters.self_occlusion, SelfOcclusion::SameMeshName); + assert_eq!( + (settings.maps.thickness.parameters.rays.rays, settings.maps.thickness.parameters.rays.spread, settings.maps.thickness.parameters.rays.max_distance), + (12, 45.0, 0.1) + ); + assert_eq!( + ( + settings.maps.bent_normal.parameters.rays.rays, + settings.maps.bent_normal.parameters.rays.max_distance, + settings.maps.bent_normal.parameters.rays.spread + ), + (6, 0.1, 180.0) + ); + assert_eq!(settings.maps.position.parameters.normalization, PositionMode::BoundingSphere); + assert_eq!(result[0]["settings"]["ao"]["selfOcclusion"], "sameMeshName"); + assert_eq!(result[0]["settings"]["thickness"]["distribution"], "cosine"); + + // The project file keeps them + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.project.texture_sets[0].bake, settings); + + // `rays` and `maxDistance` set every ray map; unknown names change nothing + execute(&mut session, "bake.settings", &json!({ "rays": 16, "maxDistance": 0.2 })).unwrap(); + let settings = session.doc.project.texture_sets[0].bake.clone(); + assert!( + [settings.maps.ao.parameters.rays, settings.maps.thickness.parameters.rays, settings.maps.bent_normal.parameters.rays] + .iter() + .all(|rays| rays.rays == 16 && rays.max_distance == 0.2) + ); + for bad in [ + json!({ "rays": 8, "ao": { "distribution": "gaussian" } }), + json!({ "ao": { "selfOcclusion": "never" } }), + json!({ "thickness": { "distribution": 3, "rays": 2 }, "positionMode": "uv" }), + ] { + assert!(execute(&mut session, "bake.settings", &bad).is_err(), "{bad}"); + assert_eq!(session.doc.project.texture_sets[0].bake, settings, "{bad} changed nothing"); + } + + // Forcing the CPU bakes there + let result = execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["ambientOcclusion"], "cpu": true })).unwrap(); + assert_eq!(result["tracer"], json!(["CPU"])); + + for (mode, expected) in [("never", BackfaceMode::Never), ("always", BackfaceMode::Always), ("byMeshName", BackfaceMode::ByMeshName)] { + let result = execute(&mut session, "bake.settings", &json!({"ao": {"ignoreBackface": mode}, "positionMode": "none"})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.ignore_backface, expected); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.position.parameters.normalization, PositionMode::None); + + let params = &result[0]["settings"]; + assert_eq!(params["ao"]["ignoreBackface"], mode); + assert_eq!(params["positionMode"], "none"); + execute(&mut session, "bake.settings", params).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.ignore_backface, expected); + } + + let before = session.doc.project.clone(); + for invalid in [json!({"ao": {"ignoreBackface": true}}), json!({"ao": {"ignoreBackface": "invalid"}})] { + assert!(execute(&mut session, "bake.settings", &invalid).is_err()); + assert_eq!(session.doc.project, before); + } +} + +/// A 4×4 PNG with quadrant alpha values 255, 128, 64 and 32 +fn quadrants_png() -> Vec { + let quadrants = [[255, 0, 0, 255], [0, 255, 0, 128], [0, 0, 255, 64], [128, 128, 128, 32]]; + let image = image::RgbaImage::from_fn(4, 4, |x, y| image::Rgba(quadrants[(y / 2 * 2 + x / 2) as usize])); + let mut png = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + png +} + +/// Check the alpha at the center of each baked quadrant +fn assert_opacity_quadrants(session: &Session) { + let opacity = &session.doc.baked[&0].maps[&BakedMap::Opacity]; + for ((x, y), alpha) in [((32, 32), 255.0), ((96, 32), 128.0), ((32, 96), 64.0), ((96, 96), 32.0)] { + let actual = opacity[y * 128 + x]; + assert!((actual - alpha / 255.0).abs() < 2e-3, "texel {x},{y}: {actual} vs {alpha}/255"); + } +} + +/// A GLB of `mesh` lifted by `dy`: one part `Part_high` whose material's base color is `png`. +fn textured_glb(mesh: &Mesh, dy: f32, png: &[u8]) -> Vec { + let mut bin = Vec::new(); + let mut view = |bytes: &[u8]| { + let offset = bin.len(); + bin.extend_from_slice(bytes); + bin.resize(bin.len().next_multiple_of(4), 0); + json!({ "buffer": 0, "byteOffset": offset, "byteLength": bytes.len() }) + }; + let floats = |v: Vec| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); + let views = [ + view(&floats(mesh.positions.iter().flat_map(|p| [p.x, p.y + dy, p.z]).collect())), + view(&floats(mesh.uvs.iter().flat_map(|uv| [uv.x, uv.y]).collect())), + view(&mesh.indices.iter().flat_map(|i| i.to_le_bytes()).collect::>()), + view(png), + ]; + let (lo, hi) = mesh.bounds(); + let doc = json!({ + "asset": { "version": "2.0" }, + "scene": 0, + "scenes": [{ "nodes": [0] }], + "nodes": [{ "name": "Part_high", "mesh": 0 }], + "meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "TEXCOORD_0": 1 }, "indices": 2, "material": 0 }] }], + "materials": [{ "name": "Painted", "pbrMetallicRoughness": { "baseColorTexture": { "index": 0 } } }], + "textures": [{ "source": 0 }], + "images": [{ "bufferView": 3, "mimeType": "image/png" }], + "buffers": [{ "byteLength": bin.len() }], + "bufferViews": views, + "accessors": [ + { "bufferView": 0, "componentType": 5126, "count": mesh.positions.len(), "type": "VEC3", "min": [lo.x, lo.y + dy, lo.z], "max": [hi.x, hi.y + dy, hi.z] }, + { "bufferView": 1, "componentType": 5126, "count": mesh.positions.len(), "type": "VEC2" }, + { "bufferView": 2, "componentType": 5125, "count": mesh.indices.len(), "type": "SCALAR" } + ] + }); + let mut text = serde_json::to_vec(&doc).unwrap(); + text.resize(text.len().next_multiple_of(4), b' '); + let mut glb = Vec::new(); + glb.extend_from_slice(b"glTF"); + glb.extend_from_slice(&2u32.to_le_bytes()); + glb.extend_from_slice(&((12 + 8 + text.len() + 8 + bin.len()) as u32).to_le_bytes()); + for (chunk, kind) in [(&text, b"JSON"), (&bin, b"BIN\0")] { + glb.extend_from_slice(&(chunk.len() as u32).to_le_bytes()); + glb.extend_from_slice(kind); + glb.extend_from_slice(chunk); + } + glb +} + +#[test] +fn opacity_samples_a_textured_gltf_high_poly() { + let mut session = plane_session(); + let low = session.mesh.as_ref().clone(); + let png = quadrants_png(); + session.add_high_poly_bytes("painted.glb", textured_glb(&low, 0.002, &png)).unwrap(); + assert!(session.log.iter().any(|l| l.contains("1 base color textures")), "{:?}", session.log); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert_opacity_quadrants(&session); + assert!(session.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|o| *o > 0.0), "the high poly covers the plane"); + + // The textures come back with the project + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color); +} + +/// USDZ opacity uses the UsdPreviewSurface texture alpha +#[test] +fn opacity_samples_a_textured_usdz_high_poly() { + use texturecraft_engine::formats::{ExportedFile, UsdFormat, usd_bytes}; + let mut session = plane_session(); + let mut high = session.mesh.as_ref().clone(); + for p in &mut high.positions { + p.y += 0.002; + } + + let png = quadrants_png(); + let texture = ExportedFile { name: "BaseColor.png".into(), bytes: png, width: 4, height: 4, warnings: vec![] }; + let usdz = usd_bytes(&high, "painted", &[vec![texture]], UsdFormat::Usdz).unwrap().bytes; + session.add_high_poly_bytes("painted.usdz", usdz).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert_opacity_quadrants(&session); +} + +/// External glTF and USD textures remain available after saving the project +#[test] +fn opacity_samples_textures_next_to_a_high_poly() { + use texturecraft_engine::formats::{ExportedFile, UsdFormat, usd_bytes}; + let dir = std::env::temp_dir().join(format!("texturecraft-bake-external-{}", std::process::id())); + std::fs::create_dir_all(dir.join("tex")).unwrap(); + let low = plane_session().mesh.as_ref().clone(); + + // The textured GLB taken apart: JSON, its .bin and the image as files + let glb = textured_glb(&low, 0.002, &quadrants_png()); + let jlen = u32::from_le_bytes(glb[12..16].try_into().unwrap()) as usize; + let mut doc: Value = serde_json::from_slice(&glb[20..20 + jlen]).unwrap(); + doc["buffers"][0]["uri"] = "painted.bin".into(); + doc["images"] = json!([{ "uri": "tex/painted%20color.png" }]); + std::fs::write(dir.join("painted.bin"), &glb[20 + jlen + 8..]).unwrap(); + std::fs::write(dir.join("tex/painted color.png"), quadrants_png()).unwrap(); + std::fs::write(dir.join("painted.gltf"), serde_json::to_vec(&doc).unwrap()).unwrap(); + + // The same high poly as a usda with its texture beside it + let mut high = low.clone(); + for p in &mut high.positions { + p.y += 0.002; + } + + let texture = ExportedFile { name: "BaseColor.png".into(), bytes: quadrants_png(), width: 4, height: 4, warnings: vec![] }; + let usda = usd_bytes(&high, "painted", &[vec![texture]], UsdFormat::Usda).unwrap(); + for (name, bytes) in &usda.textures { + std::fs::write(dir.join(name), bytes).unwrap(); + } + std::fs::write(dir.join("painted.usda"), &usda.bytes).unwrap(); + for (file, stored) in [("painted.gltf", "painted.gltf"), ("painted.usda", "painted.usdz")] { + let mut session = plane_session(); + let result = execute(&mut session, "bake.highPoly.add", &json!({ "path": dir.join(file).display().to_string() })).unwrap(); + assert_eq!(result["name"], stored); + assert!(session.log.iter().any(|l| l.contains("1 base color textures")), "{file}: {:?}", session.log); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert_opacity_quadrants(&session); + + // The project holds the folded file: the textures come back without the folder + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color, "{file}"); + } + + // A missing image is named in the log; the high poly still loads, untextured + std::fs::remove_file(dir.join("tex/painted color.png")).unwrap(); + let mut session = plane_session(); + execute(&mut session, "bake.highPoly.add", &json!({ "path": dir.join("painted.gltf").display().to_string() })).unwrap(); + assert!(session.log.iter().any(|l| l.contains("tex/painted color.png was not found")), "{:?}", session.log); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert!(session.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|opacity| *opacity == 1.0)); + + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A plane session whose vertex normals lean, with a high poly plane `dy` above it. +fn leaning_session(lean: bool) -> Session { + let mut mesh = primitives::builtin("plane").unwrap(); + if lean { + mesh.normals = vec![texturecraft_engine::geom::glam::Vec3::new(0.6, 0.8, 0.0); mesh.positions.len()]; + mesh.compute_tangents(); + } + let high_text = obj(&mesh, 0.1, f32::MAX, [1.0; 3]); + let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + + // Tests run in parallel, so each call needs its own folder + static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let call = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("texturecraft-lean-test-{}-{call}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let high = dir.join("high.obj"); + std::fs::write(&high, high_text).unwrap(); + execute(&mut s, "bake.highPoly.add", &json!({ "path": high.display().to_string() })).unwrap(); + + // The imported mesh remains after its source file is removed + let _ = std::fs::remove_dir_all(&dir); + execute( + &mut s, + "bake.settings", + &json!({ "resolution": 128, "dilation": 0, "maps": ["height"], "maxFrontal": 0.5, "maxRear": 0.2, "averageNormals": true }), + ) + .unwrap(); + s +} + +#[test] +fn the_skew_map_is_saved_with_the_project() { + let mut s = leaning_session(false); + execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap(); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.bake_paint, s.doc.bake_paint); + + // Clearing skew persists + execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); + assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.bake_paint.is_empty()); + + // Invalid saved skew is skipped without preventing project load + let mut pf = s.project_file(); + pf.bake_paint.insert((0, texturecraft_core::BakePaintTarget::Skew), texturecraft_formats::BakePaintData { width: 1, height: 1, values: vec![f32::NAN] }); + let opened = Session::from_project_file(pf).unwrap(); + assert!( + !opened.doc.bake_paint.contains_key(&(0, texturecraft_core::BakePaintTarget::Skew)) + && opened.log.iter().any(|line| line.contains("skipped bake paint map")), + "{:?}", + opened.log + ); +} + +#[test] +fn the_skew_map_steers_only_a_distance_cage_with_averaged_normals() { + let mut s = leaning_session(false); + execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap(); + assert!(s.bake_task(0).unwrap().skew.is_some()); + + s.doc.project.texture_sets[0].bake.cage.average_normals = false; + assert!(s.bake_task(0).unwrap().skew.is_none(), "without averaged normals the skew map is left out"); + s.doc.project.texture_sets[0].bake.cage.average_normals = true; + let cage = obj(&s.mesh.clone(), 0.05, f32::MAX, [1.0; 3]); + s.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + s.doc.project.texture_sets[0].bake.cage.kind = texturecraft_core::CageType::CustomFile; + assert!(s.bake_task(0).unwrap().skew.is_none(), "a cage file sets the rays itself"); +} + +#[test] +fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() { + let mut s = leaning_session(true); + + // The first stroke creates a black map at the requested size + let r = execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 })).unwrap(); + assert_eq!(r["skew"]["width"], 64); + let map = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); + assert!(map.values.iter().any(|v| *v > 0.99) && map.values.contains(&0.0)); + let rev = s.revision; + + // Erasing retains the map size + execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.2, "value": 0.0, "hardness": 1.0 })).unwrap(); + let after = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); + assert_eq!(after.width, 64); + assert!(after.values.iter().all(|v| *v < 0.01) && s.revision > rev); + + // Resizing preserves untouched constant values + execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); + execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.1, 0.1]], "radius": 0.05, "size": 32 })).unwrap(); + let wide = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); + assert_eq!(wide.width, 32); + assert!((wide.values[wide.values.len() / 2] - 0.5).abs() < 1e-5, "{}", wide.values[wide.values.len() / 2]); + + // Invalid strokes leave the map unchanged + let before = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(); + for bad in [ + json!({}), + json!({ "points": [] }), + json!({ "points": [[0.5]] }), + json!({ "points": [["a", "b"]] }), + json!({ "points": [[0.5, 0.5]], "radius": 0.0 }), + json!({ "points": [[0.5, 0.5]], "radius": 5.0 }), + json!({ "points": [[0.5, 0.5]], "radius": -1.0 }), + json!({ "points": [[0.5, 0.5]], "size": 2 }), + json!({ "points": [[0.5, 0.5]], "size": 100000 }), + json!({ "points": [[0.0, 0.0], [1e9, 1e9]], "radius": 1e-4 }), + ] { + assert!(execute(&mut s, "bake.skew.paint", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(), before); + + // Painted skew survives a project round trip + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.bake_paint, s.doc.bake_paint); +} + +#[test] +fn bake_brush_strokes_are_undoable_and_continuations_merge() { + use texturecraft_core::BakePaintTarget; + let mut session = plane_session(); + let key = (0, BakePaintTarget::Skew); + execute(&mut session, "bake.skew.paint", &json!({"points": [[0.2, 0.2]], "radius": 0.1, "size": 64})).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({"points": [[0.2, 0.2], [0.8, 0.8]], "radius": 0.1, "continue": true})).unwrap(); + let painted = session.doc.bake_paint.get(&key).cloned().unwrap(); + session.undo().unwrap(); + assert!(!session.doc.bake_paint.contains_key(&key)); + session.redo().unwrap(); + assert_eq!(session.doc.bake_paint.get(&key), Some(&painted)); +} + +#[test] +fn cage_paint_is_scoped_saved_and_undoable() { + use texturecraft_core::BakePaintTarget; + let mut session = plane_session(); + let mut second_set = session.doc.project.texture_sets[0].clone(); + second_set.stack.clear(); + session.doc.project.texture_sets.push(second_set); + execute(&mut session, "bake.cage.paint", &json!({"ts": 1, "points": [[0.25, 0.25]], "radius": 0.1, "value": 0.2, "size": 32})).unwrap(); + let key = (1, BakePaintTarget::Cage); + let painted = session.doc.bake_paint[&key].clone(); + assert!(painted.values.iter().any(|value| *value < 0.5)); + assert!(painted.values.contains(&1.0)); + assert!(!session.doc.bake_paint.contains_key(&(0, BakePaintTarget::Cage))); + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.bake_paint[&key], painted); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(!session.doc.bake_paint.contains_key(&key)); + execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert_eq!(session.doc.bake_paint[&key], painted); + execute(&mut session, "bake.cage.reset", &json!({"ts": 1})).unwrap(); + assert!(!session.doc.bake_paint.contains_key(&key)); +} + +#[test] +fn changing_bake_aspect_replaces_incompatible_maps() { + let mut session = plane_session(); + execute(&mut session, "bake.run", &json!({"resolution": 64, "maps": ["normal", "id"]})).unwrap(); + execute(&mut session, "bake.settings", &json!({"model": {"common": {"resolution": "R64", "resolution_height": "R128"}}})).unwrap(); + execute(&mut session, "bake.run", &json!({"maps": ["id"]})).unwrap(); + let baked = &session.doc.baked[&0]; + assert_eq!((baked.resolution, baked.height(BakedMap::Id)), (64, 128)); + assert_eq!(baked.maps.len(), 1); + assert_eq!(session.doc.project.texture_sets[0].baked.len(), 1); + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.baked[&0], *baked); +} + +#[test] +fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { + let mut session = leaning_session(false); + let mut second = session.doc.project.texture_sets[0].clone(); + second.stack.clear(); + second.bake.cage.kind = texturecraft_core::CageType::CustomFile; + session.doc.project.texture_sets.push(second); + let original = session.doc.clone(); + let history = session.history_labels(); + let error = execute(&mut session, "bake.run", &json!({"ts": "all", "resolution": 64, "maps": ["id"]})).unwrap_err(); + assert!(error.to_string().contains("requires a cage"), "{error}"); + assert_eq!(session.doc.project, original.project); + assert_eq!(session.doc.baked, original.baked); + assert_eq!(session.history_labels(), history); +} + +/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay, +/// the project counts as changed, and image resources are decoded in the new session. +#[test] +fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { + let mut s = plane_session(); + let plane = s.mesh.as_ref().clone(); + let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3])); + execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap(); + execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap(); + // 1x1 PNG as an image resource. + let png = [ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, + 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00, + 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + s.import_resource_bytes("dot.png", png.to_vec()).unwrap(); + s.modified = false; + let mesh_id = s.mesh_id; + + let mut low = String::new(); + for p in &plane.positions { + low += &format!("v {} {} {}\n", p.x, p.y, p.z); + } + for uv in &plane.uvs { + low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y); + } + for t in plane.indices.as_chunks::<3>().0 { + low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1); + } + let low = temp_file("change_low.obj", &low); + execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap(); + + assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh"); + assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays"); + assert!(s.modified, "the project differs from the saved one"); + assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); +} diff --git a/crates/engine/tests/it/bake_checks.rs b/crates/engine/tests/it/bake_checks.rs new file mode 100644 index 00000000..52825e95 --- /dev/null +++ b/crates/engine/tests/it/bake_checks.rs @@ -0,0 +1,112 @@ +//! What bake mode lists before a bake: overlapping UVs and parts "By Mesh Name" leaves unpaired + +use texturecraft_engine::Session; +use texturecraft_engine::bake::NamePair; +use texturecraft_engine::core::MeshMatchMode; + +/// Two quads side by side; `shared_uvs` lays both on the same UV square instead of side by side in UV space +fn two_quads(shared_uvs: bool) -> Session { + let second_u = if shared_uvs { 0.0 } else { 0.5 }; + let obj = format!( + "o Box_low\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\ + o Lone_low\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt {second_u} 0\nvt {} 0\nvt {} 1\nvt {second_u} 1\nf 5/5 6/6 7/7 8/8\n", + second_u + 0.5, + second_u + 0.5 + ); + Session::from_mesh_bytes("quads.obj", obj.as_bytes(), 128, "quads").unwrap() +} + +const HIGH_POLY: &[u8] = b"o Box_high\nv 0 0 0.01\nv 1 0 0.01\nv 0 1 0.01\nf 1 2 3\no Extra_high\nv 2 0 0.01\nv 3 0 0.01\nv 2 1 0.01\nf 4 5 6\n"; + +#[test] +fn overlapping_uvs_are_measured_before_the_bake() { + assert!(two_quads(true).bake_uv_overlap(0).unwrap() > 0.4, "the second quad covers the first one's UVs"); + assert_eq!(two_quads(false).bake_uv_overlap(0).unwrap(), 0.0, "side by side in UV space nothing overlaps"); + const MISSING_TEXTURE_SET: usize = 9; + assert!(two_quads(false).bake_uv_overlap(MISSING_TEXTURE_SET).is_err()); +} + +#[test] +fn overlap_in_a_uv_tile_left_out_of_the_bake_is_not_counted() { + // One quad in tile 1001, two on the same UVs in tile 1002 + let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\ + o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 5/5 6/6 7/7 8/8\n\ + o Third\nv 4 0 0\nv 5 0 0\nv 5 1 0\nv 4 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 9/9 10/10 11/11 12/12\n"; + let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "the last two quads share tile 1002's UVs"); + + session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002); + assert_eq!(session.bake_uv_overlap(0).unwrap(), 0.0, "tile 1001 alone has no overlap"); +} + +#[test] +fn overlap_is_measured_at_the_same_detail_in_every_uv_tile() { + // Tiles 1001 and 1010 make a grid ten tiles wide; 512 texels across all ten would give each tile about 51 + const TEXELS_PER_TILE: f32 = 512.0; + const SLIVER_TEXELS: f32 = 4.0; + + // Inside tile 1010 (column 9), clear of the wide raster's texel centres + const SLIVER_LEFT_U: f32 = 9.1; + let (left, right) = (SLIVER_LEFT_U, SLIVER_LEFT_U + SLIVER_TEXELS / TEXELS_PER_TILE); + let sliver = |name: &str, first: u32, x: f32| { + let (second, third, fourth) = (first + 1, first + 2, first + 3); + let corners = format!("v {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\n", x + 1.0, x + 1.0); + format!( + "o {name}\n{corners}vt {left} 0\nvt {right} 0\nvt {right} 1\nvt {left} 1\nf {first}/{first} {second}/{second} {third}/{third} {fourth}/{fourth}\n" + ) + }; + let corner = "o Corner\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; + let obj = [corner.to_owned(), sliver("First", 5, 2.0), sliver("Second", 9, 4.0)].concat(); + let session = Session::from_mesh_bytes("wide.obj", obj.as_bytes(), 128, "wide").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1010]); + + assert!(session.bake_uv_overlap(0).unwrap() > 0.0, "two slivers a few texels wide overlap in tile 1010"); +} + +#[test] +fn a_triangle_across_a_uv_tile_border_counts_in_both_tiles() { + // Two quads on the same UVs, from u 0.9 in tile 1001 to u 1.1 in tile 1002 + let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 1/1 2/2 3/3 4/4\n\ + o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 5/5 6/6 7/7 8/8\n"; + let mut session = Session::from_mesh_bytes("border.obj", obj.as_bytes(), 128, "border").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + + for (excluded, kept) in [(1002, 1001), (1001, 1002)] { + let excluded_tiles = &mut session.doc.project.texture_sets[0].bake_excluded_tiles; + excluded_tiles.clear(); + excluded_tiles.insert(excluded); + assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "tile {kept} holds part of the overlap"); + } +} + +#[test] +fn unpaired_parts_are_listed_only_when_matching_by_name() { + let mut session = two_quads(false); + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "no high poly"); + session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap(); + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "\"Always\" pairs every part"); + + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let pairs = session.bake_name_pairs(0).unwrap().unwrap(); + let unpaired: Vec<&NamePair> = pairs.iter().filter(|pair| pair.unpaired()).collect(); + assert_eq!(unpaired, [&NamePair { low: Some("Lone_low".into()), high: None }, &NamePair { low: None, high: Some("Extra_high".into()) }], "{pairs:?}"); + assert!(pairs.contains(&NamePair { low: Some("Box_low".into()), high: Some("Box_high".into()) })); + + session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "the low poly as its own high poly pairs every part"); +} + +#[test] +fn a_set_matching_always_bakes_from_every_high_poly_part() { + let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap(); + let both = [0, 1]; + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), Vec::::new(), "the other set matches \"Always\""); + + session.doc.project.texture_sets[1].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), ["Extra_high"]); +} 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..16851173 --- /dev/null +++ b/crates/engine/tests/it/bake_tiles.rs @@ -0,0 +1,177 @@ +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.as_chunks::<64>().0 { + 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].as_chunks::<128>().0 { + 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/generator_inputs.rs b/crates/engine/tests/it/generator_inputs.rs new file mode 100644 index 00000000..d61dac5a --- /dev/null +++ b/crates/engine/tests/it/generator_inputs.rs @@ -0,0 +1,132 @@ +//! Generator inputs that read an anchor point or an image, through engine commands. + +use serde_json::{Value, json}; +use std::sync::Arc; +use texturecraft_engine::core::{BakedMap, Channel, EffectKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The texture set's texels per side. +const RESOLUTION: u32 = 256; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + session.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// Composited value of `channel` under the viewport center. +fn center(session: &mut Session, channel: Channel) -> [f32; 3] { + session.update(); + let hit = session.pick(session.viewport * 0.5, session.viewport).unwrap(); + let texels = RESOLUTION as f32; + session.caches[0].composite.value(channel, (hit.uv.x * texels) as u32, (hit.uv.y * texels) as u32) +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +/// A low fill (height 0.8) with an anchor, then a white fill whose black mask holds an AO generator reading it: (anchor, low layer, generator). +fn anchored_generator(session: &mut Session) -> (u64, u64, u64) { + let low = id(execute(session, "layer.add.fill", &json!({"height": 0.8})).unwrap(), "layer"); + let anchor = id(execute(session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(), "effect"); + execute(session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(session, "effect.add.generator", &json!({"generator": "ambientOcclusion", "level": 0.5, "softness": 0.5})).unwrap(), "effect"); + execute(session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputAnchor": anchor, "anchorChannel": "height"})).unwrap(); + (anchor, low, generator) +} + +#[test] +fn a_generator_input_reads_the_anchor_points_value() { + let mut session = session(); + anchored_generator(&mut session); + + // The low fill's gray, then white through the mask: an occlusion of 0.8 masks most of it, the channel default (0) none + let base = center(&mut session, Channel::BaseColor)[0]; + assert!(base > 0.9, "the generator reads the anchor's height, not the default: {base}"); +} + +#[test] +fn a_generator_reading_an_anchor_cannot_be_pasted_below_it() { + let mut session = session(); + let (_, low, generator) = anchored_generator(&mut session); + execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap(); + + let pasted = execute(&mut session, "effect.paste", &json!({"layer": low, "target": "mask"})); + assert!(pasted.is_err(), "the anchor point is on that layer, not below it"); +} + +#[test] +fn removing_unused_resources_keeps_an_image_read_by_a_generator_input() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("occlusion.png", bytes).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": name})).unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the generator input"); +} + +#[test] +fn removing_unused_resources_keeps_an_image_read_by_a_content_effect() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("content.png", bytes).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let effect = id(execute(&mut session, "effect.add.fill", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut session, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "image": name})).unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert!(session.doc.resources.contains_key(&name), "the content effect still reads the image"); +} + +#[test] +fn generator_input_rejects_a_resource_that_is_not_an_image() { + let mut session = session(); + session.doc.resources.insert("linked.mcmat".into(), Arc::new(vec![1, 2, 3])); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect"); + + let result = execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": "linked.mcmat"})); + + assert!(result.is_err(), "a package resource has no image pixels for the generator to sample"); +} + +#[test] +fn importing_a_missing_generator_input_invalidates_the_composite() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let effect = id(execute(&mut session, "effect.add.generator", &json!({"generator": "ambientOcclusion"})).unwrap(), "effect"); + session + .edit("Reference an absent image", |session| { + let effect = session.doc.project.effect_mut(texturecraft_engine::core::LayerId(effect)).unwrap(); + let EffectKind::Generator(generator) = &mut effect.kind else { panic!("expected generator") }; + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("later.png")); + Ok(()) + }) + .unwrap(); + let before = center(&mut session, Channel::BaseColor)[0]; + + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 0, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("later.png", bytes).unwrap(); + let after = center(&mut session, Channel::BaseColor)[0]; + + assert!((after - before).abs() > 0.2, "the new image must update the generator's composited mask: {before} -> {after}"); +} 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..2af1e085 --- /dev/null +++ b/crates/engine/tests/it/high_poly_missed.rs @@ -0,0 +1,58 @@ +use texturecraft_engine::bake::{HIDDEN_HIGH_POLY_VERTEX, 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_hides_other_sets_vertices() { + const H: f32 = HIDDEN_HIGH_POLY_VERTEX; + let reaches = sets(); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, H, H, H, H]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![H, H, 0.0, 1.0, H, H]); + for only_set in [0, reaches.len(), usize::MAX] { + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![H; 6], "a set without a reach shows none of the high poly"); + } +} + +#[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 84% rename from crates/engine/tests/instances.rs rename to crates/engine/tests/it/instances.rs index b9f14bcd..099a41b0 100644 --- a/crates/engine/tests/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -2,7 +2,7 @@ //! frame-budgeted compositor, through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId, LayerKind}; +use texturecraft_engine::core::{Channel, Fill, LayerId, LayerKind, Source}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; @@ -206,6 +206,52 @@ fn edits_invalidate_only_the_sets_they_change() { assert!((rough(&mut s, 0) - 0.4).abs() < 1e-3); } +#[test] +fn importing_images_invalidates_only_sets_with_newly_resolved_references() { + use std::sync::Arc; + + let mut session = session(); + let referenced_layer = session.doc.project.texture_sets[1].stack[0]; + session + .edit("Reference missing image", |session| { + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::image("later.png")); + session.doc.project.layer_mut(referenced_layer).unwrap().kind = LayerKind::Fill(fill); + Ok(()) + }) + .unwrap(); + session.update(); + + let mut image_bytes = Vec::new(); + let image = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])); + image.write_to(&mut std::io::Cursor::new(&mut image_bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("later.png", image_bytes.clone()).unwrap(); + assert!(session.caches[0].dirty.is_empty(), "unrelated set stays clean"); + assert!(!session.caches[1].dirty.is_empty(), "newly resolved image invalidates its set"); + session.update(); + let (x, y) = covered(&session, 1); + assert!(session.caches[1].composite.value(Channel::BaseColor, x, y)[0] > 0.9); + let imported_image = Arc::downgrade(&session.images["later.png"]); + + session.undo().unwrap(); + assert!(!session.caches[0].dirty.is_empty(), "resource removal retains broad invalidation"); + assert!(!session.caches[1].dirty.is_empty()); + assert!(imported_image.upgrade().is_none(), "undo releases the decoded image even while encoded bytes remain in history"); + session.update(); + session.redo().unwrap(); + assert!(session.caches[0].dirty.is_empty()); + assert!(!session.caches[1].dirty.is_empty()); + assert!(!imported_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "redo decodes a new image allocation"); + session.update(); + + session.import_resource_bytes("unused.png", image_bytes).unwrap(); + assert!(session.caches.iter().all(|cache| cache.dirty.is_empty()), "unused image leaves every set clean"); + + let resolved_image = Arc::downgrade(&session.images["later.png"]); + session.sync_images(); + assert!(resolved_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "sync reuses already decoded images"); +} + #[test] fn budgeted_updates_spread_work_and_end_identical() { let mut s = session(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs new file mode 100644 index 00000000..8973da23 --- /dev/null +++ b/crates/engine/tests/it/main.rs @@ -0,0 +1,34 @@ +//! 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_checks; +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 generator_inputs; +mod high_poly_missed; +mod instances; +mod materialcraft_link; +mod materialx; +mod materialx_import; +mod meshmap_import; +mod painter_gaps; +mod path_perf; +mod path_tool; +mod perf; +mod polygon_fill; +mod project_recovery; +mod sample; +mod thumbs; +mod tool_availability; +mod tools; +mod udim; +mod uv_strokes; + +mod symmetry; diff --git a/crates/engine/tests/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs similarity index 51% rename from crates/engine/tests/materialcraft_link.rs rename to crates/engine/tests/it/materialcraft_link.rs index 057621b1..cbe75532 100644 --- a/crates/engine/tests/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -21,9 +21,14 @@ fn session() -> Session { /// A `.mcmat` as MaterialCraft writes it: uniform maps, one float input `wear` cooked at `wear`. fn mcmat(roughness: f32, wear: f32) -> Vec { + mcmat_version(roughness, wear, 1) +} + +fn mcmat_version(roughness: f32, wear: f32, version: u32) -> Vec { + let source = if version == 2 { "source.sbs" } else { "source.mcraft" }; let gray = |v: f32| mesh_map_png(4, 1, &[v; 16]).unwrap(); let manifest = json!({ - "format": "craft-material", "version": 1, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], + "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [ {"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}, {"usage": "roughness", "file": "maps/roughness.png", "colorSpace": "linear"}, @@ -34,9 +39,15 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { {"id": "tint", "label": "Tint", "default": {"t": "color", "v": [1.0, 1.0, 1.0, 1.0]}, "value": {"t": "color", "v": [1.0, 1.0, 1.0, 1.0]}}, {"id": "note", "label": "Note", "default": {"t": "text", "v": ""}, "value": {"t": "text", "v": ""}} ], - "inputs": [{"identifier": "curvature", "kind": "gray"}], + "inputs": [ + {"identifier": "curvature", "kind": "gray"}, + {"identifier": "normal", "kind": "color"}, + {"identifier": "worldNormal", "kind": "color"}, + {"identifier": "ambientOcclusion", "kind": "gray"}, + {"identifier": "bentNormal", "kind": "color"} + ], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}], - "source": "source.mcraft" + "source": source }); let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -45,7 +56,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { ("maps/baseColor.png", mesh_map_png(4, 3, &[0.5; 48]).unwrap()), ("maps/roughness.png", gray(roughness)), ("maps/ambientOcclusion.png", gray(1.0)), - ("source.mcraft", b"package bytes".to_vec()), + (source, b"package bytes".to_vec()), ] { z.start_file(name, o).unwrap(); z.write_all(&bytes).unwrap(); @@ -75,6 +86,24 @@ fn map_name(s: &Session, id: LayerId, c: Channel) -> String { } } +#[test] +fn version_two_preserves_the_sbs_source_for_future_cooks() { + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat_version(0.25, 0.5, 2), Place::Selection).unwrap(); + let linked = link(&session, id); + assert!(linked.package.ends_with(".sbs")); + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); + assert_eq!(job.source_ext, "sbs"); + assert_eq!(job.graph.as_deref(), Some("Brick_wall")); + assert_eq!(job.package.as_slice(), b"package bytes"); + let base = std::env::temp_dir().join(format!("texturecraft-sbs-source-{}", std::process::id())); + let saved = execute(&mut session, "material.link.saveSource", &json!({"layer": id.0, "path": base.to_str().unwrap()})).unwrap(); + let path = saved["path"].as_str().unwrap(); + assert!(path.ends_with(".sbs")); + assert_eq!(std::fs::read(path).unwrap(), b"package bytes"); + let _ = std::fs::remove_file(path); +} + #[test] fn imports_as_a_linked_fill_with_its_maps() { let mut s = session(); @@ -86,7 +115,7 @@ fn imports_as_a_linked_fill_with_its_maps() { let l = link(&s, id); assert_eq!(l.graph, "Brick_wall"); assert_eq!(l.params.iter().map(|p| p.id.as_str()).collect::>(), ["wear", "tint"]); - assert_eq!(l.inputs, ["curvature"]); + assert_eq!(l.inputs, ["curvature", "normal", "worldNormal", "ambientOcclusion", "bentNormal"]); assert_eq!(s.doc.resources.get(&l.package).map(|b| b.as_slice()), Some(&b"package bytes"[..])); assert!(!s.images.contains_key(&l.package), "the package is not decoded as an image"); // Inspect shows the link; one undo removes everything. @@ -102,64 +131,71 @@ fn imports_as_a_linked_fill_with_its_maps() { /// An image marked DirectX keeps the mark when a re-cook replaces it. #[test] fn recooks_keep_the_normal_format_of_a_map() { - let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); - execute(&mut s, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap(); - s.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); - let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("a fill") }; + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap(); + + session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); + + let LayerKind::Fill(fill) = &session.doc.project.layer(id).unwrap().kind else { panic!("a fill") }; + assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { normal_format: NormalFormat::DirectX, .. }))); } #[test] fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { - let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); - let set = |s: &mut Session, p: Value| execute(s, "material.link.set", &p); - assert!(set(&mut s, json!({"id": "nope", "value": 1, "cook": false})).is_err()); - assert!(set(&mut s, json!({"id": "wear", "value": "soft", "cook": false})).is_err()); - assert!(set(&mut s, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err()); - set(&mut s, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap(); - assert_eq!(link(&s, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]})); - set(&mut s, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap(); - assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.9})); + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let set = |session: &mut Session, params: Value| execute(session, "material.link.set", ¶ms); + + assert!(set(&mut session, json!({"id": "nope", "value": 1, "cook": false})).is_err()); + assert!(set(&mut session, json!({"id": "wear", "value": "soft", "cook": false})).is_err()); + assert!(set(&mut session, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err()); + set(&mut session, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]})); + set(&mut session, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.9})); + + // Cooks follow the texture set resolution + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); - // The job carries every value and the texture set's resolution. - let job = s.link_job(id, &serde_json::Map::new()).unwrap(); assert_eq!(job.size, 128); assert_eq!(job.values["wear"], json!({"t": "float", "v": 0.9})); - // What the job cooked (here: built by hand) replaces the maps, merged into the edit. - let old = map_name(&s, id, Channel::Roughness); - s.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap(); - assert!((roughness(&mut s) - 0.75).abs() < 2e-3); - assert!(!s.doc.resources.contains_key(&old), "old maps are dropped"); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert!((roughness(&mut s) - 0.25).abs() < 2e-3, "undo restores the earlier maps"); - assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.5})); - execute(&mut s, "edit.redo", &Value::Null).unwrap(); - assert!((roughness(&mut s) - 0.75).abs() < 2e-3); + // Merge the cooked maps into the parameter edit + let old = map_name(&session, id, Channel::Roughness); + session.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap(); - // Presets skip inputs the painter can't set; unknown presets are errors. - assert!(execute(&mut s, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err()); - execute(&mut s, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap(); - assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 1.0})); + assert!((roughness(&mut session) - 0.75).abs() < 2e-3); + assert!(!session.doc.resources.contains_key(&old), "old maps are dropped"); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!((roughness(&mut session) - 0.25).abs() < 2e-3, "undo restores the earlier maps"); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.5})); + + execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert!((roughness(&mut session) - 0.75).abs() < 2e-3); + + // Presets skip unsupported inputs and reject unknown names + assert!(execute(&mut session, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err()); + execute(&mut session, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 1.0})); } #[test] fn duplicates_keep_their_maps_and_mesh_maps_feed_inputs() { - let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); - let dup = LayerId(execute(&mut s, "layer.duplicate", &json!({"layer": id.0})).unwrap()["layer"].as_u64().unwrap()); - let shared = map_name(&s, dup, Channel::Roughness); - s.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); - assert!(s.doc.resources.contains_key(&shared), "the duplicate still shows the first cook"); + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let duplicate = LayerId(execute(&mut session, "layer.duplicate", &json!({"layer": id.0})).unwrap()["layer"].as_u64().unwrap()); + let shared = map_name(&session, duplicate, Channel::Roughness); + session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); + assert!(session.doc.resources.contains_key(&shared), "the duplicate still shows the first cook"); - s.doc.baked.insert(0, BakedMaps { resolution: 4, maps: [(BakedMap::Curvature, Arc::new(vec![0.5f32; 16]))].into_iter().collect() }); - let job = s.link_job(id, &serde_json::Map::new()).unwrap(); - assert_eq!(job.inputs.len(), 1); - assert_eq!(job.inputs[0].0, "curvature"); - assert_eq!(BakedMap::for_input("ambient_occlusion"), Some(BakedMap::AmbientOcclusion)); - assert_eq!(BakedMap::for_input("worldNormal"), Some(BakedMap::WorldNormal)); + let maps = [BakedMap::Curvature, BakedMap::Normal, BakedMap::WorldNormal, BakedMap::AmbientOcclusion, BakedMap::BentNormal]; + session.doc.baked.insert(0, BakedMaps { resolution: 4, maps: maps.into_iter().map(|map| (map, Arc::new(vec![0.5f32; 16 * map.components()]))).collect() }); + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); + assert_eq!(job.inputs.iter().map(|(identifier, _)| identifier.as_str()).collect::>(), maps.map(BakedMap::id)); + assert_eq!(maps.map(BakedMap::id), ["curvature", "normal", "worldNormal", "ambientOcclusion", "bentNormal"]); } #[test] @@ -186,7 +222,7 @@ fn cooks_through_materialcraft_cli_when_available() { let dir = std::env::temp_dir().join(format!("tc-mc-link-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("bricks.mcraft"); - let ok = std::process::Command::new(&cli).args(["new", "bricks"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); + let ok = std::process::Command::new(&cli).args(["new", "pbr"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); assert!(ok.success()); let exposed = dir.join("exposed.mcraft"); let ok = std::process::Command::new(&cli) @@ -204,9 +240,24 @@ fn cooks_through_materialcraft_cli_when_available() { assert_eq!(link(&s, id).size, 128, "cooked at the texture set's resolution"); assert!(link(&s, id).params.iter().any(|p| p.id == "wear")); execute(&mut s, "material.link.set", &json!({"layer": id.0, "id": "wear", "value": 0.8})).unwrap(); - assert_eq!(link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value, json!({"t": "float", "v": 0.8})); - let out = dir.join("back.mcraft"); + let wear = link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value["v"].as_f64().unwrap(); + assert!((wear - 0.8).abs() < 1e-6); + let out = dir.join("back.sbs"); execute(&mut s, "material.link.saveSource", &json!({"layer": id.0, "path": out.to_str().unwrap()})).unwrap(); assert!(std::fs::metadata(&out).unwrap().len() > 0); + + // The portable material can name a graph other than the first in the embedded source. + let multi = dir.join("multi.mcraft"); + let ok = std::process::Command::new(&cli).arg("run").arg(&exposed).arg("graph.duplicate").arg("{}").arg("-o").arg(&multi).status().unwrap(); + assert!(ok.success()); + let portable = dir.join("second.mcmat"); + let params = json!({"graph": 1, "size": 64, "path": portable.to_str().unwrap()}); + let ok = std::process::Command::new(&cli).arg("run").arg(&multi).arg("file.exportMaterial").arg(params.to_string()).status().unwrap(); + assert!(ok.success()); + let second = s.add_linked_material_bytes_at(&std::fs::read(&portable).unwrap(), Place::Selection).unwrap(); + let expected_graph = link(&s, second).graph; + let job = s.link_job(second, &serde_json::Map::new()).unwrap(); + let result = texturecraft_engine::formats::mcmat::read_mcmat(&job.run().unwrap()).unwrap(); + assert_eq!(result.manifest.graph, expected_graph); let _ = std::fs::remove_dir_all(&dir); } 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 77% rename from crates/engine/tests/painter_gaps.rs rename to crates/engine/tests/it/painter_gaps.rs index e15a69bb..f729476e 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -34,6 +34,9 @@ fn red(v: [f32; 3]) -> bool { v[0] > 0.85 && v[1] < 0.15 } +/// Distance between the view points searched for a texture set +const SEARCH_STEP: f32 = 10.0; + fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec { let mut out = Vec::new(); image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); @@ -345,6 +348,129 @@ fn decal_drags_merge_into_one_undo_step() { assert_eq!(execute(&mut s, "project.inspect", &Value::Null).unwrap()["layers"], start); } +/// A decal dropped on another texture set lands there and selects it, in one undo step +#[test] +fn a_decal_on_another_texture_set_selects_that_set() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.update(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap(); + let selected = s.ts(); + let (columns, rows) = ((s.viewport.x / SEARCH_STEP) as u32, (s.viewport.y / SEARCH_STEP) as u32); + let other_set_pixel = (0..rows) + .flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP)) + .find(|&pixel| s.texture_set_at(pixel, s.viewport).is_some_and(|ts| ts != selected)) + .expect("the material ball shows both of its texture sets"); + let other = s.texture_set_at(other_set_pixel, s.viewport).unwrap(); + let steps = s.history_labels().len(); + + let drop = json!({"image": name, "x": other_set_pixel.x, "y": other_set_pixel.y, "viewport": [s.viewport.x, s.viewport.y]}); + let layer = id(execute(&mut s, "layer.add.decal", &drop).unwrap(), "layer"); + + assert_eq!(s.ts(), other, "the set under the point is selected"); + assert_eq!(s.doc.project.locate(layer).map(|(ts, _, _)| ts), Some(other), "the decal is in that set"); + assert_eq!(s.selected_layer(), Some(layer)); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.locate(layer).is_none(), "one undo takes the decal away"); + + let background = json!({"image": name, "x": 2, "y": 2, "viewport": [s.viewport.x, s.viewport.y]}); + assert!(s.texture_set_at(Vec2::new(2.0, 2.0), s.viewport).is_none()); + assert!(execute(&mut s, "layer.add.decal", &background).is_err(), "the background still takes nothing"); +} + +/// A decal's image goes in the channel asked for, or masks a new fill layer +#[test] +fn a_decal_image_fills_a_chosen_channel_or_a_mask() { + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5}); + + let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer"); + assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal"); + assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel"); + let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap(); + assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks"); + + let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); + let masked = id(added.clone(), "layer"); + let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); + assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. }))); + assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); + execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); + assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere"); + + let effect = &added["maskEffect"]; + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); + assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer"); + let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4}); + assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused"); +} + +#[test] +fn editing_a_decal_checks_its_own_texture_set_after_selection_changes() { + for channel in ["baseColor", "mask"] { + 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 image = session.import_resource_bytes("logo.png", png(8, 8, |_, _| [255; 4])).unwrap(); + let (columns, rows) = ((session.viewport.x / SEARCH_STEP) as u32, (session.viewport.y / SEARCH_STEP) as u32); + let point_on = |texture_set| { + (0..rows) + .flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP)) + .find(|&point| session.texture_set_at(point, session.viewport) == Some(texture_set)) + .expect("both material-ball sets are visible") + }; + let original_point = point_on(0); + let other_point = point_on(1); + let added = + execute(&mut session, "layer.add.decal", &json!({"image": image, "channel": channel, "x": original_point.x, "y": original_point.y})).unwrap(); + let layer = added["layer"].clone(); + let effect = added["maskEffect"].clone(); + execute(&mut session, "textureSet.select", &json!({"ts": 1})).unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + let before = serde_json::to_value(&session.doc.project).unwrap(); + let history = session.history_labels(); + + let rejected = execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "x": other_point.x, "y": other_point.y})); + + assert!(rejected.is_err(), "{channel}: selecting another set must not allow moving the decal onto that set"); + assert_eq!(serde_json::to_value(&session.doc.project).unwrap(), before); + assert_eq!(session.history_labels(), history); + + let replaced = execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "x": original_point.x, "y": original_point.y})); + + assert!(replaced.is_ok(), "{channel}: the decal's own set remains a valid placement: {replaced:?}"); + let decal = replaced.unwrap()["decal"].clone(); + + execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "position": decal["center"], "normal": decal["normal"]})).unwrap(); + + assert_eq!(session.ts(), 1, "editing an explicit decal does not change selection"); + } +} + +/// A decal's new image stays in the channel the decal was placed in, read as gray there +#[test] +fn a_channel_decal_reads_its_image_as_gray_and_keeps_its_channel() { + let mut s = session(); + let white = s.import_resource_bytes("white.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let green = s.import_resource_bytes("green.png", png(8, 8, |_, _| [0, 255, 0, 255])).unwrap(); + let place = json!({"image": white, "channel": "roughness", "x": 200, "y": 200, "size": 0.5}); + let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer"); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "image": green})).unwrap(); + + assert_eq!(s.doc.project.layer(layer).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + let roughness = at(&mut s, Channel::Roughness, 200.0, 200.0)[0]; + assert!((roughness - texturecraft_engine::core::lum([0.0, 1.0, 0.0])).abs() < 0.02, "green reads as its gray, not its red: {roughness}"); +} + /// The Geometry mask tool: a click toggles the selected layer on the part under it. #[test] fn geometry_mask_tool_toggles_the_clicked_part() { @@ -382,11 +508,11 @@ fn images_fill_mesh_map_slots() { let mut s = session(); // Dark on the left, light on the right. let ao = s.import_resource_bytes("ao.png", png(8, 8, |x, _| if x < 4 { [64, 64, 64, 255] } else { [192, 192, 192, 255] })).unwrap(); - let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": ao})).unwrap(); - let res = s.doc.project.texture_sets[0].bake.resolution; - assert_eq!(r, json!({"map": "ambient_occlusion", "resolution": res})); + let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": ao})).unwrap(); + let res = s.doc.project.texture_sets[0].bake.common.resolution.pixels(); + assert_eq!(r, json!({"map": "ambientOcclusion", "resolution": res})); assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); - let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap(); + let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, (100, 100)).unwrap(); assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized"); assert!((sample(&s, BakedMap::AmbientOcclusion, 90)[0] - 192.0 / 255.0).abs() < 1e-3); // A normal map is read in the project's normal format (DirectX: green flipped). @@ -396,10 +522,10 @@ fn images_fill_mesh_map_slots() { let v = sample(&s, BakedMap::Normal, 50); assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}"); // Clearing empties the slot (one undo step); bad params are errors. - execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).unwrap(); - assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none()); + execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambientOcclusion"})).unwrap(); + assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, (100, 100)).is_none()); assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); - assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).is_err(), "already empty"); + assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambientOcclusion"})).is_err(), "already empty"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "nope", "image": ao})).is_err()); diff --git a/crates/engine/tests/it/path_perf.rs b/crates/engine/tests/it/path_perf.rs new file mode 100644 index 00000000..ac09c302 --- /dev/null +++ b/crates/engine/tests/it/path_perf.rs @@ -0,0 +1,115 @@ +//! Path preview timings and a repeatable memory soak (release, --ignored --nocapture). + +use std::time::{Duration, Instant}; + +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_engine::geom::glam::Vec2; + +/// Sort a nonempty timing sample in place and report its middle value in milliseconds +fn median_ms(samples: &mut [Duration]) -> f64 { + samples.sort_unstable(); + samples[samples.len() / 2].as_secs_f64() * 1_000.0 +} + +/// Separate repaint cost from dirty-tile and full-set compositing across representative brush sizes +#[test] +#[ignore = "release benchmark: two texture resolutions and brush sizes"] +fn path_preview_timings() { + for resolution in [2048, 4096] { + let mut session = texturecraft_engine::sample_session(resolution, 64).unwrap(); + session.viewport = Vec2::splat(400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + for size in [4, 20] { + execute(&mut session, "tool.brush", &json!({"size": size})).unwrap(); + execute(&mut session, "tool.path", &json!({"points": [[150, 210], [175, 180], [200, 210], [225, 180], [250, 210]]})).unwrap(); + session.update(); + let original = session.tool.path.points[2]; + let (mut paint, mut composite, mut full) = (Vec::new(), Vec::new(), Vec::new()); + let mut dirty_tiles = Vec::new(); + + for step in 0..20 { + let point = original + texturecraft_engine::geom::glam::Vec3::Y * (step as f32 + 1.0) * 0.001; + assert!(session.move_path_point(2, point, step == 0)); + let started = Instant::now(); + assert!(session.path_live().unwrap()); + paint.push(started.elapsed()); + dirty_tiles.push(session.pending_tiles()); + let started = Instant::now(); + session.update(); + composite.push(started.elapsed()); + // The same document with full invalidation isolates the compositor saving + if step < 3 { + for cache in &mut session.caches { + cache.invalidate_all(); + } + let started = Instant::now(); + session.update(); + full.push(started.elapsed()); + } + } + + println!( + "path {resolution}px brush={size}: paint {:.2} ms, dirty composite {:.2} ms, full composite {:.2} ms; dirty tiles {:?}", + median_ms(&mut paint), + median_ms(&mut composite), + median_ms(&mut full), + dirty_tiles + ); + session.cancel_path(); + session.update(); + } + } +} + +/// Observe resident memory without treating allocator-retained pages as a leak +#[cfg(target_os = "linux")] +fn resident_kib() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + status.lines().find_map(|line| line.strip_prefix("VmRSS:").and_then(|rest| rest.split_whitespace().next()).and_then(|n| n.parse().ok())).unwrap() +} + +/// Check that repeated canceled previews release tile buffers and leave no document history +#[cfg(target_os = "linux")] +#[test] +#[ignore = "release memory soak: 1,000 edits across 100 canceled previews"] +fn path_preview_memory_soak() { + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives; + + let mut session = Session::new_project("Path soak", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); + session.viewport = Vec2::splat(400.0); + session.update(); + let history = session.history_labels().len(); + let mut resident = Vec::new(); + + for cycle in 0..100 { + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.35, 0.45], [0.5, 0.5], [0.65, 0.45], [0.8, 0.5]]})).unwrap(); + for step in 0..10 { + let point = texturecraft_engine::geom::glam::Vec3::new(0.5, 0.5 + (step as f32 + 1.0) * 0.002, 0.0); + session.move_path_point(2, point, true); + assert!(session.path_live().unwrap()); + session.update(); + } + let preview_tiles: Vec<_> = session + .doc + .pixels + .layers + .values() + .flat_map(|image| image.allocated().map(|(x, y)| std::sync::Arc::downgrade(image.tile_handle(x, y).unwrap()))) + .collect(); + assert!(!preview_tiles.is_empty()); + session.cancel_path(); + session.update(); + assert!(preview_tiles.iter().all(|tile| tile.upgrade().is_none()), "canceled previews release their painted tile buffers"); + assert_eq!(session.history_labels().len(), history, "canceled previews retain no document history"); + if (cycle + 1) % 10 == 0 { + resident.push(resident_kib()); + } + } + + println!("path soak VmRSS KiB after each 100 edits: {resident:?}"); + // RSS is an observation, not a portable leak assertion: allocators can retain freed pages +} diff --git a/crates/engine/tests/it/path_tool.rs b/crates/engine/tests/it/path_tool.rs new file mode 100644 index 00000000..bb4ea764 --- /dev/null +++ b/crates/engine/tests/it/path_tool.rs @@ -0,0 +1,711 @@ +//! The Path tool (stroked and filled paths, 3D and 2D) and the particle brush, driven through +//! engine commands the way agents paint. + +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; +use texturecraft_engine::geom::{Mesh, primitives}; +use texturecraft_engine::{Session, execute}; + +const RES: f32 = 256.0; + +fn session(mesh: Mesh) -> Session { + let mut s = Session::new_project("t", mesh, "builtin:test", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + s +} + +fn red_uv(s: &Session, u: f32, v: f32) -> bool { + let c = s.caches[0].composite.value(Channel::BaseColor, (u * RES) as u32, (v * RES) as u32); + c[0] > 0.85 && c[1] < 0.15 +} + +/// Is the surface under a viewport point painted red? +fn red_at(s: &Session, x: f32, y: f32) -> bool { + let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); + red_uv(s, hit.uv.x, hit.uv.y) +} + +#[test] +fn path_stroke_paints_along_the_curve() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + assert_eq!(r["points"], 3); + assert_eq!(s.tool.tool, texturecraft_engine::Tool::Path); + assert!(red_at(&s, 200.0, 180.0), "the path is previewed before it is applied"); + let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + assert!(r["committed"]["stamps"].as_u64().unwrap() > 10, "{r}"); + assert_eq!(r["points"], 0, "commit clears the path"); + for (x, y) in [(140.0, 210.0), (200.0, 180.0), (260.0, 210.0), (170.0, 191.0)] { + assert!(red_at(&s, x, y), "on the curve at {x},{y}"); + } + assert!(!red_at(&s, 200.0, 240.0), "below the curve"); + assert!(!red_at(&s, 200.0, 130.0), "above the curve"); + // One undo step + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 180.0)); + // Errors: no points, points off the mesh + assert!(execute(&mut s, "tool.path", &json!({"commit": true})).is_err()); + assert!(execute(&mut s, "tool.path", &json!({"points": [[2, 2]]})).is_err()); +} + +#[test] +fn uv_path_strokes_in_texture_space() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]], "commit": true})).unwrap(); + assert!(red_uv(&s, 0.5, 0.45) && red_uv(&s, 0.2, 0.5) && red_uv(&s, 0.8, 0.5)); + assert!(!red_uv(&s, 0.5, 0.6)); +} + +#[test] +fn closed_filled_path_fills_the_inside_only() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let square = json!([[160, 160], [240, 160], [240, 240], [160, 240]]); + execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + for (x, y) in [(200.0, 200.0), (170.0, 170.0), (230.0, 230.0)] { + assert!(red_at(&s, x, y), "inside at {x},{y}"); + } + for (x, y) in [(200.0, 125.0), (275.0, 200.0), (125.0, 200.0), (200.0, 275.0)] { + assert!(!red_at(&s, x, y), "outside at {x},{y}"); + } + // The far side of the sphere, hidden from the camera, stays clean. + s.camera.yaw = std::f32::consts::PI; + assert!(!red_at(&s, 200.0, 200.0), "hidden back side"); + + // A 2D lasso fills the UV region. + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.3, 0.3], [0.7, 0.3], [0.7, 0.7], [0.3, 0.7]], "closed": true, "fill": true, "commit": true})).unwrap(); + assert!(red_uv(&s, 0.5, 0.5) && red_uv(&s, 0.35, 0.65)); + assert!(!red_uv(&s, 0.2, 0.5) && !red_uv(&s, 0.5, 0.85)); + // Options persist between paths; a filled path needs three points. + assert!(execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.1], [0.2, 0.2]], "closed": false, "commit": true})).is_ok()); + assert!(execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.1], [0.2, 0.2]], "closed": true, "fill": true, "commit": true})).is_err()); +} + +#[test] +fn closed_filled_path_is_symmetrized() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.brush", &json!({"symmetryX": true})).unwrap(); + + let square = json!([[230, 160], [270, 160], [270, 240], [230, 240]]); + execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&s, 250.0, 200.0), "the drawn side"); + assert!(red_at(&s, 150.0, 200.0), "the mirrored side"); + assert!(!red_at(&s, 200.0, 200.0), "between the two"); +} + +#[test] +fn closed_filled_path_copies_from_visible_source_to_backfacing_destination() { + let mut mesh = wall(); + for (position, normal) in mesh.positions.iter().zip(&mut mesh.normals) { + *normal = if position.x < 0.0 { Vec3::NEG_Z } else { Vec3::Z }; + } + + let mut s = session(mesh.clone()); + execute(&mut s, "tool.brush", &json!({"symmetryX": true})).unwrap(); + + let square = json!([[230, 170], [270, 170], [270, 230], [230, 230]]); + execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&s, 250.0, 200.0), "visible source"); + assert!(red_at(&s, 150.0, 200.0), "backfacing symmetry copy"); + assert!(!red_at(&s, 200.0, 200.0), "outside the lasso and its copy"); + + let mut s = session(mesh); + execute(&mut s, "tool.brush", &json!({"symmetryX": true})).unwrap(); + + let square = json!([[130, 170], [170, 170], [170, 230], [130, 230]]); + execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(!red_at(&s, 150.0, 200.0), "backfacing source"); + assert!(!red_at(&s, 250.0, 200.0), "no copy from a hidden source"); +} + +/// A 2×2 wall facing the camera (+Z): v grows downward (world −Y). +fn wall() -> Mesh { + let mut m = primitives::plane(2.0, 8); + for p in &mut m.positions { + *p = Vec3::new(p.x, -p.z, 0.0); + } + m.normals.iter_mut().for_each(|n| *n = Vec3::Z); + m.tangents.iter_mut().for_each(|t| *t = Vec4::new(1.0, 0.0, 0.0, 1.0)); + m +} + +/// Painted texel rows (v) after one particle dab at the wall's center. +fn particle_rows() -> Vec { + let mut s = session(wall()); + execute(&mut s, "tool.brush", &json!({"size": 10, "particles": {"enabled": true, "count": 6, "lifetime": 40, "gravity": 1.5}})).unwrap(); + let hit = s.pick(Vec2::new(200.0, 200.0), s.viewport).unwrap(); + assert!((hit.uv.y - 0.5).abs() < 0.02, "{hit:?}"); + execute(&mut s, "tool.stroke", &json!({"points": [[200, 200]]})).unwrap(); + let mut rows = Vec::new(); + for y in 0..RES as u32 { + for x in 0..RES as u32 { + let c = s.caches[0].composite.value(Channel::BaseColor, x, y); + if c[0] > 0.85 && c[1] < 0.5 { + rows.push(y); + } + } + } + rows +} + +#[test] +fn particle_brush_paints_below_the_start_and_is_deterministic() { + let rows = particle_rows(); + assert!(!rows.is_empty()); + let start = (0.5 * RES) as u32; + let lowest = rows.iter().max().copied().unwrap(); + let highest = rows.iter().min().copied().unwrap(); + assert!(lowest > start + 40, "trails run down the wall: {lowest}"); + assert!(highest + 20 > start, "nothing well above the start: {highest}"); + assert_eq!(rows, particle_rows()); +} + +#[test] +fn radial_symmetry_paints_copies_around_the_axis() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + assert!(execute(&mut s, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "w"})).is_err()); + let r = execute(&mut s, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "y"})).unwrap(); + assert_eq!(r["radialSymmetry"], json!({"copies": 2, "axis": "y"})); + execute(&mut s, "tool.stroke", &json!({"points": [[200, 200]]})).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 200.0)); + // Half a turn around Y: the copy faces the other way. + s.camera.yaw = std::f32::consts::PI; + assert!(red_at(&s, 200.0, 200.0), "the radial copy on the back"); +} + +/// The selected layer's content path sublayers: (effect id, stored paths). +fn path_sublayers(s: &Session) -> Vec<(u64, usize)> { + let l = s.doc.project.layer(s.selected_layer().unwrap()).unwrap(); + l.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id.0, p.len()))).collect() +} + +#[test] +fn committed_paths_stay_editable_in_a_path_sublayer() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = r["committed"]["effect"].as_u64().unwrap(); + assert_eq!(r["committed"]["index"], 0); + assert_eq!(path_sublayers(&s), vec![(eid, 1)]); + // The next path goes into the same (selected) sublayer. + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.9], [0.8, 0.9]], "commit": true})).unwrap(); + assert_eq!((r["committed"]["effect"].as_u64(), r["committed"]["index"].as_u64()), (Some(eid), Some(1))); + assert_eq!(path_sublayers(&s), vec![(eid, 2)]); + assert!(red_at(&s, 200.0, 180.0) && red_uv(&s, 0.5, 0.9)); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("\"paths\""), "inspect lists the paths"); + // Paths are saved with the project; editing a loaded path repaints only once it changes. + let saved = serde_json::to_string(&s.doc.project).unwrap(); + s.doc.project = serde_json::from_str(&saved).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 2)]); + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert!(!s.path_live().unwrap(), "a loaded path matches its settings"); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + + // Manual strokes can't paint over a path sublayer. + let err = execute(&mut s, "tool.stroke", &json!({"points": [[200, 240]]})).unwrap_err().to_string(); + assert!(err.contains("path sublayer"), "{err}"); + + // Edit the first path: moving its points repaints it live, the other path stays. + let undo_before = s.history_labels().len(); + let r = execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(r["points"], 3); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 250], [200, 230], [260, 250]]})).unwrap(); + assert_eq!(r["editing"]["index"], 0, "{r}"); + assert!(red_at(&s, 200.0, 230.0), "the edited curve shows at once"); + assert!(!red_at(&s, 200.0, 180.0), "the old curve is gone"); + assert!(red_uv(&s, 0.5, 0.9), "the other path is kept"); + // Brush changes repaint too, merged into the same undo step. + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + execute(&mut s, "tool.path", &json!({})).unwrap(); + assert!(!red_at(&s, 200.0, 230.0), "repainted with the new color"); + assert_eq!(s.history_labels().len(), undo_before + 1); + execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + assert_eq!(s.history_labels().len(), undo_before + 1, "one step for the whole edit"); + assert!(s.tool.path.editing.is_none() && s.tool.path.points.is_empty()); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 230.0), "undo restores the original path"); + + // Remove a path: its paint goes, the sublayer keeps the rest. + execute(&mut s, "path.remove", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 1)]); + assert!(!red_at(&s, 200.0, 180.0) && red_uv(&s, 0.5, 0.9)); + assert!(execute(&mut s, "path.edit", &json!({"effect": eid, "index": 5})).is_err()); + assert!(execute(&mut s, "path.remove", &json!({"effect": 999999, "index": 0})).is_err()); +} + +#[test] +fn undo_while_editing_a_path_stops_the_edit() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = r["committed"]["effect"].as_u64().unwrap(); + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 250], [200, 230], [260, 250]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.tool.path.editing.is_none()); + assert!(!s.path_live().unwrap(), "nothing repaints over the undone state"); + s.update(); + assert!(red_at(&s, 200.0, 180.0)); +} + +#[test] +fn each_path_and_each_edit_of_one_is_its_own_undo_step() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let steps = |s: &Session| s.history_labels().len(); + let start = steps(&s); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = r["committed"]["effect"].as_u64().unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.9], [0.8, 0.9]], "commit": true})).unwrap(); + assert_eq!(steps(&s), start + 2, "two paths, two steps"); + for y in [250, 230] { + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, y], [200, y - 20], [260, y]]})).unwrap(); + execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + } + assert_eq!(steps(&s), start + 4, "a second edit of the same path doesn't join the first"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 230.0), "undo brings back the first edit"); +} + +/// The pixels of every path sublayer of the selected layer, comparable +fn path_pixels(s: &Session) -> Vec { + let ids: Vec = path_sublayers(s).into_iter().map(|(id, _)| id).collect(); + let mut v: Vec = s.doc.pixels.layers.iter().filter(|((id, _), _)| ids.contains(&id.0)).map(|(k, img)| format!("{k:?}{img:?}")).collect(); + v.sort(); + v +} + +#[test] +fn placing_points_previews_the_path_with_no_undo_step_until_it_is_applied() { + let points = json!([[140, 210], [200, 180], [260, 210]]); + let mut direct = session(primitives::sphere(1.0, 48, 24)); + execute(&mut direct, "tool.path", &json!({"points": points, "commit": true})).unwrap(); + + let mut s = session(primitives::sphere(1.0, 48, 24)); + let start = s.history_labels(); + execute(&mut s, "tool.path", &json!({"points": [[140, 280], [260, 280]]})).unwrap(); + assert!(red_at(&s, 200.0, 280.0)); + execute(&mut s, "tool.path", &json!({"points": points})).unwrap(); + assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 280.0), "the preview follows the points"); + assert_eq!(s.history_labels(), start, "no undo step while placing"); + execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + assert_eq!(s.history_labels().len(), start.len() + 1, "applying is one undo step"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(path_pixels(&s), path_pixels(&direct), "the same pixels as applying without a preview"); + + // Cancelling removes the preview + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(red_at(&s, 200.0, 250.0)); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0) && red_at(&s, 200.0, 180.0)); + assert_eq!(s.history_labels().len(), start.len() + 1); +} + +#[test] +fn undo_while_placing_removes_the_preview_only() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0), "the preview is gone"); + assert!(red_at(&s, 200.0, 180.0), "the applied path stays"); + assert_eq!(s.history_labels().len(), steps); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none()); +} + +#[test] +fn another_change_while_placing_makes_the_path_its_own_step_first() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let labels = s.history_labels(); + assert_eq!(labels.len(), steps + 2); + assert_eq!(labels.get(steps).map(String::as_str), Some("Path")); + // Undoing the other change keeps the path; undoing again removes it + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 180.0)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 180.0)); +} + +#[test] +fn editing_another_path_while_placing_applies_the_new_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = r["committed"]["effect"].as_u64().unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 2)], "the new path was applied"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(s.tool.path.editing, Some((texturecraft_engine::core::LayerId(eid), 0))); +} + +#[test] +fn the_next_path_starts_open_after_a_closed_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "closed": true, "commit": true})).unwrap(); + assert!(!s.tool.path.closed, "applying a closed path leaves the tool open for the next one"); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]], "closed": true})).unwrap(); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + assert!(!s.tool.path.closed, "cancelling does too"); +} + +/// A short path's repaint marks under 1/N of a 1024-texel set's 256 tiles +const SHORT_PATH_TILE_SHARE_DIVISOR: usize = 4; + +/// Move the middle point of the Path tool's curve down to viewport row `y` and repaint, returning the (dirty, all) tile counts +fn move_middle_point(s: &mut Session, y: f32) -> (usize, usize) { + s.tool.path.points[1] = s.pick(Vec2::new(200.0, y), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len()) +} + +#[test] +fn moving_a_point_recomposites_only_the_paths_tiles() { + // 1024 texels: 256 tiles, so a short path covers few of them + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:test", None, 1024).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + (s.camera.yaw, s.camera.pitch) = (0.0, 0.0); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + s.update(); + + let (dirty, all) = move_middle_point(&mut s, 190.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "a new path: {dirty} of {all} tiles to recomposite"); + s.update(); + + let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": r["committed"]["effect"], "index": 0})).unwrap(); + s.update(); + // Another row than the applied one, so the edit changes the path + let (dirty, all) = move_middle_point(&mut s, 200.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "an applied path being edited: {dirty} of {all} tiles to recomposite"); +} + +#[test] +fn another_change_ends_the_point_undo_of_an_edited_path() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = texturecraft_engine::core::LayerId(r["committed"]["effect"].as_u64().unwrap()); + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 0})).unwrap(); + s.path_checkpoint(); + s.tool.path.points[1] = s.pick(Vec2::new(200.0, 230.0), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + let moved: Vec<[f32; 3]> = s.tool.path.points.iter().map(|p| p.to_array()).collect(); + let layers = s.doc.project.layers.len(); + + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layers.len(), layers, "undo removes the new layer"); + assert_eq!(s.paths(eid).unwrap()[0].points, moved, "the path keeps its moved point"); +} + +#[test] +fn placing_a_path_ends_redo() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.can_redo()); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(!s.can_redo(), "redo would throw the path being placed away"); +} + +#[test] +fn switching_texture_sets_applies_the_path_being_placed() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]]})).unwrap(); + + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1); + assert_eq!(s.undo_label(), Some("Path")); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none(), "the path no longer paints into the other set"); +} + +#[test] +fn applying_after_orbit_preserves_preview_pixels_and_storage() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + let preview = session.doc.clone(); + let steps = session.history_labels().len(); + session.camera.yaw += 0.6; + session.viewport = Vec2::new(600.0, 400.0); + assert!(!session.path_live().unwrap()); + + execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); + + assert_eq!(session.doc.project, preview.project, "apply must keep the preview's camera and viewport"); + assert_eq!(session.doc.pixels.layers, preview.pixels.layers, "apply must keep the preview pixels"); + for (key, image) in &preview.pixels.layers { + for (x, y) in image.allocated() { + assert!(std::sync::Arc::ptr_eq(image.tile_handle(x, y).unwrap(), session.doc.pixels.layers[key].tile_handle(x, y).unwrap())); + } + } + assert_eq!(session.history_labels().len(), steps + 1); +} + +#[test] +fn applying_an_unchanged_stored_path_after_orbit_adds_no_history() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let before = session.doc.clone(); + let history = session.history_labels(); + session.camera.yaw += 0.6; + assert!(!session.path_live().unwrap()); + + execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); + + assert_eq!(session.history_labels(), history, "accepting an unchanged path is not an edit"); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert!(session.tool.path.editing.is_none()); +} + +#[test] +fn removing_the_final_preview_point_removes_its_pixels() { + let mut session = session(wall()); + let before = session.doc.clone(); + let history = session.history_labels(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]]})).unwrap(); + assert!(!path_sublayers(&session).is_empty()); + + session.path_checkpoint(); + session.tool.path.remove_selected(); + assert!(session.path_live().unwrap()); + session.update(); + + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.history_labels(), history); + assert!(session.tool.path.editing.is_none()); +} + +#[test] +fn preview_uses_the_commands_explicit_viewport() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + let params = json!({"points": [[170, 210], [200, 180], [230, 210]], "viewport": [400, 600]}); + execute(&mut session, "tool.path", ¶ms).unwrap(); + let preview = path_pixels(&session); + let (effect, index) = session.tool.path.editing.unwrap(); + + let mut direct = self::session(primitives::sphere(1.0, 48, 24)); + let mut params = params; + params["commit"] = json!(true); + execute(&mut direct, "tool.path", ¶ms).unwrap(); + + assert_eq!(session.paths(effect).unwrap()[index].viewport, [400.0, 600.0]); + assert_eq!(preview, path_pixels(&direct)); +} + +/// An opposite-view placement must preserve the stored curve, painted pixels and point redo +#[test] +fn stored_paths_ignore_point_placement_from_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let params = + if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true}) } else { json!({"points": [[140, 210], [260, 210]], "commit": true}) }; + let report = execute(&mut session, "tool.path", ¶ms).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let (effect, index) = session.tool.path.editing.unwrap(); + let uv_point = Vec3::new(0.5, 0.6, 0.0); + let world_point = session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos; + assert_eq!(session.append_path_point(if uv { uv_point } else { world_point }, uv), Some(2)); + session.path_live().unwrap(); + let extended = session.tool.path.points.clone(); + session.undo().unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + + let placed = session.append_path_point(if uv { world_point } else { uv_point }, !uv); + session.path_live().unwrap(); + + assert_eq!(session.paths(effect).unwrap()[index].uv, uv, "the stored path must keep its coordinate space"); + assert_eq!(placed, None); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.doc.pixels.masks, before.pixels.masks); + assert_eq!(session.history_labels(), history); + assert!(session.can_redo(), "ignored placement must preserve point redo"); + + session.redo().unwrap(); + assert_eq!(session.tool.path.points, extended); + } +} + +/// A new, uncommitted curve can still switch views and cancel without changing the document +#[test] +fn draft_paths_can_switch_to_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let before = session.doc.clone(); + let history = session.history_labels(); + let params = if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]}) } else { json!({"points": [[140, 210], [260, 210]]}) }; + execute(&mut session, "tool.path", ¶ms).unwrap(); + let point = if uv { session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos } else { Vec3::new(0.5, 0.6, 0.0) }; + + assert_eq!(session.append_path_point(point, !uv), Some(0)); + session.path_live().unwrap(); + + assert_eq!(session.tool.path.points, vec![point]); + assert_eq!(session.tool.path.uv, !uv); + assert_eq!(session.history_labels(), history); + session.cancel_path(); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + } +} + +/// Headless history commands must restore geometry and pixels before any frame or subsequent edit +#[test] +fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + let original_pixels = session.doc.pixels.clone(); + let history = session.history_labels().len(); + session.insert_path_point(1, Vec3::new(0.5, 0.5, 0.0)); + session.path_live().unwrap(); + let inserted = session.tool.path.points.clone(); + let inserted_pixels = session.doc.pixels.clone(); + session.move_path_point(1, Vec3::new(0.5, 0.6, 0.0), true); + session.move_path_point(1, Vec3::new(0.5, 0.7, 0.0), false); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + let moved_pixels = session.doc.pixels.clone(); + session.remove_selected_path_point(); + session.path_live().unwrap(); + let removed = session.tool.path.points.clone(); + let removed_pixels = session.doc.pixels.clone(); + + for (expected, pixels) in [(&moved, &moved_pixels), (&inserted, &inserted_pixels), (&original, &original_pixels)] { + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); + } + + session.select_path_point(0); + assert!(session.can_redo(), "selection must preserve point redo"); + for (expected, pixels) in [(&inserted, &inserted_pixels), (&moved, &moved_pixels), (&removed, &removed_pixels)] { + execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); + } + assert_eq!(session.history_labels().len(), history + 1, "all point edits share one document step"); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(session.paths(effect).unwrap()[0].points, moved.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, moved_pixels.layers, "a subsequent command keeps the undone path pixels"); +} + +/// A bad path above the edited one must not consume undo or redo when repainting fails +#[test] +fn point_history_repaint_errors_preserve_the_edit_and_can_be_retried() { + use texturecraft_engine::core::{EffectKind, LayerId}; + + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let effect = LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap(); + let paint = session.paths(effect).unwrap()[1].paint.clone(); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + + for (command, expected) in [("edit.undo", &original), ("edit.redo", &moved)] { + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = Value::Null; + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = (session.history_labels(), session.redo_labels()); + + let error = execute(&mut session, command, &Value::Null).unwrap_err(); + + assert!(error.to_string().contains("unreadable path settings"), "{error}"); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!((session.history_labels(), session.redo_labels()), history); + + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = paint.clone(); + execute(&mut session, command, &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected, "the failed step remains available"); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + } +} + +/// Point history repaints an uncommitted preview without creating document undo steps +#[test] +fn draft_point_history_repaints_immediately_and_undoing_all_points_cancels() { + let mut session = session(wall()); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + let before = session.doc.clone(); + let history = session.history_labels(); + session.append_path_point(Vec3::new(0.2, 0.5, 0.0), true); + session.path_live().unwrap(); + let one_point = session.doc.clone(); + session.append_path_point(Vec3::new(0.8, 0.5, 0.0), true); + session.path_live().unwrap(); + let two_points = session.doc.clone(); + + for (command, expected) in [("edit.undo", &one_point), ("edit.redo", &two_points), ("edit.undo", &one_point), ("edit.undo", &before)] { + execute(&mut session, command, &Value::Null).unwrap(); + + assert_eq!(session.doc.project, expected.project); + assert_eq!(session.doc.pixels.layers, expected.pixels.layers); + assert_eq!(session.history_labels(), history); + } + assert!(session.tool.path.points.is_empty()); + assert!(session.tool.path.editing.is_none()); +} + +#[test] +fn removing_the_final_stored_point_removes_the_path_and_undo_restores_it() { + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let before = session.doc.clone(); + + session.remove_selected_path_point(); + assert!(session.path_live().unwrap()); + + assert!(session.paths(effect).unwrap().is_empty()); + assert!(session.doc.pixels.layers.keys().all(|(id, _)| *id != effect)); + assert!(session.tool.path.editing.is_none()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); +} diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/it/perf.rs similarity index 82% rename from crates/engine/tests/perf.rs rename to crates/engine/tests/it/perf.rs index 46ff0780..9251b9b7 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/it/perf.rs @@ -384,7 +384,7 @@ fn bench_undo_at(res: u32, blur: bool) { s.update(); let label = if blur { "blur mask kept" } else { "no neighbourhood filters" }; println!("[{res}², {label}] setup {:.2?} ({} covered tiles)", t.elapsed(), s.caches[0].covered_tiles.len()); - // The first stroke on a layer creates its images (and recomposites everything when undone). + // Seed the layer image before measuring partial undo execute(&mut s, "tool.stroke", &json!({"points": [[500, 500], [520, 510]]})).unwrap(); execute(&mut s, "tool.stroke", &json!({"points": [[300, 300], [330, 310]]})).unwrap(); s.update(); @@ -398,7 +398,7 @@ fn bench_undo_at(res: u32, blur: bool) { #[test] #[ignore] fn bench_undo() { - // 4096 only: the 8192 setup takes many minutes under load. + // The 8192 setup takes many minutes under load let res = 4096; bench_undo_at(res, true); bench_undo_at(res, false); @@ -435,3 +435,90 @@ fn bench_8k_resize() { println!("[resize] dilation {:.2?}", t.elapsed()); drop(d); } + +/// Layer-panel thumbnails on the 4K stack: the snapshot, each kind of picture, and a whole panel. +#[test] +#[ignore] +fn bench_layer_thumbs_4k() { + use texturecraft_engine::compose::ThumbTarget; + use texturecraft_engine::core::Channel; + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + let s = stack(4096); + let ts = s.ts(); + let mut gbufs = GbufCache::default(); + let t = Instant::now(); + let snap = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let first = t.elapsed(); + let t = Instant::now(); + let _again = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let cached = t.elapsed(); + let p = &s.doc.project; + let mut targets = Vec::new(); + for l in p.layers.values() { + targets.push(("content", ThumbTarget::Content { layer: l.id, channel: Channel::BaseColor })); + if l.mask.is_some() { + targets.push(("mask", ThumbTarget::Mask { layer: l.id })); + } + for e in l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()) { + targets.push(("stage", ThumbTarget::Stage { effect: e.id, channel: Channel::BaseColor })); + } + } + let mut per: std::collections::BTreeMap<&str, (Duration, usize, Duration)> = Default::default(); + let all = Instant::now(); + for (kind, target) in &targets { + let t = Instant::now(); + let _ = snap.render(*target); + let d = t.elapsed(); + let e = per.entry(kind).or_default(); + e.0 += d; + e.1 += 1; + e.2 = e.2.max(d); + } + let total = all.elapsed(); + eprintln!("layer thumbnails, 4096 set, {} layers, 64 px:", p.layers.len()); + eprintln!(" snapshot: {:.2} ms first (with the 64 px G-buffer), {:.2} ms after", first.as_secs_f64() * 1e3, cached.as_secs_f64() * 1e3); + for (kind, (sum, n, max)) in per { + eprintln!(" {kind:8} {n:3} × avg {:.2} ms, max {:.2} ms", sum.as_secs_f64() * 1e3 / n as f64, max.as_secs_f64() * 1e3); + } + eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len()); +} + +/// A full recomposite in one call against the same one spread over frames, as the UI runs it, with and without a blurred mask +/// in the stack: neighbourhood filters are what a frame slice pays for apart from its own tiles. +#[test] +#[ignore] +fn bench_sliced_filters_4k() { + for blur in [false, true] { + let mut session = Session::new_project("sliced", primitives::sphere(1.0, 64, 32), "builtin:sphere", None, 4096).unwrap(); + session.viewport = Vec2::new(800.0, 800.0); + let run = |session: &mut Session, id: &str, params: Value| execute(session, id, ¶ms).unwrap(); + run(&mut session, "layer.add.fill", json!({"color": [0.6, 0.5, 0.4], "roughness": 0.6})); + run(&mut session, "layer.add.fill", json!({"color": [0.1, 0.3, 0.6]})); + run(&mut session, "mask.add.black", Value::Null); + run(&mut session, "effect.add.generator", json!({"generator": "position", "level": 0.5})); + if blur { + run(&mut session, "effect.add.filter", json!({"filter": "blur", "radius": 8})); + } + + session.update(); + + session.caches[0].invalidate_all(); + let started = Instant::now(); + session.update(); + let direct = started.elapsed(); + + session.caches[0].invalidate_all(); + let clock = Instant::now(); + let elapsed_ms = || clock.elapsed().as_secs_f64() * 1000.0; + let (mut frames, mut longest_frame) = (0, Duration::ZERO); + while session.pending_tiles() > 0 { + let started = Instant::now(); + session.update_for(30.0, elapsed_ms); + longest_frame = longest_frame.max(started.elapsed()); + frames += 1; + } + + let label = if blur { "blurred mask" } else { "no filter" }; + println!("[sliced 4096², {label}] one call {direct:.2?}; in 30 ms slices {frames} frames, worst {longest_frame:.2?}, total {:.2?}", clock.elapsed()); + } +} 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/it/project_recovery.rs b/crates/engine/tests/it/project_recovery.rs new file mode 100644 index 00000000..90612b56 --- /dev/null +++ b/crates/engine/tests/it/project_recovery.rs @@ -0,0 +1,35 @@ +use std::io::{Cursor, Write}; + +use serde_json::json; +use texturecraft_engine::{Session, execute, geom::primitives}; +use zip::{ZipWriter, write::SimpleFileOptions}; + +#[test] +fn recovered_project_opens_with_a_warning_in_the_session_log() { + let mut original = Session::new_project("Recovery", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + execute(&mut original, "layer.add.fill", &json!({"color": "#336699"})).unwrap(); + let mut json = serde_json::to_value(&original.doc.project).unwrap(); + json["texture_sets"][0]["bake"]["maps"] = json!(["Normal", "AmbientOcclusion"]); + let mut archive = ZipWriter::new(Cursor::new(Vec::new())); + archive.start_file("project.json", SimpleFileOptions::default()).unwrap(); + archive.write_all(&serde_json::to_vec(&json).unwrap()).unwrap(); + let bytes = archive.finish().unwrap().into_inner(); + + let recovered = Session::from_project_bytes(&bytes).unwrap(); + assert_eq!(recovered.doc.project, original.doc.project); + let warnings: Vec<_> = recovered.log.iter().filter(|message| message.starts_with("Warning:")).collect(); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("could not be imported")); + assert!(warnings[0].contains("recovered what it could")); + + let reopened = Session::from_project_bytes(&recovered.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project, original.doc.project); + assert!(!reopened.log.iter().any(|message| message.starts_with("Warning:"))); + + let path = std::env::temp_dir().join(format!("texturecraft-recovery-{}.tcraft", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + execute(&mut original, "file.open", &json!({"path": path})).unwrap(); + assert_eq!(original.log, recovered.log); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + std::fs::remove_file(path).unwrap(); +} 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/it/symmetry.rs b/crates/engine/tests/it/symmetry.rs new file mode 100644 index 00000000..6beb03cc --- /dev/null +++ b/crates/engine/tests/it/symmetry.rs @@ -0,0 +1,283 @@ +//! Symmetry around a moved plane or axis, driven through engine commands the way agents paint + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; +use texturecraft_engine::geom::{Mesh, primitives}; +use texturecraft_engine::{Session, execute}; + +const TEXTURE_SIZE: f32 = 256.0; +const VIEWPORT: f32 = 400.0; + +fn session(mesh: Mesh) -> Session { + let mut session = Session::new_project("t", mesh, "builtin:test", None, TEXTURE_SIZE as u32).unwrap(); + session.viewport = Vec2::splat(VIEWPORT); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + session +} + +/// A 2×2 wall in the XY plane facing the camera (+Z) +fn wall() -> Mesh { + let mut mesh = primitives::plane(2.0, 8); + for point in &mut mesh.positions { + *point = Vec3::new(point.x, -point.z, 0.0); + } + mesh.normals.iter_mut().for_each(|normal| *normal = Vec3::Z); + mesh.tangents.iter_mut().for_each(|tangent| *tangent = Vec4::new(1.0, 0.0, 0.0, 1.0)); + mesh +} + +/// Viewport pixel of world `point` +fn screen(session: &Session, point: Vec3) -> Vec2 { + let ndc = session.camera.project(point, 1.0).unwrap(); + Vec2::new((ndc.x * 0.5 + 0.5) * VIEWPORT, (0.5 - ndc.y * 0.5) * VIEWPORT) +} + +/// Is the surface at world `point` painted red? +fn red_at(session: &Session, point: Vec3) -> bool { + let hit = session.pick(screen(session, point), session.viewport).unwrap(); + let color = session.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * TEXTURE_SIZE) as u32, (hit.uv.y * TEXTURE_SIZE) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +/// Where a viewport pixel lands on the mesh +fn surface(session: &Session, x: f32, y: f32) -> Vec3 { + session.pick(Vec2::new(x, y), session.viewport).unwrap().pos +} + +#[test] +fn a_moved_mirror_plane_paints_the_copy_at_the_mirrored_point() { + let mut session = session(wall()); + let reply = execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.25, 0.0, 0.0]})).unwrap(); + + // Right of the view's center, on the wall + let stroke = surface(&session, 300.0, 200.0); + execute(&mut session, "tool.stroke", &json!({"points": [[300, 200]]})).unwrap(); + session.update(); + + let mirrored = Vec3::new(0.5 - stroke.x, stroke.y, stroke.z); + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, mirrored), "its copy across x = 0.25"); + assert!(!red_at(&session, Vec3::new(-stroke.x, stroke.y, stroke.z)), "nothing across the mesh center"); + assert_eq!(reply["symmetryOffset"], json!([0.25, 0.0, 0.0]), "agents read the offset back"); +} + +#[test] +fn radial_copies_turn_around_the_moved_axis() { + let mut session = session(wall()); + let axis = Vec3::new(0.2, -0.1, 0.0); + execute(&mut session, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "z", "symmetryOffset": axis.to_array()})).unwrap(); + + // Up and right of the view's center, on the wall + let stroke = surface(&session, 290.0, 160.0); + execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap(); + session.update(); + + // Half a turn around Z through the moved axis + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, axis * 2.0 - stroke), "its copy half a turn around the moved axis"); + assert!(!red_at(&session, Vec3::new(-stroke.x, -stroke.y, 0.0)), "nothing around the mesh center"); +} + +#[test] +fn a_closed_path_fill_mirrors_around_the_moved_plane() { + let mut session = session(wall()); + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [-0.2, 0.0, 0.0]})).unwrap(); + + // A small square right of the view's center, on the wall + let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + let inside = surface(&session, 265.0, 200.0); + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, Vec3::new(-0.4 - inside.x, inside.y, 0.0)), "its copy across x = -0.2"); + assert!(!red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), "nothing across the mesh center"); +} + +#[test] +fn a_closed_path_fill_reaches_a_curved_copy_across_a_moved_plane() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + + // Occlusion must still protect the rear surface when normal-based culling is disabled + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0], "backfaceCulling": false})).unwrap(); + let inside = surface(&session, 185.0, 200.0); + let mirrored_x = 0.2 - inside.x; + let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt()); + + let square = json!([[175, 190], [195, 190], [195, 210], [175, 210]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, copy), "its copy where the sphere curves away across x = 0.1"); + + session.camera.yaw = std::f32::consts::PI; + assert!(!red_at(&session, Vec3::new(copy.x, copy.y, -copy.z)), "the hidden back of the copy stays clean"); + assert!(!red_at(&session, Vec3::new(inside.x, inside.y, -inside.z)), "the hidden back of the source stays clean"); +} + +#[test] +fn a_closed_path_fill_reaches_a_copy_in_front_of_the_source_surface() { + for ortho in [false, true] { + for screen_space in [false, true] { + let mut session = session(primitives::sphere(1.0, 48, 24)); + session.camera.ortho = ortho; + execute(&mut session, "tool.brush", &json!({"size": 10, "screenSpace": screen_space, "symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]})) + .unwrap(); + let inside = surface(&session, 235.0, 200.0); + let mirrored_x = 0.2 - inside.x; + let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt()); + assert!(copy.z > inside.z + 0.01, "the copy must be nearer the camera than its source"); + + let square = json!([[225, 190], [245, 190], [245, 210], [225, 210]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, copy), "the ray must reach the source: ortho={ortho}, screen_space={screen_space}"); + } + } +} + +#[test] +fn screen_space_fill_copy_depth_is_limited_at_the_source_hit() { + // The source hit allows about 0.071 world units; the search bound allows about 0.122 + for (displacement, painted) in [(-0.074, false), (0.068, true), (0.1, false)] { + let mut session = session(wall()); + session.camera.ortho = true; + session.camera.distance = 1.0; + execute( + &mut session, + "tool.brush", + &json!({"size": 10, "screenSpace": true, "symmetryRadial": 2, "symmetryAxis": "y", "symmetryOffset": [0.0, 0.0, displacement * 0.5]}), + ) + .unwrap(); + let inside = surface(&session, 265.0, 200.0); + + let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert_eq!(red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), painted, "source displacement {displacement}"); + } +} + +/// How much redder than green a texel must be to count as painted (faded edges included) +const PAINTED_TINT: f32 = 0.05; + +/// Texels tinted red in the top and bottom half of the texture +fn painted_halves(session: &Session) -> (usize, usize) { + let painted = |x: u32, y: u32| { + let color = session.caches[0].composite.value(Channel::BaseColor, x, y); + color[0] - color[1] > PAINTED_TINT + }; + let half = TEXTURE_SIZE as u32 / 2; + let count = |rows: std::ops::Range| rows.flat_map(|y| (0..TEXTURE_SIZE as u32).map(move |x| (x, y))).filter(|&(x, y)| painted(x, y)).count(); + (count(0..half), count(half..TEXTURE_SIZE as u32)) +} + +#[test] +fn a_mirror_copy_paints_exactly_where_its_stroke_does() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.brush", &json!({"size": 4, "symmetryY": true})).unwrap(); + + // From the middle of the view to past the ball's right edge, above center, where it fades out; the copy below must fade the same way + let points: Vec = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect(); + execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap(); + session.update(); + + let (stroke, copy) = painted_halves(&session); + assert!(stroke > 0); + // Within 4%: the ball's texture layout is not exactly symmetric texel for texel + assert!(stroke.abs_diff(copy) * 25 <= stroke, "stroke {stroke} texels, copy {copy}"); +} + +#[test] +fn a_copy_paints_on_a_curved_mesh_across_a_moved_plane() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]})).unwrap(); + + // Left of the view's center; across x = 0.1 its copy lands where the ball curves away a little more + let stroke = surface(&session, 185.0, 200.0); + execute(&mut session, "tool.stroke", &json!({"points": [[185, 200]]})).unwrap(); + session.update(); + + let mirrored_x = 0.2 - stroke.x; + let on_ball = Vec3::new(mirrored_x, stroke.y, (1.0 - mirrored_x * mirrored_x - stroke.y * stroke.y).sqrt()); + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, on_ball), "its copy on the ball across x = 0.1"); +} + +#[test] +fn symmetry_offsets_require_exactly_three_finite_numbers() { + let mut session = session(wall()); + let invalid = [json!([1, 2, 3, null]), json!([null, 1, 2, 3]), json!([1, "bad", 2, 3]), json!([1, 2, 3, 1e100]), json!([1, 2]), json!([1, 2, 1e100])]; + + for offset in invalid { + let result = execute(&mut session, "tool.brush", &json!({"symmetryOffset": offset})); + + assert!(result.is_err(), "accepted malformed offset: {offset}"); + } +} + +#[test] +fn invalid_brush_settings_leave_the_tool_unchanged() { + let mut session = session(wall()); + let before = session.tool.clone(); + let revision = session.revision; + + for invalid in [ + json!({"size": 20, "symmetryOn": false, "symmetryOffset": [1, 2]}), + json!({"size": 20, "symmetryAxis": "bad"}), + json!({"symmetryOffset": [0.2, 0, 0], "smudgeStrength": 70, "cloneSource": "bad"}), + ] { + let result = execute(&mut session, "tool.brush", &invalid); + + assert!(result.is_err()); + assert_eq!(session.tool, before, "a rejected partial update must not change the tool"); + assert_eq!(session.revision, revision); + } +} + +#[test] +fn symmetry_commands_report_effective_limits_and_keep_updates_out_of_history() { + let mut session = session(wall()); + let history = session.history_labels(); + + for (span, expected) in [(-20.0, 0.0), (120.0, 120.0), (500.0, 360.0)] { + let reply = execute(&mut session, "tool.brush", &json!({"symmetryAngleSpan": span, "symmetryOffset": [1e30, -1e30, 0.25]})).unwrap(); + + assert_eq!(reply["symmetryAngleSpan"], json!(expected)); + assert_eq!(reply["symmetryOffset"], json!([1e6, -1e6, 0.25])); + assert_eq!(session.tool.brush, session.tool.brush.sanitized()); + } + assert_eq!(session.history_labels(), history); +} + +#[test] +fn disabling_symmetry_paints_only_the_source_and_keeps_the_settings() { + for radial in [false, true] { + let mut session = session(wall()); + execute(&mut session, "tool.brush", &json!({"symmetryX": !radial, "symmetryRadial": if radial { 2 } else { 0 }, "symmetryAxis": "z"})).unwrap(); + let settings = session.tool.brush.symmetry; + let stroke = surface(&session, 290.0, 160.0); + let copy = if radial { -stroke } else { Vec3::new(-stroke.x, stroke.y, stroke.z) }; + + execute(&mut session, "tool.brush", &json!({"symmetryOn": false})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap(); + session.update(); + + assert!(red_at(&session, stroke)); + assert!(!red_at(&session, copy), "disabled symmetry must not paint its copy"); + assert_eq!(session.tool.brush.symmetry, texturecraft_engine::paint::Symmetry { enabled: false, ..settings }); + + execute(&mut session, "tool.brush", &json!({"symmetryOn": true})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap(); + session.update(); + + assert!(red_at(&session, copy), "enabling symmetry restores its copies"); + assert_eq!(session.tool.brush.symmetry, settings); + } +} diff --git a/crates/engine/tests/it/thumbs.rs b/crates/engine/tests/it/thumbs.rs new file mode 100644 index 00000000..f5f32a5e --- /dev/null +++ b/crates/engine/tests/it/thumbs.rs @@ -0,0 +1,439 @@ +//! Layer-panel thumbnails: they equal a plain CPU evaluation of the same sub-stack at 64 px, +//! follow edits, drop stale and vanished work, and only render what was asked for. + +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use texturecraft_engine::compose::{Inputs, ThumbImage, ThumbTarget, all_tiles, flatten_layer, mask_image}; +use texturecraft_engine::core::{Channel, ChannelKind, LayerId}; +use texturecraft_engine::geom::UvGBuffer; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::texel::{from_u16, from_u16_signed, linear_to_srgb}; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; +use texturecraft_engine::{Session, execute}; + +const N: u32 = 64; + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, 256).unwrap() +} + +fn id(v: Value, key: &str) -> LayerId { + LayerId(v[key].as_u64().unwrap()) +} + +/// A fill layer with two content effects (invert, then posterize) and a masked generator. +struct Stack { + layer: LayerId, + invert: LayerId, + posterize: LayerId, + gen_: LayerId, +} + +fn stack(s: &mut Session) -> Stack { + let layer = id(execute(s, "layer.add.fill", &json!({"color": "#336699", "roughness": 0.2})).unwrap(), "layer"); + let invert = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let posterize = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "posterize"})).unwrap(), "effect"); + execute(s, "mask.add.black", &Value::Null).unwrap(); + let gen_ = id(execute(s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + Stack { layer, invert, posterize, gen_ } +} + +fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, gbuf: &'a UvGBuffer) -> Inputs<'a> { + static EMPTY_BAKED: std::sync::LazyLock = std::sync::LazyLock::new(Default::default); + let baked = s.doc.baked.get(&0).unwrap_or(&EMPTY_BAKED); + Inputs { + project, + ts: 0, + mesh: &s.mesh, + gbuf, + pixels: &s.doc.pixels, + baked, + block_scales: Default::default(), + preview: None, + images: &s.images, + bounds: s.mesh.bounds(), + } +} + +/// The reference: the same sub-stack cut by hand and evaluated at 64 px with the ordinary CPU +/// evaluator (the mask with `mask_image`, the content with `flatten_layer`), then encoded. +fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { + let gbuf = UvGBuffer::new(&s.mesh, 0, N, N); + let mut p = s.doc.project.clone(); + let (layer, upto, channel) = match target { + ThumbTarget::Content { layer, channel } => (layer, None, channel), + ThumbTarget::Mask { layer } => (layer, None, Channel::BaseColor), + ThumbTarget::Stage { effect, channel } => (p.effect(effect).unwrap().0, Some(effect), channel), + }; + let l = p.layers.get_mut(&layer).unwrap(); + l.visible = true; + let in_mask = upto.is_some_and(|e| l.mask.as_ref().is_some_and(|m| m.effects.iter().any(|x| x.id == e))) || matches!(target, ThumbTarget::Mask { .. }); + if in_mask { + let m = l.mask.as_mut().unwrap(); + m.enabled = true; + if let Some(e) = upto { + let k = m.effects.iter().position(|x| x.id == e).unwrap(); + m.effects.truncate(k + 1); + } + let gray = mask_image(&inputs(s, &p, &gbuf), layer, N).unwrap(); + let rgba = gray.iter().enumerate().flat_map(|(i, g)| [*g, *g, *g, if gbuf.covered(i) { 255 } else { 0 }]).collect(); + return ThumbImage { width: N, height: N, rgba }; + } + l.mask = None; + l.channels.insert(channel, texturecraft_engine::core::ChannelBlend::default()); + if let Some(e) = upto { + let k = l.content_effects.iter().position(|x| x.id == e).unwrap(); + l.content_effects.truncate(k + 1); + } + // A paint or fill layer: its own (premultiplied value, coverage), coverage as alpha. + let flat = flatten_layer(&inputs(s, &p, &gbuf), layer, &all_tiles(N, N)).unwrap(); + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let mut rgba = vec![0u8; (N * N * 4) as usize]; + let comps = channel.components(); + for (_, _, buf) in flat.iter().filter(|(c, _, _)| *c == channel) { + for (i, px) in buf.chunks_exact(comps + 1).enumerate() { + let a = from_u16(px[comps]); + if a <= 0.0 { + continue; + } + let v: [f32; 3] = std::array::from_fn(|k| { + let raw = px[k.min(comps - 1)]; + (if channel.kind() == ChannelKind::Signed { from_u16_signed(raw) } else { from_u16(raw) }) / a + }); + let px = match channel.kind() { + ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)), + _ => v.map(byte), + }; + rgba[i * 4..i * 4 + 4].copy_from_slice(&[px[0], px[1], px[2], byte(a)]); + } + } + ThumbImage { width: N, height: N, rgba } +} + +/// Frames of `svc` until every target is current (or a timeout). +fn settle(svc: &mut ThumbService, s: &Session, targets: &[ThumbTarget], clock: &mut f64) { + let t0 = Instant::now(); + loop { + *clock += 0.2; + svc.begin_frame(s, *clock); + for t in targets { + svc.get(s, *t); + } + svc.poll(s); + if targets.iter().all(|t| svc.is_fresh(*t)) { + return; + } + assert!(t0.elapsed() < Duration::from_secs(60), "thumbnails never settled"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn image(svc: &mut ThumbService, s: &Session, t: ThumbTarget) -> ThumbImage { + (*svc.get(s, t).image.expect("a picture")).clone() +} + +#[test] +fn thumbnails_equal_a_cpu_evaluation_of_the_same_sub_stack() { + let mut session = session(); + let stack = stack(&mut session); + let base_color = Channel::BaseColor; + let targets = [ + ThumbTarget::Content { layer: stack.layer, channel: base_color }, + ThumbTarget::Content { layer: stack.layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer: stack.layer }, + ThumbTarget::Stage { effect: stack.invert, channel: base_color }, + ThumbTarget::Stage { effect: stack.posterize, channel: base_color }, + ThumbTarget::Stage { effect: stack.gen_, channel: base_color }, + ]; + let (mut service, mut clock) = (ThumbService::new(), 0.0); + + settle(&mut service, &session, &targets, &mut clock); + + for target in targets { + assert_eq!(image(&mut service, &session, target), oracle(&session, target), "{target:?}"); + } + + // The first stage inverts #336699 in linear light + let inverted = image(&mut service, &session, targets[3]); + let pixel = inverted.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + let expected = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; + assert!((i32::from(pixel[0]) - expected(51.0)).abs() <= 1 && (i32::from(pixel[2]) - expected(153.0)).abs() <= 1, "{pixel:?}"); + + // A position generator must produce a nonuniform mask + let mask = image(&mut service, &session, targets[2]); + let grays: Vec = mask.rgba.as_chunks::<4>().0.iter().filter(|pixel| pixel[3] == 255).map(|pixel| pixel[0]).collect(); + assert!(grays.iter().max() != grays.iter().min()); +} + +#[test] +fn earlier_stages_never_show_later_effects_and_hidden_effects_are_bypassed() { + let mut s = session(); + let st = stack(&mut s); + let base = Channel::BaseColor; + let (first, second) = (ThumbTarget::Stage { effect: st.invert, channel: base }, ThumbTarget::Stage { effect: st.posterize, channel: base }); + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[first, second], &mut clock); + let (a, b) = (image(&mut svc, &s, first), image(&mut svc, &s, second)); + // Hide the second effect: its stage now shows the first one's result; the first is unchanged. + execute(&mut s, "effect.set", &json!({"effect": st.posterize.0, "visible": false})).unwrap(); + settle(&mut svc, &s, &[first, second], &mut clock); + assert_eq!(image(&mut svc, &s, first), a); + assert_eq!(image(&mut svc, &s, second), a); + assert_ne!(a, b, "posterize should change something for the test to mean anything"); + // And the content thumbnail (everything) follows. + let all = ThumbTarget::Content { layer: st.layer, channel: base }; + settle(&mut svc, &s, &[all], &mut clock); + assert_eq!(image(&mut svc, &s, all), a); +} + +#[test] +fn editing_invalidates_and_unrelated_changes_do_not() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[t], &mut clock); + let before = image(&mut svc, &s, t); + let rendered = svc.rendered; + // A camera move changes the session revision but no thumbnail input: nothing is re-rendered. + execute(&mut s, "camera.set", &json!({"yaw": 0.7})).ok(); + s.revision += 1; + for _ in 0..3 { + clock += 0.3; + svc.begin_frame(&s, clock); + svc.get(&s, t); + svc.poll(&s); + } + assert!(svc.is_fresh(t)); + assert_eq!(svc.rendered, rendered, "an unrelated change re-rendered a thumbnail"); + // An edit of the layer re-renders it, and the new picture is the new oracle. + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + clock += 0.3; + svc.begin_frame(&s, clock); + assert!(!svc.is_fresh(t)); + settle(&mut svc, &s, &[t], &mut clock); + let after = image(&mut svc, &s, t); + assert_ne!(before, after); + assert_eq!(after, oracle(&s, t)); + // Undo brings the first picture back. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + settle(&mut svc, &s, &[t], &mut clock); + assert_eq!(image(&mut svc, &s, t), before); +} + +#[test] +fn deleting_a_layer_with_a_pending_thumbnail_is_harmless() { + let mut s = session(); + let st = stack(&mut s); + let (a, b) = (ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }, ThumbTarget::Mask { layer: st.layer }); + let mut svc = ThumbService::new(); + // Queue the work and hand it to the worker, then delete the layer before collecting. + svc.begin_frame(&s, 1.0); + svc.get(&s, a); + svc.get(&s, b); + svc.poll(&s); + execute(&mut s, "layer.remove", &json!({"layer": st.layer.0})).unwrap(); + let mut clock = 2.0; + for _ in 0..200 { + clock += 0.2; + svc.begin_frame(&s, clock); + // The row is gone, so nobody asks for it any more; the pending result is dropped. + svc.poll(&s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!svc.is_fresh(a) && !svc.is_fresh(b)); + assert_eq!(svc.cached(), 0); + assert!(!svc.busy()); + // Asking for a layer that no longer exists renders nothing and does not panic either. + settle_gone(&mut svc, &s, a, &mut clock); +} + +fn settle_gone(svc: &mut ThumbService, s: &Session, t: ThumbTarget, clock: &mut f64) { + for _ in 0..20 { + *clock += 0.2; + svc.begin_frame(s, *clock); + svc.get(s, t); + svc.poll(s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(svc.get(s, t).image.is_none()); +} + +#[test] +fn a_result_of_an_older_document_never_replaces_a_newer_one() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let mut svc = ThumbService::new(); + svc.begin_frame(&s, 1.0); + svc.get(&s, t); + svc.poll(&s); // the job of the first document is running + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + let mut clock = 2.0; + settle(&mut svc, &s, &[t], &mut clock); + // Whatever the first job returned, what is shown is the current document. + assert_eq!(image(&mut svc, &s, t), oracle(&s, t)); +} + +#[test] +fn only_requested_rows_render_and_the_cache_is_bounded() { + let mut session = session(); + let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); + let target = |layer: LayerId| ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let mut service = ThumbService::new(); + + // A frame asks for six rows, then scrolling leaves only one visible + service.begin_frame(&session, 1.0); + for layer in &layers[..6] { + service.get(&session, target(*layer)); + } + service.poll(&session); + let mut clock = 2.0; + for _ in 0..300 { + clock += 0.2; + service.begin_frame(&session, clock); + service.get(&session, target(layers[0])); + service.poll(&session); + std::thread::sleep(Duration::from_millis(1)); + } + + assert!(service.is_fresh(target(layers[0]))); + let completed = layers[..6].iter().filter(|layer| service.is_fresh(target(**layer))).count(); + assert!(completed <= 3, "{completed} of the scrolled-away rows were rendered"); + + // Scrolling through every layer evicts pictures and releases their allocations + let mut images = Vec::new(); + for chunk in layers.chunks(12) { + let targets: Vec = chunk.iter().map(|layer| target(*layer)).collect(); + settle(&mut service, &session, &targets, &mut clock); + for target in targets { + images.push(std::sync::Arc::downgrade(&service.get(&session, target).image.unwrap())); + } + assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached()); + } + clock += 0.2; + service.begin_frame(&session, clock); + service.poll(&session); + + assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached()); + assert!(images.len() > CACHE_ENTRIES); + assert!(images.first().unwrap().upgrade().is_none(), "the oldest image was evicted"); + assert_eq!(images.iter().filter(|image| image.strong_count() > 0).count(), service.cached()); + + drop(service); + + assert!(images.iter().all(|image| image.upgrade().is_none()), "closing the cache releases every picture"); +} + +#[test] +fn an_empty_paint_layer_is_transparent_and_a_folder_composites_its_children() { + let mut session = session(); + let paint = id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer"); + let fill = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + let folder = id(execute(&mut session, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); + let paint_target = ThumbTarget::Content { layer: paint, channel: Channel::BaseColor }; + let folder_target = ThumbTarget::Content { layer: folder, channel: Channel::BaseColor }; + let (mut service, mut clock) = (ThumbService::new(), 0.0); + + settle(&mut service, &session, &[paint_target, folder_target], &mut clock); + + assert!(image(&mut service, &session, paint_target).rgba.as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0), "nothing painted: nothing shown"); + let folder_image = image(&mut service, &session, folder_target); + let pixel = folder_image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + assert!((i32::from(pixel[0]) - 51).abs() <= 1 && (i32::from(pixel[2]) - 153).abs() <= 1, "{pixel:?}"); +} + +#[test] +fn instances_preview_the_source_content_and_inherited_mask() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let mut session = session(); + let stack = stack(&mut session); + let instance = id(execute(&mut session, "layer.instance", &json!({"layer": stack.layer.0})).unwrap(), "layer"); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + for channel in [Channel::BaseColor, Channel::Roughness] { + let source = snapshot.render(ThumbTarget::Content { layer: stack.layer, channel }).unwrap(); + let preview = snapshot.render(ThumbTarget::Content { layer: instance, channel }); + + assert!(preview == Some(source), "the instance inherits {channel:?} from its source"); + } + + assert_eq!(snapshot.render(ThumbTarget::Mask { layer: instance }), snapshot.render(ThumbTarget::Mask { layer: stack.layer })); +} + +/// A lower height anchor and an independent upper fill that can read it. +fn anchor_stack() -> (Session, LayerId, LayerId) { + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"height": 0.25})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + (session, anchor, layer) +} + +#[test] +fn thumbnails_keep_anchor_inputs_from_lower_layers() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let (mut session, anchor, layer) = anchor_stack(); + execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let mask_effect = id(execute(&mut session, "effect.add.fill", &json!({"anchor": anchor.0, "anchorChannel": "height"})).unwrap(), "effect"); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + for target in [ + ThumbTarget::Content { layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer }, + ThumbTarget::Stage { effect: mask_effect, channel: Channel::BaseColor }, + ] { + let image = snapshot.render(target).unwrap(); + let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + + assert!((i32::from(pixel[0]) - 64).abs() <= 1, "{target:?} must read the lower anchor's 0.25, got {pixel:?}"); + } +} + +#[test] +fn folder_thumbnails_keep_anchors_outside_the_folder() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let (mut session, anchor, layer) = anchor_stack(); + execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); + let folder = id(execute(&mut session, "layer.group", &json!({"layer": layer.0})).unwrap(), "layer"); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + let image = snapshot.render(ThumbTarget::Content { layer: folder, channel: Channel::Roughness }).unwrap(); + let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + + assert!((i32::from(pixel[0]) - 64).abs() <= 1, "the folder must read the external anchor's 0.25, got {pixel:?}"); +} + +#[test] +fn effect_only_anchor_reads_keep_the_lower_stack() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + for target_kind in ["content", "mask"] { + let (mut session, anchor, layer) = anchor_stack(); + if target_kind == "mask" { + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + } + let effect = id(execute(&mut session, "effect.add.fill", &json!({"target": target_kind})).unwrap(), "effect"); + if target_kind == "content" { + execute(&mut session, "layer.fill.set", &json!({"effect": effect.0, "channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})) + .unwrap(); + } else { + execute(&mut session, "effect.set", &json!({"effect": effect.0, "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); + } + let target = if target_kind == "content" { ThumbTarget::Content { layer, channel: Channel::Roughness } } else { ThumbTarget::Mask { layer } }; + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + for target in [target, ThumbTarget::Stage { effect, channel: Channel::Roughness }] { + let image = snapshot.render(target).unwrap(); + let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + + assert!((i32::from(pixel[0]) - 64).abs() <= 1, "{target_kind} {target:?} must read the lower anchor's 0.25, got {pixel:?}"); + } + } +} diff --git a/crates/engine/tests/it/tool_availability.rs b/crates/engine/tests/it/tool_availability.rs new file mode 100644 index 00000000..5c17e29b --- /dev/null +++ b/crates/engine/tests/it/tool_availability.rs @@ -0,0 +1,336 @@ +//! Which tools can act on each selection, and that every usable tool acts there in both views + +mod selection; + +use selection::Selection; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Effect, EffectKind, LayerId}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; +use texturecraft_engine::{Session, StackTarget, Tool, execute}; + +/// Two triangles side by side, each a mesh part with its own corner of the UV square +const PARTS_OBJ: &str = "o Lid\nv 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 0.5 0\nvt 0 0.5\nf 1/1 2/2 3/3\n\ +o Body\nv 2 2 0\nv 4 2 0\nv 2 4 0\nvt 0.5 0.5\nvt 1 0.5\nvt 0.5 1\nf 4/4 5/5 6/6\n"; + +const VIEWPORT_PIXELS: f32 = 400.0; + +fn stencil_png() -> Vec { + let mut out = Vec::new(); + let green = image::RgbaImage::from_fn(8, 8, |_, _| image::Rgba([0, 255, 0, 255])); + green.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn base_session() -> Session { + let mut session = Session::from_mesh_bytes("parts.obj", PARTS_OBJ.as_bytes(), 256, "parts").unwrap(); + session.viewport = Vec2::splat(VIEWPORT_PIXELS); + (session.camera.yaw, session.camera.pitch) = (0.0, 0.0); + let (low, high) = session.mesh.bounds(); + session.camera.frame(low, high); + session.update(); + + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap(); + let stencil = session.import_resource_bytes("stencil.png", stencil_png()).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": stencil})).unwrap(); + session +} + +fn screen(session: &Session, point: [f32; 3]) -> Vec2 { + let ndc = session.camera.project(Vec3::from(point), 1.0).unwrap(); + Vec2::new((ndc.x + 1.0) * VIEWPORT_PIXELS / 2.0, (1.0 - ndc.y) * VIEWPORT_PIXELS / 2.0) +} + +fn add_layer(session: &mut Session, command: &str) -> u64 { + execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn select(session: &mut Session, layer: u64, target: Value) { + execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap(); +} + +fn select_nothing(session: &mut Session) { + let set = session.ts(); + session.selected.remove(&set); + session.target = StackTarget::Content; +} + +/// Adds an effect with `command` to the layer's content or mask and selects it +fn select_new_effect(session: &mut Session, layer: u64, mask: bool, command: &str, effect_params: Value) { + if mask { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + } + + let target = if mask { "mask" } else { "content" }; + let mut params = effect_params; + params["layer"] = json!(layer); + params["target"] = json!(target); + execute(session, command, ¶ms).unwrap(); + + let owner = session.doc.project.layer(LayerId(layer)).unwrap(); + let effects = if mask { &owner.mask.as_ref().unwrap().effects } else { &owner.content_effects }; + let effect = effects.last().unwrap().id.0; + select(session, layer, json!(effect)); +} + +fn select_new_mask(session: &mut Session, layer: u64) { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + select(session, layer, json!("mask")); +} + +fn session_with(selection: Selection) -> Session { + let mut session = base_session(); + match selection { + Selection::PaintContent => { + let layer = add_layer(&mut session, "layer.add.paint"); + select(&mut session, layer, json!("content")); + } + Selection::FillContent => { + let layer = add_layer(&mut session, "layer.add.fill"); + select(&mut session, layer, json!("content")); + } + Selection::PaintMask => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_mask(&mut session, layer); + } + Selection::FillMask => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_mask(&mut session, layer); + } + Selection::FolderMask => { + let folder = add_layer(&mut session, "layer.add.group"); + select_new_mask(&mut session, folder); + } + Selection::InstanceOwnMask => { + let source = add_layer(&mut session, "layer.add.paint"); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + select_new_mask(&mut session, instance); + } + Selection::PaintSublayer => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, false, "effect.add.paint", json!({})); + } + Selection::PaintSublayerInMask => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, true, "effect.add.paint", json!({})); + } + Selection::PaintSublayerInFill => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_effect(&mut session, layer, false, "effect.add.paint", json!({})); + } + Selection::PathSublayer => { + let layer = add_layer(&mut session, "layer.add.paint"); + select(&mut session, layer, json!("content")); + let (start, end) = (screen(&session, [0.2, 0.2, 0.0]), screen(&session, [1.0, 0.4, 0.0])); + execute(&mut session, "tool.path", &json!({"points": [[start.x, start.y], [end.x, end.y]]})).unwrap(); + execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); + let path = session.doc.project.layer(LayerId(layer)).unwrap().content_effects.last().unwrap().id.0; + select(&mut session, layer, json!(path)); + } + Selection::FilterInPaint | Selection::FilterInFill | Selection::FilterInMask => { + let command = if selection == Selection::FilterInFill { "layer.add.fill" } else { "layer.add.paint" }; + let layer = add_layer(&mut session, command); + select_new_effect(&mut session, layer, selection == Selection::FilterInMask, "effect.add.filter", json!({"filter": "invert"})); + } + Selection::FillEffectInPaint => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, false, "effect.add.fill", json!({})); + } + Selection::GeneratorInFillMask => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_effect(&mut session, layer, true, "effect.add.generator", json!({})); + } + Selection::FolderContent => { + let folder = add_layer(&mut session, "layer.add.group"); + select(&mut session, folder, json!("content")); + } + Selection::InstanceOfPaint | Selection::InstanceOfFill => { + let command = if selection == Selection::InstanceOfFill { "layer.add.fill" } else { "layer.add.paint" }; + let source = add_layer(&mut session, command); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + select(&mut session, instance, json!("content")); + } + Selection::Nothing => select_nothing(&mut session), + Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill => { + let command = if selection == Selection::QuickMaskOverFill { "layer.add.fill" } else { "layer.add.paint" }; + let layer = add_layer(&mut session, command); + select(&mut session, layer, json!("content")); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + } + Selection::QuickMaskOverNothing => { + select_nothing(&mut session); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + } + } + + session +} + +/// Uses `tool` once the way the viewport does: a stroke, a click or a committed path +fn use_tool(session: &mut Session, tool: Tool, in_2d_view: bool) -> texturecraft_engine::Result<()> { + session.tool.tool = tool; + if tool == Tool::Clone { + let source = screen(session, [1.2, 0.3, 0.0]); + execute(session, "tool.cloneSource", &json!({"x": source.x, "y": source.y}))?; + } + + let points = [screen(session, [0.3, 0.3, 0.0]), screen(session, [0.6, 0.4, 0.0]), screen(session, [0.9, 0.5, 0.0])]; + let uv_points = [Vec2::new(0.05, 0.95), Vec2::new(0.1, 0.92), Vec2::new(0.15, 0.9)]; + if tool == Tool::Path { + let params = if in_2d_view { + json!({"uvPoints": uv_points.iter().map(|uv| [uv.x, uv.y]).collect::>()}) + } else { + json!({"points": points.iter().map(|point| [point.x, point.y]).collect::>()}) + }; + execute(session, "tool.path", ¶ms)?; + execute(session, "tool.path", &json!({"commit": true}))?; + return Ok(()); + } + + let single_click = matches!(tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask); + let viewport = session.viewport; + if in_2d_view { + session.begin_stroke_uv(uv_points[0], 1.0)?; + } else { + session.begin_stroke(points[0], viewport, 1.0)?; + } + + if single_click { + return Ok(()); + } + + for (point, uv) in points.iter().zip(&uv_points).skip(1) { + if in_2d_view { + session.continue_stroke_uv(*uv, 1.0); + } else { + session.continue_stroke(*point, 1.0); + } + } + + session.end_stroke() +} + +#[test] +fn every_selection_offers_the_tools_that_can_act_on_it() { + let mut wrong = Vec::new(); + for selection in Selection::ALL { + let session = session_with(selection); + for tool in Tool::ALL { + let usable = session.tool_usable(tool); + if usable != selection.offers(tool) { + wrong.push(format!("{selection:?} {tool:?}: usable {usable}")); + } + } + } + + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn every_usable_tool_acts_in_both_views() { + let mut wrong = Vec::new(); + for in_2d_view in [false, true] { + for selection in Selection::ALL { + for tool in Tool::ALL { + // The picker and the geometry mask read the 3D view only, whatever is selected + if in_2d_view && matches!(tool, Tool::ColorPicker | Tool::GeometryMask) { + continue; + } + + let mut session = session_with(selection); + let usable = session.tool_usable(tool); + + let result = use_tool(&mut session, tool, in_2d_view); + + let view = if in_2d_view { "2D" } else { "3D" }; + match result { + Err(error) if usable => wrong.push(format!("{view} {selection:?} {tool:?}: usable but {error}")), + Ok(()) if !usable && !selection.scripts_still_paint() => wrong.push(format!("{view} {selection:?} {tool:?}: greyed but acts")), + _ => {} + } + } + } + } + + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +fn commit_path(session: &mut Session) -> texturecraft_engine::Result { + execute(session, "tool.path", &json!({"uvPoints": [[0.05, 0.95], [0.15, 0.9]], "commit": true})) +} + +fn path_count(session: &Session, path_sublayer: LayerId) -> usize { + match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Path(paths)) => paths.len(), + _ => 0, + } +} + +#[test] +fn paths_are_refused_on_fill_layers_and_the_quick_mask_but_saved_ones_stay_editable() { + let mut session = session_with(Selection::FillContent); + let fill = session.selected_layer().unwrap(); + + assert!(commit_path(&mut session).is_err(), "no new paths in a fill layer"); + assert!(session.doc.project.layer(fill).unwrap().content_effects.is_empty()); + + let mut session = session_with(Selection::QuickMaskOverPaint); + assert!(commit_path(&mut session).is_err(), "paths can't edit the quick mask"); + + // A project saved while paths could go into fill layers + let mut session = session_with(Selection::FillContent); + let fill = session.selected_layer().unwrap(); + let saved_path = session.doc.project.alloc_id(); + session.doc.project.layer_mut(fill).unwrap().content_effects.push(Effect::new(saved_path, EffectKind::Path(Vec::new()))); + select(&mut session, fill.0, json!(saved_path.0)); + + assert!(session.tool_usable(Tool::Path)); + + commit_path(&mut session).unwrap(); + + assert_eq!(path_count(&session, saved_path), 1, "the saved path sublayer takes the new path"); +} + +#[test] +fn quick_mask_edit_and_invert_need_the_mask_on() { + let mut session = base_session(); + + assert!(execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).is_err()); + assert!(execute(&mut session, "viewport.quickMask.invert", &json!({})).is_err()); + + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap(); + + assert!(!session.quick_mask.editing, "turning the mask off stops editing it"); +} + +#[test] +fn a_saved_path_cannot_be_committed_while_editing_the_quick_mask() { + let mut session = session_with(Selection::PaintContent); + commit_path(&mut session).unwrap(); + let StackTarget::Effect(path_sublayer) = session.target else { panic!("the committed path is not selected") }; + + let points_before = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Path(paths)) => paths[0].points.clone(), + _ => panic!("the committed path is missing"), + }; + + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": path_sublayer.0, "index": 0})).unwrap(); + assert!(!session.tool_usable(Tool::Path)); + + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.3, 0.7]]})).unwrap(); + assert!(!session.path_live().unwrap(), "live preview must leave the stored path alone"); + let result = execute(&mut session, "tool.path", &json!({"commit": true})); + assert!(result.is_err(), "a greyed Path tool must not commit a stored path into the quick mask edit state"); + + let points_after = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Path(paths)) => paths[0].points.clone(), + _ => panic!("the stored path is missing"), + }; + assert_eq!(points_after, points_before); +} diff --git a/crates/engine/tests/it/tool_availability/selection.rs b/crates/engine/tests/it/tool_availability/selection.rs new file mode 100644 index 00000000..aaca56a8 --- /dev/null +++ b/crates/engine/tests/it/tool_availability/selection.rs @@ -0,0 +1,83 @@ +//! Selection cases for the tool availability tests + +use texturecraft_engine::Tool; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Selection { + PaintContent, + FillContent, + PaintMask, + FillMask, + FolderMask, + InstanceOwnMask, + PaintSublayer, + PaintSublayerInMask, + PaintSublayerInFill, + PathSublayer, + FilterInPaint, + FilterInFill, + FilterInMask, + FillEffectInPaint, + GeneratorInFillMask, + FolderContent, + InstanceOfPaint, + InstanceOfFill, + Nothing, + QuickMaskOverPaint, + QuickMaskOverFill, + QuickMaskOverNothing, +} + +impl Selection { + pub(super) const ALL: [Selection; 22] = [ + Selection::PaintContent, + Selection::FillContent, + Selection::PaintMask, + Selection::FillMask, + Selection::FolderMask, + Selection::InstanceOwnMask, + Selection::PaintSublayer, + Selection::PaintSublayerInMask, + Selection::PaintSublayerInFill, + Selection::PathSublayer, + Selection::FilterInPaint, + Selection::FilterInFill, + Selection::FilterInMask, + Selection::FillEffectInPaint, + Selection::GeneratorInFillMask, + Selection::FolderContent, + Selection::InstanceOfPaint, + Selection::InstanceOfFill, + Selection::Nothing, + Selection::QuickMaskOverPaint, + Selection::QuickMaskOverFill, + Selection::QuickMaskOverNothing, + ]; + + /// Whether the shelf offers `tool` for this selection + pub(super) fn offers(self, tool: Tool) -> bool { + let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); + match tool { + Tool::ColorPicker => true, + Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing), + _ => match self { + Selection::PaintContent | Selection::PaintSublayer => true, + Selection::PaintSublayerInFill => tool != Tool::Path, + Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => { + !reads_content + } + Selection::PathSublayer => tool == Tool::Path, + Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path, + _ => false, + }, + } + } + + /// Greyed in the shelf, but scripts still paint here: below the effect, or the instance's source + pub(super) fn scripts_still_paint(self) -> bool { + matches!( + self, + Selection::FilterInPaint | Selection::FillEffectInPaint | Selection::FilterInMask | Selection::GeneratorInFillMask | Selection::InstanceOfPaint + ) + } +} diff --git a/crates/engine/tests/it/tools.rs b/crates/engine/tests/it/tools.rs new file mode 100644 index 00000000..0e217d88 --- /dev/null +++ b/crates/engine/tests/it/tools.rs @@ -0,0 +1,304 @@ +//! Clone, smudge, image and library alphas and the quick mask, driven through engine commands the way +//! agents paint. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +const RES: f32 = 256.0; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// Base color of the composite under a viewport point. +fn color_at(s: &Session, x: f32, y: f32) -> [f32; 3] { + let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); + s.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * RES) as u32, (hit.uv.y * RES) as u32) +} + +fn red(v: [f32; 3]) -> bool { + v[0] > 0.85 && v[1] < 0.15 +} + +fn dab(s: &mut Session, x: f32, y: f32) { + execute(s, "tool.stroke", &json!({"points": [[x, y]]})).unwrap(); +} + +fn paint_red(s: &mut Session, size: f32) { + execute(s, "tool.paint", &Value::Null).unwrap(); + execute(s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(s, "tool.brush", &json!({"size": size, "hardness": 90})).unwrap(); +} + +#[test] +fn clone_copies_values_from_the_source_offset() { + let mut s = session(); + paint_red(&mut s, 20.0); + dab(&mut s, 160.0, 200.0); + assert!(red(color_at(&s, 160.0, 200.0))); + assert!(!red(color_at(&s, 240.0, 200.0))); + + execute(&mut s, "tool.clone", &Value::Null).unwrap(); + assert!(execute(&mut s, "tool.stroke", &json!({"points": [[240, 200]]})).is_err(), "no source yet"); + execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + dab(&mut s, 240.0, 200.0); + let v = color_at(&s, 240.0, 200.0); + assert!(red(v), "cloned red: {v:?}"); + // The offset stays for the next strokes: the source moved along with the destination. + let off = s.tool.clone_source.unwrap().offset.unwrap(); + assert!(off[0].abs() > 0.01, "{off:?}"); + // One undo step per clone stroke. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red(color_at(&s, 240.0, 200.0))); +} + +#[test] +fn smudge_drags_color_along_the_stroke() { + let mut s = session(); + paint_red(&mut s, 12.0); + dab(&mut s, 170.0, 200.0); + let before = color_at(&s, 205.0, 200.0); + assert!(!red(before), "{before:?}"); + execute(&mut s, "tool.smudge", &Value::Null).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap(); + let pts: Vec<[f32; 2]> = (0..=40).map(|i| [170.0 + i as f32, 200.0]).collect(); + execute(&mut s, "tool.stroke", &json!({"points": pts})).unwrap(); + let after = color_at(&s, 205.0, 200.0); + assert!(after[0] - before[0] > 0.2 && after[1] < before[1], "red dragged right: {before:?} -> {after:?}"); +} + +#[test] +fn image_alpha_shapes_the_stamp() { + let mut s = session(); + let mut png = Vec::new(); + // Top half white, bottom half black. + let img = image::RgbaImage::from_fn(16, 16, |_, y| if y < 8 { image::Rgba([255; 4]) } else { image::Rgba([0, 0, 0, 255]) }); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = s.import_resource_bytes("half.png", png).unwrap(); + paint_red(&mut s, 20.0); + assert!(execute(&mut s, "tool.brush", &json!({"alpha": {"image": "missing.png"}})).is_err()); + let r = execute(&mut s, "tool.brush", &json!({"alpha": {"image": name}})).unwrap(); + assert_eq!(r["alpha"]["image"], json!(name)); + execute(&mut s, "tool.strokeUv", &json!({"points": [[0.5, 0.5]]})).unwrap(); + // In the 2D view +v points down: the image's top half lands above the center. + let at = |s: &Session, dy: i32| s.caches[0].composite.value(Channel::BaseColor, 128, (128 + dy) as u32); + assert!(red(at(&s, -12)), "{:?}", at(&s, -12)); + assert!(!red(at(&s, 12)), "{:?}", at(&s, 12)); + // A procedural alpha clears the image. + let r = execute(&mut s, "tool.brush", &json!({"alpha": "round"})).unwrap(); + assert_eq!(r["alpha"], json!("Round")); +} + +/// Offsets (dx, dy) of red composite texels within `r` texels of (cx, cy), with their lengths. +fn red_offsets(s: &Session, cx: i32, cy: i32, r: i32) -> Vec<(i32, i32, f32)> { + let mut out = Vec::new(); + for dy in -r..=r { + for dx in -r..=r { + let (x, y) = (cx + dx, cy + dy); + if (0..RES as i32).contains(&x) && (0..RES as i32).contains(&y) && red(s.caches[0].composite.value(Channel::BaseColor, x as u32, y as u32)) { + out.push((dx, dy, ((dx * dx + dy * dy) as f32).sqrt())); + } + } + } + out +} + +#[test] +fn library_alphas_shape_the_stamp() { + let mut s = session(); + paint_red(&mut s, 20.0); + let list = execute(&mut s, "alpha.list", &Value::Null).unwrap(); + assert!(list["library"].as_array().is_some_and(|a| a.len() >= 60), "{list}"); + assert_eq!(list["procedural"][0], json!("Round")); + assert!(execute(&mut s, "tool.brush", &json!({"alpha": {"library": "nope"}})).is_err()); + let r = execute(&mut s, "tool.brush", &json!({"alpha": {"library": "Ring"}})).unwrap(); + assert_eq!(r["alpha"], json!({"library": "ring"})); + + // 2D view: a ring with a clean middle. + execute(&mut s, "tool.strokeUv", &json!({"points": [[0.5, 0.5]]})).unwrap(); + let ring = red_offsets(&s, 128, 128, 48); + let outer = ring.iter().map(|t| t.2).fold(0.0, f32::max); + assert!(outer > 6.0 && outer < 47.0, "{outer}"); + assert!(ring.iter().all(|t| t.2 > outer * 0.45), "the middle stays clean"); + let mid = (outer * 0.72 / 0.92).round() as i32; + for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { + assert!(ring.iter().any(|t| (t.0, t.1) == (dx * mid, dy * mid)), "ring at {:?}", (dx * mid, dy * mid)); + } + + // 3D view: the same hollow stamp on the sphere. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + dab(&mut s, 200.0, 200.0); + let hit = s.pick(Vec2::new(200.0, 200.0), s.viewport).unwrap(); + let (cx, cy) = ((hit.uv.x * RES) as i32, (hit.uv.y * RES) as i32); + let ring = red_offsets(&s, cx, cy, 48); + assert!(!ring.is_empty(), "painted"); + assert!(ring.iter().all(|t| t.2 > 2.0), "the middle stays clean"); + + // A procedural alpha clears the library alpha. + let r = execute(&mut s, "tool.brush", &json!({"alpha": "square"})).unwrap(); + assert_eq!(r["alpha"], json!("Square")); + assert!(s.tool.brush.alpha_library.is_none()); +} + +#[test] +fn quick_mask_limits_painting() { + let mut session = session(); + paint_red(&mut session, 20.0); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + + let state = execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap(); + let undo = session.history_labels().len(); + dab(&mut session, 150.0, 200.0); + + assert_eq!(state["editing"], json!(true)); + assert!(!red(color_at(&session, 150.0, 200.0)), "mask strokes do not paint the layer"); + assert_eq!(session.history_labels().len(), undo, "mask strokes stay out of the history"); + let overlay_size: u32 = 64; + let rgba_bytes = (overlay_size * overlay_size * 4) as usize; + assert!(session.quick_mask_rgba(0, overlay_size).is_some_and(|pixels| pixels.len() == rgba_bytes), "an RGBA8 overlay of the requested size"); + + execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap(); + dab(&mut session, 150.0, 200.0); + dab(&mut session, 250.0, 200.0); + + assert!(red(color_at(&session, 150.0, 200.0)), "inside the mask"); + assert!(!red(color_at(&session, 250.0, 200.0)), "outside the mask"); + + execute(&mut session, "viewport.quickMask.invert", &Value::Null).unwrap(); + dab(&mut session, 250.0, 200.0); + + assert!(red(color_at(&session, 250.0, 200.0)), "inverted: outside is open"); + + execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap(); + dab(&mut session, 150.0, 200.0); + + assert!(color_at(&session, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); +} + +/// How much redder than green a texel must be to count as painted (faded edges included) +const PAINTED_TINT: f32 = 0.05; + +/// Separate painted runs down texture column `x` (base color tinted red) +fn painted_runs(session: &Session, x: u32) -> usize { + let painted = |y: u32| { + let color = session.caches[0].composite.value(Channel::BaseColor, x, y); + color[0] - color[1] > PAINTED_TINT + }; + (0..RES as u32).filter(|&y| painted(y) && (y == 0 || !painted(y - 1))).count() +} + +#[test] +fn a_stroke_to_the_edge_of_the_mesh_fades_without_breaking_into_dots() { + let mut session = session(); + paint_red(&mut session, 4.0); + // From the middle of the view to past the ball's right edge, above center + let points: Vec = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect(); + execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap(); + session.update(); + + // The stroke crosses each texture column once, also where the surface turns away from the camera + let broken: Vec = (0..RES as u32).filter(|&x| painted_runs(&session, x) > 1).collect(); + assert!(broken.is_empty(), "columns with gaps: {broken:?}"); +} + +#[test] +fn swap_mask_value_inverts_only_while_a_mask_is_the_target() { + let mut session = session(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + let swap = |session: &mut Session| execute(session, "tool.swapMaskValue", &Value::Null); + let effect_target = |result: Value| StackTarget::Effect(LayerId(result["effect"].as_u64().unwrap())); + + assert!(swap(&mut session).is_err(), "painting the layer content: nothing to invert"); + + let content_effect = effect_target(execute(&mut session, "effect.add.paint", &json!({"target": "content"})).unwrap()); + session.target = content_effect; + assert!(swap(&mut session).is_err(), "a content effect is not a mask"); + + execute(&mut session, "mask.add.white", &Value::Null).unwrap(); + session.target = StackTarget::Mask; + session.tool.mask_value = 0.2; + + swap(&mut session).unwrap(); + + assert_eq!(session.tool.mask_value, 0.8); + + session.tool.mask_value = 1.0; + + swap(&mut session).unwrap(); + + assert_eq!(session.tool.mask_value, 0.0); + + swap(&mut session).unwrap(); + + assert_eq!(session.tool.mask_value, 1.0, "pressing it again goes back"); + + session.target = effect_target(execute(&mut session, "effect.add.paint", &json!({"target": "mask"})).unwrap()); + + swap(&mut session).unwrap(); + + assert_eq!(session.tool.mask_value, 0.0, "a mask effect paints the mask too"); +} + +#[test] +fn stroke_after_undoing_mask_is_paint_stroke() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap(); + execute(&mut s, "tool.paint", &Value::Null).unwrap(); + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.9, 0.3, 0.9]})).unwrap(); + + execute(&mut s, "tool.stroke", &json!({"points": [[130, 130], [170, 150]]})).unwrap(); + s.update(); + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "tool.stroke", &json!({"points": [[167, 183], [207, 203]]})).unwrap(); + s.update(); + + let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(undone["undone"], "Paint stroke", "the stroke after undoing the mask was recorded as {}", undone["undone"]); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + s.update(); + + let settled = s.caches[0].composite.clone(); + s.caches[0].below.clear(); + s.caches[0].invalidate_all(); + s.update(); + assert_eq!(settled, s.caches[0].composite, "the composite after the stroke matches a full recomposite"); +} + +#[test] +fn undoing_after_painting_on_instance_source_mask_keeps_mask_target() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + execute(&mut s, "layer.instance", &Value::Null).unwrap(); + s.update(); + s.target = StackTarget::Mask; + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[170, 180], [210, 200]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.target, StackTarget::Mask); + + execute(&mut s, "tool.stroke", &json!({"points": [[180, 180], [210, 200]]})).unwrap(); + let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(undone["undone"], "Mask stroke"); +} diff --git a/crates/engine/tests/udim.rs b/crates/engine/tests/it/udim.rs similarity index 86% rename from crates/engine/tests/udim.rs rename to crates/engine/tests/it/udim.rs index 6ba37904..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] @@ -142,7 +146,7 @@ fn mesh_maps_from_images_take_one_image_per_tile() { image::RgbaImage::from_pixel(4, 4, image::Rgba([v, v, v, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); out }; - let set = |s: &mut Session, image: &str| execute(s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": image})); + let set = |s: &mut Session, image: &str| execute(s, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": image})); let left = s.import_resource_bytes("ao.1001.png", png(255)).unwrap(); assert!(set(&mut s, &left).unwrap_err().to_string().contains("ao.1002.png"), "tile 1002 has no image yet"); let plain = s.import_resource_bytes("ao.png", png(255)).unwrap(); 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/path_tool.rs b/crates/engine/tests/path_tool.rs deleted file mode 100644 index b053e979..00000000 --- a/crates/engine/tests/path_tool.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! The Path tool (stroked and filled paths, 3D and 2D) and the particle brush, driven through -//! engine commands the way agents paint. - -use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; -use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; -use texturecraft_engine::geom::{Mesh, primitives}; -use texturecraft_engine::{Session, execute}; - -const RES: f32 = 256.0; - -fn session(mesh: Mesh) -> Session { - let mut s = Session::new_project("t", mesh, "builtin:test", None, 256).unwrap(); - s.viewport = Vec2::new(400.0, 400.0); - s.camera.yaw = 0.0; - s.camera.pitch = 0.0; - s.update(); - execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); - execute(&mut s, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); - s -} - -fn red_uv(s: &Session, u: f32, v: f32) -> bool { - let c = s.caches[0].composite.value(Channel::BaseColor, (u * RES) as u32, (v * RES) as u32); - c[0] > 0.85 && c[1] < 0.15 -} - -/// Is the surface under a viewport point painted red? -fn red_at(s: &Session, x: f32, y: f32) -> bool { - let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); - red_uv(s, hit.uv.x, hit.uv.y) -} - -#[test] -fn path_stroke_paints_along_the_curve() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); - assert_eq!(r["points"], 3); - assert_eq!(s.tool.tool, texturecraft_engine::Tool::Path); - assert!(!red_at(&s, 200.0, 180.0), "nothing painted before commit"); - let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); - assert!(r["committed"]["stamps"].as_u64().unwrap() > 10, "{r}"); - assert_eq!(r["points"], 0, "commit clears the path"); - for (x, y) in [(140.0, 210.0), (200.0, 180.0), (260.0, 210.0), (170.0, 191.0)] { - assert!(red_at(&s, x, y), "on the curve at {x},{y}"); - } - assert!(!red_at(&s, 200.0, 240.0), "below the curve"); - assert!(!red_at(&s, 200.0, 130.0), "above the curve"); - // One undo step. - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - s.update(); - assert!(!red_at(&s, 200.0, 180.0)); - // Errors: no points, points off the mesh. - assert!(execute(&mut s, "tool.path", &json!({"commit": true})).is_err()); - assert!(execute(&mut s, "tool.path", &json!({"points": [[2, 2]]})).is_err()); -} - -#[test] -fn uv_path_strokes_in_texture_space() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]], "commit": true})).unwrap(); - assert!(red_uv(&s, 0.5, 0.45) && red_uv(&s, 0.2, 0.5) && red_uv(&s, 0.8, 0.5)); - assert!(!red_uv(&s, 0.5, 0.6)); -} - -#[test] -fn closed_filled_path_fills_the_inside_only() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - let square = json!([[160, 160], [240, 160], [240, 240], [160, 240]]); - execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); - for (x, y) in [(200.0, 200.0), (170.0, 170.0), (230.0, 230.0)] { - assert!(red_at(&s, x, y), "inside at {x},{y}"); - } - for (x, y) in [(200.0, 125.0), (275.0, 200.0), (125.0, 200.0), (200.0, 275.0)] { - assert!(!red_at(&s, x, y), "outside at {x},{y}"); - } - // The far side of the sphere, hidden from the camera, stays clean. - s.camera.yaw = std::f32::consts::PI; - assert!(!red_at(&s, 200.0, 200.0), "hidden back side"); - - // A 2D lasso fills the UV region. - let mut s = session(primitives::sphere(1.0, 48, 24)); - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.3, 0.3], [0.7, 0.3], [0.7, 0.7], [0.3, 0.7]], "closed": true, "fill": true, "commit": true})).unwrap(); - assert!(red_uv(&s, 0.5, 0.5) && red_uv(&s, 0.35, 0.65)); - assert!(!red_uv(&s, 0.2, 0.5) && !red_uv(&s, 0.5, 0.85)); - // Options persist between paths; a filled path needs three points. - assert!(execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.1], [0.2, 0.2]], "closed": false, "commit": true})).is_ok()); - assert!(execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.1], [0.2, 0.2]], "closed": true, "fill": true, "commit": true})).is_err()); -} - -#[test] -fn closed_filled_path_is_symmetrized() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - execute(&mut s, "tool.brush", &json!({"symmetryX": true})).unwrap(); - - let square = json!([[230, 160], [270, 160], [270, 240], [230, 240]]); - execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); - - assert!(red_at(&s, 250.0, 200.0), "the drawn side"); - assert!(red_at(&s, 150.0, 200.0), "the mirrored side"); - assert!(!red_at(&s, 200.0, 200.0), "between the two"); -} - -#[test] -fn closed_filled_path_copies_from_visible_source_to_backfacing_destination() { - let mut mesh = wall(); - for (position, normal) in mesh.positions.iter().zip(&mut mesh.normals) { - *normal = if position.x < 0.0 { Vec3::NEG_Z } else { Vec3::Z }; - } - - let mut s = session(mesh.clone()); - execute(&mut s, "tool.brush", &json!({"symmetryX": true})).unwrap(); - - let square = json!([[230, 170], [270, 170], [270, 230], [230, 230]]); - execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); - - assert!(red_at(&s, 250.0, 200.0), "visible source"); - assert!(red_at(&s, 150.0, 200.0), "backfacing symmetry copy"); - assert!(!red_at(&s, 200.0, 200.0), "outside the lasso and its copy"); - - let mut s = session(mesh); - execute(&mut s, "tool.brush", &json!({"symmetryX": true})).unwrap(); - - let square = json!([[130, 170], [170, 170], [170, 230], [130, 230]]); - execute(&mut s, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); - - assert!(!red_at(&s, 150.0, 200.0), "backfacing source"); - assert!(!red_at(&s, 250.0, 200.0), "no copy from a hidden source"); -} - -/// A 2×2 wall facing the camera (+Z): v grows downward (world −Y). -fn wall() -> Mesh { - let mut m = primitives::plane(2.0, 8); - for p in &mut m.positions { - *p = Vec3::new(p.x, -p.z, 0.0); - } - m.normals.iter_mut().for_each(|n| *n = Vec3::Z); - m.tangents.iter_mut().for_each(|t| *t = Vec4::new(1.0, 0.0, 0.0, 1.0)); - m -} - -/// Painted texel rows (v) after one particle dab at the wall's center. -fn particle_rows() -> Vec { - let mut s = session(wall()); - execute(&mut s, "tool.brush", &json!({"size": 10, "particles": {"enabled": true, "count": 6, "lifetime": 40, "gravity": 1.5}})).unwrap(); - let hit = s.pick(Vec2::new(200.0, 200.0), s.viewport).unwrap(); - assert!((hit.uv.y - 0.5).abs() < 0.02, "{hit:?}"); - execute(&mut s, "tool.stroke", &json!({"points": [[200, 200]]})).unwrap(); - let mut rows = Vec::new(); - for y in 0..RES as u32 { - for x in 0..RES as u32 { - let c = s.caches[0].composite.value(Channel::BaseColor, x, y); - if c[0] > 0.85 && c[1] < 0.5 { - rows.push(y); - } - } - } - rows -} - -#[test] -fn particle_brush_paints_below_the_start_and_is_deterministic() { - let rows = particle_rows(); - assert!(!rows.is_empty()); - let start = (0.5 * RES) as u32; - let lowest = rows.iter().max().copied().unwrap(); - let highest = rows.iter().min().copied().unwrap(); - assert!(lowest > start + 40, "trails run down the wall: {lowest}"); - assert!(highest + 20 > start, "nothing well above the start: {highest}"); - assert_eq!(rows, particle_rows()); -} - -#[test] -fn radial_symmetry_paints_copies_around_the_axis() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - assert!(execute(&mut s, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "w"})).is_err()); - let r = execute(&mut s, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "y"})).unwrap(); - assert_eq!(r["radialSymmetry"], json!({"copies": 2, "axis": "y"})); - execute(&mut s, "tool.stroke", &json!({"points": [[200, 200]]})).unwrap(); - s.update(); - assert!(red_at(&s, 200.0, 200.0)); - // Half a turn around Y: the copy faces the other way. - s.camera.yaw = std::f32::consts::PI; - assert!(red_at(&s, 200.0, 200.0), "the radial copy on the back"); -} - -/// The selected layer's content path sublayers: (effect id, stored paths). -fn path_sublayers(s: &Session) -> Vec<(u64, usize)> { - let l = s.doc.project.layer(s.selected_layer().unwrap()).unwrap(); - l.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id.0, p.len()))).collect() -} - -#[test] -fn committed_paths_stay_editable_in_a_path_sublayer() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); - let eid = r["committed"]["effect"].as_u64().unwrap(); - assert_eq!(r["committed"]["index"], 0); - assert_eq!(path_sublayers(&s), vec![(eid, 1)]); - // The next path goes into the same (selected) sublayer. - let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.9], [0.8, 0.9]], "commit": true})).unwrap(); - assert_eq!((r["committed"]["effect"].as_u64(), r["committed"]["index"].as_u64()), (Some(eid), Some(1))); - assert_eq!(path_sublayers(&s), vec![(eid, 2)]); - assert!(red_at(&s, 200.0, 180.0) && red_uv(&s, 0.5, 0.9)); - let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); - assert!(inspect.contains("\"paths\""), "inspect lists the paths"); - // Paths are saved with the project; editing a loaded path repaints only once it changes. - let saved = serde_json::to_string(&s.doc.project).unwrap(); - s.doc.project = serde_json::from_str(&saved).unwrap(); - assert_eq!(path_sublayers(&s), vec![(eid, 2)]); - execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); - assert!(!s.path_live().unwrap(), "a loaded path matches its settings"); - execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); - - // Manual strokes can't paint over a path sublayer. - let err = execute(&mut s, "tool.stroke", &json!({"points": [[200, 240]]})).unwrap_err().to_string(); - assert!(err.contains("path sublayer"), "{err}"); - - // Edit the first path: moving its points repaints it live, the other path stays. - let undo_before = s.history_labels().len(); - let r = execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); - assert_eq!(r["points"], 3); - let r = execute(&mut s, "tool.path", &json!({"points": [[140, 250], [200, 230], [260, 250]]})).unwrap(); - assert_eq!(r["editing"]["index"], 0, "{r}"); - assert!(red_at(&s, 200.0, 230.0), "the edited curve shows at once"); - assert!(!red_at(&s, 200.0, 180.0), "the old curve is gone"); - assert!(red_uv(&s, 0.5, 0.9), "the other path is kept"); - // Brush changes repaint too, merged into the same undo step. - execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); - execute(&mut s, "tool.path", &json!({})).unwrap(); - assert!(!red_at(&s, 200.0, 230.0), "repainted with the new color"); - assert_eq!(s.history_labels().len(), undo_before + 1); - execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); - assert_eq!(s.history_labels().len(), undo_before + 1, "one step for the whole edit"); - assert!(s.tool.path.editing.is_none() && s.tool.path.points.is_empty()); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - s.update(); - assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 230.0), "undo restores the original path"); - - // Remove a path: its paint goes, the sublayer keeps the rest. - execute(&mut s, "path.remove", &json!({"effect": eid, "index": 0})).unwrap(); - assert_eq!(path_sublayers(&s), vec![(eid, 1)]); - assert!(!red_at(&s, 200.0, 180.0) && red_uv(&s, 0.5, 0.9)); - assert!(execute(&mut s, "path.edit", &json!({"effect": eid, "index": 5})).is_err()); - assert!(execute(&mut s, "path.remove", &json!({"effect": 999999, "index": 0})).is_err()); -} - -#[test] -fn undo_while_editing_a_path_stops_the_edit() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); - let eid = r["committed"]["effect"].as_u64().unwrap(); - execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); - execute(&mut s, "tool.path", &json!({"points": [[140, 250], [200, 230], [260, 250]]})).unwrap(); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert!(s.tool.path.editing.is_none()); - assert!(!s.path_live().unwrap(), "nothing repaints over the undone state"); - s.update(); - assert!(red_at(&s, 200.0, 180.0)); -} - -#[test] -fn each_path_and_each_edit_of_one_is_its_own_undo_step() { - let mut s = session(primitives::sphere(1.0, 48, 24)); - let steps = |s: &Session| s.history_labels().len(); - let start = steps(&s); - let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); - let eid = r["committed"]["effect"].as_u64().unwrap(); - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.9], [0.8, 0.9]], "commit": true})).unwrap(); - assert_eq!(steps(&s), start + 2, "two paths, two steps"); - for y in [250, 230] { - execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); - execute(&mut s, "tool.path", &json!({"points": [[140, y], [200, y - 20], [260, y]]})).unwrap(); - execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); - } - assert_eq!(steps(&s), start + 4, "a second edit of the same path doesn't join the first"); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - s.update(); - assert!(red_at(&s, 200.0, 230.0), "undo brings back the first edit"); -} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index a752e79b..554a712a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -54,6 +54,84 @@ fn layers_masks_materials_and_bake() { assert_eq!(s.doc.project.walk(0).len(), 1, "back to the initial paint layer"); } +#[test] +fn generator_offset_is_settable_and_clamped() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "position", "offset": 0.25})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + let offset = |s: &Session| { + let layer = s.doc.project.layers.values().find(|l| l.mask.is_some()).unwrap(); + layer + .mask + .as_ref() + .unwrap() + .effects + .iter() + .find_map(|e| match &e.kind { + texturecraft_engine::core::EffectKind::Generator(g) => Some(g.offset), + _ => None, + }) + .unwrap() + }; + assert_eq!(offset(&s), 0.25); + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": 5.0})).unwrap(); + assert_eq!(offset(&s), 1.0, "clamped to 1"); +} + +fn generator_offset_of(s: &Session) -> f32 { + let layer = s.doc.project.layers.values().find(|l| l.mask.is_some()).unwrap(); + layer + .mask + .as_ref() + .unwrap() + .effects + .iter() + .find_map(|e| match &e.kind { + texturecraft_engine::core::EffectKind::Generator(g) => Some(g.offset), + _ => None, + }) + .unwrap() +} + +#[test] +fn generator_offset_survives_save_and_reopen_and_undo_restores_it() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "position", "offset": 0.25})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": -0.6})).unwrap(); + assert_eq!(generator_offset_of(&s), -0.6); + + let path = std::env::temp_dir().join(format!("tc-generator-offset-{}.tcraft", std::process::id())); + let path = path.to_str().unwrap(); + execute(&mut s, "file.saveCopy", &json!({"path": path})).unwrap(); + let reopened = texturecraft_engine::file_cmds::open_path(path); + let _ = std::fs::remove_file(path); + assert_eq!(generator_offset_of(&reopened.unwrap()), -0.6, "the offset is saved and read back"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(generator_offset_of(&s), 0.25, "undo restores the previous offset"); +} + +#[test] +fn generator_offset_works_alongside_curvature_mode_and_sizes() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities", "offset": 0.5})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + assert_eq!(generator_offset_of(&s), 0.5); + + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": -0.5, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap(); + assert_eq!(generator_offset_of(&s), -0.5); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""offset":-0.5"#) && inspect.contains(r#""mode":"Cavities""#), "{inspect}"); + assert!(inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}"); +} + #[test] fn layer_rename_and_undo() { let mut s = session(); @@ -105,6 +183,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 +236,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(); } @@ -189,6 +308,67 @@ fn image_resources_fill_layers_and_round_trip() { assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err()); } +#[test] +fn image_resource_lookup_accepts_extension_and_stem() { + let mut s = session(); + + // No resources imported yet + let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err(); + assert!(err.to_string().contains("no resource `missing` (no resources imported: use resource.import)")); + + let mut png = Vec::new(); + let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.import_resource_bytes("tile.png", png.clone()).unwrap(); + + // Lookup by stem + let r = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap(); + assert!(r["layer"].as_u64().is_some()); + + // Lookup by full name + let r2 = execute(&mut s, "layer.add.image", &json!({"name": "tile.png"})).unwrap(); + assert!(r2["layer"].as_u64().is_some()); + + // Missing resource lists available + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err(); + assert!(err.to_string().contains("no resource `wood` (available: tile.png)")); + + // Ambiguous stem resolution + s.import_resource_bytes("tile.jpg", png).unwrap(); + let err = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap_err(); + assert!(err.to_string().contains("ambiguous resource `tile`")); +} + +#[test] +fn image_resource_lookup_ignores_linked_packages() { + use std::sync::Arc; + use texturecraft_engine::core::{LayerId, LayerKind, Source}; + + let mut s = session(); + s.doc.resources.insert("wood.mcraft".into(), Arc::new(b"package bytes".to_vec())); + s.sync_images(); + assert!(!s.images.contains_key("wood.mcraft")); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err(); + assert!(err.to_string().contains("no resources imported"), "{err}"); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood.mcraft"})).unwrap_err(); + assert!(err.to_string().contains("no resource `wood.mcraft` (no resources imported"), "{err}"); + + let mut png = Vec::new(); + let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.import_resource_bytes("wood.png", png).unwrap(); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err(); + assert!(err.to_string().contains("no resource `missing` (available: wood.png)"), "{err}"); + + let res = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap(); + let id = LayerId(res["layer"].as_u64().unwrap()); + let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("expected fill layer") }; + assert_eq!(fill.sources.get(&Channel::BaseColor), Some(&Source::image("wood.png"))); +} + #[test] fn brush_presets_apply_save_and_load() { let mut s = session(); @@ -390,8 +570,7 @@ fn painted_set() -> Session { execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap(); execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); execute(&mut s, "tool.brush", &json!({"size": 12, "hardness": 70, "opacity": 0.8})).unwrap(); - // A stroke creates the layer's images; later edits only rewrite tiles of images that exist - // (the first stroke of a channel adds an image, which recomposites the whole set). + // Seed the image so later strokes change existing tiles execute(&mut s, "tool.stroke", &json!({"points": [[150, 160], [170, 170]]})).unwrap(); s.update(); s @@ -425,7 +604,7 @@ fn check_undo_redo(s: &mut Session, change: impl FnOnce(&mut Session), limit: Op fn undo_recomposites_only_changed_tiles() { let mut s = painted_set(); let stroke = |s: &mut Session| drop(execute(s, "tool.stroke", &json!({"points": [[150, 200], [190, 210]]})).unwrap()); - // The stroke covers a handful of the set's 1024 tiles. + // The stroke covers a handful of the set's 1024 tiles check_undo_redo(&mut s, stroke, Some(64)); } @@ -472,3 +651,143 @@ fn undo_of_a_layer_change_recomposites_everything() { let change = |s: &mut Session| drop(execute(s, "layer.blend", &json!({"channel": "all", "opacity": 0.5})).unwrap()); check_undo_redo(&mut s, change, None); } + +#[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"); +} + +#[test] +fn generators_take_blur_balance_and_contrast() { + 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": "dirt", "blur": 0.25})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""blur":0.25"#) && inspect.contains(r#""balance":0.75"#), "{inspect}"); + assert!(inspect.contains(r#""contrast":1.0"#), "contrast is clamped to 0..1: {inspect}"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "custom", "customResolution": 512, "resolutionFactor": -9})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""resolution":{"custom":512,"factor":-3,"mode":"Custom"}"#), "the factor is clamped to 1/8: {inspect}"); + assert!(execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "huge"})).is_err(), "unknown resolutions are rejected"); +} + +#[test] +fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"uniform":[0.25,0.25,0.25]}}"#), "{inspect}"); + + let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5})); + assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature"); + let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"})); + assert!(missing_image.is_err(), "the image must be a resource of the project"); + let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true})); + assert!(two_sources.is_err(), "an input takes one source"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputBaked": true})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(!inspect.contains(r#""inputs""#), "the mesh map is read again: {inspect}"); +} + +#[test] +fn changing_generator_kind_keeps_the_effect_identity_and_settings() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut state, "effect.set", &json!({"effect": effect, "name": "Keep me", "opacity": 0.4, "level": 0.2})).unwrap(); + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap(); + let later = execute(&mut state, "effect.add.generator", &json!({"generator": "position"})).unwrap()["effect"].as_u64().unwrap(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "generator": "ambientOcclusion"})).unwrap(); + + let (owner, edited) = state.doc.project.effect(texturecraft_core::LayerId(effect)).unwrap(); + assert!(matches!(&edited.kind, texturecraft_core::EffectKind::Generator(generator) + if generator.kind == texturecraft_core::GeneratorKind::AmbientOcclusion + && generator.level == 0.2 + && matches!(generator.inputs.get(&texturecraft_core::BakedMap::AmbientOcclusion), Some(texturecraft_core::Source::Uniform([0.25, 0.25, 0.25]))))); + assert_eq!(edited.name, "Keep me"); + assert_eq!(edited.opacity, 0.4); + let layer = state.doc.project.layer(owner).unwrap(); + let ids: Vec = layer.mask.as_ref().unwrap().effects.iter().map(|item| item.id.0).collect(); + assert_eq!(ids, vec![effect, later]); +} + +#[test] +fn unparseable_color_param_returns_error() { + let mut s = session(); + let err = execute(&mut s, "layer.add.fill", &json!({"color": "#fff"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "color": "#123"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "mask.add.colorSelection", &json!({"color": "#xyz"})).unwrap_err(); + assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "display.set", &json!({"scatterColor": "#12345"})).unwrap_err(); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let rev_before = s.revision; + let exposure_before = s.doc.project.display.env_exposure; + let err = execute(&mut s, "display.set", &json!({"exposure": 2.0, "scatterColor": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.doc.project.display.env_exposure, exposure_before); + assert_eq!(s.revision, rev_before); + + let mask_before = s.tool.mask_value; + let err = execute(&mut s, "tool.material", &json!({"maskValue": 0.25, "channel": "baseColor", "color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.tool.mask_value, mask_before); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "tool.material", &json!({"color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "layer.add.fill", &json!({"color": [1e40, 0.0, 0.0]})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "noise", "color": "red"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + assert!(execute(&mut s, "tool.cloneSource", &json!({"uv": [0.2, 0.8, 0.4]})).is_err()); + execute(&mut s, "tool.polygonFill", &Value::Null).unwrap(); + let err = execute(&mut s, "tool.click", &json!({"uv": [0.2, 0.8, 0.4]})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.click`: a 2D view point needs `uv` as [u, v]"); +} diff --git a/crates/engine/tests/tools.rs b/crates/engine/tests/tools.rs deleted file mode 100644 index dcd65100..00000000 --- a/crates/engine/tests/tools.rs +++ /dev/null @@ -1,182 +0,0 @@ -//! Clone, smudge, image and library alphas and the quick mask, driven through engine commands the way -//! agents paint. - -use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; -use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; - -const RES: f32 = 256.0; - -fn session() -> Session { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); - s.viewport = Vec2::new(400.0, 400.0); - s.camera.yaw = 0.0; - s.camera.pitch = 0.0; - s.update(); - s -} - -/// Base color of the composite under a viewport point. -fn color_at(s: &Session, x: f32, y: f32) -> [f32; 3] { - let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); - s.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * RES) as u32, (hit.uv.y * RES) as u32) -} - -fn red(v: [f32; 3]) -> bool { - v[0] > 0.85 && v[1] < 0.15 -} - -fn dab(s: &mut Session, x: f32, y: f32) { - execute(s, "tool.stroke", &json!({"points": [[x, y]]})).unwrap(); -} - -fn paint_red(s: &mut Session, size: f32) { - execute(s, "tool.paint", &Value::Null).unwrap(); - execute(s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); - execute(s, "tool.brush", &json!({"size": size, "hardness": 90})).unwrap(); -} - -#[test] -fn clone_copies_values_from_the_source_offset() { - let mut s = session(); - paint_red(&mut s, 20.0); - dab(&mut s, 160.0, 200.0); - assert!(red(color_at(&s, 160.0, 200.0))); - assert!(!red(color_at(&s, 240.0, 200.0))); - - execute(&mut s, "tool.clone", &Value::Null).unwrap(); - assert!(execute(&mut s, "tool.stroke", &json!({"points": [[240, 200]]})).is_err(), "no source yet"); - execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap(); - execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); - dab(&mut s, 240.0, 200.0); - let v = color_at(&s, 240.0, 200.0); - assert!(red(v), "cloned red: {v:?}"); - // The offset stays for the next strokes: the source moved along with the destination. - let off = s.tool.clone_source.unwrap().offset.unwrap(); - assert!(off[0].abs() > 0.01, "{off:?}"); - // One undo step per clone stroke. - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - s.update(); - assert!(!red(color_at(&s, 240.0, 200.0))); -} - -#[test] -fn smudge_drags_color_along_the_stroke() { - let mut s = session(); - paint_red(&mut s, 12.0); - dab(&mut s, 170.0, 200.0); - let before = color_at(&s, 205.0, 200.0); - assert!(!red(before), "{before:?}"); - execute(&mut s, "tool.smudge", &Value::Null).unwrap(); - execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap(); - let pts: Vec<[f32; 2]> = (0..=40).map(|i| [170.0 + i as f32, 200.0]).collect(); - execute(&mut s, "tool.stroke", &json!({"points": pts})).unwrap(); - let after = color_at(&s, 205.0, 200.0); - assert!(after[0] - before[0] > 0.2 && after[1] < before[1], "red dragged right: {before:?} -> {after:?}"); -} - -#[test] -fn image_alpha_shapes_the_stamp() { - let mut s = session(); - let mut png = Vec::new(); - // Top half white, bottom half black. - let img = image::RgbaImage::from_fn(16, 16, |_, y| if y < 8 { image::Rgba([255; 4]) } else { image::Rgba([0, 0, 0, 255]) }); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - let name = s.import_resource_bytes("half.png", png).unwrap(); - paint_red(&mut s, 20.0); - assert!(execute(&mut s, "tool.brush", &json!({"alpha": {"image": "missing.png"}})).is_err()); - let r = execute(&mut s, "tool.brush", &json!({"alpha": {"image": name}})).unwrap(); - assert_eq!(r["alpha"]["image"], json!(name)); - execute(&mut s, "tool.strokeUv", &json!({"points": [[0.5, 0.5]]})).unwrap(); - // In the 2D view +v points down: the image's top half lands above the center. - let at = |s: &Session, dy: i32| s.caches[0].composite.value(Channel::BaseColor, 128, (128 + dy) as u32); - assert!(red(at(&s, -12)), "{:?}", at(&s, -12)); - assert!(!red(at(&s, 12)), "{:?}", at(&s, 12)); - // A procedural alpha clears the image. - let r = execute(&mut s, "tool.brush", &json!({"alpha": "round"})).unwrap(); - assert_eq!(r["alpha"], json!("Round")); -} - -/// Offsets (dx, dy) of red composite texels within `r` texels of (cx, cy), with their lengths. -fn red_offsets(s: &Session, cx: i32, cy: i32, r: i32) -> Vec<(i32, i32, f32)> { - let mut out = Vec::new(); - for dy in -r..=r { - for dx in -r..=r { - let (x, y) = (cx + dx, cy + dy); - if (0..RES as i32).contains(&x) && (0..RES as i32).contains(&y) && red(s.caches[0].composite.value(Channel::BaseColor, x as u32, y as u32)) { - out.push((dx, dy, ((dx * dx + dy * dy) as f32).sqrt())); - } - } - } - out -} - -#[test] -fn library_alphas_shape_the_stamp() { - let mut s = session(); - paint_red(&mut s, 20.0); - let list = execute(&mut s, "alpha.list", &Value::Null).unwrap(); - assert!(list["library"].as_array().is_some_and(|a| a.len() >= 60), "{list}"); - assert_eq!(list["procedural"][0], json!("Round")); - assert!(execute(&mut s, "tool.brush", &json!({"alpha": {"library": "nope"}})).is_err()); - let r = execute(&mut s, "tool.brush", &json!({"alpha": {"library": "Ring"}})).unwrap(); - assert_eq!(r["alpha"], json!({"library": "ring"})); - - // 2D view: a ring with a clean middle. - execute(&mut s, "tool.strokeUv", &json!({"points": [[0.5, 0.5]]})).unwrap(); - let ring = red_offsets(&s, 128, 128, 48); - let outer = ring.iter().map(|t| t.2).fold(0.0, f32::max); - assert!(outer > 6.0 && outer < 47.0, "{outer}"); - assert!(ring.iter().all(|t| t.2 > outer * 0.45), "the middle stays clean"); - let mid = (outer * 0.72 / 0.92).round() as i32; - for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { - assert!(ring.iter().any(|t| (t.0, t.1) == (dx * mid, dy * mid)), "ring at {:?}", (dx * mid, dy * mid)); - } - - // 3D view: the same hollow stamp on the sphere. - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - s.update(); - dab(&mut s, 200.0, 200.0); - let hit = s.pick(Vec2::new(200.0, 200.0), s.viewport).unwrap(); - let (cx, cy) = ((hit.uv.x * RES) as i32, (hit.uv.y * RES) as i32); - let ring = red_offsets(&s, cx, cy, 48); - assert!(!ring.is_empty(), "painted"); - assert!(ring.iter().all(|t| t.2 > 2.0), "the middle stays clean"); - - // A procedural alpha clears the library alpha. - let r = execute(&mut s, "tool.brush", &json!({"alpha": "square"})).unwrap(); - assert_eq!(r["alpha"], json!("Square")); - assert!(s.tool.brush.alpha_library.is_none()); -} - -#[test] -fn quick_mask_limits_painting() { - let mut s = session(); - paint_red(&mut s, 20.0); - let r = execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap(); - assert_eq!(r["editing"], json!(true)); - assert_eq!(r["enabled"], json!(true), "editing enables the mask"); - let undo = s.history_labels().len(); - dab(&mut s, 150.0, 200.0); - assert!(!red(color_at(&s, 150.0, 200.0)), "mask strokes do not paint the layer"); - assert_eq!(s.history_labels().len(), undo, "mask strokes stay out of the history"); - assert!(s.quick_mask_rgba(0, 64).is_some_and(|v| v.len() == 64 * 64 * 4)); - execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap(); - - execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); - dab(&mut s, 150.0, 200.0); - dab(&mut s, 250.0, 200.0); - assert!(red(color_at(&s, 150.0, 200.0)), "inside the mask"); - assert!(!red(color_at(&s, 250.0, 200.0)), "outside the mask"); - - execute(&mut s, "viewport.quickMask.invert", &Value::Null).unwrap(); - dab(&mut s, 250.0, 200.0); - assert!(red(color_at(&s, 250.0, 200.0)), "inverted: outside is open"); - - execute(&mut s, "viewport.quickMask", &json!({"enabled": false})).unwrap(); - execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap(); - dab(&mut s, 150.0, 200.0); - assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); -} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index cb0fa8c5..f7053917 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,13 +9,20 @@ license.workspace = true workspace = true [dependencies] +craft-usd.workspace = true +# ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local. +craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "272a095b61257917693da3d09f2f8ecccd7f0295" } +craft-materialx = { workspace = true } +craft-mesh = { workspace = true } +craft-mcmat = { workspace = true } +craft-tcraft = { workspace = true } +craft-zip = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } texturecraft-compose = { workspace = true } image = { workspace = true } gltf = { workspace = true } -tobj = { workspace = true } flate2 = { workspace = true } lz4_flex = { workspace = true } half = { workspace = true } @@ -27,3 +34,6 @@ serde_json = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true } base64 = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +sysinfo = { workspace = true } diff --git a/crates/formats/README.md b/crates/formats/README.md index 70f8429b..9c0580fe 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -122,11 +122,14 @@ Built-in presets: pub struct ProjectFile { pub project: Project, pub pixels: PixelStore, pub baked: BTreeMap, pub mesh: Option<(String /* ext */, Vec)>, pub thumbnail: Option>, + pub warnings: Vec, // Import warnings, never saved } pub fn save_project_bytes(pf: &ProjectFile) -> Result>; pub fn load_project_bytes(bytes: &[u8]) -> Result; pub fn save_project(path: &Path, pf: &ProjectFile) -> Result<()>; // native, atomic pub fn load_project(path: &Path) -> Result; // native +pub fn set_project_open_limit_gib(limit_gib: u32); // subsequent loads, minimum 1 GiB +pub fn project_open_limit_gib() -> u32; ``` `.tcraft` layout (zip, deflate): @@ -144,7 +147,34 @@ 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 -total decompressed size at 8 GiB. +out-of-range tiles and trailing data, and drops pixels of layers that are in no stack. Total +decompressed project data is limited to 8 GiB by default. Settings › Project › Max project size on +open changes this limit, in GiB, independently of the save CPU and RAM preferences. Each load keeps +the limit it started with; individual resource, mesh, image and entry-count limits still apply. +The limit counts file data, including binary headers and tile coordinates, rather than peak process +memory. Saves and autosaves are not refused by this open limit; raise it to reopen a larger project. + +Opening checks the sum of all declared ZIP payload sizes before decompression, including unknown +entries, and checks actual reads against the same limit independently. Overlapping ZIP entries are +rejected. ZIP indexing is restricted to the final 32 MiB with a 64 MiB read allowance before the +100,000-entry limit can be checked. Baked-map dimensions must agree with the entry size; float data +is read in bounded chunks with fallible allocation. Nested archives are not recursively extracted +by the project reader. Subsequent image and mesh decoding has separate format-specific limits; +the project-open limit is not a combined budget for those decoded assets or the application's heap. + +Native saves compress entries in parallel within the configured CPU allowance and an estimated +in-flight byte budget. Stored resources and entries larger than that budget stream directly into +the destination without a whole-entry temporary buffer. The save RAM percentage is an estimate, +excluding compressor, allocator and project-snapshot overhead; it is not a peak process memory cap. + +Unreadable bake settings fall back to defaults field by field while readable settings and project +content are retained. Legacy baked-map filenames remain readable; unsupported baked-map types are +skipped. Recovery adds a warning to `ProjectFile::warnings`, displayed in the session log when the +project opens. Structural errors and corrupt pixel data still fail validation. diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index bba40729..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).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/export/tests.rs b/crates/formats/src/export/tests.rs index 83e8cf46..8bf6ad66 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -200,7 +200,7 @@ fn ao_mixes_baked_and_channel() { let mesh_maps = fx.render_preset("Mesh maps"); assert_eq!(mesh_maps.len(), 1, "only baked maps are exported"); let ao = decode(&mesh_maps[0]); - assert_eq!(mesh_maps[0].name, "sphere_Body_Set_ambient_occlusion.png"); + assert_eq!(mesh_maps[0].name, "sphere_Body_Set_ambientOcclusion.png"); assert_eq!(ao.color(), image::ColorType::L16); } diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs index b047ba49..fbd27985 100644 --- a/crates/formats/src/fonts.rs +++ b/crates/formats/src/fonts.rs @@ -72,34 +72,37 @@ fn collect(dir: &Path, depth: usize, out: &mut Vec) { /// The faces of the font file at `path` (each face of a collection). pub fn faces_of(path: &Path) -> std::io::Result> { - let mut f = std::fs::File::open(path)?; - let mut at = |offset: u64, len: usize| -> std::io::Result> { - f.seek(SeekFrom::Start(offset))?; - let mut buf = vec![0; len]; - f.read_exact(&mut buf)?; + let mut file = std::fs::File::open(path)?; + let mut read_at = |offset: u64, length: usize| -> std::io::Result> { + file.seek(SeekFrom::Start(offset))?; + let mut buf = vec![0; length]; + file.read_exact(&mut buf)?; Ok(buf) }; - let head = at(0, 12)?; - let offsets: Vec = if head.get(..4) == Some(b"ttcf") { - let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); - let table = at(12, 4 * n as usize)?; - (0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() + + let header = read_at(0, 12)?; + let offsets: Vec = if header.get(..4) == Some(b"ttcf") { + let face_count = u32_at(&header, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); + let table = read_at(12, 4 * face_count as usize)?; + (0..face_count as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() } else { vec![0] }; + let mut faces = Vec::new(); for (index, offset) in offsets.into_iter().enumerate() { - let dir = at(offset, 12)?; - let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?; - let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue }; - let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue }; - let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?; + let directory = read_at(offset, 12)?; + let tables = read_at(offset + 12, 16 * usize::from(u16_at(&directory, 4).unwrap_or(0)))?; + let Some(record) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue }; + let (Some(offset), Some(length)) = (u32_at(record, 8), u32_at(record, 12)) else { continue }; + let names = read_at(u64::from(offset), length.min(MAX_NAME_TABLE) as usize)?; let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id)); if let Some(family) = name([16, 1]) { let style = name([17, 2]).unwrap_or_else(|| "Regular".into()); faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 }); } } + Ok(faces) } @@ -113,30 +116,32 @@ fn u32_at(b: &[u8], o: usize) -> Option { /// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode /// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1). -fn name_string(t: &[u8], id: u16) -> Option { - let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?)); +fn name_string(table: &[u8], id: u16) -> Option { + let (count, base) = (usize::from(u16_at(table, 2)?), usize::from(u16_at(table, 4)?)); let mut best: Option<(u8, String)> = None; - for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) { - let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?); - let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?)); - let Some(bytes) = t.get(base + off..base + off + len) else { continue }; + for record in (0..count).filter_map(|i| table.get(6 + 12 * i..18 + 12 * i)) { + let (platform, language, name_id) = (u16_at(record, 0)?, u16_at(record, 4)?, u16_at(record, 6)?); + let (length, offset) = (usize::from(u16_at(record, 8)?), usize::from(u16_at(record, 10)?)); + let Some(bytes) = table.get(base + offset..base + offset + length) else { continue }; if name_id != id { continue; } - let (rank, s) = match platform { + + let (rank, name) = match platform { 3 | 0 => { - let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); - (if language == 0x409 { 0 } else { 1 }, s) + let name = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect::>()); + (if language == 0x409 { 0 } else { 1 }, name) } 1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()), _ => continue, }; - let s = s.trim().to_string(); - if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) { - best = Some((rank, s)); + let name = name.trim().to_string(); + if !name.is_empty() && best.as_ref().is_none_or(|(best_rank, _)| rank < *best_rank) { + best = Some((rank, name)); } } - best.map(|(_, s)| s) + + best.map(|(_, name)| name) } #[cfg(test)] diff --git a/crates/formats/src/icc.rs b/crates/formats/src/icc.rs index 9323f561..f0f16a84 100644 --- a/crates/formats/src/icc.rs +++ b/crates/formats/src/icc.rs @@ -1,63 +1,7 @@ -//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small -//! (about 1.2 KiB) and readable by every colour-managed viewer and editor. -//! -//! The colorants come from the space's primaries adapted to the D50 profile connection space -//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear -//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied -//! from a colour-management library or from another profile. - +//! ICC v2.1 export policy; byte serialization is shared with craft-cms. +use craft_cms_icc_v2::write_v2::{MatrixProfile, ToneCurve, matrix_profile}; use texturecraft_texel::{ColorSpace, srgb_to_linear}; - -/// Samples of the sRGB curve table. const CURVE_POINTS: usize = 1024; -/// The D50 white of the profile connection space. -const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; - -fn s15f16(v: f64) -> [u8; 4] { - ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() -} - -fn xyz_tag(v: [f64; 3]) -> Vec { - let mut b = b"XYZ \0\0\0\0".to_vec(); - for c in v { - b.extend_from_slice(&s15f16(c)); - } - b -} - -fn text_tag(text: &str) -> Vec { - let mut b = b"text\0\0\0\0".to_vec(); - b.extend_from_slice(text.as_bytes()); - b.push(0); - b -} - -/// `textDescriptionType` with the ASCII description only. -fn desc_tag(text: &str) -> Vec { - let mut b = b"desc\0\0\0\0".to_vec(); - b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); - b.extend_from_slice(text.as_bytes()); - b.push(0); - // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. - b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); - b -} - -fn curve_tag(space: ColorSpace) -> Vec { - let mut b = b"curv\0\0\0\0".to_vec(); - if space == ColorSpace::Srgb { - b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes()); - for i in 0..CURVE_POINTS { - let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); - b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); - } - } else { - // One entry is a gamma, u8Fixed8: 1.0 is linear. - b.extend_from_slice(&1u32.to_be_bytes()); - b.extend_from_slice(&0x0100u16.to_be_bytes()); - } - b -} fn description(space: ColorSpace) -> &'static str { match space { @@ -68,64 +12,41 @@ fn description(space: ColorSpace) -> &'static str { } } -/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones). +/// The ICC profile of `space`, or None if its primaries are degenerate. pub fn profile(space: ColorSpace) -> Option> { - let m = space.to_xyz_d50()?; - let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; - let curve = curve_tag(space); - // The green and blue curves are the red one's entry. - let tags: [(&[u8; 4], Vec); 9] = [ - (b"desc", desc_tag(description(space))), - (b"cprt", text_tag("No copyright, generated by TextureCraft")), - (b"wtpt", xyz_tag(D50_XYZ)), - (b"rXYZ", xyz_tag(column(0))), - (b"gXYZ", xyz_tag(column(1))), - (b"bXYZ", xyz_tag(column(2))), - (b"rTRC", curve.clone()), - (b"gTRC", curve.clone()), - (b"bTRC", curve), - ]; - // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. - let table_end = 128 + 4 + 12 * tags.len(); - let mut offsets = Vec::new(); - let mut data: Vec = Vec::new(); - for (i, (_, bytes)) in tags.iter().enumerate() { - let shared = i >= 7; - let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; - offsets.push(at); - if !shared { - data.extend_from_slice(bytes); - while !data.len().is_multiple_of(4) { - data.push(0); - } - } - } - let total = table_end + data.len(); - let mut out = vec![0u8; 128]; - out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); - out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 - out.get_mut(12..16)?.copy_from_slice(b"mntr"); - out.get_mut(16..20)?.copy_from_slice(b"RGB "); - out.get_mut(20..24)?.copy_from_slice(b"XYZ "); - // A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes. - out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]); - out.get_mut(36..40)?.copy_from_slice(b"acsp"); - for (k, v) in D50_XYZ.iter().enumerate() { - out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); - } - out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); - for ((sig, bytes), at) in tags.iter().zip(&offsets) { - out.extend_from_slice(*sig); - out.extend_from_slice(&(*at as u32).to_be_bytes()); - out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); - } - out.extend_from_slice(&data); - Some(out) + let matrix = space.to_xyz_d50()?; + let samples: Vec = if space == ColorSpace::Srgb { + (0..CURVE_POINTS) + .map(|i| { + let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); + (v * 65535.0).round().clamp(0.0, 65535.0) as u16 + }) + .collect() + } else { + Vec::new() + }; + matrix_profile(&MatrixProfile { + matrix, + curve: if samples.is_empty() { ToneCurve::Linear } else { ToneCurve::Samples(&samples) }, + description: description(space), + copyright: "No copyright, generated by TextureCraft", + date: [2026, 1, 1, 0, 0, 0], + }) } +#[cfg(test)] +#[path = "icc_legacy_test.rs"] +mod legacy; + #[cfg(test)] mod tests { use super::*; + #[test] + fn all_spaces_match_legacy_wire_bytes() { + for space in ColorSpace::ALL { + assert_eq!(profile(space), legacy::profile(space), "{space:?}"); + } + } fn u32_at(b: &[u8], i: usize) -> u32 { u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) diff --git a/crates/formats/src/icc_legacy_test.rs b/crates/formats/src/icc_legacy_test.rs new file mode 100644 index 00000000..47b4e600 --- /dev/null +++ b/crates/formats/src/icc_legacy_test.rs @@ -0,0 +1,124 @@ +//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small +//! (about 1.2 KiB) and readable by every colour-managed viewer and editor. +//! +//! The colorants come from the space's primaries adapted to the D50 profile connection space +//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear +//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied +//! from a colour-management library or from another profile. + +use texturecraft_texel::{ColorSpace, srgb_to_linear}; + +/// Samples of the sRGB curve table. +const CURVE_POINTS: usize = 1024; +/// The D50 white of the profile connection space. +const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; + +fn s15f16(v: f64) -> [u8; 4] { + ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() +} + +fn xyz_tag(v: [f64; 3]) -> Vec { + let mut b = b"XYZ \0\0\0\0".to_vec(); + for c in v { + b.extend_from_slice(&s15f16(c)); + } + b +} + +fn text_tag(text: &str) -> Vec { + let mut b = b"text\0\0\0\0".to_vec(); + b.extend_from_slice(text.as_bytes()); + b.push(0); + b +} + +/// `textDescriptionType` with the ASCII description only. +fn desc_tag(text: &str) -> Vec { + let mut b = b"desc\0\0\0\0".to_vec(); + b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); + b.extend_from_slice(text.as_bytes()); + b.push(0); + // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. + b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); + b +} + +fn curve_tag(space: ColorSpace) -> Vec { + let mut b = b"curv\0\0\0\0".to_vec(); + if space == ColorSpace::Srgb { + b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes()); + for i in 0..CURVE_POINTS { + let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); + b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); + } + } else { + // One entry is a gamma, u8Fixed8: 1.0 is linear. + b.extend_from_slice(&1u32.to_be_bytes()); + b.extend_from_slice(&0x0100u16.to_be_bytes()); + } + b +} + +fn description(space: ColorSpace) -> &'static str { + match space { + ColorSpace::Srgb => "sRGB (Rec.709 primaries, sRGB curve)", + ColorSpace::LinearRec709 => "Linear Rec.709 (sRGB primaries, D65)", + ColorSpace::AcesCg => "ACEScg (AP1 primaries, linear)", + ColorSpace::Aces2065 => "ACES2065-1 (AP0 primaries, linear)", + } +} + +/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones). +pub fn profile(space: ColorSpace) -> Option> { + let m = space.to_xyz_d50()?; + let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; + let curve = curve_tag(space); + // The green and blue curves are the red one's entry. + let tags: [(&[u8; 4], Vec); 9] = [ + (b"desc", desc_tag(description(space))), + (b"cprt", text_tag("No copyright, generated by TextureCraft")), + (b"wtpt", xyz_tag(D50_XYZ)), + (b"rXYZ", xyz_tag(column(0))), + (b"gXYZ", xyz_tag(column(1))), + (b"bXYZ", xyz_tag(column(2))), + (b"rTRC", curve.clone()), + (b"gTRC", curve.clone()), + (b"bTRC", curve), + ]; + // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. + let table_end = 128 + 4 + 12 * tags.len(); + let mut offsets = Vec::new(); + let mut data: Vec = Vec::new(); + for (i, (_, bytes)) in tags.iter().enumerate() { + let shared = i >= 7; + let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; + offsets.push(at); + if !shared { + data.extend_from_slice(bytes); + while !data.len().is_multiple_of(4) { + data.push(0); + } + } + } + let total = table_end + data.len(); + let mut out = vec![0u8; 128]; + out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); + out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 + out.get_mut(12..16)?.copy_from_slice(b"mntr"); + out.get_mut(16..20)?.copy_from_slice(b"RGB "); + out.get_mut(20..24)?.copy_from_slice(b"XYZ "); + // A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes. + out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]); + out.get_mut(36..40)?.copy_from_slice(b"acsp"); + for (k, v) in D50_XYZ.iter().enumerate() { + out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); + } + out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); + for ((sig, bytes), at) in tags.iter().zip(&offsets) { + out.extend_from_slice(*sig); + out.extend_from_slice(&(*at as u32).to_be_bytes()); + out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); + } + out.extend_from_slice(&data); + Some(out) +} diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 49e1e014..324c1d26 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -1,6 +1,6 @@ //! Decoding imported image resources (fills, alphas, stencils). -use crate::{FormatError, MAX_IMAGE_SIZE, Result}; +use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result}; /// A decoded image: RGBA as 0..1 floats in the file's own encoding (8/16-bit files stay /// sRGB-encoded; `srgb` says so), row-major, top row first. @@ -15,26 +15,37 @@ pub struct DecodedImage { /// Decode PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR bytes. pub fn decode_image(bytes: &[u8]) -> Result { - decode_image_within(bytes, u64::MAX) + decode_image_within(bytes, MAX_RESOURCE_TEXELS) } /// [`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 = - 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})"))); + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })?; + + // 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(|error| FormatError::Malformed { kind: "image", msg: error.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(|error| FormatError::Malformed { kind: "image", msg: error.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 }) } @@ -56,28 +67,62 @@ mod tests { #[test] fn decodes_png_and_rejects_garbage() { let mut png = Vec::new(); - let img = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255])); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - let d = decode_image(&png).unwrap(); - assert_eq!((d.width, d.height), (4, 2)); - assert!(d.srgb); - assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3); + let image = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255])); + image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + + let decoded = decode_image(&png).unwrap(); + + assert_eq!((decoded.width, decoded.height), (4, 2)); + assert!(decoded.srgb); + assert!((decoded.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3); assert!(decode_image(b"not an image").is_err()); assert!(decode_image(&png[..png.len() / 2]).is_err()); + let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap(); + assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]); 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 = { - let mut b = Vec::new(); - image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap(); - b + let mut bytes = Vec::new(); + image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes }; + assert_eq!(decode_image_within(&png, 64).unwrap().width, 8); assert!(matches!(decode_image_within(&png, 63), Err(FormatError::TooLarge(_)))); assert!(decode_image(&png).is_ok()); } + + #[test] + fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() { + // The edge limit permits 16384² but the default resource budget does not + let mut header = [0u8; 18]; + header[2] = 2; + header[12..14].copy_from_slice(&16_384u16.to_le_bytes()); + header[14..16].copy_from_slice(&16_384u16.to_le_bytes()); + header[16] = 24; + + assert!(matches!(decode_image(&header), Err(FormatError::TooLarge(_)))); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 31a6daea..c7309f2e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -47,14 +47,19 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; -pub use project_file::{ProjectFile, SkewData, load_project_bytes, sanitize_resource_name, save_project_bytes}; +pub use project_file::{ + BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, + set_project_open_limit_gib, +}; #[cfg(not(target_arch = "wasm32"))] pub use export::write_files; #[cfg(not(target_arch = "wasm32"))] pub use mesh_import::{import_mesh, read_mesh_file}; #[cfg(not(target_arch = "wasm32"))] -pub use project_file::{load_project, save_project}; +pub use project_file::{ + DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, load_project, save_project, save_ram_budget, set_save_resources, +}; #[derive(Debug, thiserror::Error)] pub enum FormatError { @@ -90,6 +95,10 @@ pub(crate) fn guard(kind: &'static str, f: impl FnOnce() -> Result) -> Res /// Largest image edge accepted or produced anywhere in this crate. pub const MAX_IMAGE_SIZE: u32 = 16_384; +/// Most texels an imported image resource may decode to by default (8192 × 8192). +/// Larger images are refused from their header before any pixels are decoded. +pub const MAX_RESOURCE_TEXELS: u64 = 1 << 26; + /// Read a whole file, refusing files over `cap` bytes. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { @@ -103,15 +112,64 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { Ok(std::fs::read(path)?) } -/// Write `bytes` to `path` atomically: `.tmp` first, then rename over the target. +/// Create a new temporary file beside `path`, refusing to reuse an existing (possibly symlinked) name. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> { + let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); + let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out"); + + // Bound retries when stale files or concurrent writers occupy candidate names + const MAX_TEMP_ATTEMPTS: u32 = 100; + + for attempt in 0..MAX_TEMP_ATTEMPTS { + let temporary_path = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&temporary_path) { + Ok(file) => return Ok((temporary_path, file)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.into()), + } + } + + Err(FormatError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not create a temporary file"))) +} + +/// Write `bytes` to `path` atomically: a new temporary file first, then rename over the target. #[cfg(not(target_arch = "wasm32"))] pub fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); - let res = std::fs::write(&tmp, bytes).and_then(|_| std::fs::rename(&tmp, path)); - if res.is_err() { - let _ = std::fs::remove_file(&tmp); + use std::io::Write; + + let (temporary_path, mut file) = create_temp(path)?; + let result = file.write_all(bytes).and_then(|_| file.sync_all()); + drop(file); + + let result = result.and_then(|_| std::fs::rename(&temporary_path, path)); + if result.is_err() { + let _ = std::fs::remove_file(&temporary_path); + } + + Ok(result?) +} + +#[cfg(all(test, unix))] +mod atomic_tests { + use super::write_atomic; + + #[test] + fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> { + let directory = std::env::temp_dir().join(format!("tc-atomic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&directory); + std::fs::create_dir_all(&directory)?; + let target = directory.join("out.png"); + let victim = directory.join("victim.txt"); + std::fs::write(&victim, b"safe")?; + std::os::unix::fs::symlink(&victim, directory.join("out.png.tmp"))?; + + write_atomic(&target, b"new").map_err(std::io::Error::other)?; + + assert_eq!(std::fs::read(&victim)?, b"safe"); + assert_eq!(std::fs::read(&target)?, b"new"); + + let _ = std::fs::remove_dir_all(&directory); + Ok(()) } - Ok(res?) } diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs index e7440328..9481ed13 100644 --- a/crates/formats/src/materialx.rs +++ b/crates/formats/src/materialx.rs @@ -1,20 +1,7 @@ -//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification -//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is -//! linked, and nothing is read from any other application. +//! TextureCraft's MaterialX export adapter. //! -//! [`write`] takes a material's name and the texture files an export produced, each tagged with -//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader -//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones -//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a -//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node -//! (OpenGL, +Y up, which is what that node expects). -//! -//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were -//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `` filename token MaterialX defines. -//! Texture file names are relative to the document. - -use std::collections::HashSet; -use std::fmt::Write as _; +//! The shared `craft-materialx` crate owns the MaterialX document writer. This module maps the +//! built-in preset's map names and TextureCraft color spaces to that format-level API. use texturecraft_texel::ColorSpace; @@ -51,7 +38,6 @@ pub const INPUTS: &[(&str, Kind)] = &[ ("height", Kind::Height), ]; -/// The file-name prefix of the built-in OpenPBR preset's maps. const PREFIX: &str = "$mesh_$textureSet_"; /// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`). @@ -59,14 +45,11 @@ const PREFIX: &str = "$mesh_$textureSet_"; pub struct Texture { pub input: String, pub file: String, - /// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...); - /// used for colour inputs only, data maps are always linear. + /// The MaterialX colour space of the file's values; used for color inputs only. pub colorspace: &'static str, } -/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no -/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the -/// specification, which 1.39 readers may not know. +/// The MaterialX colour space of colour maps written in `space`. pub fn colorspace_name(space: ColorSpace) -> &'static str { match space { ColorSpace::Srgb => "srgb_texture", @@ -76,116 +59,28 @@ pub fn colorspace_name(space: ColorSpace) -> &'static str { } } -/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → -/// `base_color`), or None for templates this module has no place for. +/// The OpenPBR input a preset map's file template feeds, or None for unsupported templates. pub fn input_of_template(template: &str) -> Option<&'static str> { let suffix = template.strip_prefix(PREFIX)?; - INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n) -} - -fn kind_of(input: &str) -> Option { - INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k) + INPUTS.iter().find(|(name, _)| *name == suffix).map(|(name, _)| *name) } /// A MaterialX name: letters, digits and underscores, not starting with a digit. -pub fn node_name(s: &str) -> String { - let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); +pub fn node_name(name: &str) -> String { + let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { out.insert(0, '_'); } out } -fn esc(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - c if c.is_control() => out.push(' '), - c => out.push(c), - } - } - out -} - -fn image_name(input: &str) -> String { - format!("image_{}", node_name(input)) -} - -/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes -/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so -/// are repeats of one input (the first wins). +/// The text of a MaterialX OpenPBR document for `name` and the given texture files. pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String { - let base = node_name(name); - let mut seen = HashSet::new(); - let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect(); - let has = |i: &str| tex.iter().any(|(t, _)| t.input == i); - let mut x = String::new(); - let _ = writeln!(x, ""); - let _ = writeln!(x, ""); - - let shader = format!("OPBR_{base}"); - let _ = writeln!(x, " ", esc(&shader)); - for (t, kind) in &tex { - let (ty, node) = match kind { - Kind::Color => ("color3", image_name(&t.input)), - Kind::Float => ("float", image_name(&t.input)), - Kind::Normal => ("vector3", "normalmap".to_owned()), - Kind::Height => continue, - }; - let _ = writeln!(x, " ", t.input); - } - if has("emission_color") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - - for (t, kind) in &tex { - let (ty, space) = match kind { - Kind::Color => ("color3", Some(t.colorspace)), - Kind::Normal => ("vector3", None), - Kind::Float | Kind::Height => ("float", None), - }; - let node = image_name(&t.input); - let _ = writeln!(x, " "); - match space { - Some(space) => { - let _ = writeln!(x, " ", esc(&t.file)); - } - None => { - let _ = writeln!(x, " ", esc(&t.file)); - } - } - let _ = writeln!(x, " "); - } - if has("geometry_normal") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("geometry_normal")); - let _ = writeln!(x, " "); - } - if has("height") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("height")); - let _ = writeln!(x, " "); - let _ = writeln!(x, " "); - } - - let doc = match physical_size_cm { - Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""), - _ => String::new(), - }; - let _ = writeln!(x, " ", esc(&base)); - let _ = writeln!(x, " ", esc(&shader)); - if has("height") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - let _ = writeln!(x, ""); - x + let textures: Vec = textures + .iter() + .map(|texture| craft_materialx::Texture { input: texture.input.clone(), file: texture.file.clone(), colorspace: texture.colorspace.to_owned() }) + .collect(); + craft_materialx::write_open_pbr(name, &textures, physical_size_cm) } #[cfg(test)] @@ -247,7 +142,7 @@ mod tests { assert!(x.contains(want), "missing {want}\n{x}"); } // Data textures carry no colour space, and height is not an OpenPBR input. - assert!(x.contains("value=\"stone_specular_roughness.png\" />")); + assert!(x.contains("value=\"stone_specular_roughness.png\"/>")); assert!(!x.contains("name=\"height\"")); } @@ -265,7 +160,7 @@ mod tests { fn colour_inputs_carry_their_files_space_and_data_inputs_none() { let lin = |input: &str, file: &str| Texture { colorspace: "lin_rec709", ..tex(input, file) }; let x = write("m", &[lin("base_color", "c.exr"), lin("specular_roughness", "r.exr")], None); - assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\" />"), "{x}"); + assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\"/>"), "{x}"); } #[test] @@ -292,7 +187,9 @@ mod tests { assert_eq!(node_name(""), "_"); let x = write("a&\"c", &[tex("base_color", "x\"&<'>..png")], Some([f32::NAN, 1.0])); assert!(balanced(&x.replace("<UDIM>", "UDIM")), "{x}"); - assert!(x.contains("value=\"x"&<'>.<UDIM>.png\"")); + let doc = craft_materialx::Document::parse(x.as_bytes()).unwrap(); + let material = doc.read_material(None).unwrap(); + assert!(material.inputs.iter().any(|(input, value)| input == "base_color" && value == &craft_materialx::Value::Image("x\"&<'>..png".into()))); assert!(!x.contains("doc="), "a non-finite size is left out"); assert!(x.contains("OPBR_a_b___c")); } diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index c8cd8b39..4de6abce 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -1,41 +1,16 @@ -//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF -//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure -//! Rust: no MaterialX library is linked. +//! MaterialX material import adapted to TextureCraft's channel model. //! -//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an -//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft -//! has a channel for into a literal value or an image file: -//! -//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted -//! to linear; a colour given for a scalar channel is averaged); -//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph` -//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and -//! `constant` nodes in between are passed through; -//! - the material's `displacementshader` becomes the height channel; -//! - `uvtiling` of the first tiled image is returned as the UV tiling. -//! -//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning -//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing -//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is. -//! -//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a -//! wiring loop stops at a depth limit, and every failure is an error, never a panic. +//! XML parsing, nodegraph traversal and shader input resolution live in `craft-materialx`. +//! This module maps those format-level values to TextureCraft's channels and color handling. -use std::collections::HashMap; - -use quick_xml::events::{BytesStart, Event}; -use texturecraft_core::Channel; +use texturecraft_core::{Channel, ChannelKind}; use texturecraft_texel::srgb_to_linear; use crate::{FormatError, Result, malformed}; const KIND: &str = "MaterialX document"; /// Largest document read, in bytes. -pub const MAX_BYTES: usize = 16 << 20; -const MAX_DEPTH: usize = 64; -const MAX_ELEMENTS: usize = 200_000; -/// Longest chain of nodes followed from one shader input. -const MAX_HOPS: usize = 16; +pub const MAX_BYTES: usize = craft_materialx::MAX_BYTES; /// What one channel is set from. #[derive(Clone, Debug, PartialEq)] @@ -58,259 +33,40 @@ pub struct Material { pub warnings: Vec, } -// --------------------------------------------------------------------------------------------- -// XML. - -#[derive(Default)] -struct El { - name: String, - attrs: Vec<(String, String)>, - children: Vec, +fn channel(shader: craft_materialx::Shader, input: &str) -> Option { + use craft_materialx::Shader::{GltfPbr, OpenPbr, StandardSurface}; + Some(match (shader, input) { + (OpenPbr, "base_color") | (StandardSurface, "base_color") | (GltfPbr, "base_color") => Channel::BaseColor, + (OpenPbr, "base_metalness") | (StandardSurface, "metalness") | (GltfPbr, "metallic") => Channel::Metallic, + (OpenPbr, "specular_roughness") | (StandardSurface, "specular_roughness") | (GltfPbr, "roughness") => Channel::Roughness, + (OpenPbr, "geometry_normal") | (StandardSurface, "normal") | (GltfPbr, "normal") => Channel::Normal, + (OpenPbr, "geometry_opacity") | (StandardSurface, "opacity") | (GltfPbr, "alpha") => Channel::Opacity, + (OpenPbr, "emission_color") | (StandardSurface, "emission_color") | (GltfPbr, "emission") => Channel::Emissive, + (OpenPbr, "coat_weight") | (StandardSurface, "coat") | (GltfPbr, "clearcoat") => Channel::CoatWeight, + (OpenPbr, "coat_roughness") | (StandardSurface, "coat_roughness") | (GltfPbr, "clearcoat_roughness") => Channel::CoatRoughness, + (OpenPbr, "geometry_coat_normal") | (StandardSurface, "coat_normal") | (GltfPbr, "clearcoat_normal") => Channel::CoatNormal, + (OpenPbr, "fuzz_weight") | (StandardSurface, "sheen") => Channel::SheenWeight, + (OpenPbr, "fuzz_color") | (StandardSurface, "sheen_color") | (GltfPbr, "sheen_color") => Channel::SheenColor, + (OpenPbr, "fuzz_roughness") | (StandardSurface, "sheen_roughness") | (GltfPbr, "sheen_roughness") => Channel::SheenRoughness, + (OpenPbr, "specular_roughness_anisotropy") | (StandardSurface, "specular_anisotropy") => Channel::AnisotropyLevel, + (OpenPbr, "transmission_weight") | (StandardSurface, "transmission") | (GltfPbr, "transmission") => Channel::Transmission, + (OpenPbr, "subsurface_weight") | (StandardSurface, "subsurface") => Channel::ScatterWeight, + (GltfPbr, "occlusion") => Channel::AmbientOcclusion, + _ => return None, + }) } -impl El { - fn attr(&self, k: &str) -> Option<&str> { - self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) +fn constant(channel: Channel, values: &[f32], colorspace: Option<&str>) -> [f32; 3] { + let mut values = values.to_vec(); + if let Some(space) = colorspace + && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) + && values.len() >= 3 + { + values.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); } - - /// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it). - fn input(&self, name: &str) -> Option<&El> { - self.children.iter().find(|c| c.attr("name") == Some(name)) - } -} - -fn element(e: &BytesStart) -> El { - let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); - let attrs = e - .attributes() - .with_checks(false) - .flatten() - .map(|a| { - (text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned())) - }) - .collect(); - El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() } -} - -fn parse_xml(bytes: &[u8]) -> Result { - let mut reader = quick_xml::Reader::from_reader(bytes); - let mut stack = vec![El::default()]; - let mut count = 0usize; - loop { - let event = reader.read_event().map_err(|e| malformed(KIND, e))?; - if matches!(event, Event::Start(_) | Event::Empty(_)) { - count += 1; - if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { - return Err(FormatError::TooLarge(format!( - "the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}" - ))); - } - } - match event { - Event::Start(e) => stack.push(element(&e)), - Event::Empty(e) => { - if let Some(parent) = stack.last_mut() { - parent.children.push(element(&e)); - } - } - Event::End(_) => { - let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?; - if let Some(parent) = stack.last_mut() { - parent.children.push(el); - } - } - Event::Eof => break, - _ => {} - } - } - match (stack.pop(), stack.is_empty()) { - (Some(root), true) => Ok(root), - _ => Err(malformed(KIND, "unclosed elements at the end of the document")), - } -} - -// --------------------------------------------------------------------------------------------- -// Shader input tables: (shader input, channel). `kind` says how to read the value. - -#[derive(Clone, Copy, PartialEq)] -enum Shader { - OpenPbr, - Standard, - Gltf, -} - -const OPEN_PBR: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("base_metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("geometry_normal", Channel::Normal), - ("geometry_opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat_weight", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("geometry_coat_normal", Channel::CoatNormal), - ("fuzz_weight", Channel::SheenWeight), - ("fuzz_color", Channel::SheenColor), - ("fuzz_roughness", Channel::SheenRoughness), - ("specular_roughness_anisotropy", Channel::AnisotropyLevel), - ("transmission_weight", Channel::Transmission), - ("subsurface_weight", Channel::ScatterWeight), -]; - -const STANDARD: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("coat_normal", Channel::CoatNormal), - ("sheen", Channel::SheenWeight), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("specular_anisotropy", Channel::AnisotropyLevel), - ("transmission", Channel::Transmission), - ("subsurface", Channel::ScatterWeight), -]; - -const GLTF: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metallic", Channel::Metallic), - ("roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("alpha", Channel::Opacity), - ("emission", Channel::Emissive), - ("occlusion", Channel::AmbientOcclusion), - ("clearcoat", Channel::CoatWeight), - ("clearcoat_roughness", Channel::CoatRoughness), - ("clearcoat_normal", Channel::CoatNormal), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("transmission", Channel::Transmission), -]; - -// --------------------------------------------------------------------------------------------- -// Resolving what feeds an input. - -struct Doc<'a> { - root: &'a El, - /// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`). - nodes: HashMap, - /// Each nodegraph's outputs: `graph/output` to the node name inside (qualified). - outputs: HashMap, - tiling: Option<[f32; 2]>, - warnings: Vec, -} - -enum Found { - Constant(Vec), - Image(String), - None, -} - -fn numbers(text: &str) -> Option> { - let v: Option> = text.split(',').map(|p| p.trim().parse::().ok().filter(|f| f.is_finite())).collect(); - v.filter(|v| !v.is_empty() && v.len() <= 4) -} - -impl<'a> Doc<'a> { - fn new(root: &'a El) -> Doc<'a> { - let mut nodes = HashMap::new(); - let mut outputs = HashMap::new(); - for c in &root.children { - match (c.name.as_str(), c.attr("name")) { - ("nodegraph", Some(g)) => { - for n in &c.children { - let Some(name) = n.attr("name") else { continue }; - if n.name == "output" { - if let Some(from) = n.attr("nodename") { - outputs.insert(format!("{g}/{name}"), format!("{g}/{from}")); - } - } else { - nodes.insert(format!("{g}/{name}"), n); - } - } - } - (_, Some(name)) => { - nodes.insert(name.to_owned(), c); - } - _ => {} - } - } - Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() } - } - - /// What `input` (an `` element of a node) resolves to; `scope` is the nodegraph the - /// node lives in, if any. - fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found { - if hops > MAX_HOPS { - self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); - return Found::None; - } - if let Some(v) = input.attr("value") { - return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n))); - } - let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) { - (Some(g), out, _) => { - let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned))); - out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned()) - } - (None, _, Some(n)) => { - Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned())) - } - _ => None, - }; - let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None }; - let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned()); - let scope = scope.as_deref(); - match node.name.as_str() { - "tiledimage" | "image" => { - let Some(file) = node.input("file").and_then(|f| f.attr("value")) else { - self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or(""))); - return Found::None; - }; - let prefix = - [node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next(); - if self.tiling.is_none() - && let Some(t) = - node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) - { - // The range a fill's UV scale accepts (`layer.fill.projection`). - self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]); - } - Found::Image(format!("{}{file}", prefix.unwrap_or(""))) - } - "normalmap" | "convert" => match node.input("in") { - Some(i) => self.resolve(i, scope, hops + 1), - None => Found::None, - }, - "constant" => match node.input("value") { - Some(v) => self.resolve(v, scope, hops + 1), - None => Found::None, - }, - other => { - self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or(""))); - Found::None - } - } - } - - /// Literal values tagged with an sRGB colour space are converted to linear. - fn tag(&self, input: &El, mut n: Vec) -> Vec { - let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or(""); - if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 { - n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); - } - n - } -} - -fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { - match (channel.kind(), n) { + match (channel.kind(), values.as_slice()) { (_, [a]) => [*a; 3], - (texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], + (ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], (_, [r, g, b, ..]) => { let mean = (r + g + b) / 3.0; [mean; 3] @@ -319,9 +75,11 @@ fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { } } -/// The literal number of `input`, if it is one. -fn literal(shader: &El, name: &str) -> Option { - shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied()) +fn app_value(channel: Channel, value: craft_materialx::Value) -> Value { + match value { + craft_materialx::Value::Constant { values, colorspace } => Value::Constant(constant(channel, &values, colorspace.as_deref())), + craft_materialx::Value::Image(file) => Value::Image(file), + } } /// Read the material called `material` (default: the first) from a `.mtlx` document. @@ -330,79 +88,30 @@ pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result } fn read_inner(bytes: &[u8], material: Option<&str>) -> Result { - if bytes.len() > MAX_BYTES { - return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20))); - } - let top = parse_xml(bytes)?; - let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no element"))?; - let mut doc = Doc::new(root); - let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect(); - let mat = match material { - Some(name) => materials - .iter() - .copied() - .find(|m| m.attr("name") == Some(name)) - .ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?, - None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?, - }; - let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() }; - let shader = mat - .input("surfaceshader") - .and_then(|i| i.attr("nodename")) - .and_then(|n| doc.nodes.get(n).copied()) - .ok_or_else(|| malformed(KIND, "the material has no surface shader"))?; - let (kind, table) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR), - "standard_surface" => (Shader::Standard, STANDARD), - "gltf_pbr" => (Shader::Gltf, GLTF), - other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))), - }; - // Emission is off by default in OpenPBR and standard_surface. - let emits = match kind { - Shader::OpenPbr => { - shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0)) - } - Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)), - Shader::Gltf => true, - }; - let weight = match kind { - Shader::OpenPbr => literal(shader, "base_weight"), - Shader::Standard => literal(shader, "base"), - Shader::Gltf => None, - }; - if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) { - doc.warnings.push("the base weight isn't 1; it was ignored".into()); - } - for &(input, channel) in table { - let Some(el) = shader.input(input) else { continue }; - if channel == Channel::Emissive && !emits && kind != Shader::Gltf { - doc.warnings.push(format!("{input} was skipped: the shader's emission is 0")); - continue; - } - match doc.resolve(el, None, 0) { - Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))), - Found::Image(f) => out.channels.push((channel, Value::Image(f))), - Found::None => {} + let document = craft_materialx::Document::parse(bytes).map_err(map_error)?; + let shared = document.read_material(material).map_err(map_error)?; + let mut channels = Vec::new(); + for (input, value) in shared.inputs { + if let Some(channel) = channel(shared.shader, &input) { + channels.push((channel, app_value(channel, value))); } } - // The displacement shader's `displacement` input is the height. - if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied()) - && let Some(i) = d.input("displacement") - { - match doc.resolve(i, None, 0) { - Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))), - Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))), - Found::None => {} - } + if let Some(value) = shared.displacement { + channels.push((Channel::Height, app_value(Channel::Height, value))); } - out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]); - out.warnings = doc.warnings; - Ok(out) + Ok(Material { name: shared.name, channels, uv_tiling: shared.uv_tiling, warnings: shared.warnings }) } -fn names(materials: &[&El]) -> String { - let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect(); - if n.is_empty() { "none".into() } else { n.join(", ") } +fn map_error(error: craft_materialx::Error) -> FormatError { + use craft_materialx::Error; + match error { + Error::Xml(xml) if xml.is_limit() => FormatError::TooLarge(xml.to_string()), + Error::MissingMaterial(name) => FormatError::Invalid(format!("no material named {name:?}")), + Error::Unsupported(message) => FormatError::Unsupported(message), + Error::Malformed(message) => malformed(KIND, message), + Error::Root => malformed(KIND, "no element"), + Error::Xml(other) => malformed(KIND, other), + } } #[cfg(test)] @@ -439,6 +148,19 @@ mod tests { m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v) } + #[test] + fn displacement_only_image_supplies_uv_tiling() { + let xml = br#" + + + + + "#; + let material = read_materialx(xml, None).unwrap(); + assert_eq!(get(&material, Channel::Height), Some(&Value::Image("height.png".into()))); + assert_eq!(material.uv_tiling, [4.0, 2.0]); + } + #[test] fn open_pbr_inputs_become_channels() { let m = read_materialx(OPENPBR.as_bytes(), None).unwrap(); @@ -456,6 +178,24 @@ mod tests { assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale"); } + #[test] + fn nodegraph_input_without_output_uses_the_first_output() { + let xml = r#" + + + + + + + + +"#; + for _ in 0..50 { + let material = read_materialx(xml.as_bytes(), None).unwrap(); + assert_eq!(get(&material, Channel::BaseColor), Some(&Value::Image("first.png".into()))); + } + } + #[test] fn emission_is_off_unless_the_shader_emits() { let x = OPENPBR.replace(r#""#, ""); diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 55b6f6ee..5040f320 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -1,11 +1,11 @@ //! MaterialCraft portable materials (`.mcmat`, read only): a zip with `material.json` (the //! manifest: maps by usage, exposed parameters, image inputs, presets), `maps/.png` -//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the source -//! `.mcraft` package. TextureCraft keeps its own reader (the apps share the format, not code). +//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the +//! source package. The shared reader handles the portable container and manifest. //! //! Also the 16-bit PNG encoder that hands baked mesh maps to MaterialCraft as graph inputs. -use std::io::{Cursor, Read}; +use std::io::Cursor; use serde::Deserialize; use texturecraft_core::{LinkParam, LinkPreset}; @@ -16,10 +16,13 @@ use crate::{FormatError, Result}; pub const MCMAT_EXT: &str = "mcmat"; /// MaterialCraft's package extension. pub const MCRAFT_EXT: &str = "mcraft"; -const FORMAT: &str = "craft-material"; -const VERSION: u32 = 1; +const VERSION: u32 = 2; /// Largest entry read (maps are at most 8192² × 16 bits, compressed). const MAX_ENTRY: u64 = 512 << 20; +/// Most map entries one manifest may name (a material has at most nine usages). +const MAX_MAPS: usize = 64; +/// Largest total payload read from one `.mcmat`: maps and source together (audit: TextureCraft #4). +const MAX_TOTAL: u64 = 1 << 30; const KIND: &str = "MaterialCraft material"; #[derive(Clone, Debug, PartialEq, Deserialize)] @@ -66,42 +69,76 @@ fn malformed(msg: impl Into) -> FormatError { FormatError::Malformed { kind: KIND, msg: msg.into() } } -/// Read `.mcmat` bytes. +fn shared_error(error: craft_mcmat::Error) -> FormatError { + match error { + craft_mcmat::Error::Version(version) => FormatError::Unsupported(format!("{KIND} version {version} (this version reads up to {VERSION})")), + craft_mcmat::Error::Limit(message) => malformed(message), + craft_mcmat::Error::Archive(ref archive) if archive.is_limit() => FormatError::TooLarge(error.to_string()), + other => malformed(other.to_string()), + } +} + +/// Read `.mcmat` bytes within TextureCraft's existing per-entry and total payload limits. pub fn read_mcmat(bytes: &[u8]) -> Result { - let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| malformed(e.to_string()))?; - let mut read = |name: &str| -> Result> { - let mut out = Vec::new(); - let f = z.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?; - f.take(MAX_ENTRY + 1).read_to_end(&mut out).map_err(|e| malformed(format!("{name}: {e}")))?; - if out.len() as u64 > MAX_ENTRY { - return Err(FormatError::TooLarge(name.to_string())); - } - Ok(out) + let limits = craft_mcmat::Limits { + min_version: 0, + max_version: VERSION, + max_entries: 100_000, + max_maps: MAX_MAPS, + max_manifest_bytes: MAX_ENTRY, + max_entry_bytes: MAX_ENTRY, + max_total_bytes: MAX_TOTAL, }; - let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|e| malformed(format!("material.json: {e}")))?; - if manifest.format != FORMAT { - return Err(malformed(format!("format `{}`", manifest.format))); - } - if manifest.version > VERSION { - return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version))); - } - let maps = manifest.maps.iter().map(|m| Ok((m.usage.clone(), read(&m.file)?))).collect::>>()?; - let source = read(&manifest.source)?; + let mut archive = craft_mcmat::Material::open(bytes, limits).map_err(shared_error)?; + // Consume the JSON values rather than cloning the entire untrusted manifest into a second tree. + let parameters = std::mem::take(&mut archive.manifest.parameters) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let inputs = std::mem::take(&mut archive.manifest.inputs) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let presets = std::mem::take(&mut archive.manifest.presets) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let shared = &archive.manifest; + let manifest = Manifest { + format: shared.format.clone(), + version: shared.version, + name: shared.name.clone(), + graph: shared.graph.clone(), + size: shared.size, + maps: shared.maps.iter().map(|m| MapEntry { usage: m.usage.clone(), file: m.file.clone() }).collect(), + parameters, + inputs, + presets, + source: shared.source.clone(), + }; + let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), archive.read(&map.file).map_err(shared_error)?))).collect::>>()?; + let source = archive.read_source().map_err(shared_error)?; Ok(PortableMaterial { manifest, maps, source }) } -/// Whether `bytes` are a zip holding `entry` (`material.json`: a portable material, -/// `package.json`: a MaterialCraft package). -fn zip_has(bytes: &[u8], entry: &str) -> bool { - zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(entry).is_ok()) -} - +/// Whether `bytes` contain a portable material manifest within the ZIP entry limit. pub fn is_mcmat(bytes: &[u8]) -> bool { - zip_has(bytes, "material.json") + craft_mcmat::is_material(bytes, 100_000) } pub fn is_mcraft(bytes: &[u8]) -> bool { - zip_has(bytes, "package.json") + let Ok(mut archive) = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 100_000, max_total_bytes: 0 }) else { return false }; + // A portable material may itself contain source.sbs, so it is not a source archive. + if archive.has_duplicate_names() || archive.contains("material.json") { + return false; + } + if archive.contains("package.json") { + return true; + } + (0..archive.len()).any(|i| archive.entry_name(i).ok().flatten().is_some_and(|name| !name.contains('/') && name.to_ascii_lowercase().ends_with(".sbs"))) } /// A baked mesh map (`components` floats per texel, 0..1, rows top first) as a 16-bit PNG @@ -131,13 +168,14 @@ mod tests { /// A `.mcmat` as MaterialCraft writes it (see its `formats/src/material.rs`). pub(crate) fn sample(version: u32) -> Vec { + let source = if version >= 2 { "source.sbs" } else { "source.mcraft" }; let manifest = serde_json::json!({ "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}], "parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0.0, "max": 1.0, "value": {"t": "float", "v": 0.25}}], "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}], - "source": "source.mcraft", "futureField": true + "source": source, "futureField": true }); let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -145,7 +183,7 @@ mod tests { z.write_all(manifest.to_string().as_bytes()).unwrap(); z.start_file("maps/baseColor.png", o).unwrap(); z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); - z.start_file("source.mcraft", o).unwrap(); + z.start_file(source, o).unwrap(); z.write_all(b"pkg").unwrap(); z.finish().unwrap().into_inner() } @@ -153,20 +191,55 @@ mod tests { #[test] fn reads_manifest_maps_and_source() { let bytes = sample(1); + assert!(is_mcmat(&bytes) && !is_mcraft(&bytes)); - let m = read_mcmat(&bytes).unwrap(); - assert_eq!(m.manifest.graph, "Brick_wall"); - assert_eq!(m.manifest.parameters[0].id, "wear"); - assert_eq!(m.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25})); - assert_eq!(m.manifest.presets[0].name, "Worn"); - assert_eq!(m.manifest.inputs[0].identifier, "curvature"); - assert_eq!(m.maps[0].0, "baseColor"); - assert_eq!(crate::decode_image(&m.maps[0].1).unwrap().width, 4); - assert_eq!(m.source, b"pkg"); - assert!(matches!(read_mcmat(&sample(2)), Err(FormatError::Unsupported(_)))); + let material = read_mcmat(&bytes).unwrap(); + + assert_eq!(material.manifest.graph, "Brick_wall"); + assert_eq!(material.manifest.parameters[0].id, "wear"); + assert_eq!(material.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25})); + assert_eq!(material.manifest.presets[0].name, "Worn"); + assert_eq!(material.manifest.inputs[0].identifier, "curvature"); + assert_eq!(material.maps[0].0, "baseColor"); + assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4); + assert_eq!(material.source, b"pkg"); + let current = read_mcmat(&sample(2)).unwrap(); + assert_eq!(current.manifest.source, "source.sbs"); + assert_eq!(current.source, b"pkg"); + assert!(matches!(read_mcmat(&sample(3)), Err(FormatError::Unsupported(_)))); assert!(read_mcmat(b"junk").is_err()); } + #[test] + fn recognizes_both_generations_of_source_archive_without_confusing_portable_materials() { + for entry in ["package.json", "package.sbs"] { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(b"source").unwrap(); + let bytes = zip.finish().unwrap().into_inner(); + assert!(is_mcraft(&bytes), "{entry}"); + } + assert!(!is_mcraft(&sample(2)), "a portable material contains source.sbs too"); + } + + #[test] + fn an_unbounded_map_list_is_refused() { + let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect(); + let manifest = serde_json::json!({"format": craft_mcmat::FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); + let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default(); + archive.start_file("material.json", options).unwrap(); + archive.write_all(manifest.to_string().as_bytes()).unwrap(); + archive.start_file("maps/baseColor.png", options).unwrap(); + archive.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); + archive.start_file("source.mcraft", options).unwrap(); + archive.write_all(b"pkg").unwrap(); + + let result = read_mcmat(&archive.finish().unwrap().into_inner()); + + assert!(matches!(result, Err(FormatError::Malformed { .. }))); + } + #[test] fn mesh_maps_encode_as_16_bit() { let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap(); diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 49b1ef81..404b09bb 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -67,47 +67,50 @@ pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec) -> String { - let mut s = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12); - let _ = writeln!(s, "# {}, exported by TextureCraft", token(name)); + let mut text = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12); + let _ = writeln!(text, "# {}, exported by TextureCraft", token(name)); if let Some(lib) = mtllib { - let _ = writeln!(s, "mtllib {lib}"); + let _ = writeln!(text, "mtllib {lib}"); } - let _ = writeln!(s, "o {}", token(name)); + let _ = writeln!(text, "o {}", token(name)); for p in &mesh.positions { - let _ = writeln!(s, "v {} {} {}", p.x, p.y, p.z); + let _ = writeln!(text, "v {} {} {}", p.x, p.y, p.z); } + let uvs = mesh.uvs.len() == mesh.positions.len(); let normals = mesh.normals.len() == mesh.positions.len(); if uvs { for t in &mesh.uvs { - let _ = writeln!(s, "vt {} {}", t.x, 1.0 - t.y); + let _ = writeln!(text, "vt {} {}", t.x, 1.0 - t.y); } } if normals { for n in &mesh.normals { - let _ = writeln!(s, "vn {} {} {}", n.x, n.y, n.z); + let _ = writeln!(text, "vn {} {} {}", n.x, n.y, n.z); } } + let materials = unique_ids(&mesh.materials, token); - for sm in &parts(mesh, name) { - let material = materials.get(sm.material).map_or("default", String::as_str); - let _ = writeln!(s, "g {}\nusemtl {material}", token(&sm.name)); - let (a, b) = (sm.start as usize, sm.start as usize + sm.count as usize); - for tri in mesh.indices.get(a..b).unwrap_or_default().chunks_exact(3) { - s.push('f'); - for i in tri { + for part in &parts(mesh, name) { + let material = materials.get(part.material).map_or("default", String::as_str); + let _ = writeln!(text, "g {}\nusemtl {material}", token(&part.name)); + let (a, b) = (part.start as usize, part.start as usize + part.count as usize); + for triangle in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 { + text.push('f'); + for i in triangle { let i = i + 1; let _ = match (uvs, normals) { - (true, true) => write!(s, " {i}/{i}/{i}"), - (true, false) => write!(s, " {i}/{i}"), - (false, true) => write!(s, " {i}//{i}"), - (false, false) => write!(s, " {i}"), + (true, true) => write!(text, " {i}/{i}/{i}"), + (true, false) => write!(text, " {i}/{i}"), + (false, true) => write!(text, " {i}//{i}"), + (false, false) => write!(text, " {i}"), }; } - s.push('\n'); + text.push('\n'); } } - s + + text } /// `id` of each material name, made unique with `_2`, `_3`… where two would be the same, also diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 77d0d5ad..2f57f7aa 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -166,60 +166,64 @@ fn identifier(s: &str, taken: &mut Vec) -> String { /// The export scene: `/` with the `Mesh` and `Materials`. `files[m]` are the texture /// file names (by slot) of material `m`. fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result { - let n = mesh.positions.len(); - if n == 0 || mesh.indices.len() < 3 { + let vertex_count = mesh.positions.len(); + if vertex_count == 0 || mesh.indices.len() < 3 { return Err(FormatError::Invalid("the mesh is empty".into())); } + let ints = |v: &[u32]| v.iter().map(|&i| i32::try_from(i).map_err(|_| FormatError::TooLarge("vertex index beyond 2^31".into()))).collect::>>(); let mut taken = Vec::new(); let root_name = identifier(name, &mut taken); let mut root = UsdPrim::new(&root_name, "Xform"); - let mut geo = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh"); - let mat_names: Vec = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect(); - let mat_path = |m: usize| mat_names.get(m).map(|id| format!("/{root_name}/Materials/{id}")); + let mut geometry = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh"); + let material_names: Vec = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect(); + let material_path = |m: usize| material_names.get(m).map(|id| format!("/{root_name}/Materials/{id}")); let (lo, hi) = mesh.bounds(); - // Faces in submesh order; subsets index them. - let mut tris: Vec = Vec::with_capacity(mesh.indices.len()); + + // Faces in submesh order; subsets index them + let mut indices: Vec = Vec::with_capacity(mesh.indices.len()); let mut faces_of: Vec> = vec![Vec::new(); mesh.materials.len()]; - for sm in parts(mesh, name) { - let range = mesh.indices.get(sm.start as usize..(sm.start as usize).saturating_add(sm.count as usize)).unwrap_or_default(); - for t in range.chunks_exact(3) { - if let Some(f) = faces_of.get_mut(sm.material) { - f.push(i32::try_from(tris.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); + for part in parts(mesh, name) { + let range = mesh.indices.get(part.start as usize..(part.start as usize).saturating_add(part.count as usize)).unwrap_or_default(); + for t in range.as_chunks::<3>().0 { + if let Some(f) = faces_of.get_mut(part.material) { + f.push(i32::try_from(indices.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); } - tris.extend_from_slice(t); + indices.extend_from_slice(t); } } + let vertex = |mut a: UsdAttr| { a.interpolation = Some("vertex"); a }; - geo.attrs = vec![ + geometry.attrs = vec![ UsdAttr::new("extent", "float3[]", Some(UsdValue::Vec3fs(vec![lo.to_array(), hi.to_array()]))), - UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; tris.len() / 3]))), - UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&tris)?))), + UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; indices.len() / 3]))), + UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&indices)?))), UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(mesh.positions.iter().map(|p| p.to_array()).collect()))), UsdAttr::new("subdivisionScheme", "token", Some(UsdValue::Token("none".into()))).uniform(), ]; - if mesh.normals.len() == n { - geo.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect()))))); + if mesh.normals.len() == vertex_count { + geometry.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect()))))); } - if mesh.uvs.len() == n { - // USD's st origin is bottom-left. + if mesh.uvs.len() == vertex_count { + // USD's st origin is bottom-left let st = mesh.uvs.iter().map(|t| [t.x, 1.0 - t.y]).collect(); - geo.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st))))); + geometry.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st))))); } + let used: Vec = (0..mesh.materials.len()).filter(|m| faces_of.get(*m).is_some_and(|f| !f.is_empty())).collect(); match used.as_slice() { [] => {} [m] => { - geo.binding_api = true; - geo.attrs.extend(mat_path(*m).map(|p| UsdAttr::rel("material:binding", p))); + geometry.binding_api = true; + geometry.attrs.extend(material_path(*m).map(|p| UsdAttr::rel("material:binding", p))); } _ => { for &m in &used { - let (Some(id), Some(path)) = (mat_names.get(m), mat_path(m)) else { continue }; + let (Some(id), Some(path)) = (material_names.get(m), material_path(m)) else { continue }; let mut subset = UsdPrim::new(id, "GeomSubset"); subset.binding_api = true; subset.attrs = vec![ @@ -228,18 +232,20 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result= codec::MIN_COMPRESSED_ARRAY => { let at = self.offset(); self.out.extend_from_slice(&(v.len() as u64).to_le_bytes()); - self.ints(&v.iter().map(|&i| i64::from(i)).collect::>()); + self.ints(&v.iter().map(|&i| i64::from(i)).collect::>())?; rep(ty::INT, codec::IS_ARRAY | codec::IS_COMPRESSED, at) } UsdValue::Ints(v) => self.raw_array(ty::INT, v.len(), v.iter().flat_map(|i| i.to_le_bytes())), @@ -174,10 +174,11 @@ impl Writer { } /// Compressed integers: their compressed size, then the LZ4-framed coding. - fn ints(&mut self, v: &[i64]) { - let comp = codec::compress(&codec::encode_ints(v, 4)); + fn ints(&mut self, v: &[i64]) -> Result<()> { + let comp = codec::compress(&codec::encode_ints(v, 4)?)?; self.out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); self.out.extend_from_slice(&comp); + Ok(()) } fn spec(&mut self, path: usize, kind: i64, fields: Vec<(&str, u64)>) { @@ -303,7 +304,7 @@ impl Writer { self.out.extend_from_slice(&(v as u64).to_le_bytes()); } - fn sections(&mut self) { + fn sections(&mut self) -> Result<()> { let mut toc = Vec::new(); let start = self.offset(); let mut raw = Vec::new(); @@ -311,7 +312,7 @@ impl Writer { raw.extend_from_slice(t.as_bytes()); raw.push(0); } - let comp = codec::compress(&raw); + let comp = codec::compress(&raw)?; self.u64(self.tokens.len()); self.u64(raw.len()); self.u64(comp.len()); @@ -327,9 +328,9 @@ impl Writer { let start = self.offset(); let fields = std::mem::take(&mut self.fields); self.u64(fields.len()); - self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>()); + self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>())?; let reps: Vec = fields.iter().flat_map(|f| f.1.to_le_bytes()).collect(); - let comp = codec::compress(&reps); + let comp = codec::compress(&reps)?; self.u64(comp.len()); self.out.extend_from_slice(&comp); self.section(&mut toc, "FIELDS", start); @@ -337,7 +338,7 @@ impl Writer { let start = self.offset(); let sets = std::mem::take(&mut self.fieldsets); self.u64(sets.len()); - self.ints(&sets); + self.ints(&sets)?; self.section(&mut toc, "FIELDSETS", start); let start = self.offset(); @@ -345,7 +346,7 @@ impl Writer { self.u64(self.paths.len()); self.u64(self.paths.len()); for column in &table { - self.ints(column); + self.ints(column)?; } self.section(&mut toc, "PATHS", start); @@ -353,7 +354,7 @@ impl Writer { let specs = std::mem::take(&mut self.specs); self.u64(specs.len()); for k in 0..3 { - self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>()); + self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>())?; } self.section(&mut toc, "SPECS", start); @@ -371,6 +372,7 @@ impl Writer { if let Some(slot) = self.out.get_mut(16..24) { slot.copy_from_slice(&toc_at.to_le_bytes()); } + Ok(()) } } @@ -400,9 +402,9 @@ impl Writer { Ok(()) } - fn finish(mut self) -> Vec { - self.sections(); - self.out + fn finish(mut self) -> Result> { + self.sections()?; + Ok(self.out) } } @@ -413,7 +415,7 @@ pub(crate) fn write(layer: &UsdLayer) -> Result> { w.add_prim_paths(0, "/", root); w.root_spec(&root.name)?; w.prim_specs(&format!("/{}", root.name), root)?; - Ok(w.finish()) + w.finish() } #[cfg(test)] @@ -504,7 +506,7 @@ mod tests { for (path, value) in attrs.into_iter().zip([points, counts, indices]) { w.spec(path, SPEC_ATTRIBUTE, vec![("default", value)]); } - let bytes = w.finish(); + let bytes = w.finish().unwrap(); let m = crate::import_mesh_bytes("crafted.usdc", &bytes).unwrap().mesh; assert_eq!(m.triangle_count(), 1, "the class prim itself is not drawn"); diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index 6730b334..e2abf0be 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -204,37 +204,38 @@ impl<'a> Ogawa<'a> { } /// The first sample of a scalar or array property as numbers (`extent` per item). - fn values(&mut self, p: &Prop) -> Result> { - let samples = self.group(p.group)?; + fn values(&mut self, property: &Prop) -> Result> { + let samples = self.group(property.group)?; let Some(&first) = samples.first() else { return Ok(Vec::new()) }; + let raw = self.data(first)?; let raw = if raw.is_empty() { raw } else { - raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", p.name)))? + raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))? }; - let size = match p.pod { + + let value_bytes = match property.pod { 0..=2 => 1, - 3 | 4 => 2, + 3 | 4 | 9 => 2, 5 | 6 | 10 => 4, 7 | 8 | 11 => 8, - other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", p.name))), + other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))), }; - self.charge((raw.len() / size).saturating_mul(8))?; - fn le(c: &[u8]) -> [u8; N] { - <[u8; N]>::try_from(c).unwrap_or([0; N]) - } - Ok(match p.pod { + self.charge((raw.len() / value_bytes).saturating_mul(8))?; + + Ok(match property.pod { 0 | 1 => raw.iter().map(|v| *v as f64).collect(), 2 => raw.iter().map(|v| *v as i8 as f64).collect(), - 3 => raw.chunks_exact(2).map(|c| u16::from_le_bytes(le(c)) as f64).collect(), - 4 => raw.chunks_exact(2).map(|c| i16::from_le_bytes(le(c)) as f64).collect(), - 5 => raw.chunks_exact(4).map(|c| u32::from_le_bytes(le(c)) as f64).collect(), - 6 => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(), - 7 => raw.chunks_exact(8).map(|c| u64::from_le_bytes(le(c)) as f64).collect(), - 8 => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - 10 => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - _ => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(), + 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(), + 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(), + 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(), + 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), + 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(), + 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + 9 => raw.as_chunks::<2>().0.iter().map(|c| half::f16::from_bits(u16::from_le_bytes(*c)).to_f64()).collect(), + 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), + _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), }) } @@ -280,19 +281,30 @@ fn read_inner(bytes: &[u8]) -> Result { if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) { return Err(malformed(KIND, "the archive group does not have the Alembic layout")); } - // Indexed metadata: a u8 length before each string. let block = o.data(root[5])?; - let mut c = Cursor { b: block, pos: 0 }; - while c.pos < block.len() { - let n = c.u8()? as usize; - o.indexed_meta.push(c.string(n)?); - } + read_indexed_meta(block, &mut o.indexed_meta)?; let mut sink = PolygonSink::default(); let mut walk = Walk { o, sink: &mut sink, visits: 0 }; walk.object(root[2], Mat4::IDENTITY, "", 0)?; Ok(sink.finish()) } +/// The most indexed metadata entries that can ever be used: objects and properties refer to one +/// with a single byte, and 0xff already means "stored inline", so only 0 to 254 are reachable. +const MAX_INDEXED_META: usize = 255; + +/// Indexed metadata: a u8 length before each string. `out` starts with the empty entry 0. Reading +/// stops once `out` holds [`MAX_INDEXED_META`] entries, because no later entry can be referred to +/// and an empty one costs a whole `String` in memory for one byte of file. +fn read_indexed_meta(block: &[u8], out: &mut Vec) -> Result<()> { + let mut c = Cursor { b: block, pos: 0 }; + while c.pos < block.len() && out.len() < MAX_INDEXED_META { + let n = c.u8()? as usize; + out.push(c.string(n)?); + } + Ok(()) +} + struct Walk<'a, 'b> { o: Ogawa<'a>, sink: &'b mut PolygonSink, @@ -491,21 +503,23 @@ impl Walk<'_, '_> { } fn mesh(&mut self, r: u64, world: Mat4, sets: &[(String, Vec)]) -> Result<()> { - let props = self.o.compound(r)?; + let properties = self.o.compound(r)?; let get = |o: &mut Ogawa, name: &str| -> Result> { - match find(&props, name) { + match find(&properties, name) { Some(p) => o.values(p), None => Err(malformed(KIND, format!("PolyMesh has no {name}"))), } }; + let p = get(&mut self.o, "P")?; let indices = get(&mut self.o, ".faceIndices")?; let counts = get(&mut self.o, ".faceCounts")?; check_vertices(p.len() / 3)?; - let points: Vec = p.chunks_exact(3).map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); + let points: Vec = p.as_chunks::<3>().0.iter().map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let n = [points.len(), counts.len(), indices.len()]; - let normals = self.param(&props, "N", n)?; - let uvs = self.param(&props, "uv", n)?; + let normals = self.param(&properties, "N", n)?; + let uvs = self.param(&properties, "uv", n)?; + let mut material = vec![None::; counts.len()]; for (s, (_, faces)) in sets.iter().enumerate() { for f in faces { @@ -514,26 +528,33 @@ impl Walk<'_, '_> { } } } - let nm = Mat3::from_mat4(world).inverse().transpose(); - // Alembic winds polygons clockwise; a mirroring transform flips them once more. + let normal_transform = Mat3::from_mat4(world).inverse().transpose(); + + // Alembic winds polygons clockwise; a mirroring transform flips them once more let keep_order = world.determinant() < 0.0; let (mut k, mut corners, mut bad_uvs) = (0usize, Vec::new(), 0usize); for (f, &count) in counts.iter().enumerate() { let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len()); let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?; corners.clear(); - for (kk, &pi) in indices.iter().enumerate().take(end).skip(k) { - let p = points.get(pi as usize).filter(|_| pi >= 0.0).ok_or_else(|| malformed(KIND, format!("point index {pi} out of range")))?; - let pi = pi as usize; - let n = normals.as_ref().and_then(|l| l.get::<3>(kk, pi, f)).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32)); - let uv = uvs.as_ref().map(|l| match l.get::<2>(kk, pi, f) { + for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) { + let p = points + .get(point_index as usize) + .filter(|_| point_index >= 0.0) + .ok_or_else(|| malformed(KIND, format!("point index {point_index} out of range")))?; + let point_index = point_index as usize; + let n = normals + .as_ref() + .and_then(|l| l.get::<3>(corner_index, point_index, f)) + .map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); + let uv = uvs.as_ref().map(|l| match l.get::<2>(corner_index, point_index, f) { Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), None => { bad_uvs += 1; Vec2::ZERO } }); - corners.push(Corner { p: *p, n, uv }); + corners.push(Corner { p: *p, n, uv, color: None }); } k = end; if !keep_order { @@ -542,9 +563,11 @@ impl Walk<'_, '_> { let name = material.get(f).copied().flatten().and_then(|s| sets.get(s)).map_or(DEFAULT_MATERIAL, |(n, _)| n.as_str()); self.sink.polygon(name, &corners)?; } + if bad_uvs > 0 { self.sink.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)")); } + Ok(()) } } diff --git a/crates/formats/src/mesh_import/abc/tests.rs b/crates/formats/src/mesh_import/abc/tests.rs index dfba3ba9..92f18620 100644 --- a/crates/formats/src/mesh_import/abc/tests.rs +++ b/crates/formats/src/mesh_import/abc/tests.rs @@ -243,6 +243,38 @@ fn strip_alone_keeps_uvs_flipped_to_v_down() { } } +#[test] +fn half_float_uvs_import_without_losing_values() { + let mut a = Abc { w: Writer::new() }; + let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0])); + let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2])); + let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3])); + let uv_bytes: Vec = [0u16, 0, 0x3800, 0x3c00, 0x3c00, 0].iter().flat_map(|x| x.to_le_bytes()).collect(); + let uv = a.array("uv", "", 9, 2, &uv_bytes); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv]); + let mesh = a.object(vec![geom], &[]); + let top = a.object(vec![], &[("m", "", mesh)]); + let imported = crate::import_mesh_bytes("m.abc", &a.archive(top, &["schema=AbcGeom_PolyMesh_v1"])).unwrap(); + assert!(!imported.report.uvs_generated); + for (p, uv) in imported.mesh.positions.iter().zip(&imported.mesh.uvs) { + assert_eq!(*uv, texturecraft_geom::glam::Vec2::new(p.x, 1.0 - p.y)); + } +} + +#[test] +fn half_float_values_preserve_special_values() { + let mut a = Abc { w: Writer::new() }; + let raw: Vec = [0xc000u16, 0x0001, 0x7c00, 0x7e00].iter().flat_map(|x| x.to_le_bytes()).collect(); + let p = a.array("values", "", 9, 1, &raw); + let property = Prop { name: p.name.into(), meta: p.meta, kind: PropKind::Array, pod: 9, extent: 1, group: p.group }; + let mut ogawa = Ogawa { b: &a.w.b, budget: MAX_DECODED_BYTES, indexed_meta: Vec::new() }; + let values = ogawa.values(&property).unwrap(); + assert_eq!(values[0], -2.0); + assert_eq!(values[1], 2f64.powi(-24)); + assert_eq!(values[2], f64::INFINITY); + assert!(values[3].is_nan()); +} + #[test] fn hdf5_and_garbage_are_clear_errors() { let e = read(b"\x89HDF\r\n\x1a\n rest of an hdf5 file").err().unwrap().to_string(); @@ -291,3 +323,29 @@ fn self_referencing_groups_are_bounded() { let bytes = a.archive(at, &[]); assert!(read(&bytes).is_err()); } + +#[test] +fn indexed_metadata_stops_at_the_entries_a_byte_can_index() { + // One real entry followed by a million empty ones: a byte each in the file, a `String` each + // in memory, and no index past 254 can be used anyway. + let mut block = vec![3, b'a', b'b', b'c']; + block.extend(std::iter::repeat_n(0u8, 1_000_000)); + let mut kept = vec![String::new()]; + read_indexed_meta(&block, &mut kept).unwrap(); + assert_eq!(kept.len(), MAX_INDEXED_META); + assert_eq!(kept.get(1).map(String::as_str), Some("abc")); + + // The mesh schema comes from metadata index 1 even when the table has unreachable entries. + let mut a = Abc { w: Writer::new() }; + let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0])); + let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2])); + let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3])); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc]); + let mesh = a.object(vec![geom], &[]); + let top = a.object(vec![], &[("tri", "", mesh)]); + let mut metas = vec!["schema=AbcGeom_PolyMesh_v1"]; + metas.extend(std::iter::repeat_n("", 5_000)); + let raw = read(&a.archive(top, &metas)).unwrap(); + assert_eq!(raw.positions, [Vec3::X, Vec3::Y, Vec3::ZERO]); + assert_eq!(raw.groups, vec![(DEFAULT_MATERIAL.into(), "tri".into(), vec![0, 1, 2])]); +} diff --git a/crates/formats/src/mesh_import/dae.rs b/crates/formats/src/mesh_import/dae.rs index d23ea61b..bb104455 100644 --- a/crates/formats/src/mesh_import/dae.rs +++ b/crates/formats/src/mesh_import/dae.rs @@ -356,6 +356,7 @@ fn add_geometry(d: &mut Doc, sink: &mut PolygonSink, geom: &El, m: Mat4, bind: & p: m.transform_point3(Vec3::from(pos)), n: n.map(|n| nm * Vec3::from(n)), uv: t.map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } next = next.saturating_add(size); diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index d7dd46fc..58a01aea 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -1,834 +1,211 @@ -//! FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib-compressed arrays) and -//! ASCII: mesh geometry with normals, UVs and per-polygon materials from the layer elements, every -//! Model's transform and parent hierarchy, and the file's unit and axis system (converted to -//! meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of -//! numbering them and lists properties in `Properties60`; both read into the same scene. -//! Materials bring their diffuse color and, when the file embeds it (a Video's `Content`), the -//! diffuse texture (for high-poly color map bakes); a texture kept as a file beside the FBX comes -//! along when the FBX is packaged with it ([`package`]: a stored zip of the FBX first and the -//! files under their paths below its folder, which [`read`] opens like the FBX). Camera Models become the file's cameras (lens -//! from their camera NodeAttribute, or the Model's own properties in FBX 6). - -use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use std::io::Read as _; - -use base64::Engine as _; -use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; - -use super::external::below; -use super::{ - Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh, check_vertices, lens_fov, zip_entry, -}; +//! FBX scene import through the shared bounded reader. +use super::{Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh}; use crate::{FormatError, Result, malformed}; - +use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; const KIND: &str = "FBX"; -const MAGIC: &[u8] = b"Kaydara FBX Binary \0"; -/// A zip package of an FBX and its texture files ([`package`]). -const ZIP_MAGIC: &[u8] = b"PK\x03\x04"; -/// First FBX version with the object/connection layout read here (6.0). -const MIN_VERSION: i64 = 6000; -/// Deepest node nesting (and Model parent chain) followed. -const MAX_DEPTH: usize = 64; -/// Memory budget for parsed nodes and properties (arrays are held as f64). -const MAX_DECODED_BYTES: usize = 1 << 31; -/// Approximate memory charged per node and per scalar property. -const NODE_COST: usize = 96; -const PROP_COST: usize = 32; - -enum Prop { - I(i64), - F(f64), - S(String), - /// Binary data (`R`), such as an embedded image. - Raw(Vec), - Arr(Vec), -} - -impl Prop { - fn num(&self) -> Option { - match self { - Prop::I(v) => Some(*v as f64), - Prop::F(v) => Some(*v), - _ => None, - } - } -} - -struct Node { - name: String, - props: Vec, - children: Vec, -} - -impl Node { - fn child(&self, name: &str) -> Option<&Node> { - self.children.iter().find(|c| c.name == name) - } - - fn all<'a>(&'a self, name: &'a str) -> impl Iterator { - self.children.iter().filter(move |c| c.name == name) - } - - fn int_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(*v), - _ => None, - } - } - - /// Object id: the number (7.x) or the `Class::Name` string (6.x). - fn id_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(v.to_string()), - Some(Prop::S(s)) if !s.is_empty() => Some(s.clone()), - _ => None, - } - } - - /// An object's name: after its id (7.x) or the id itself (6.x). - fn object_name(&self) -> &str { - clean_name(if self.int_at(0).is_some() { self.str_at(1) } else { self.str_at(0) }) - } - - /// An object's class (`Mesh`, `Camera`, …): after its name. - fn class(&self) -> &str { - self.str_at(if self.int_at(0).is_some() { 2 } else { 1 }) - } - - fn str_at(&self, i: usize) -> &str { - match self.props.get(i) { - Some(Prop::S(s)) => s, - _ => "", - } - } - - fn child_str(&self, name: &str) -> &str { - self.child(name).map_or("", |c| c.str_at(0)) - } - - /// Embedded file bytes of a Video: binary data, or base64 text in ASCII files. - fn content(&self) -> Option> { - let c = self.child("Content")?; - let bytes = match c.props.first()? { - Prop::Raw(b) => b.clone(), - _ => { - let text: String = c.props.iter().filter_map(|p| if let Prop::S(s) = p { Some(s.as_str()) } else { None }).collect(); - base64::engine::general_purpose::STANDARD.decode(text.trim()).ok()? - } - }; - (!bytes.is_empty()).then_some(bytes) - } - - /// Array payload: a binary array, an ASCII `*N { a: ... }` block or a bare value list. - fn arr(&self) -> Cow<'_, [f64]> { - if let Some(Prop::Arr(a)) = self.props.first() { - return Cow::Borrowed(a); - } - if let Some(a) = self.child("a") { - return a.arr(); - } - Cow::Owned(self.props.iter().filter_map(Prop::num).collect()) - } - - /// The numbers of entry `name` in Properties70 (`P: name, type, subtype, flags, values`) or - /// Properties60 (`Property: name, type, flags, values`). - fn property(&self, name: &str) -> Option> { - let list = self.child("Properties70").or_else(|| self.child("Properties60"))?; - list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().filter_map(Prop::num).collect()) - } - - fn vec3(&self, name: &str, default: Vec3) -> Vec3 { - match self.property(name).as_deref() { - Some([x, y, z, ..]) => Vec3::new(*x as f32, *y as f32, *z as f32), - _ => default, - } - } - - fn number(&self, name: &str) -> Option { - self.property(name)?.first().copied() - } -} - -/// Charges parsed data against [`MAX_DECODED_BYTES`]. -struct Budget(usize); - -impl Budget { - fn charge(&mut self, bytes: usize) -> Result<()> { - self.0 = self.0.checked_sub(bytes).ok_or_else(|| FormatError::TooLarge(format!("the FBX file decodes to more than {MAX_DECODED_BYTES} bytes")))?; - Ok(()) - } -} - -// --------------------------------------------------------------------------------------------- -// Binary. - -struct Binary<'a> { - b: &'a [u8], - pos: usize, - /// 64-bit node records (version 7500 and later). - wide: bool, - budget: Budget, -} - -impl<'a> Binary<'a> { - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "unexpected end of file"))?; - self.pos += n; - Ok(s) - } - - fn bytes(&mut self) -> Result<[u8; N]> { - let mut a = [0u8; N]; - a.copy_from_slice(self.take(N)?); - Ok(a) - } - - fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.bytes()?) as usize) - } - - fn uint(&mut self) -> Result { - Ok(if self.wide { u64::from_le_bytes(self.bytes()?) } else { u32::from_le_bytes(self.bytes()?) as u64 }) - } - - /// The next node ending at or before `limit`, or None at a null record / the end. - fn node(&mut self, limit: usize, depth: usize) -> Result> { - let header = if self.wide { 25 } else { 13 }; - if limit.saturating_sub(self.pos) < header { - return Ok(None); - } - let (end, nprops, plen) = (self.uint()?, self.uint()?, self.uint()?); - let [name_len] = self.bytes()?; - if end == 0 { - return Ok(None); - } - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let end = usize::try_from(end).ok().filter(|e| *e > self.pos && *e <= limit).ok_or_else(|| malformed(KIND, "node end offset out of range"))?; - self.budget.charge(NODE_COST)?; - let name = String::from_utf8_lossy(self.take(name_len as usize)?).into_owned(); - let props_end = usize::try_from(plen).ok().and_then(|p| self.pos.checked_add(p)).filter(|e| *e <= end); - let props_end = props_end.ok_or_else(|| malformed(KIND, format!("properties of \"{name}\" overrun the node")))?; - let mut props = Vec::new(); - for _ in 0..nprops { - if self.pos >= props_end { - return Err(malformed(KIND, format!("\"{name}\" claims more properties than it holds"))); - } - props.push(self.prop()?); - } - if self.pos > props_end { - return Err(malformed(KIND, format!("properties of \"{name}\" overrun their list"))); - } - self.pos = props_end; - let mut children = Vec::new(); - while let Some(c) = self.node(end, depth + 1)? { - children.push(c); - } - self.pos = end; - Ok(Some(Node { name, props, children })) - } - - fn prop(&mut self) -> Result { - self.budget.charge(PROP_COST)?; - let [ty] = self.bytes()?; - Ok(match ty { - b'Y' => Prop::I(i16::from_le_bytes(self.bytes()?) as i64), - b'C' | b'B' => Prop::I(self.bytes::<1>()?[0] as i64), - b'I' => Prop::I(i32::from_le_bytes(self.bytes()?) as i64), - b'L' => Prop::I(i64::from_le_bytes(self.bytes()?)), - b'F' => Prop::F(f32::from_le_bytes(self.bytes()?) as f64), - b'D' => Prop::F(f64::from_le_bytes(self.bytes()?)), - b'S' => { - let n = self.u32()?; - Prop::S(String::from_utf8_lossy(self.take(n)?).into_owned()) - } - b'R' => { - let n = self.u32()?; - self.budget.charge(n)?; - Prop::Raw(self.take(n)?.to_vec()) - } - b'f' | b'd' | b'l' | b'i' | b'b' => Prop::Arr(self.array(ty)?), - other => return Err(malformed(KIND, format!("unknown property type 0x{other:02x}"))), - }) - } - - fn array(&mut self, ty: u8) -> Result> { - let (count, encoding, stored) = (self.u32()?, self.u32()?, self.u32()?); - let size = match ty { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - let len = count.checked_mul(size).ok_or_else(|| malformed(KIND, "array too large"))?; - self.budget.charge(count.saturating_mul(8))?; - let data = self.take(stored)?; - let raw: Cow<[u8]> = match encoding { - 0 if stored == len => Cow::Borrowed(data), - 1 => { - let mut out = Vec::new(); - flate2::read::ZlibDecoder::new(data) - .take(len as u64 + 1) - .read_to_end(&mut out) - .map_err(|e| malformed(KIND, format!("bad compressed array: {e}")))?; - if out.len() != len { - return Err(malformed(KIND, "compressed array has the wrong length")); - } - Cow::Owned(out) - } - _ => return Err(malformed(KIND, format!("array encoding {encoding} with {stored} bytes for {count} items"))), - }; - fn le(c: &[u8]) -> [u8; N] { - <[u8; N]>::try_from(c).unwrap_or([0; N]) - } - Ok(match ty { - b'd' => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(), - b'l' => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - b'f' => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - b'i' => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(), - _ => raw.iter().map(|b| *b as f64).collect(), - }) - } -} - -fn parse_binary(b: &[u8]) -> Result<(Vec, i64)> { - let mut r = Binary { b, pos: MAGIC.len(), wide: false, budget: Budget(MAX_DECODED_BYTES) }; - let _reserved: [u8; 2] = r.bytes()?; - let version = u32::from_le_bytes(r.bytes()?); - r.wide = version >= 7500; - let mut nodes = Vec::new(); - while let Some(n) = r.node(b.len(), 0)? { - nodes.push(n); - } - Ok((nodes, version as i64)) -} - -// --------------------------------------------------------------------------------------------- -// ASCII. - -#[derive(Clone, Copy)] -enum Tok<'a> { - /// `name:` - Key(&'a str), - Str(&'a [u8]), - Word(&'a str), - Comma, - Open, - Close, -} - -struct Ascii<'a> { - s: &'a [u8], - pos: usize, - budget: Budget, -} - -impl<'a> Ascii<'a> { - /// The next token and the position after it (the position is not advanced). - fn lex(&self) -> Result, usize)>> { - let mut i = self.pos; - loop { - match self.s.get(i) { - None => return Ok(None), - Some(c) if c.is_ascii_whitespace() => i += 1, - Some(b';') => i += self.s.get(i..).unwrap_or_default().iter().position(|c| *c == b'\n').unwrap_or(self.s.len() - i), - Some(_) => break, - } - } - let rest = self.s.get(i..).unwrap_or_default(); - Ok(Some(match rest.first() { - Some(b',') => (Tok::Comma, i + 1), - Some(b'{') => (Tok::Open, i + 1), - Some(b'}') => (Tok::Close, i + 1), - Some(b'"') => { - let len = rest.get(1..).unwrap_or_default().iter().position(|c| *c == b'"').ok_or_else(|| malformed(KIND, "unterminated string"))?; - (Tok::Str(rest.get(1..1 + len).unwrap_or_default()), i + len + 2) - } - _ => { - let len = rest.iter().position(|c| c.is_ascii_whitespace() || b",{}\":;".contains(c)).unwrap_or(rest.len()); - if len == 0 { - return Err(malformed(KIND, format!("unexpected character at byte {i}"))); - } - let word = std::str::from_utf8(rest.get(..len).unwrap_or_default()).map_err(|_| malformed(KIND, "text is not UTF-8"))?; - if rest.get(len) == Some(&b':') { (Tok::Key(word), i + len + 1) } else { (Tok::Word(word), i + len) } - } - })) - } - - /// Nodes until `}` (left for the caller) or the end. - fn nodes(&mut self, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let mut out = Vec::new(); - while let Some((tok, after)) = self.lex()? { - match tok { - Tok::Close => break, - Tok::Key(name) => { - self.pos = after; - out.push(self.node(name, depth)?); - } - _ => return Err(malformed(KIND, format!("expected a property name at byte {}", self.pos))), - } - } - Ok(out) - } - - fn node(&mut self, name: &str, depth: usize) -> Result { - self.budget.charge(NODE_COST)?; - let mut props = Vec::new(); - // An empty first value (`Content: , "..."`). - if let Some((Tok::Comma, after)) = self.lex()? { - self.pos = after; - } - while let Some((tok, after)) = self.lex()? { - let prop = match tok { - Tok::Str(s) => Some(Prop::S(String::from_utf8_lossy(s).into_owned())), - // `*N` announces an array's length. - Tok::Word(w) if w.starts_with('*') => None, - Tok::Word(w) => Some(w.parse::().map(Prop::I).or_else(|_| w.parse::().map(Prop::F)).unwrap_or_else(|_| Prop::S(w.to_string()))), - _ => break, - }; - self.pos = after; - if let Some(p) = prop { - self.budget.charge(PROP_COST)?; - props.push(p); - } - match self.lex()? { - Some((Tok::Comma, after)) => self.pos = after, - _ => break, - } - } - let mut children = Vec::new(); - if let Some((Tok::Open, after)) = self.lex()? { - self.pos = after; - children = self.nodes(depth + 1)?; - match self.lex()? { - Some((Tok::Close, after)) => self.pos = after, - _ => return Err(malformed(KIND, format!("\"{name}\" is missing its closing brace"))), - } - } - // Long value lists (arrays) are stored compactly. - if props.len() > 1 && props.iter().all(|p| p.num().is_some()) { - props = vec![Prop::Arr(props.iter().filter_map(Prop::num).collect())]; - } - Ok(Node { name: name.to_string(), props, children }) - } -} - -fn parse_ascii(s: &[u8]) -> Result<(Vec, i64)> { - let mut a = Ascii { s, pos: 0, budget: Budget(MAX_DECODED_BYTES) }; - let nodes = a.nodes(0)?; - if a.lex()?.is_some() { - return Err(malformed(KIND, "unbalanced closing brace")); - } - let version = nodes.iter().find(|n| n.name == "FBXHeaderExtension").and_then(|h| h.child("FBXVersion")).and_then(|v| v.int_at(0)); - let version = version.ok_or_else(|| malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)"))?; - Ok((nodes, version)) -} - -// --------------------------------------------------------------------------------------------- -// Scene. - -/// The bytes of the first of a texture's candidate file paths (relative to the FBX's folder) -/// that exists. type Files<'a> = dyn FnMut(&[&str]) -> Option> + 'a; - -/// An FBX, or a package of one and its texture files. -pub(crate) fn read(bytes: &[u8]) -> Result { - if !bytes.starts_with(ZIP_MAGIC) { - return crate::guard(KIND, || read_inner(bytes, &mut |_| None)); +fn limits() -> craft_mesh::Limits { + craft_mesh::Limits { + max_vertices: super::MAX_VERTICES, + max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_face_corners: super::MAX_VERTICES, + max_meshes: super::MAX_VERTICES, + max_parts: super::MAX_VERTICES, + max_materials: super::MAX_VERTICES, + max_nodes: super::MAX_VERTICES, + max_data_bytes: 1 << 31, + max_extras: 100_000, + ..Default::default() } +} + +fn package_limits() -> craft_mesh::fbx::package::PackageLimits { + craft_mesh::fbx::package::PackageLimits { + max_entries: MAX_ZIP_ENTRIES as u64, + max_model_bytes: MAX_MESH_FILE_BYTES, + max_texture_bytes: MAX_TEXTURE_BYTES, + max_total_bytes: MAX_MESH_FILE_BYTES, + } +} + +fn convert(e: craft_mesh::Error) -> FormatError { + match e { + craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), + craft_mesh::Error::Unsupported(s) => FormatError::Unsupported(s), + e => FormatError::Invalid(e.to_string()), + } +} + +pub(crate) fn read(bytes: &[u8]) -> Result { crate::guard(KIND, || { - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| malformed(KIND, format!("FBX package: {e}")))?; - if zip.len() > MAX_ZIP_ENTRIES { - return Err(FormatError::TooLarge(format!("the FBX package has more than {MAX_ZIP_ENTRIES} entries"))); + if !craft_mesh::fbx::package::is_package(bytes) { + return read_inner(bytes, &mut |_| None); } - let name = zip.file_names().flatten().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(Cow::into_owned); - let name = name.ok_or_else(|| malformed(KIND, "the package contains no FBX file"))?; - let fbx = zip_entry(&mut zip, &name, MAX_MESH_FILE_BYTES) - .ok_or_else(|| FormatError::TooLarge("the packaged FBX is unreadable or larger than 2 GiB".into()))?; - if fbx.starts_with(ZIP_MAGIC) { - return Err(malformed(KIND, "the package holds another package")); - } - read_inner(&fbx, &mut |paths| paths.iter().find_map(|p| zip_entry(&mut zip, &below(p)?, MAX_TEXTURE_BYTES))) + let mut package = craft_mesh::fbx::package::Package::open(bytes, package_limits()).map_err(convert)?; + let fbx = package.model().map_err(convert)?; + read_inner(&fbx, &mut |paths| package.texture(paths)) }) } -/// An FBX whose base color textures are files, as a package holding it (first) and the files -/// `found` has, under their paths below its folder; None when it found none (or `bytes` is a -/// package already). Also the texture paths it could not find. pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) -> Option>) -> Result<(Option>, Vec)> { - if bytes.starts_with(ZIP_MAGIC) { + if craft_mesh::fbx::package::is_package(bytes) { return Ok((None, Vec::new())); } crate::guard(KIND, || { - let (mut files, mut missing): (Vec<(String, Vec)>, Vec) = (Vec::new(), Vec::new()); - read_inner(bytes, &mut |paths| { - if let Some((_, data)) = files.iter().find(|(n, _)| paths.iter().any(|p| below(p).as_ref() == Some(n))) { - return Some(data.clone()); - } - for p in paths { - if let (Some(name), Some(data)) = (below(p), found(p).filter(|d| d.len() as u64 <= MAX_TEXTURE_BYTES)) { - files.push((name, data.clone())); - return Some(data); - } - } - // A texture is missing when none of its paths was found; named by its first. - if let Some(first) = paths.first().filter(|f| !missing.iter().any(|m| m == *f)) { - missing.push(first.to_string()); - } - None - })?; - if files.is_empty() { - return Ok((None, missing)); + let limits = limits(); + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let total = files.iter().fold(bytes.len() as u64, |t, (_, d)| t.saturating_add(d.len() as u64)); - if total > MAX_MESH_FILE_BYTES { - return Err(FormatError::TooLarge("the FBX and its textures exceed 2 GiB".into())); - } - let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh.fbx"); - Ok((Some(crate::mesh_export::usd::usdz(leaf, bytes, &files)?), missing)) + doc.scene_with_options( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, + ) + .map_err(convert)?; + craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } fn read_inner(bytes: &[u8], files: &mut Files) -> Result { - let (nodes, version) = if bytes.starts_with(MAGIC) { parse_binary(bytes)? } else { parse_ascii(bytes)? }; - if version < MIN_VERSION { - return Err(FormatError::Unsupported(format!("FBX version {version} (re-export as FBX 2006 / 6.1 or newer)"))); + let limits = limits(); + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let root = |name: &str| nodes.iter().find(|n| n.name == name); - let objects = root("Objects").ok_or_else(|| malformed(KIND, "the file has no Objects"))?; - let (mut geometries, mut models, mut materials) = (HashMap::new(), HashMap::new(), HashMap::new()); - let (mut textures, mut videos, mut attributes) = (HashMap::new(), HashMap::new(), HashMap::new()); - // (geometry, model) instances; an FBX 6 Model holds its geometry itself. - let mut instances: Vec<(String, Option)> = Vec::new(); - for o in &objects.children { - let Some(id) = o.id_at(0) else { continue }; - match o.name.as_str() { - "Geometry" if o.child("Vertices").is_some() => geometries.insert(id, o), - "Model" => { - if o.child("Vertices").is_some() { - geometries.insert(id.clone(), o); - instances.push((id.clone(), Some(id.clone()))); - } - models.insert(id, o) - } - "Material" => materials.insert(id, o), - "Texture" => textures.insert(id, o), - "Video" => videos.insert(id, o), - "NodeAttribute" => attributes.insert(id, o), - _ => None, - }; - } - // Model parents, and each Model's materials in slot order. - let mut parents: HashMap = HashMap::new(); - let mut slots: HashMap> = HashMap::new(); - let mut attribute_of: HashMap = HashMap::new(); - let connections: Vec<&Node> = root("Connections").into_iter().flat_map(|c| c.all("C").chain(c.all("Connect"))).collect(); - for c in &connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if c.str_at(0) != "OO" || child == parent || !models.contains_key(&parent) { - continue; - } - if models.contains_key(&child) { - parents.insert(child, parent); - } else if geometries.contains_key(&child) { - instances.push((child, Some(parent))); - } else if let Some(m) = materials.get(&child) { - slots.entry(parent).or_default().push(material_name(&child, m)); - } else if let Some(a) = attributes.get(&child) { - attribute_of.insert(parent, *a); - } - } - let placed: HashSet<&String> = instances.iter().map(|(g, _)| g).collect(); - let mut unplaced: Vec = geometries.keys().filter(|g| !placed.contains(g)).cloned().collect(); - unplaced.sort_unstable(); - instances.extend(unplaced.into_iter().map(|g| (g, None))); - - let base_colors = base_colors(&materials, &textures, &videos, &connections, files); - let global = global_transform(root("GlobalSettings").or_else(|| objects.child("GlobalSettings"))); + let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; + let (scene, placements) = doc + .scene_with_placements( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, + ) + .map_err(convert)?; + let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); + let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); - let no_slots = Vec::new(); - for (geom, model) in instances { - let Some(g) = geometries.get(&geom) else { continue }; - let m = match model.as_ref().and_then(|m| models.get(m).map(|n| (m, n))) { - Some((id, node)) => { - sink.part = node.object_name().to_string(); - world(&models, &parents, id)? * geometric(node) + let mut cameras = Vec::new(); + cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); + // Bound the stored world matrices and pending node indices together: neither depends on + // copying model names, even when a hierarchy fans out widely. + let placement_bytes = + scene.nodes.len().checked_mul(std::mem::size_of::>()).ok_or_else(|| FormatError::TooLarge("FBX hierarchy size overflow".into()))?; + let remaining = limits.max_data_bytes.checked_sub(placement_bytes).ok_or_else(|| FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into()))?; + let stack_limit = remaining / std::mem::size_of::<(usize, Mat4, usize)>(); + if scene.roots.len() > stack_limit { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); + } + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, 0usize)).collect(); + let mut worlds = vec![None; scene.nodes.len()]; + let mut visited = 0usize; + let mut points = 0usize; + while let Some((id, parent, depth)) = stack.pop() { + visited += 1; + if visited > limits.max_nodes || depth > limits.max_depth { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); + } + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; + let world = parent * to_mat(node.transform); + if let Some(slot) = worlds.get_mut(id) { + *slot = Some(world); + } + for child in node.children.iter().rev() { + if stack.len() >= stack_limit { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } - None => { - sink.part.clear(); - Mat4::IDENTITY + stack.push((*child, world, depth + 1)); + } + if let Some(index) = node.camera + && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) + { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); + } + } + for placement in placements { + let id = placement.node; + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "placement index out of range"))?; + let world = worlds.get(id).copied().flatten().ok_or_else(|| malformed(KIND, "cycle in model hierarchy"))?; + let Some(index) = node.mesh else { continue }; + let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; + points = points.checked_add(mesh.positions.len()).ok_or_else(|| FormatError::TooLarge("FBX instance work overflow".into()))?; + if points > 200_000_000 { + return Err(FormatError::TooLarge("FBX instances exceed the 200000000 control-point work limit".into())); + } + let normal_transform = Mat3::from_mat4(world).inverse().transpose(); + let flip = world.determinant() < 0.0; + sink.part = placement.model.and_then(|i| scene.nodes.get(i)).map_or_else(String::new, |n| n.name.clone()); + let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); + for group in &mesh.parts { + let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); + for face in group.faces() { + let mut corners = Vec::with_capacity(face.len()); + for c in face { + let p = mesh.positions.get(c.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; + let p = world.transform_point3(Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32)); + let n = mesh.normals.get(c.normal as usize).map(|n| normal_transform * Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); + if !mesh.normals.is_empty() && n.is_none() { + bad_normals += 1; + } + let uv = mesh.uv_sets.first().map(|set| match set.get(c.uv as usize) { + Some(v) => Vec2::new(v[0], v[1]), + None => { + bad_uvs += 1; + Vec2::ZERO + } + }); + let color = mesh.colors.get(c.position as usize).copied().map(Vec4::from_array); + corners.push(Corner { p, n, uv, color }); + } + if flip { + corners.reverse(); + } + sink.polygon(material, &corners)?; } - }; - let names = model.as_ref().and_then(|m| slots.get(m)).unwrap_or(&no_slots); - add_geometry(&mut sink, g, global * m, names)?; + } + if bad_normals > 0 { + sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); + } + if bad_uvs > 0 { + sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); + } + } + for warning in scene.warnings { + sink.warn(warning); } let mut raw = sink.finish(); - raw.base_colors = base_colors; - // In file order; FBX 6's built-in "Producer" views are not the scene's cameras. - for o in objects.children.iter().filter(|o| o.name == "Model" && o.class() == "Camera" && !o.object_name().starts_with("Producer ")) { - let Some(id) = o.id_at(0) else { continue }; - if let Ok(m) = world(&models, &parents, &id) { - raw.cameras.push(camera(o, attribute_of.get(&id).copied().unwrap_or(o), global * m)); - } - } + raw.cameras = cameras.into_iter().flatten().collect(); + raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } -/// A camera Model at `m` with its lens in `lens`: FBX cameras look down +X with +Y up. The -/// vertical field of view comes from the focal length (mm) over the film height (inches). -/// shortcut: `OrthoZoom` is taken as the orthographic half view height in scene units; check it -/// against an exporter's orthographic camera when one is at hand. -fn camera(model: &Node, lens: &Node, m: Mat4) -> RawCamera { - let num = |k: &str| lens.number(k).map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0); - let fov = match num("FocalLength") { - Some(f) => lens_fov(f, num("FilmHeight").unwrap_or(0.612) * 25.4), - None => num("FieldOfViewY").or_else(|| num("FieldOfView")).unwrap_or(40.0), - }; - let ortho = (lens.number("CameraProjectionType") == Some(1.0)).then(|| num("OrthoZoom").unwrap_or(1.0)); - RawCamera::placed(model.object_name().to_string(), m, Vec3::X, fov, ortho) +#[cfg(test)] +mod tests { + #[test] + fn incomplete_uv_layer_keeps_other_uvs() { + let bytes = br#"FBXHeaderExtension: { FBXVersion: 7400 } +Objects: { + Geometry: 1, "Geometry::G", "Mesh" { + Vertices: 0,0,0,1,0,0,0,1,0 + PolygonVertexIndex: 0,1,-3 + LayerElementUV: 0 { + MappingInformationType: "ByPolygonVertex" + ReferenceInformationType: "IndexToDirect" + UV: 0.25,0.5, 0.75,0.5 + UVIndex: 0,1 + } + } + Model: 2, "Model::M", "Mesh" {} } - -/// A material's name in the mesh: its object name, or `Material_` when it has none. -fn material_name(id: &str, m: &Node) -> String { - let name = m.object_name(); - if name.is_empty() { format!("Material_{id}") } else { name.to_string() } -} - -/// Each material's diffuse color (× diffuse factor) or, when one is connected and embedded, -/// its diffuse texture (the texture replaces the color, as in most FBX viewers). -fn base_colors( - materials: &HashMap, - textures: &HashMap, - videos: &HashMap, - connections: &[&Node], - files: &mut Files, -) -> Vec { - // Texture → its Video, material → its diffuse texture (a property connection wins). - let (mut video_of, mut diffuse) = (HashMap::new(), HashMap::new()); - for c in connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if videos.contains_key(&child) && textures.contains_key(&parent) { - video_of.insert(parent, child); - } else if textures.contains_key(&child) && materials.contains_key(&parent) { - match (c.str_at(0), c.str_at(3)) { - ("OP", "DiffuseColor" | "Maya|baseColor") => { - diffuse.insert(parent, child); - } - ("OO", _) => { - diffuse.entry(parent).or_insert(child); - } - _ => {} - } - } - } - let mut out: Vec = materials - .iter() - .filter_map(|(id, m)| { - let texture = diffuse.get(id); - let (video, tex) = (texture.and_then(|t| video_of.get(t)).and_then(|v| videos.get(v)), texture.and_then(|t| textures.get(t))); - // Embedded content first, then the file the texture (or its video) names. - let image = video.or(tex).and_then(|n| n.content()).or_else(|| [tex, video].into_iter().flatten().find_map(|n| texture_file(n, files))); - let factor = match (&image, m.property("DiffuseColor").as_deref()) { - (None, Some([r, g, b, ..])) => { - let f = m.number("DiffuseFactor").unwrap_or(1.0); - Vec4::new((r * f) as f32, (g * f) as f32, (b * f) as f32, 1.0) - } - _ => Vec4::ONE, - }; - (image.is_some() || (factor != Vec4::ONE && factor.is_finite())).then(|| RawBaseColor { material: material_name(id, m), factor, image }) - }) - .collect(); - out.sort_by(|a, b| a.material.cmp(&b.material)); - out -} - -/// The file a Texture or Video names: its relative path, else its absolute path's file name -/// (looked for in the FBX's folder). -fn texture_file(n: &Node, files: &mut Files) -> Option> { - let relative = n.child_str("RelativeFilename"); - let absolute = [n.child_str("FileName"), n.child_str("Filename")].into_iter().find(|s| !s.is_empty()).unwrap_or_default(); - let leaf = absolute.rsplit(['/', '\\']).next().unwrap_or_default(); - let mut paths: Vec<&str> = Vec::new(); - for p in [relative, leaf] { - if !p.is_empty() && !paths.contains(&p) { - paths.push(p); - } - } - if paths.is_empty() { None } else { files(&paths) } -} - -/// `Name\0\1Class` (binary) or `Class::Name` (ASCII) to `Name`. -fn clean_name(s: &str) -> &str { - match s.split_once("\u{0}\u{1}") { - Some((name, _)) => name, - None => s.split_once("::").map_or(s, |(_, name)| name), +Connections: { C: "OO",1,2 } +"#; + let raw = super::read(bytes).unwrap(); + let uvs = raw.uvs.unwrap(); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::new(0.25, 0.5))); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::ZERO)); + assert!(raw.warnings.iter().any(|w| w.contains("1 polygon corners have no UV"))); } } - -/// Unit scale to meters and the file's axis system to Y up (+Z front, +X right). -fn global_transform(settings: Option<&Node>) -> Mat4 { - let get = |name: &str, default: f64| settings.and_then(|s| s.number(name)).filter(|v| v.is_finite()).unwrap_or(default); - let unit = get("UnitScaleFactor", 1.0); - let unit = if unit > 0.0 { unit / 100.0 } else { 0.01 }; - let axis = |a: &str, s: &str, default: f64| (get(a, default) as i64, if get(s, 1.0) < 0.0 { -1.0 } else { 1.0 }); - let [(right, rs), (up, us), (front, fs)] = - [axis("CoordAxis", "CoordAxisSign", 0.0), axis("UpAxis", "UpAxisSign", 1.0), axis("FrontAxis", "FrontAxisSign", 2.0)]; - let basis = |a: i64| [Vec3::X, Vec3::Y, Vec3::Z].get(a as usize).copied().filter(|_| a >= 0); - let rows = match (basis(right), basis(up), basis(front)) { - (Some(r), Some(u), Some(f)) if r.cross(u).dot(f).abs() > 0.5 => Mat3::from_cols(r * rs, u * us, f * fs).transpose(), - _ => Mat3::IDENTITY, - }; - Mat4::from_mat3(rows) * Mat4::from_scale(Vec3::splat(unit as f32)) -} - -/// Euler rotation in degrees, `order` as FBX RotationOrder (0 = XYZ: X applied first). -fn euler(deg: Vec3, order: i64) -> Mat4 { - use Vec3 as V; - let axes = match order { - 1 => [V::X, V::Z, V::Y], - 2 => [V::Y, V::Z, V::X], - 3 => [V::Y, V::X, V::Z], - 4 => [V::Z, V::X, V::Y], - 5 => [V::Z, V::Y, V::X], - _ => [V::X, V::Y, V::Z], - }; - axes.iter().fold(Mat4::IDENTITY, |m, a| Mat4::from_axis_angle(*a, deg.dot(*a).to_radians()) * m) -} - -/// A Model's local transform: T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹. -fn local(m: &Node) -> Mat4 { - let t = |name: &str| Mat4::from_translation(m.vec3(name, Vec3::ZERO)); - let order = m.number("RotationOrder").unwrap_or(0.0) as i64; - let (rp, sp) = (m.vec3("RotationPivot", Vec3::ZERO), m.vec3("ScalingPivot", Vec3::ZERO)); - t("Lcl Translation") - * t("RotationOffset") - * Mat4::from_translation(rp) - * euler(m.vec3("PreRotation", Vec3::ZERO), 0) - * euler(m.vec3("Lcl Rotation", Vec3::ZERO), order) - * euler(m.vec3("PostRotation", Vec3::ZERO), 0).inverse() - * Mat4::from_translation(-rp) - * t("ScalingOffset") - * Mat4::from_translation(sp) - * Mat4::from_scale(m.vec3("Lcl Scaling", Vec3::ONE)) - * Mat4::from_translation(-sp) -} - -/// The geometry offset of a Model (not inherited by its children). -fn geometric(m: &Node) -> Mat4 { - Mat4::from_translation(m.vec3("GeometricTranslation", Vec3::ZERO)) - * euler(m.vec3("GeometricRotation", Vec3::ZERO), 0) - * Mat4::from_scale(m.vec3("GeometricScaling", Vec3::ONE)) -} - -fn world(models: &HashMap, parents: &HashMap, id: &str) -> Result { - let mut m = Mat4::IDENTITY; - let mut cur = Some(id); - for _ in 0..=MAX_DEPTH { - let Some(node) = cur.and_then(|c| models.get(c)) else { return Ok(m) }; - m = local(node) * m; - cur = cur.and_then(|c| parents.get(c)).map(String::as_str); - } - Err(malformed(KIND, "the Model hierarchy is nested too deeply (or cyclic)")) -} - -#[derive(Clone, Copy)] -enum Mapping { - PolygonVertex, - ControlPoint, - Polygon, - AllSame, -} - -/// One LayerElement's items, optionally through an index array. -struct Layer<'a> { - mapping: Mapping, - data: Cow<'a, [f64]>, - index: Option>, -} - -impl Layer<'_> { - /// Element `index` names the index array (empty: the data is never indexed). - fn read<'a>(geom: &'a Node, element: &str, data: &str, index: &str) -> Option> { - let el = geom.children.iter().filter(|c| c.name == element).min_by_key(|e| e.int_at(0) != Some(0))?; - let mapping = match el.child_str("MappingInformationType") { - "ByPolygonVertex" => Mapping::PolygonVertex, - "ByVertice" | "ByVertex" | "ByControlPoint" => Mapping::ControlPoint, - "ByPolygon" => Mapping::Polygon, - "AllSame" => Mapping::AllSame, - _ => return None, - }; - let indexed = !index.is_empty() && matches!(el.child_str("ReferenceInformationType"), "IndexToDirect" | "Index"); - let index = if indexed { Some(el.child(index)?.arr()) } else { None }; - Some(Layer { mapping, data: el.child(data)?.arr(), index }) - } - - /// The `W` numbers of polygon vertex `k` (control point `cp`, polygon `poly`). - fn get(&self, k: usize, cp: usize, poly: usize) -> Option<[f64; W]> { - let i = match self.mapping { - Mapping::PolygonVertex => k, - Mapping::ControlPoint => cp, - Mapping::Polygon => poly, - Mapping::AllSame => 0, - }; - let i = match &self.index { - Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize, - None => i, - }; - let start = i.checked_mul(W)?; - self.data.get(start..start.checked_add(W)?)?.try_into().ok() - } -} - -fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> Result<()> { - let verts = g.child("Vertices").map(Node::arr).unwrap_or_default(); - check_vertices(verts.len() / 3)?; - let points: Vec = verts.chunks_exact(3).map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); - let pvi = g.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); - let normals = Layer::read(g, "LayerElementNormal", "Normals", "NormalsIndex"); - let uvs = Layer::read(g, "LayerElementUV", "UV", "UVIndex"); - let mats = Layer::read(g, "LayerElementMaterial", "Materials", ""); - let nm = Mat3::from_mat4(m).inverse().transpose(); - let flip = m.determinant() < 0.0; - let (mut corners, mut poly, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); - for (k, &v) in pvi.iter().enumerate() { - // The last corner of each polygon is stored as -(index + 1). - let (cp, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; - let p = points.get(cp as usize).filter(|_| cp.fract() == 0.0).ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; - let cp = cp as usize; - let n = normals.as_ref().and_then(|l| { - let n = l.get(k, cp, poly).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32)); - bad_normals += usize::from(n.is_none()); - n - }); - // A UV layer with holes keeps its layout: missing items read as 0, 0. - let uv = uvs.as_ref().map(|l| match l.get(k, cp, poly) { - Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), - None => { - bad_uvs += 1; - Vec2::ZERO - } - }); - corners.push(Corner { p: *p, n, uv }); - if last || k + 1 == pvi.len() { - if flip { - corners.reverse(); - } - let slot = mats.as_ref().and_then(|l| l.get(poly, poly, poly)).map_or(0.0, |[s]| s); - let name = slots.get(slot as usize).filter(|_| slot >= 0.0).map_or("Default", String::as_str); - sink.polygon(name, &corners)?; - corners.clear(); - poly += 1; - } - } - if bad_normals > 0 { - sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); - } - if bad_uvs > 0 { - sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); - } - Ok(()) -} diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index bf1f88e0..92e52f72 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -20,8 +20,34 @@ pub(crate) fn read(bytes: &[u8]) -> Result { crate::guard(KIND, || read_inner(bytes)) } +/// Loads and validates the document like `gltf::Gltf::from_slice`, except that a scene without a +/// `nodes` array is an empty scene. The `gltf` crate declares the field as required, but the +/// glTF 2.0 schema lists no required properties for a scene, and exporters write such scenes +/// for scenes that contain no objects. +fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { + let (json, blob) = if bytes.starts_with(b"glTF") { + let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?; + let blob = glb.bin.take().map(std::borrow::Cow::into_owned); + (glb.json, blob) + } else { + (std::borrow::Cow::Borrowed(bytes), None) + }; + let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?; + if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) { + for scene in scenes { + if let Some(scene) = scene.as_object_mut() { + scene.entry("nodes").or_insert_with(|| serde_json::Value::Array(Vec::new())); + } + } + } + // Consume the DOM directly rather than serialising it back to a second full-size buffer. + let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?; + let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?; + Ok((document, blob)) +} + fn read_inner(bytes: &[u8]) -> Result { - let gltf::Gltf { document, blob } = gltf::Gltf::from_slice(bytes).map_err(|e| malformed(KIND, e))?; + let (document, blob) = parse(bytes)?; check_buffer_uris(&document)?; let buffers = gltf::import_buffers(&document, None, blob).map_err(|e| match e { gltf::Error::ExternalReferenceInSliceImport => FormatError::Unsupported( @@ -96,33 +122,36 @@ struct Attrs { color_seen: bool, } -fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> { - if prim.mode() != Mode::Triangles { - raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", prim.mode())); +fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, primitive: &gltf::Primitive, transform: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> { + if primitive.mode() != Mode::Triangles { + raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", primitive.mode())); return Ok(()); } - let Some(pacc) = prim.get(&Semantic::Positions) else { + + let Some(position_accessor) = primitive.get(&Semantic::Positions) else { raw.warnings.push("skipped a primitive without positions".into()); return Ok(()); }; - check_accessor(&pacc, buffers, Dimensions::Vec3, &[DataType::F32], "position")?; - let nacc = prim.get(&Semantic::Normals); - if let Some(a) = &nacc { + + check_accessor(&position_accessor, buffers, Dimensions::Vec3, &[DataType::F32], "position")?; + let normal_accessor = primitive.get(&Semantic::Normals); + if let Some(a) = &normal_accessor { check_accessor(a, buffers, Dimensions::Vec3, &[DataType::F32], "normal")?; } - let tacc = prim.get(&Semantic::TexCoords(0)); - if let Some(a) = &tacc { + let texcoord_accessor = primitive.get(&Semantic::TexCoords(0)); + if let Some(a) = &texcoord_accessor { check_accessor(a, buffers, Dimensions::Vec2, &[DataType::F32, DataType::U8, DataType::U16], "texcoord")?; } - let cacc = prim.get(&Semantic::Colors(0)); - if let Some(a) = &cacc { + let color_accessor = primitive.get(&Semantic::Colors(0)); + if let Some(a) = &color_accessor { let dims = if a.dimensions() == Dimensions::Vec3 { Dimensions::Vec3 } else { Dimensions::Vec4 }; check_accessor(a, buffers, dims, &[DataType::F32, DataType::U8, DataType::U16], "color")?; } - if let Some(a) = prim.indices() { + if let Some(a) = primitive.indices() { check_accessor(&a, buffers, Dimensions::Scalar, &[DataType::U8, DataType::U16, DataType::U32], "index")?; } - let reader = prim.reader(|b| buffers.get(b.index()).map(|d| &d.0[..])); + + let reader = primitive.reader(|b| buffers.get(b.index()).map(|d| &d.0[..])); let positions: Vec = reader.read_positions().ok_or_else(|| malformed(KIND, "unreadable positions"))?.map(Vec3::from).collect(); let n = positions.len(); check_vertices(raw.positions.len().saturating_add(n))?; @@ -134,64 +163,67 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m if let Some(bad) = indices.iter().find(|i| **i as usize >= n) { return Err(malformed(KIND, format!("index {bad} out of range ({n} vertices)"))); } + check_triangles(raw.triangle_count(), indices.len() / 3)?; - let normals: Option> = nacc.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect()); - let texcoords: Option> = tacc.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect()); + let normals: Option> = normal_accessor.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect()); + let texcoords: Option> = texcoord_accessor.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect()); let colors: Option> = - cacc.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec| c.len() == n); + color_accessor.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec| c.len() == n); attrs.color_seen |= colors.is_some(); let color_of = |i: usize| colors.as_ref().and_then(|c| c.get(i)).copied().unwrap_or(Vec4::ONE); - let m3 = Mat3::from_mat4(m); - let nm = m3.inverse().transpose(); - let flip = m3.determinant() < 0.0; - let world: Vec = positions.iter().map(|p| m.transform_point3(*p)).collect(); - let name = match prim.material().index() { + let linear_transform = Mat3::from_mat4(transform); + let normal_transform = linear_transform.inverse().transpose(); + let flip = linear_transform.determinant() < 0.0; + let world: Vec = positions.iter().map(|p| transform.transform_point3(*p)).collect(); + let name = match primitive.material().index() { None => "Default".to_string(), - Some(i) => prim.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")), + Some(i) => primitive.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")), }; if !raw.base_colors.iter().any(|c| c.material == name) { - base_color(raw, &prim.material(), &name, buffers); + base_color(raw, &primitive.material(), &name, buffers); } let base = raw.positions.len() as u32; - let tex_ok = texcoords.as_ref().is_some_and(|t| t.len() == n); - if tex_ok { + let has_texcoords = texcoords.as_ref().is_some_and(|t| t.len() == n); + if has_texcoords { attrs.uv_seen.0 = true } else { attrs.uv_seen.1 = true } + let uv_of = |i: usize| texcoords.as_ref().and_then(|t| t.get(i)).copied().unwrap_or_default(); let raw_normals = raw.normals.get_or_insert_with(Vec::new); match normals.filter(|v| v.len() == n) { Some(nrm) => { raw.positions.extend_from_slice(&world); - raw_normals.extend(nrm.iter().map(|v| (nm * *v).try_normalize().unwrap_or(Vec3::Y))); + raw_normals.extend(nrm.iter().map(|v| (normal_transform * *v).try_normalize().unwrap_or(Vec3::Y))); attrs.uvs.extend((0..n).map(uv_of)); attrs.colors.extend((0..n).map(color_of)); let group = raw.group(&name, part); - for t in indices.chunks_exact(3) { + for t in indices.as_chunks::<3>().0 { let (a, b, c) = (t[0] + base, t[1] + base, t[2] + base); group.extend_from_slice(&if flip { [a, c, b] } else { [a, b, c] }); } } None => { - // glTF: flat normals when none are given, so every triangle gets its own corners. - let mut tris = Vec::with_capacity(indices.len()); - for t in indices.chunks_exact(3) { + // glTF: flat normals when none are given, so every triangle gets its own corners + let mut triangles = Vec::with_capacity(indices.len()); + for t in indices.as_chunks::<3>().0 { let order = if flip { [t[0], t[2], t[1]] } else { [t[0], t[1], t[2]] }; let p = order.map(|i| world.get(i as usize).copied().unwrap_or_default()); let face = (p[1] - p[0]).cross(p[2] - p[0]).try_normalize().unwrap_or(Vec3::Y); for (k, i) in order.iter().enumerate() { - tris.push(raw.positions.len() as u32); + triangles.push(raw.positions.len() as u32); raw.positions.push(p[k]); raw_normals.push(face); attrs.uvs.push(uv_of(*i as usize)); attrs.colors.push(color_of(*i as usize)); } } - raw.group(&name, part).extend_from_slice(&tris); + raw.group(&name, part).extend_from_slice(&triangles); } } + Ok(()) } diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 3daff3c2..f0231d11 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -2,7 +2,7 @@ //! world-space [`Mesh`] with one submesh per material and part (glTF node, OBJ object, FBX //! model, COLLADA node, USD Mesh prim, Alembic PolyMesh; unnamed parts take the file stem), materials contiguous, //! glTF UV convention (origin top-left, v down), -//! normals (computed when missing), vertex colors (glTF, OBJ, PLY), UVs (auto-unwrapped when +//! normals (computed when missing), vertex colors (glTF, FBX, OBJ, PLY), UVs (auto-unwrapped when //! missing) and MikkTSpace tangents. glTF, FBX, COLLADA and USD cameras come along as the //! project's camera list. @@ -182,10 +182,11 @@ pub(crate) struct Corner { pub p: Vec3, pub n: Option, pub uv: Option, + pub color: Option, } /// Collects polygons into a [`RawMesh`]: fan triangulation, one vertex per unique corner, and -/// normals / UVs kept only when every corner has them (else computed / unwrapped). +/// normals / UVs / colors kept only when every corner has them (else computed / unwrapped / white). #[derive(Default)] pub(crate) struct PolygonSink { /// Part name of the polygons that follow. @@ -193,10 +194,13 @@ pub(crate) struct PolygonSink { raw: RawMesh, normals: Vec, uvs: Vec, + /// Allocated by the first coloured corner, so a scene without colors pays nothing for them. + colors: Option>, missing_normals: bool, missing_uvs: bool, some_uvs: bool, - ids: HashMap<[u32; 8], u32>, + missing_colors: bool, + ids: HashMap<[u32; 12], u32>, polygon: Vec, triangles: usize, } @@ -213,13 +217,24 @@ impl PolygonSink { self.missing_normals |= c.n.is_none(); self.missing_uvs |= c.uv.is_none(); self.some_uvs |= c.uv.is_some(); + self.missing_colors |= c.color.is_none(); let (n, uv) = (c.n.unwrap_or_default(), c.uv.unwrap_or_default()); + // A corner without a color must not merge with one that has it. + let color_key = c.color.map_or([u32::MAX; 4], |v| v.to_array().map(f32::to_bits)); let key = [c.p.x, c.p.y, c.p.z, n.x, n.y, n.z, uv.x, uv.y].map(f32::to_bits); + let key = [key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], color_key[0], color_key[1], color_key[2], color_key[3]]; let id = match self.ids.entry(key) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { let id = self.raw.positions.len(); check_vertices(id + 1)?; + // White stands in for the corners before the first coloured one. + if c.color.is_some() && self.colors.is_none() { + self.colors = Some(vec![Vec4::ONE; id]); + } + if let Some(colors) = self.colors.as_mut() { + colors.push(c.color.unwrap_or(Vec4::ONE)); + } self.raw.positions.push(c.p); self.normals.push(n); self.uvs.push(uv); @@ -242,8 +257,12 @@ impl PolygonSink { if self.missing_uvs && self.some_uvs { self.warn("some polygons have no UVs; the whole mesh was unwrapped automatically".into()); } + if self.missing_colors && self.colors.is_some() { + self.warn("some polygon corners have no color in the color layer; vertex colors were dropped".into()); + } self.raw.normals = (!self.missing_normals).then_some(self.normals); self.raw.uvs = (!self.missing_uvs).then_some(self.uvs); + self.raw.colors = if self.missing_colors { None } else { self.colors.take() }; self.raw } } @@ -379,6 +398,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { let RawMesh { positions, normals, uvs, colors, groups, warnings, diagonals, .. } = raw; check_vertices(positions.len())?; check_triangles(0, groups.iter().map(|(_, _, g)| g.len() / 3).sum())?; + let mut mesh = Mesh { positions, ..Mesh::default() }; let mut groups: Vec<(usize, String, Vec)> = groups .into_iter() @@ -398,22 +418,27 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { mesh.indices.extend_from_slice(tris.get(..count as usize).unwrap_or_default()); mesh.submeshes.push(SubMesh { name, material, start, count }); } + if mesh.indices.is_empty() { return Err(FormatError::Invalid("the file contains no triangles".into())); } + if !diagonals.is_empty() { let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b))); - mesh.diagonals = mesh.indices.chunks_exact(3).map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); + mesh.diagonals = mesh.indices.as_chunks::<3>().0.iter().map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); } if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) { return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len()))); } + if mesh.positions.iter().any(|p| !p.is_finite()) { return Err(FormatError::Invalid("the mesh has non-finite vertex positions".into())); } + if all_triangles_degenerate(&mesh) { return Err(FormatError::Invalid("every triangle of the mesh is degenerate (zero area)".into())); } + mesh.normals = match normals { Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(), _ => smooth_normals(&mesh), @@ -421,6 +446,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) { mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect(); } + Ok((mesh, warnings, uvs)) } @@ -482,18 +508,19 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { - let weld = weld_ids(&mesh.positions); - let mut acc = vec![Vec3::ZERO; mesh.positions.len()]; - for t in mesh.indices.chunks_exact(3) { + let welded_vertices = weld_ids(&mesh.positions); + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for triangle in mesh.indices.as_chunks::<3>().0 { let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default(); - let face = (p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])); - for v in t { - if let Some(a) = weld.get(*v as usize).and_then(|w| acc.get_mut(*w as usize)) { + let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); + for v in triangle { + if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) { *a += face; } } } - weld.iter().map(|w| acc.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() + + welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() } /// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings). diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index f9002ad0..267aa8ea 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -1,10 +1,9 @@ -//! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn. - +//! Wavefront OBJ through the shared bounded mesh reader. +use super::{MAX_VERTICES, RawMesh, check_vertices}; +use crate::{FormatError, Result, malformed}; +use std::collections::HashMap; use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; -use super::{RawMesh, check_triangles, check_vertices}; -use crate::{Result, malformed}; - const KIND: &str = "OBJ"; pub(crate) fn read(bytes: &[u8]) -> Result { @@ -12,85 +11,77 @@ pub(crate) fn read(bytes: &[u8]) -> Result { } fn read_inner(bytes: &[u8]) -> Result { - let text = String::from_utf8_lossy(bytes); - // Material names come from `usemtl` (MTL files are never read): tobj only assigns a face's - // material when a library defines it, so every library request gets a synthetic one. - let mut names: Vec<&str> = Vec::new(); - for line in text.lines().map(str::trim) { - if line.split_whitespace().next() == Some("usemtl") - && let Some((_, name)) = line.split_once(' ') - && !name.trim().is_empty() - && !names.contains(&name.trim()) - { - names.push(name.trim()); - } - } - let library: String = names.iter().map(|n| format!("newmtl {n}\n")).collect(); - let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); - // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates. - let opts = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; - let (models, materials) = - tobj::load_obj_buf(&mut source.as_bytes(), &opts, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; - let materials = materials.unwrap_or_default(); - + let limits = craft_mesh::Limits { + max_vertices: MAX_VERTICES, + max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_face_corners: MAX_VERTICES, + max_meshes: MAX_VERTICES, + max_parts: MAX_VERTICES, + max_materials: MAX_VERTICES, + max_data_bytes: super::MAX_MESH_FILE_BYTES as usize, + ..Default::default() + }; + let options = craft_mesh::obj::ReadOptions { strict: true, preserve_runs: true, ignore_material_libraries: true, groups_as_objects: true }; + let scene = craft_mesh::obj::read_with_options(bytes, &limits, &mut craft_mesh::no_external, &options).map_err(|e| match e { + craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), + e => FormatError::Invalid(e.to_string()), + })?; + let any_uvs = scene.meshes.iter().flat_map(|mesh| mesh.parts.iter()).flat_map(|part| part.corners.iter()).any(|c| c.uv != craft_mesh::NONE); + let any_colors = scene.meshes.iter().any(|mesh| !mesh.colors.is_empty()); let mut raw = RawMesh::default(); - let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), Some(Vec::new()), Vec::new()); - let mut partial_uvs = false; - for model in &models { - let m = &model.mesh; - let n = m.positions.len() / 3; - check_vertices(raw.positions.len().saturating_add(n))?; - // Corners per face; without arities every face is a triangle. - let arities: Vec = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() }; - check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; - let base = raw.positions.len() as u32; - raw.positions.extend(m.positions.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); - if m.normals.len() == n * 3 { - if let Some(v) = &mut normals { - v.extend(m.normals.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); - } - } else { - normals = None; - } - if m.texcoords.len() == n * 2 { - if let Some(v) = &mut uvs { - // OBJ UVs have their origin bottom-left. - v.extend(m.texcoords.chunks_exact(2).map(|t| Vec2::new(t[0], 1.0 - t[1]))); - } - } else { - partial_uvs |= n > 0 && !m.indices.is_empty(); - uvs = None; - } - // `v x y z r g b`: objects without colors are white. - match m.vertex_color.len() == n * 3 { - true => colors.extend(m.vertex_color.chunks_exact(3).map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), - false => colors.extend(std::iter::repeat_n(Vec4::ONE, n)), - } - let name = match m.material_id { - Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")), - None => "Default".to_string(), - }; - if let Some(i) = m.indices.iter().find(|i| **i as usize >= n) { - return Err(malformed(KIND, format!("face index {i} out of range"))); - } - // tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem. - let part = if model.name == "unnamed_object" { "" } else { model.name.as_str() }; - let (mut rest, mut corners) = (m.indices.as_slice(), Vec::new()); - for arity in arities { - let Some((face, tail)) = rest.split_at_checked(arity) else { break }; - rest = tail; - corners.clear(); - corners.extend(face.iter().map(|i| base + i)); - if arity >= 3 { - raw.polygon(&name, part, &corners); + let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); + let (mut missing_normals, mut missing_uvs) = (false, false); + for mesh in &scene.meshes { + for part in &mesh.parts { + let material = part.material.and_then(|i| scene.materials.get(i)).map_or("Default", |m| m.name.as_str()); + let name = if part.name.is_empty() { mesh.name.as_str() } else { part.name.as_str() }; + // OBJ model/material runs have independent v/vt/vn deduplication. + let mut ids = HashMap::new(); + for face in part.faces() { + let mut polygon = Vec::with_capacity(face.len()); + for corner in face { + let id = if let Some(id) = ids.get(corner) { + *id + } else { + let position = mesh.positions.get(corner.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; + check_vertices(raw.positions.len().saturating_add(1))?; + // Bound both the output pools and the per-run corner map before growth. + let staging = raw + .positions + .len() + .checked_add(1) + .and_then(|n| n.checked_mul(64)) + .and_then(|n| ids.len().checked_add(1).and_then(|m| m.checked_mul(48)).and_then(|m| n.checked_add(m))); + if staging.is_none_or(|n| n > limits.max_data_bytes) { + return Err(FormatError::TooLarge("OBJ mesh exceeds the memory limit".into())); + } + let id = u32::try_from(raw.positions.len()).map_err(|_| FormatError::TooLarge("OBJ vertex count".into()))?; + raw.positions.push(Vec3::new(position[0] as f32, position[1] as f32, position[2] as f32)); + let normal = mesh.normals.get(corner.normal as usize).map(|n| Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); + missing_normals |= normal.is_none(); + normals.push(normal.unwrap_or_default()); + if any_uvs { + let uv = mesh.uv_sets.first().and_then(|set| set.get(corner.uv as usize)).map(|v| Vec2::new(v[0], v[1])); + missing_uvs |= uv.is_none(); + uvs.push(uv.unwrap_or_default()); + } + if any_colors { + colors.push(mesh.colors.get(corner.position as usize).copied().map(Vec4::from_array).unwrap_or(Vec4::ONE)); + } + ids.insert(*corner, id); + id + }; + polygon.push(id); + } + raw.polygon(material, name, &polygon); } } } - if partial_uvs && models.iter().any(|m| !m.mesh.texcoords.is_empty()) { - raw.warnings.push("some objects have no UVs; the whole mesh was unwrapped automatically".into()); + if missing_uvs { + raw.warnings.push("some objects have no UVs; default UVs were assigned".into()); } - raw.normals = normals; - raw.uvs = uvs; - raw.colors = models.iter().any(|m| !m.mesh.vertex_color.is_empty()).then_some(colors); + raw.normals = (!missing_normals).then_some(normals); + raw.uvs = any_uvs.then_some(uvs); + raw.colors = any_colors.then_some(colors); Ok(raw) } diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index 34e1c1da..fd923ee8 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -10,40 +10,20 @@ const KIND: &str = "PLY"; /// Longest polygon accepted (a list count above this is treated as corruption). const MAX_FACE_VERTICES: usize = 4096; -#[derive(Clone, Copy, PartialEq)] -enum Ty { - I8, - U8, - I16, - U16, - I32, - U32, - F32, - F64, -} +use craft_mesh::ply::{Encoding as SharedEncoding, Header, Rows, Scalar as Ty}; -impl Ty { - fn parse(s: &str) -> Option { - Some(match s { - "char" | "int8" => Ty::I8, - "uchar" | "uint8" => Ty::U8, - "short" | "int16" => Ty::I16, - "ushort" | "uint16" => Ty::U16, - "int" | "int32" => Ty::I32, - "uint" | "uint32" => Ty::U32, - "float" | "float32" => Ty::F32, - "double" | "float64" => Ty::F64, - _ => return None, - }) - } - fn size(self) -> usize { - match self { - Ty::I8 | Ty::U8 => 1, - Ty::I16 | Ty::U16 => 2, - Ty::I32 | Ty::U32 | Ty::F32 => 4, - Ty::F64 => 8, - } - } +fn parse_type(s: &str) -> Option { + Some(match s { + "char" | "int8" => Ty::I8, + "uchar" | "uint8" => Ty::U8, + "short" | "int16" => Ty::I16, + "ushort" | "uint16" => Ty::U16, + "int" | "int32" => Ty::I32, + "uint" | "uint32" => Ty::U32, + "float" | "float32" => Ty::F32, + "double" | "float64" => Ty::F64, + _ => return None, + }) } struct Property { @@ -66,60 +46,36 @@ enum Encoding { Be, } -/// Reads scalars from the body in either encoding. -struct Body<'a> { - data: &'a [u8], - pos: usize, - enc: Encoding, -} - -impl Body<'_> { - fn next_token(&mut self) -> Option<&str> { - let rest = self.data.get(self.pos..)?; - let start = rest.iter().position(|b| !b.is_ascii_whitespace())?; - let len = rest.get(start..)?.iter().position(|b| b.is_ascii_whitespace()).unwrap_or(rest.len() - start); - self.pos += start + len; - std::str::from_utf8(rest.get(start..start + len)?).ok() - } - - fn read(&mut self, ty: Ty) -> Result { - if self.enc == Encoding::Ascii { - let tok = self.next_token().ok_or_else(|| malformed(KIND, "unexpected end of data"))?; - return tok.parse::().map_err(|_| malformed(KIND, format!("bad number \"{tok}\""))); - } - let n = ty.size(); - let bytes = self.data.get(self.pos..self.pos + n).ok_or_else(|| malformed(KIND, "unexpected end of data"))?; - self.pos += n; - let mut b = [0u8; 8]; - b.get_mut(..n).unwrap_or_default().copy_from_slice(bytes); - if self.enc == Encoding::Be { - b.get_mut(..n).unwrap_or_default().reverse(); - } - Ok(match ty { - Ty::I8 => b[0] as i8 as f64, - Ty::U8 => b[0] as f64, - Ty::I16 => i16::from_le_bytes([b[0], b[1]]) as f64, - Ty::U16 => u16::from_le_bytes([b[0], b[1]]) as f64, - Ty::I32 => i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::U32 => u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::F64 => f64::from_le_bytes(b), - }) - } - - fn remaining(&self) -> usize { - self.data.len().saturating_sub(self.pos) - } -} - pub(crate) fn read(bytes: &[u8]) -> Result { let (elements, enc, body_start) = header(bytes)?; - let mut body = Body { data: bytes.get(body_start..).unwrap_or_default(), pos: 0, enc }; + // Keep the strict app header grammar and mesh policy; delegate only wire scalars. + let encoding = match enc { + Encoding::Ascii => SharedEncoding::Ascii, + Encoding::Le => SharedEncoding::Little, + Encoding::Be => SharedEncoding::Big, + }; + let shared_header = Header { encoding, elements: Vec::new(), body: body_start, comments: Vec::new() }; + let mut body = Rows::new(&shared_header, bytes); let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); // Elements may appear in any order, so take the vertex count from the header. let nverts: usize = elements.iter().filter(|e| e.name == "vertex").map(|e| e.count).fold(0, usize::saturating_add); + // The shared ASCII reader counts the delimiter after a value as read; the previous reader + // left it in the remaining bytes. Only an element without properties can notice the difference. + let ascii_slack = usize::from(enc == Encoding::Ascii); for el in &elements { + // An element without properties reads nothing, so its rows are skipped. Its count stays + // bounded by the bytes left, as the previous reader counted them. + if el.props.is_empty() { + if el.count > body.remaining().saturating_add(ascii_slack) { + return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count))); + } + // A vertex element still needs positions, as below. + if el.name == "vertex" { + return Err(malformed(KIND, "vertices have no x, y, z")); + } + continue; + } // Every item takes at least one byte, so the count can never exceed what is left. if el.count > body.remaining() { return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count))); @@ -149,17 +105,17 @@ pub(crate) fn read(bytes: &[u8]) -> Result { match p.list { None => { if let Some(v) = vals.get_mut(k) { - *v = body.read(p.ty)?; + *v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?; } } Some(ct) => { - let len = body.read(ct)?; + let len = body.value(ct).map_err(|e| malformed(KIND, e.to_string()))?; if !(0.0..=MAX_FACE_VERTICES as f64).contains(&len) { return Err(malformed(KIND, format!("bad list length {len}"))); } poly.clear(); for _ in 0..len as usize { - let v = body.read(p.ty)?; + let v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?; if face_list == Some(k) { if !(0.0..nverts as f64).contains(&v) { return Err(malformed(KIND, format!("face index {v} out of range"))); @@ -240,13 +196,13 @@ fn header(bytes: &[u8]) -> Result<(Vec, Encoding, usize)> { } ["property", "list", ct, ty, name] => { let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?; - let (ct, ty) = (Ty::parse(ct), Ty::parse(ty)); + let (ct, ty) = (parse_type(ct), parse_type(ty)); let (Some(ct), Some(ty)) = (ct, ty) else { return Err(malformed(KIND, format!("bad list types in \"{line}\""))) }; el.props.push(Property { name: name.to_string(), ty, list: Some(ct) }); } ["property", ty, name] => { let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?; - let ty = Ty::parse(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?; + let ty = parse_type(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?; el.props.push(Property { name: name.to_string(), ty, list: None }); } ["ply"] | [] | ["comment", ..] | ["obj_info", ..] => {} @@ -256,3 +212,52 @@ fn header(bytes: &[u8]) -> Result<(Vec, Encoding, usize)> { let enc = enc.ok_or_else(|| malformed(KIND, "header has no format line"))?; Ok((elements, enc, pos)) } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod shared_rows_tests { + use super::*; + + #[test] + fn trailing_propertyless_element_after_a_newline_still_opens() { + let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 1\nend_header\n0 0 0\n"; + assert_eq!(read(bytes).unwrap().positions, vec![Vec3::new(0.0, 0.0, 0.0)]); + let huge = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 3\nend_header\n0 0 0\n"; + assert!(read(huge).is_err()); + } + + #[test] + fn propertyless_vertex_element_is_still_rejected() { + let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n3 0 0 0\n"; + let Err(e) = read(bytes) else { panic!("a vertex element without x, y, z must not open") }; + let err = e.to_string(); + assert!(err.contains("vertices have no x, y, z"), "{err}"); + } + + #[test] + fn binary_scalar_endianness_matches_ascii() { + for (format, big) in [("binary_little_endian", false), ("binary_big_endian", true)] { + let mut bytes = + format!("ply\nformat {format} 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n").into_bytes(); + bytes.extend(if big { (-123i16).to_be_bytes() } else { (-123i16).to_le_bytes() }); + bytes.extend(if big { 1.25f32.to_be_bytes() } else { 1.25f32.to_le_bytes() }); + bytes.extend(if big { (-2.5f64).to_be_bytes() } else { (-2.5f64).to_le_bytes() }); + assert_eq!(read(&bytes).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]); + bytes.pop(); + assert!(read(&bytes).is_err()); + } + let ascii = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n -123 \t1.25\r\n -2.5 "; + assert_eq!(read(ascii).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]); + } + + #[test] + fn strict_header_and_invalid_face_policy_remain_local() { + for extra in ["unknown directive\n", "property nonsense x\n"] { + let bytes = format!("ply\nformat ascii 1.0\nelement vertex 1\n{extra}end_header\n0"); + assert!(read(bytes.as_bytes()).is_err()); + } + assert!(read(b"ply\nformat ascii 1.0\ncomment \xff\nend_header\n").is_err()); + let bytes = b"ply\nformat ascii 1.0\nelement face 1\nproperty list uchar int vertex_indices\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nend_header\n3 0 0 1\n0 0 0\n"; + assert!(read(bytes).is_err()); // Do not turn a bad face into a warning/skip. + } +} diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 08609687..015724a1 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -3,7 +3,7 @@ use std::io::Write as _; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use super::tests::hammer; use super::*; @@ -298,7 +298,46 @@ fn fbx_binary_32_and_64_bit_compressed_or_not() { } } +/// [`scene`] with a per-polygon-vertex color layer: corner `i` gets `(i/8, 1 - i/8, 0.25, 1)`. +fn colored_scene() -> Vec { + let mut nodes = scene(false); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + let geometry = objects.children.iter_mut().find(|node| node.name == "Geometry").unwrap(); + let colors: Vec = (0..7).flat_map(|i| [i as f64 / 8.0, 1.0 - i as f64 / 8.0, 0.25, 1.0]).collect(); + geometry.children.push(layer( + "LayerElementColor", + "ByPolygonVertex", + "IndexToDirect", + vec![n("Colors", vec![P::Doubles(colors)], vec![]), n("ColorIndex", vec![P::Ints((0..7).collect())], vec![])], + )); + nodes +} + +#[test] +fn fbx_vertex_colors_reach_the_mesh_and_high_polys() { + let nodes = colored_scene(); + let expected: Vec = (0..7).map(|i| Vec4::new(i as f32 / 8.0, 1.0 - i as f32 / 8.0, 0.25, 1.0)).collect(); + for (label, bytes) in [("binary", binary_fbx(&nodes, 7400, false)), ("ascii", ascii_fbx(&nodes).into_bytes())] { + let imported = import_mesh_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(imported.mesh.colors, expected, "{label}: the color layer reaches the mesh"); + let high = import_high_poly_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(high.mesh.colors, expected, "{label}: and the high poly used for ID bakes"); + } +} + /// [`scene`] with a diffuse color on Red and an embedded diffuse texture on Blue. +#[test] +fn fbx_camera_models_are_capped_during_import() { + let mut nodes = scene(false); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + for id in 100..199 { + objects.children.push(n("Model", vec![P::L(id), P::S("Camera\\u{0}\\u{1}Model"), P::S("Camera")], vec![])); + } + + let raw = fbx::read(&binary_fbx(&nodes, 7500, true)).unwrap(); + assert_eq!(raw.cameras.len(), MAX_CAMERAS); +} + fn textured_scene(png: &[u8]) -> Vec { let mut nodes = scene(false); let objects = nodes.iter_mut().find(|n| n.name == "Objects").unwrap(); @@ -338,6 +377,23 @@ fn fbx_diffuse_colors_and_embedded_textures_reach_high_polys() { hammer("x.fbx", &binary_fbx(&nodes, 7500, false)); } +#[test] +fn fbx_retains_white_materials_and_colors_beside_textures() { + let mut nodes = textured_scene(&tiny_png()); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + let red = objects.children.iter_mut().find(|node| matches!(node.props.first(), Some(P::L(30)))).unwrap(); + red.children = vec![props70(vec![prop("DiffuseColor", &[1.0, 1.0, 1.0])])]; + let blue = objects.children.iter_mut().find(|node| matches!(node.props.first(), Some(P::L(31)))).unwrap(); + blue.children.push(props70(vec![prop("DiffuseColor", &[0.1, 0.2, 0.3])])); + + let imported = import_high_poly_bytes("colors.fbx", &binary_fbx(&nodes, 7500, true)).unwrap(); + let white = imported.base_color[0].as_ref().unwrap(); + let textured = imported.base_color[1].as_ref().unwrap(); + assert_eq!(white.factor, texturecraft_geom::glam::Vec4::ONE); + assert_eq!(textured.factor, texturecraft_geom::glam::Vec4::new(0.1, 0.2, 0.3, 1.0)); + assert_eq!(textured.texels.len(), 4); +} + /// [`textured_scene`] with Blue's texture kept as a file: `tex/wood.png` relative to the FBX, or /// only an absolute path elsewhere (found by its file name next to the FBX). fn texture_file_scene(relative: &'static str) -> Vec { @@ -398,6 +454,24 @@ fn fbx_ascii_and_z_up() { check_fbx_scene(&import_mesh_bytes("z.fbx", &binary_fbx(&scene(true), 7700, true)).unwrap().mesh, true); } +#[test] +fn fbx_duplicate_geometry_connections_do_not_duplicate_instances() { + let mut nodes = scene(false); + let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap(); + for _ in 0..50 { + connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(21)], vec![])); + } + let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap(); + assert_eq!(imported.report.triangles, 3); + + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + objects.children.push(n("Model", vec![P::L(22), P::S("Other\u{0}\u{1}Model"), P::S("Mesh")], vec![])); + let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap(); + connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(22)], vec![])); + let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap(); + assert_eq!(imported.report.triangles, 6, "a different model must remain a distinct instance"); +} + /// The scene of [`scene`] (Y up) as FBX 6.1 writes it: geometry inside the Model, objects named /// `Class::Name`, `Properties60`, `Connect` records, GlobalSettings inside Objects. const FBX61: &str = r#"; FBX 6.1.0 project file @@ -572,19 +646,55 @@ fn fbx_old_versions_and_garbage_are_errors() { assert!(import_mesh_bytes("h.fbx", &huge).is_err()); } +// Keep these fixtures independently schedulable: one serial test took 24 minutes in +// instrumented coverage. Splitting cases keeps every mutation and assertion intact. #[test] -fn malformed_fbx_and_dae_never_panic() { +fn malformed_fbx_and_dae_never_panic_binary_7400() { hammer("x.fbx", &binary_fbx(&scene(false), 7400, false)); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_binary_7500() { hammer("x.fbx", &binary_fbx(&scene(true), 7500, true)); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_ascii() { hammer("x.fbx", ascii_fbx(&scene(false)).as_bytes()); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_collada() { hammer("x.dae", DAE.as_bytes()); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_binary() { + random_scene_corruptions(0); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_ascii() { + random_scene_corruptions(1); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_collada() { + random_scene_corruptions(2); +} + +fn random_scene_corruptions(selected_fixture: usize) { // Random multi-byte corruptions (a fixed LCG keeps failures reproducible). let mut seed = 0x2545_f491_4f6c_dd1du64; let mut next = move || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) as usize }; - for good in [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()] { + // Replay earlier mutations without parsing them so each fixture receives exactly + // its original LCG stream, not a fresh seed. Fixture sizes and all 1,500 cases + // per fixture stay unchanged; generating these bytes is cheap next to parsing. + let fixtures = [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()]; + for (fixture, good) in fixtures.into_iter().enumerate().take(selected_fixture + 1) { let name = if good.starts_with(b" Result { - let count = bytes.get(80..84).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); - let binary_len = count.and_then(|c| c.checked_mul(50)).and_then(|n| n.checked_add(84)); - let looks_ascii = bytes.iter().position(|b| !b.is_ascii_whitespace()).and_then(|i| bytes.get(i..i + 5)) == Some(b"solid".as_slice()); - let tris = match (count, binary_len) { - // Exact size wins: many binary files also start with "solid". - (Some(c), Some(len)) if len == bytes.len() => binary(bytes, c)?, - _ if looks_ascii => ascii(bytes)?, - (Some(c), Some(len)) if len < bytes.len() => binary(bytes, c)?, - _ => return Err(malformed(KIND, "neither a complete binary STL nor an ascii STL")), - }; + let scene = craft_mesh::stl::read(bytes, &stl_limits()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut raw = RawMesh::default(); - check_triangles(0, tris.len())?; - let mut normals = Vec::with_capacity(tris.len() * 3); - for t in &tris { - let n = (t[1] - t[0]).cross(t[2] - t[0]).try_normalize().unwrap_or(Vec3::Y); - raw.positions.extend_from_slice(t); - normals.extend_from_slice(&[n; 3]); + raw.warnings = scene.warnings; + + let mut tri_count = 0; + let mut vertex_colors = Vec::new(); + let has_colors = !scene.materials.is_empty(); + for mesh in scene.meshes { + // The shared model groups colored facets into parts. Position indices still reflect + // source order, so merge the parts back into STL order for TextureCraft's raw mesh. + let mut triangles = Vec::new(); + for part in mesh.parts { + let material = part.material.and_then(|i| scene.materials.get(i)); + let color = material.map(|m| Vec4::from_array(m.base_color)); + for tri in part.triangles() { + let first_position = tri.iter().map(|c| c.position).min().unwrap_or(u32::MAX); + triangles.push((first_position, tri, color)); + } + } + triangles.sort_by_key(|(first_position, _, _)| *first_position); + for (_, tri, color) in triangles { + check_triangles(tri_count, 1)?; + tri_count += 1; + let mut points = [Vec3::ZERO; 3]; + for (i, corner) in tri.into_iter().enumerate() { + let p = mesh.positions.get(corner.position as usize).ok_or_else(|| FormatError::Invalid(format!("{KIND}: position index out of range")))?; + points[i] = Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32); + } + // Recompute per-facet normals as TextureCraft's old importer did; stored STL + // normals are often zero or disagree with the vertex winding. + let normal = (points[1] - points[0]).cross(points[2] - points[0]).try_normalize().unwrap_or(Vec3::Y); + raw.positions.extend_from_slice(&points); + raw.normals.get_or_insert_with(Vec::new).extend_from_slice(&[normal; 3]); + if has_colors { + // The shared reader normalizes STL's color extensions to linear RGBA. + // Uncolored facets alongside colored ones receive its neutral gray material. + let color = color.unwrap_or(Vec4::new(0.6, 0.6, 0.6, 1.0)); + vertex_colors.extend_from_slice(&[color; 3]); + } + } + } + if raw.positions.is_empty() { + return Err(crate::malformed(KIND, "no facets")); + } + if has_colors { + raw.colors = Some(vertex_colors); } - raw.normals = Some(normals); raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); Ok(raw) } -fn binary(bytes: &[u8], count: usize) -> Result> { - check_triangles(0, count)?; - let mut out = Vec::with_capacity(count); - for i in 0..count { - let f = |k: usize| -> Result { - let o = 84 + i * 50 + 12 + k * 4; - let b = bytes.get(o..o + 4).ok_or_else(|| malformed(KIND, "truncated facet"))?; - Ok(f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - }; - let v = |c: usize| -> Result { Ok(Vec3::new(f(c * 3)?, f(c * 3 + 1)?, f(c * 3 + 2)?)) }; - out.push([v(0)?, v(1)?, v(2)?]); - } - Ok(out) +/// STL stores three positions per facet; retain the app's established triangle capacity. +fn stl_limits() -> craft_mesh::Limits { + craft_mesh::Limits { max_vertices: MAX_VERTICES, ..craft_mesh::Limits::default() } } -fn ascii(bytes: &[u8]) -> Result> { - let text = std::str::from_utf8(bytes).map_err(|_| malformed(KIND, "ascii STL is not text"))?; - let mut out = Vec::new(); - let mut facet: Vec = Vec::new(); - let mut words = text.split_whitespace(); - while let Some(w) = words.next() { - match w { - "vertex" => { - let mut c = [0.0f32; 3]; - for v in &mut c { - let tok = words.next().ok_or_else(|| malformed(KIND, "truncated vertex"))?; - *v = tok.parse().map_err(|_| malformed(KIND, format!("bad number \"{tok}\"")))?; - } - facet.push(Vec3::from(c)); - } - "endfacet" => { - for i in 1..facet.len().saturating_sub(1) { - check_triangles(out.len(), 1)?; - out.push([facet[0], facet[i], facet[i + 1]]); - } - facet.clear(); - } - _ => {} - } +#[cfg(test)] +mod tests { + #[test] + fn shared_reader_accepts_the_app_vertex_limit() { + let limits = super::stl_limits(); + assert_eq!(limits.max_vertices, super::MAX_VERTICES); + assert_eq!(limits.max_triangles, texturecraft_geom::MAX_TRIANGLES); } - if out.is_empty() { - return Err(malformed(KIND, "no facets")); - } - Ok(out) } diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index fd45cc87..88509a05 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -118,6 +118,48 @@ fn glb_two_materials_mirrored_node() { m.validate().unwrap(); } +/// A scene without a `nodes` array is legal glTF (Blender writes one for a scene with no exported +/// objects); it must not stop the default scene from importing. +#[test] +fn gltf_scene_without_nodes_imports_the_default_scene() { + let mut json: serde_json::Value = serde_json::from_slice(&embedded_gltf()).unwrap(); + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]); + json["scene"] = 1.into(); + let im = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap(); + assert_eq!(im.report.triangles, 2); + // Only an empty scene: nothing to import, but a clear error rather than a parse failure. + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }]); + json["scene"] = 0.into(); + let err = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap_err(); + assert!(!err.to_string().contains("missing field"), "{err}"); +} + +#[test] +fn glb_scene_without_nodes_keeps_binary_mesh_in_default_scene() { + let original = glb(true, true); + let jlen = u32::from_le_bytes(original[12..16].try_into().unwrap()) as usize; + let mut json: serde_json::Value = serde_json::from_slice(&original[20..20 + jlen]).unwrap(); + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]); + json["scene"] = 1.into(); + let mut js = serde_json::to_vec(&json).unwrap(); + while !js.len().is_multiple_of(4) { + js.push(b' '); + } + let bin_chunk = &original[20 + jlen..]; + let mut glb = Vec::new(); + glb.extend(b"glTF"); + glb.extend(2u32.to_le_bytes()); + glb.extend(((20 + js.len() + bin_chunk.len()) as u32).to_le_bytes()); + glb.extend((js.len() as u32).to_le_bytes()); + glb.extend(b"JSON"); + glb.extend(js); + glb.extend(bin_chunk); + let im = import_mesh_bytes("scene.glb", &glb).unwrap(); + assert_eq!(im.report.triangles, 2); + assert_eq!(im.mesh.materials, ["Red", "Material_1"]); + assert_outward(&im.mesh); +} + #[test] fn gltf_embedded_buffers_and_missing_attributes() { let im = import_mesh_bytes("scene.gltf", &embedded_gltf()).unwrap(); @@ -235,6 +277,33 @@ fn obj_without_uvs_or_normals_is_completed() { assert!(n0.len() > 1 && n0.iter().all(|n| (*n - n0[0]).length() < 1e-5)); } +#[test] +fn obj_with_some_objects_having_uvs_preserves_uvs_without_full_unwrap() { + let obj = "o Body +v 0 0 0 +v 1 0 0 +v 1 1 0 +vt 0 0 +vt 1 0 +vt 1 1 +f 1/1 2/2 3/3 +o Helper +v 2 0 0 +v 3 0 0 +v 3 1 0 +f 4 5 6 +"; + let im = import_mesh_bytes("character.obj", obj.as_bytes()).unwrap(); + assert!(!im.report.uvs_generated); + assert_eq!(im.mesh.uvs[0], Vec2::new(0.0, 1.0)); + assert_eq!(im.mesh.uvs[1], Vec2::new(1.0, 1.0)); + assert_eq!(im.mesh.uvs[2], Vec2::new(1.0, 0.0)); + assert_eq!(im.mesh.uvs[3], Vec2::ZERO); + assert_eq!(im.mesh.uvs[4], Vec2::ZERO); + assert_eq!(im.mesh.uvs[5], Vec2::ZERO); + assert!(im.report.warnings.iter().any(|w| w.contains("some objects have no UVs"))); +} + #[test] fn polygons_keep_their_edges_for_the_wireframe() { // An OBJ quad and pentagon (with UVs, so no unwrap splits them), a triangle, and a PLY quad. @@ -345,6 +414,43 @@ fn stl_ascii_and_binary() { assert_eq!(import_mesh_bytes("c.stl", &b).unwrap().mesh.triangle_count(), 2); } +#[test] +fn stl_shared_reader_keeps_flat_normals_and_surfaces_shared_repairs_and_colors() { + let mut bytes = stl_binary(); + // VisCAM/SolidView: bit 15 marks a facet color; red occupies bits 10..14. + bytes[132..134].copy_from_slice(&0xfc00u16.to_le_bytes()); + // A third facet repeats that color after an uncolored facet. The shared reader groups its + // parts by color, so the adapter must restore the source facet order. + bytes.extend([0.0f32; 3].iter().flat_map(|v| v.to_le_bytes())); + for v in [[0.0f32, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]] { + bytes.extend(v.iter().flat_map(|x| x.to_le_bytes())); + } + bytes.extend(0xfc00u16.to_le_bytes()); + // Some exporters leave the header count at zero despite having facets. + bytes[80..84].copy_from_slice(&0u32.to_le_bytes()); + let imported = import_mesh_bytes("colored.stl", &bytes).unwrap(); + assert_eq!(imported.mesh.triangle_count(), 3); + assert_eq!(imported.mesh.submeshes.len(), 1); + assert_eq!(imported.mesh.submeshes[0].name, "colored"); + assert_eq!( + imported.mesh.positions, + vec![ + Vec3::ZERO, + Vec3::X, + Vec3::new(1.0, 1.0, 0.0), + Vec3::ZERO, + Vec3::new(1.0, 1.0, 0.0), + Vec3::Y, + Vec3::Z, + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 1.0, 1.0) + ] + ); + assert_eq!(imported.mesh.normals, vec![Vec3::Z; 9]); + assert!(imported.mesh.colors.iter().any(|c| c.x > 0.99 && c.y < 0.01 && c.z < 0.01)); + assert!(imported.report.warnings.iter().any(|w| w.contains("counts no facets"))); +} + /// Every prefix and some corruptions of a valid file: errors, never panics (and never an /// error from the panic guard, which would mean a parser panicked). pub(crate) fn hammer(name: &str, good: &[u8]) { diff --git a/crates/formats/src/mesh_import/usd/codec.rs b/crates/formats/src/mesh_import/usd/codec.rs index a336db33..4221e390 100644 --- a/crates/formats/src/mesh_import/usd/codec.rs +++ b/crates/formats/src/mesh_import/usd/codec.rs @@ -104,35 +104,13 @@ pub(crate) fn numeric(t: u8) -> Option<(Scalar, usize)> { /// Decompress Crate's LZ4 framing into at most `max_out` bytes. pub(crate) fn decompress(input: &[u8], max_out: usize) -> Result> { - let bad = |e: lz4_flex::block::DecompressError| malformed(KIND, format!("LZ4 data: {e}")); - let (&chunks, mut rest) = input.split_first().ok_or_else(|| malformed(KIND, "empty compressed block"))?; - // LZ4 expands at most ~255×: never allocate more than the input can produce. - let mut out = vec![0u8; max_out.min(input.len().saturating_mul(256).saturating_add(64))]; - let written = if chunks == 0 { - lz4_flex::block::decompress_into(rest, &mut out).map_err(bad)? - } else { - if chunks > 127 { - return Err(malformed(KIND, "bad LZ4 chunk count")); - } - let mut total = 0usize; - for _ in 0..chunks { - let size = rest.get(..4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?; - let size = usize::try_from(size).map_err(|_| malformed(KIND, "negative LZ4 chunk size"))?; - let chunk = rest.get(4..4usize.saturating_add(size)).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?; - rest = rest.get(4 + size..).unwrap_or_default(); - total += lz4_flex::block::decompress_into(chunk, out.get_mut(total..).unwrap_or_default()).map_err(bad)?; - } - total - }; - out.truncate(written); - Ok(out) + craft_usd::decompress(input, max_out).map_err(|e| malformed(KIND, e.to_string())) } /// Crate's LZ4 framing for one chunk (inputs are far below LZ4's ~2 GB chunk limit). -pub(crate) fn compress(input: &[u8]) -> Vec { - let mut out = vec![0u8]; - out.extend_from_slice(&lz4_flex::block::compress(input)); - out +pub(crate) fn compress(input: &[u8]) -> Result> { + // Keep one compressed output reservation within the app's decoded-data ceiling. + craft_usd::compress::compress(input, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } /// Upper bound of the encoded size of `n` integers of `width` bytes. @@ -140,89 +118,24 @@ pub(crate) fn encoded_ints_len(n: usize, width: usize) -> usize { if n == 0 { 0 } else { width.saturating_add(n.saturating_mul(2).saturating_add(7) / 8).saturating_add(n.saturating_mul(width)) } } -fn read_signed(b: &[u8], at: usize, width: usize) -> Option { - let s = b.get(at..at.checked_add(width)?)?; - Some(match width { - 1 => i64::from(i8::from_le_bytes(s.try_into().ok()?)), - 2 => i64::from(i16::from_le_bytes(s.try_into().ok()?)), - 4 => i64::from(i32::from_le_bytes(s.try_into().ok()?)), - _ => i64::from_le_bytes(s.try_into().ok()?), - }) -} - -/// Decode `n` integers of `width` (4 or 8) bytes; 32-bit values are sign-extended (reinterpret -/// as u32 for unsigned data). +/// Decode packed integers after the caller charges its aggregate decoded-byte budget. pub(crate) fn decode_ints(data: &[u8], n: usize, width: usize) -> Result> { - let err = || malformed(KIND, "truncated integer array"); - if n == 0 { - return Ok(Vec::new()); - } - let common = read_signed(data, 0, width).ok_or_else(err)?; - let codes_at = width; - let mut at = codes_at + n.div_ceil(4); - let mut out = Vec::with_capacity(n); - let mut prev = 0i64; - for i in 0..n { - let code = (data.get(codes_at + i / 4).ok_or_else(err)? >> (2 * (i % 4))) & 3; - let delta = match code { - 0 => common, - c => { - let w = (width >> (3 - c as usize)).max(1); - let v = read_signed(data, at, w).ok_or_else(err)?; - at += w; - v - } - }; - prev = if width == 4 { i64::from((prev as i32).wrapping_add(delta as i32)) } else { prev.wrapping_add(delta) }; - out.push(prev); - } - Ok(out) + let width = match width { + 4 => craft_usd::integers::Width::I32, + 8 => craft_usd::integers::Width::I64, + _ => return Err(malformed(KIND, "unsupported integer width")), + }; + craft_usd::integers::decode(data, n, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } -/// Encode integers of `width` (4 or 8) bytes (values must fit the width). -pub(crate) fn encode_ints(values: &[i64], width: usize) -> Vec { - if values.is_empty() { - return Vec::new(); - } - let wrap = |v: i64| if width == 4 { i64::from(v as i32) } else { v }; - let mut prev = 0i64; - let deltas: Vec = values - .iter() - .map(|&v| { - let d = wrap(v.wrapping_sub(prev)); - prev = v; - d - }) - .collect(); - let mut counts = std::collections::HashMap::new(); - for d in &deltas { - *counts.entry(*d).or_insert(0usize) += 1; - } - let common = counts.into_iter().max_by_key(|&(v, c)| (c, v)).map_or(0, |(v, _)| v); - let mut out = Vec::with_capacity(encoded_ints_len(values.len(), width)); - out.extend_from_slice(&common.to_le_bytes()[..width]); - let codes_at = out.len(); - out.resize(codes_at + values.len().div_ceil(4), 0); - for (i, &d) in deltas.iter().enumerate() { - let small = |bits: u32| d >= -(1i64 << (bits - 1)) && d < (1i64 << (bits - 1)); - let code: u8 = if d == common { - 0 - } else if small(width as u32 * 2) { - 1 - } else if small(width as u32 * 4) { - 2 - } else { - 3 - }; - if code > 0 { - let w = (width >> (3 - code as usize)).max(1); - out.extend_from_slice(&d.to_le_bytes()[..w]); - } - if let Some(b) = out.get_mut(codes_at + i / 4) { - *b |= code << (2 * (i % 4)); - } - } - out +/// Encode packed integers with a combined scratch/output reservation cap. +pub(crate) fn encode_ints(values: &[i64], width: usize) -> Result> { + let width = match width { + 4 => craft_usd::integers::Width::I32, + 8 => craft_usd::integers::Width::I64, + _ => return Err(malformed(KIND, "unsupported integer width")), + }; + craft_usd::integers::encode(values, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } /// Error for counts that cannot be real (more items than bytes left could describe). diff --git a/crates/formats/src/mesh_import/usd/mod.rs b/crates/formats/src/mesh_import/usd/mod.rs index e7f9d0fe..9f6f6d41 100644 --- a/crates/formats/src/mesh_import/usd/mod.rs +++ b/crates/formats/src/mesh_import/usd/mod.rs @@ -576,6 +576,7 @@ impl<'a> Stage<'a> { p: m.transform_point3(Vec3::from(p)), n: normals.as_ref().and_then(|pv| pv.get::<3>(at)).map(|v| nm * Vec3::from(v)), uv: uvs.as_ref().and_then(|pv| pv.get::<2>(at)).map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } if flip { diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 1797093b..c8a8cf25 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -408,18 +408,50 @@ fn usd_extension_detects_the_encoding() { fn integer_coding_round_trips() { let values: Vec = vec![0, 1, 2, 3, 3, 3, -5, 1000, -70000, i64::from(i32::MAX), i64::from(i32::MIN), 7, 7, 7, 8]; for width in [4, 8] { - let enc = codec::encode_ints(&values, width); + let enc = codec::encode_ints(&values, width).unwrap(); assert!(enc.len() <= codec::encoded_ints_len(values.len(), width)); assert_eq!(codec::decode_ints(&enc, values.len(), width).unwrap(), values); assert!(codec::decode_ints(&enc[..enc.len() - 1], values.len(), width).is_err()); } let wide = vec![i64::MAX, i64::MIN, 0, 1 << 40]; - assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8), 4, 8).unwrap(), wide); + assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8).unwrap(), 4, 8).unwrap(), wide); let big: Vec = (0..5000u32).flat_map(|i| (i % 7).to_le_bytes()).collect(); - assert_eq!(codec::decompress(&codec::compress(&big), big.len()).unwrap(), big); + assert_eq!(codec::decompress(&codec::compress(&big).unwrap(), big.len()).unwrap(), big); assert!(codec::decompress(&[0, 0xF0], 10).is_err()); } +#[test] +fn shared_crate_lz4_writer_preserves_bytes() { + for len in [0, 1, 15, 16, 255, 4096] { + let data: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + let mut previous = vec![0]; + previous.extend(lz4_flex::block::compress(&data)); + assert_eq!(codec::compress(&data).unwrap(), previous); + } +} + +#[test] +fn shared_integer_decoder_rejects_unsupported_width_and_oversized_output() { + assert!(codec::decode_ints(&[], 1, 3).is_err()); + assert!(codec::decode_ints(&[], super::MAX_DECODED_BYTES / 8 + 1, 8).is_err()); + assert!(codec::decode_ints(&[], 0, 4).unwrap().is_empty()); +} + +#[test] +fn shared_crate_lz4_retains_chunk_and_budget_policy() { + let mut frame = vec![2]; + for raw in [b"abc".as_slice(), b"def".as_slice()] { + let block = lz4_flex::block::compress(raw); + frame.extend((block.len() as i32).to_le_bytes()); + frame.extend(block); + } + frame.extend(b"old reader ignores this tail"); + assert_eq!(codec::decompress(&frame, 6).unwrap(), b"abcdef"); + assert!(codec::decompress(&frame, 5).is_err()); + assert!(codec::decompress(&[1, 255, 255, 255, 255], 64).is_err()); + assert!(codec::decompress(&[128], 64).is_err()); +} + #[test] fn malformed_usd_never_panics() { // A small two-material mesh keeps the byte loops fast. @@ -477,3 +509,10 @@ fn loose_layer_textures_are_packaged() { assert_eq!((f.name, f.bytes == out.bytes, f.warnings.len()), (format!("t.{ext}"), true, 1), "{ext}"); } } + +#[test] +fn shared_integer_writer_preserves_tie_wire_and_rejects_invalid_width() { + assert_eq!(codec::encode_ints(&[1, 3, 4, 6], 4).unwrap(), vec![2, 0, 0, 0, 17, 1, 1]); + assert!(codec::encode_ints(&[1], 3).is_err()); + assert!(codec::encode_ints(&[], 8).unwrap().is_empty()); +} diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 61874c67..fb925765 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -15,6 +15,9 @@ const MIN_VERSION: (u8, u8, u8) = (0, 4, 0); const MAX_SECTIONS: usize = 64; /// Items in one table or array. const MAX_ITEMS: usize = 1 << 28; +/// Entries in the PATHS table. The declared count is tiny in the file but each entry is a +/// materialised path, so it needs its own ceiling as well as the decoded-byte budget. +const MAX_PATHS: usize = 4_000_000; /// Spec types. const SPEC_ATTRIBUTE: i64 = 1; @@ -134,7 +137,7 @@ fn is_quat(t: u8) -> bool { /// Quaternions are stored imaginary first; values keep USD's text order (real first). fn quat_order(t: u8, v: &mut [f64]) { if is_quat(t) { - for q in v.chunks_exact_mut(4) { + for q in v.as_chunks_mut::<4>().0 { q.rotate_right(1); } } @@ -224,74 +227,91 @@ impl<'a> Crate<'a> { Ok(()) } - fn read_fields(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> { - let n = s.count(0)?; - let tokens = s.ints(n, 4, budget)?; - let size = s.u64()?; - let comp = s.bytes(usize::try_from(size).map_err(|_| truncated())?)?; - budget.take(n.saturating_mul(24))?; - let reps = codec::decompress(comp, n.saturating_mul(8))?; - if reps.len() != n * 8 { + fn read_fields(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let count = section.count(0)?; + let tokens = section.ints(count, 4, budget)?; + let size = section.u64()?; + let compressed = section.bytes(usize::try_from(size).map_err(|_| truncated())?)?; + budget.take(count.saturating_mul(24))?; + let representations = codec::decompress(compressed, count.saturating_mul(8))?; + if representations.len() != count * 8 { return Err(malformed(KIND, "field values are truncated")); } - self.fields = tokens.iter().zip(reps.chunks_exact(8)).map(|(t, r)| (*t as u32, u64::from_le_bytes(r.try_into().unwrap_or_default()))).collect(); + + self.fields = tokens.iter().zip(representations.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); + Ok(()) } /// Paths are stored as a pre-order tree: element token (negative for properties) and a /// jump per node (-2 leaf, -1 child only, 0 sibling only, >0 child and sibling at +jump). - fn read_paths(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> { - let total = s.count(0)?; - let n = s.count(0)?; - let index = s.ints(n, 4, budget)?; - let elements = s.ints(n, 4, budget)?; - let jumps = s.ints(n, 4, budget)?; - budget.take(total.saturating_mul(64))?; - self.paths = vec![None; total]; - let mut work: Vec<(usize, Option)> = vec![(0, None)]; - let mut steps = 0usize; - let bad = || malformed(KIND, "corrupt path table"); - while let Some((mut i, mut parent)) = work.pop() { + fn read_paths(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let path_count = section.count(0)?; + let encoded_count = section.count(0)?; + let path_indices = section.ints(encoded_count, 4, budget)?; + let elements = section.ints(encoded_count, 4, budget)?; + let jumps = section.ints(encoded_count, 4, budget)?; + if path_count > MAX_PATHS { + return Err(FormatError::TooLarge(format!("the USD path table has {path_count} entries (limit {MAX_PATHS})"))); + } + + // Charge slot storage before allocating the table + budget.take(path_count.saturating_mul(std::mem::size_of::>()))?; + self.paths = vec![None; path_count]; + let mut pending_branches: Vec<(usize, Option)> = vec![(0, None)]; + let mut visited_count = 0usize; + let path_error = || malformed(KIND, "corrupt path table"); + while let Some((mut cursor_index, mut parent)) = pending_branches.pop() { loop { - steps += 1; - if steps > n { - return Err(bad()); + visited_count += 1; + if visited_count > encoded_count { + return Err(path_error()); } - let this = i; - i += 1; - let at = index.get(this).map(|v| *v as u32 as usize).filter(|p| *p < total).ok_or_else(bad)?; - let el = match parent { + + let node_index = cursor_index; + cursor_index += 1; + let path_index = + path_indices.get(node_index).map(|v| *v as u32 as usize).filter(|parent_index| *parent_index < path_count).ok_or_else(path_error)?; + let path_element = match parent { None => PathEl { text: "/".into(), parent: None, name: String::new(), prop: false }, - Some(p) => { - let e = *elements.get(this).ok_or_else(bad)?; - let name = self.token(e.unsigned_abs())?.to_string(); - let base = self.paths.get(p).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(bad)?; - let text = match (e < 0, base) { - (true, _) => format!("{base}.{name}"), - (false, _) if name.starts_with('{') => format!("{base}{name}"), + Some(parent_index) => { + let element_token = *elements.get(node_index).ok_or_else(path_error)?; + let name = self.token(element_token.unsigned_abs())?; + let parent_path = self.paths.get(parent_index).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(path_error)?; + let separator_bytes = usize::from(element_token < 0 || (!name.starts_with('{') && parent_path != "/")); + let text_bytes = parent_path.len().saturating_add(name.len()).saturating_add(separator_bytes); + + // Charge both retained strings before allocating either one + budget.take(text_bytes.saturating_add(name.len()))?; + let name = name.to_string(); + let text = match (element_token < 0, parent_path) { + (true, _) => format!("{parent_path}.{name}"), + (false, _) if name.starts_with('{') => format!("{parent_path}{name}"), (false, "/") => format!("/{name}"), - (false, _) => format!("{base}/{name}"), + (false, _) => format!("{parent_path}/{name}"), }; - budget.take(text.len())?; - PathEl { text, parent: Some(p), name, prop: e < 0 } + PathEl { text, parent: Some(parent_index), name, prop: element_token < 0 } } }; - if let Some(slot) = self.paths.get_mut(at) { - *slot = Some(el); + + if let Some(slot) = self.paths.get_mut(path_index) { + *slot = Some(path_element); } - let jump = *jumps.get(this).ok_or_else(bad)?; + + let jump = *jumps.get(node_index).ok_or_else(path_error)?; let (child, sibling) = (jump > 0 || jump == -1, jump >= 0); if child { if sibling { - work.push((this.checked_add(usize::try_from(jump).map_err(|_| bad())?).ok_or_else(bad)?, parent)); + pending_branches.push((node_index.checked_add(usize::try_from(jump).map_err(|_| path_error())?).ok_or_else(path_error)?, parent)); } - parent = Some(at); + parent = Some(path_index); } if !child && !sibling { break; } } } + Ok(()) } @@ -640,11 +660,47 @@ mod tests { } fn compressed_ints(out: &mut Vec, v: &[i64]) { - let comp = codec::compress(&codec::encode_ints(v, 4)); + let comp = codec::compress(&codec::encode_ints(v, 4).unwrap()).unwrap(); out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); out.extend_from_slice(&comp); } + #[test] + fn repeated_path_names_count_toward_the_decode_budget() { + let name = "long_name_reused"; + let mut section = Vec::new(); + section.extend_from_slice(&3u64.to_le_bytes()); + section.extend_from_slice(&3u64.to_le_bytes()); + compressed_ints(&mut section, &[0, 1, 2]); + compressed_ints(&mut section, &[0, 0, 0]); + compressed_ints(&mut section, &[-1, 0, -2]); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + + let decoded_arrays_bytes = 3 * 3 * std::mem::size_of::(); + let path_slots_bytes = 3 * std::mem::size_of::>(); + let path_text_bytes = 2 * (1 + name.len()); + let one_name_budget = decoded_arrays_bytes + path_slots_bytes + path_text_bytes + name.len(); + let mut insufficient_budget = Budget(one_name_budget); + + let rejected = crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut insufficient_budget); + + assert!(matches!(rejected, Err(FormatError::TooLarge(_))), "two path names cannot fit a one-name budget"); + drop(crate_data); + + let mut complete_budget = Budget(one_name_budget + name.len()); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut complete_budget).unwrap(); + + assert_eq!(complete_budget.0, 0); + assert_eq!(crate_data.path(1).unwrap().text, format!("/{name}")); + assert_eq!(crate_data.path(2).unwrap().text, format!("/{name}")); + let retained_name_bytes: usize = crate_data.paths.iter().filter_map(Option::as_ref).map(|path| path.name.capacity()).sum(); + assert!(retained_name_bytes >= 2 * name.len()); + println!("retained names: 2, buffer capacity: {retained_name_bytes} bytes"); + } + #[test] fn compressed_float_and_int_arrays() { let n = 20usize; @@ -665,7 +721,7 @@ mod tests { compressed_ints(&mut b, &idx); let i64_at = b.len() as u64; b.extend_from_slice(&(n as u64).to_le_bytes()); - let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8)); + let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8).unwrap()).unwrap(); b.extend_from_slice(&(comp.len() as u64).to_le_bytes()); b.extend_from_slice(&comp); let c = crate_over(&b, (0, 8, 0)); diff --git a/crates/formats/src/project_file/bake_paint_data.rs b/crates/formats/src/project_file/bake_paint_data.rs new file mode 100644 index 00000000..e4797bed --- /dev/null +++ b/crates/formats/src/project_file/bake_paint_data.rs @@ -0,0 +1,6 @@ +#[derive(Clone, Debug, PartialEq)] +pub struct BakePaintData { + pub width: u32, + pub height: u32, + pub values: Vec, +} diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs new file mode 100644 index 00000000..7e0238e0 --- /dev/null +++ b/crates/formats/src/project_file/entries.rs @@ -0,0 +1,294 @@ +//! Writing the zip entries of a project file. +//! +//! Compressing the baked maps dominates a save (deflate level 6 over gigabytes of `f32`), and every +//! entry is independent, so on native targets the entries are compressed on several threads. Each +//! worker builds a one-entry zip in memory with the same options the serial writer uses; the writing +//! thread copies those entries into the real file in the original order with +//! [`ZipWriter::raw_copy_file`]. The compressed bytes of every entry and the entry order are +//! therefore the same as in a serial save. +//! +//! Workers share an estimated byte budget for entries started but not yet written. Stored entries +//! and entries larger than that budget stream directly into the destination, without a whole-entry +//! buffer. The estimate excludes allocator and compressor overhead; it is not a process memory cap. + +use std::io::{Seek, Write}; + +use zip::ZipWriter; +use zip::write::SimpleFileOptions; + +use super::zip_err; +use crate::Result; + +/// Produces the uncompressed bytes of one entry into the zip writer. +pub(super) type Body<'a> = Box std::io::Result<()> + Send + 'a>; + +pub(super) struct Entry<'a> { + pub name: String, + pub options: SimpleFileOptions, + /// Estimated entry size in bytes, based on its uncompressed payload. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub weight: u64, + pub body: Body<'a>, +} + +/// How much of the machine a save may use. Native targets only; the browser saves on one thread. +#[cfg(not(target_arch = "wasm32"))] +mod limits { + use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; + + /// Cores a save leaves to the UI (an autosave runs while the user keeps painting). + static RESERVED_CORES: AtomicUsize = AtomicUsize::new(DEFAULT_RESERVED_CORES); + /// Share of the available RAM, in percent, that entries in flight may hold. + static RAM_PERCENT: AtomicU8 = AtomicU8::new(DEFAULT_RAM_PERCENT); + + pub const DEFAULT_RESERVED_CORES: usize = 1; + pub const DEFAULT_RAM_PERCENT: u8 = 50; + + pub fn set(reserved_cores: usize, ram_percent: u8) { + RESERVED_CORES.store(reserved_cores, Ordering::Relaxed); + RAM_PERCENT.store(ram_percent.clamp(1, 100), Ordering::Relaxed); + } + + pub fn get() -> (usize, u8) { + (RESERVED_CORES.load(Ordering::Relaxed), RAM_PERCENT.load(Ordering::Relaxed)) + } + + /// RAM the system can give out now, in bytes (the total when the system does not say it; 8 GiB + /// when the system tells nothing). + pub fn available_ram() -> u64 { + let Ok(mut sys) = sysinfo::System::new() else { return 8 << 30 }; + sys.refresh_memory(); + match sys.available_memory() { + 0 => sys.total_memory(), + n => n, + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub use limits::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES}; + +/// Set what saves may use: cores left to the UI (any number; at least one worker always runs) and +/// the percentage (1 to 100) of available RAM used as the estimated in-flight entry budget. +#[cfg(not(target_arch = "wasm32"))] +pub fn set_save_resources(reserved_cores: usize, ram_percent: u8) { + limits::set(reserved_cores, ram_percent); +} + +/// Logical CPUs and currently available RAM in bytes, using the same readings as project saves. +#[cfg(not(target_arch = "wasm32"))] +pub fn available_save_resources() -> (usize, u64) { + let cores = std::thread::available_parallelism().map_or(1, usize::from); + (cores, limits::available_ram()) +} + +/// Estimated in-flight entry budget, shared by the save planner and the Settings readout. +#[cfg(not(target_arch = "wasm32"))] +pub fn save_ram_budget(available_ram_bytes: u64, ram_percent: u8) -> u64 { + u64::try_from(u128::from(available_ram_bytes) * u128::from(ram_percent.clamp(1, 100)) / 100).unwrap_or(u64::MAX) +} + +/// Worker threads and in-flight byte budget for a save of `entries` entries. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn plan(cpus: usize, reserved_cores: usize, entries: usize, available_ram: u64, ram_percent: u8) -> (usize, u64) { + let workers = cpus.saturating_sub(reserved_cores).max(1).min(entries); + (workers, save_ram_budget(available_ram, ram_percent)) +} + +/// Write `entries` in order: in parallel where threads exist, else one after the other. +pub(super) fn write_entries(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + #[cfg(not(target_arch = "wasm32"))] + { + let (cores, available_ram_bytes) = available_save_resources(); + let (reserved_cores, ram_percent) = limits::get(); + let (workers, budget) = plan(cores, reserved_cores, entries.len(), available_ram_bytes, ram_percent); + if workers > 1 { + return parallel::write(zip, entries, workers, budget); + } + } + write_serial(zip, entries) +} + +/// One entry after the other straight into `zip`. +pub(super) fn write_serial(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + for e in entries { + zip.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(zip)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) mod parallel { + use std::collections::BTreeMap; + use std::io::{Cursor, Seek, Write}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::{Condvar, Mutex, MutexGuard}; + + use zip::{CompressionMethod, ZipArchive, ZipWriter}; + + use super::Entry; + use crate::project_file::zip_err; + use crate::{FormatError, Result}; + + struct State { + /// Next entry to start. + next: usize, + /// Estimated bytes of the entries started and not yet written. + in_flight: u64, + /// Finished entries (one-entry zips) waiting for their turn. + ready: BTreeMap>>, + /// The writer failed: start nothing more. + stop: bool, + } + + fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn wait<'a>(cv: &Condvar, g: MutexGuard<'a, State>) -> MutexGuard<'a, State> { + cv.wait(g).unwrap_or_else(|e| e.into_inner()) + } + + /// Compress one entry into a zip of its own. + fn compress(e: Entry<'_>) -> Result> { + let mut z = ZipWriter::new(Cursor::new(Vec::new())); + z.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(&mut z)?; + Ok(z.finish().map_err(zip_err)?.into_inner()) + } + + fn worker(slots: &[Mutex>>], weights: &[u64], budget: u64, state: &Mutex, cv: &Condvar) { + loop { + let entry_index = { + let mut state_guard = lock(state); + loop { + if state_guard.stop || state_guard.next >= slots.len() { + return; + } + + let weight = weights.get(state_guard.next).copied().unwrap_or(0); + + // Oversized entries stream separately, so every queued weight fits the budget + if state_guard.in_flight <= budget.saturating_sub(weight) { + let entry_index = state_guard.next; + state_guard.next += 1; + state_guard.in_flight = state_guard.in_flight.saturating_add(weight); + break entry_index; + } + state_guard = wait(cv, state_guard); + } + }; + let entry = slots.get(entry_index).and_then(|slot| lock(slot).take()); + let result = match entry { + Some(entry) => catch_unwind(AssertUnwindSafe(|| compress(entry))) + .unwrap_or_else(|_| Err(FormatError::Invalid("compressing a project entry failed".into()))), + None => Err(FormatError::Invalid("project entry missing".into())), + }; + + lock(state).ready.insert(entry_index, result); + cv.notify_all(); + } + } + + /// Copy the compressed entry of a one-entry zip into `zip` without recompressing. + fn copy_entry(zip: &mut ZipWriter, bytes: Vec) -> Result<()> { + let mut a = ZipArchive::new(Cursor::new(bytes)).map_err(zip_err)?; + let f = a.by_index_raw(0).map_err(zip_err)?; + zip.raw_copy_file(f).map_err(zip_err) + } + + fn streams_directly(entry: &Entry<'_>, budget: u64) -> bool { + let stored_options = entry.options.compression_method(CompressionMethod::Stored); + entry.options == stored_options || entry.weight > budget + } + + pub(in crate::project_file) fn write(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { + if workers == 0 { + return super::write_serial(zip, entries); + } + + let mut remaining = entries.into_iter().peekable(); + while let Some(entry) = remaining.next() { + // Storing bytes gains nothing from a worker; oversized entries must not get a whole-entry buffer + if streams_directly(&entry, budget) { + zip.start_file(entry.name, entry.options).map_err(zip_err)?; + (entry.body)(zip)?; + continue; + } + + let mut batch = vec![entry]; + while remaining.peek().is_some_and(|entry| !streams_directly(entry, budget)) { + if let Some(entry) = remaining.next() { + batch.push(entry); + } + } + + // Finish the workers before direct compression, keeping the CPU allowance shared + write_buffered(zip, batch, workers, budget)?; + } + + Ok(()) + } + + fn write_buffered(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { + if entries.len() == 1 { + return super::write_serial(zip, entries); + } + + let weights: Vec = entries.iter().map(|entry| entry.weight).collect(); + let slots: Vec>>> = entries.into_iter().map(|entry| Mutex::new(Some(entry))).collect(); + let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false }); + let cv = Condvar::new(); + std::thread::scope(|scope| { + let mut started = 0; + for _ in 0..workers.min(slots.len()) { + // If thread creation fails, the workers already started drain the queue + if std::thread::Builder::new().spawn_scoped(scope, || worker(&slots, &weights, budget, &state, &cv)).is_ok() { + started += 1; + } + } + + let result = (|| -> Result<()> { + for (entry_index, weight) in weights.iter().enumerate() { + if started == 0 { + // If no workers started, stream directly into the destination + let entry = + slots.get(entry_index).and_then(|slot| lock(slot).take()).ok_or_else(|| FormatError::Invalid("project entry missing".into()))?; + zip.start_file(entry.name, entry.options).map_err(zip_err)?; + (entry.body)(zip)?; + continue; + } + + let done = { + let mut state_guard = lock(&state); + loop { + if let Some(result) = state_guard.ready.remove(&entry_index) { + break result; + } + state_guard = wait(&cv, state_guard); + } + }; + let copied = done.and_then(|bytes| copy_entry(zip, bytes)); + + // Release the entry's share only once its bytes are gone + { + let mut state_guard = lock(&state); + state_guard.in_flight = state_guard.in_flight.saturating_sub(*weight); + } + cv.notify_all(); + copied?; + } + + Ok(()) + })(); + + if result.is_err() { + lock(&state).stop = true; + cv.notify_all(); + } + + result + }) + } +} diff --git a/crates/formats/src/project_file/load_budget.rs b/crates/formats/src/project_file/load_budget.rs new file mode 100644 index 00000000..a183336a --- /dev/null +++ b/crates/formats/src/project_file/load_budget.rs @@ -0,0 +1,72 @@ +/// Decompressed bytes accepted by one project load, fixed when the load starts. +pub(super) struct LoadBudget { + limit_bytes: u64, + used_bytes: u64, +} + +impl LoadBudget { + pub(super) fn new(limit_bytes: u64) -> Self { + Self { limit_bytes, used_bytes: 0 } + } + + pub(super) fn remaining(&self) -> u64 { + self.limit_bytes - self.used_bytes + } + + pub(super) fn exceeded_message(&self) -> String { + format!( + "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", + self.limit_bytes, + self.limit_bytes as f64 / (1u64 << 30) as f64, + ) + } + + /// Reserve bytes before retaining decoded data so entries share one allocation budget. + pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> { + if bytes > self.remaining() { + return Err(self.exceeded_message()); + } + + self.used_bytes += bytes; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::LoadBudget; + + #[test] + fn entries_share_the_limit_and_the_exact_boundary_is_allowed() { + let mut budget = LoadBudget::new(10); + + budget.take(4).unwrap(); + budget.take(6).unwrap(); + let error = budget.take(1).unwrap_err(); + + assert_eq!(budget.remaining(), 0); + assert!(error.contains("10 bytes"), "{error}"); + assert!(error.contains("Settings > Project"), "{error}"); + } + + #[test] + fn a_rejected_entry_does_not_consume_the_remaining_budget() { + let mut budget = LoadBudget::new(10); + budget.take(4).unwrap(); + + assert!(budget.take(7).is_err()); + + assert_eq!(budget.remaining(), 6); + assert!(budget.take(6).is_ok()); + } + + #[test] + fn accounting_cannot_wrap_at_the_integer_boundary() { + let mut budget = LoadBudget::new(u64::MAX); + budget.take(u64::MAX).unwrap(); + + assert!(budget.take(1).is_err()); + assert!(budget.take(0).is_ok()); + assert_eq!(budget.remaining(), 0); + } +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..e1d98196 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -6,7 +6,7 @@ //! | `mesh.` | the original imported mesh file (absent for built-in meshes, `Project.mesh = "builtin:"`) | //! | `highpoly/` | a high-definition mesh file for baking, in list order | //! | `cage/` | the baking cage mesh file | -//! | `skew.bin` | the skew correction map of the bake (magic `TCSK`, version, width, height, edge distance, edge contrast, per-triangle flag; then `width × height` f32 LE) | +//! | `bake_paint/_.bin` | cage or skew paint, stored as a one-component baked map | //! | `pixels/layer__.bin` | painted pixels of a paint layer (or content paint effect) channel | //! | `pixels/mask_.bin` | painted pixels of a mask paint effect | //! | `baked/_.bin` | a baked mesh map of texture set `` | @@ -23,38 +23,41 @@ use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; use texturecraft_compose::{BakedMaps, PixelStore}; -use texturecraft_core::{BakedMap, Channel, FORMAT_VERSION, LayerId, Project}; +use texturecraft_core::{BakePaintTarget, Channel, FORMAT_VERSION, LayerId, Project}; use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; +use self::entries::Entry; +use self::load_budget::LoadBudget; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; +mod entries; +mod load_budget; +mod project_open_limit; +#[cfg(not(target_arch = "wasm32"))] +pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources}; +pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; + const KIND: &str = "project file"; +#[cfg(test)] const MAGIC: &[u8; 4] = b"TCTX"; -/// Version of the `.bin` layout. +#[cfg(test)] const BIN_VERSION: u32 = 1; -const SKEW_MAGIC: &[u8; 4] = b"TCSK"; +#[cfg(test)] +const BIN_HEADER_BYTES: usize = 24; const MAX_JSON: u64 = 256 << 20; const MAX_THUMBNAIL: u64 = 64 << 20; const MAX_RESOURCE: u64 = 512 << 20; const MAX_ENTRIES: usize = 100_000; -/// Total decompressed bytes accepted from one project file (zip-bomb guard). -const MAX_TOTAL: u64 = 8 << 30; +/// Bound ZIP index parsing before the archive exposes its entry count. +const MAX_ZIP_METADATA_BYTES: u64 = 32 << 20; /// Largest image (texels) of a texture set or baked map: UV-tiled sets hold several tiles. const MAX_TEXELS: u64 = 1 << 28; -/// The skew correction map of a bake, as stored (the baker's `SkewMap` without its type). -#[derive(Clone, Debug, PartialEq)] -pub struct SkewData { - pub width: u32, - pub height: u32, - /// `width * height` values, row 0 at the top. - pub values: Vec, - pub edge_distance: f32, - pub edge_contrast: f32, - pub per_triangle: bool, -} +mod bake_paint_data; +mod recovery; +pub use bake_paint_data::BakePaintData; /// Everything a project file holds. #[derive(Clone, Debug)] @@ -70,11 +73,12 @@ pub struct ProjectFile { pub high_poly: Vec<(String, Vec)>, /// Baking cage mesh file: (file name, bytes). pub cage: Option<(String, Vec)>, - /// Skew correction of the bake rays. - pub skew: Option, + pub bake_paint: BTreeMap<(usize, BakePaintTarget), BakePaintData>, pub thumbnail: Option>, /// Imported resources (images used by fills, alphas, stencils), by name: original bytes. pub resources: BTreeMap>, + /// Import warnings for the caller's log; never saved in the archive + pub warnings: Vec, } /// A resource name safe as a zip entry and a file name: `[A-Za-z0-9_.-]`, at most 120 chars. @@ -93,23 +97,23 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result> { Ok(out.into_inner()) } -/// Save atomically: `.tmp` first, then rename over `path`. +/// Save atomically through a newly created temporary file beside `path`. #[cfg(not(target_arch = "wasm32"))] -pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); - let res = (|| -> Result<()> { - let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?); - write_project(&mut file, pf)?; - file.into_inner().map_err(|e| e.into_error())?.sync_all()?; - std::fs::rename(&tmp, path)?; +pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Result<()> { + let (temporary_path, file) = crate::create_temp(path)?; + let result = (|| -> Result<()> { + let mut file = std::io::BufWriter::new(file); + write_project(&mut file, project_file)?; + file.into_inner().map_err(|error| error.into_error())?.sync_all()?; + std::fs::rename(&temporary_path, path)?; Ok(()) })(); - if res.is_err() { - let _ = std::fs::remove_file(&tmp); + + if result.is_err() { + let _ = std::fs::remove_file(&temporary_path); } - res + + result } fn zip_err(e: zip::result::ZipError) -> FormatError { @@ -119,6 +123,7 @@ fn zip_err(e: zip::result::ZipError) -> FormatError { } } +#[cfg(test)] fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { let mut b = MAGIC.to_vec(); for v in [BIN_VERSION, w, h, comps as u32, count as u32] { @@ -127,19 +132,18 @@ fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { b } -fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { - w.write_all(&header(img.width(), img.height(), img.comps(), img.allocated_count()))?; - let mut buf = Vec::with_capacity(TILE_AREA * img.comps() * 2 + 8); - for (tx, ty) in img.allocated() { - buf.clear(); - buf.extend_from_slice(&tx.to_le_bytes()); - buf.extend_from_slice(&ty.to_le_bytes()); - for v in img.tile(tx, ty).unwrap_or_default() { - buf.extend_from_slice(&v.to_le_bytes()); - } - w.write_all(&buf)?; +fn codec_write_error(error: craft_tcraft::Error) -> std::io::Error { + match error { + craft_tcraft::Error::Io(error) => error, + other => std::io::Error::other(other), } - Ok(()) +} + +fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { + let layout = craft_tcraft::Layout { width: img.width(), height: img.height(), components: img.comps() }; + let count = u32::try_from(img.allocated_count()).map_err(std::io::Error::other)?; + let tiles = img.allocated().map(|(x, y)| (x, y, img.tile(x, y).unwrap_or_default())); + craft_tcraft::write_tiles(w, layout, count, tiles).map_err(codec_write_error) } /// Keep `[a-z0-9]`, at most 8 characters (the mesh entry's extension). @@ -164,47 +168,68 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet) -> Strin entry } -fn write_project(out: W, pf: &ProjectFile) -> Result<()> { - let mut zip = ZipWriter::new(out); +#[cfg(test)] +const BAKED_CHUNK: usize = 1 << 16; + +fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> { + let layout = craft_tcraft::Layout { width: res, height: h, components: comps }; + craft_tcraft::write_baked(w, layout, data).map_err(codec_write_error) +} + +/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. +fn entries(pf: &ProjectFile) -> Result>> { let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; - zip.start_file("project.json", deflate).map_err(zip_err)?; - zip.write_all(&json)?; + let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }]; if let Some((ext, bytes)) = &pf.mesh { - zip.start_file(format!("mesh.{}", sanitize_ext(ext)), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: format!("mesh.{}", sanitize_ext(ext)), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } let mut used = HashSet::new(); for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) { - zip.start_file(unique_entry_name(dir, name, &mut used), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name(dir, name, &mut used), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } - if let Some(k) = pf.skew.as_ref().filter(|k| k.width > 0 && k.height > 0 && k.values.len() as u64 == u64::from(k.width) * u64::from(k.height)) { - zip.start_file("skew.bin", deflate).map_err(zip_err)?; - let mut b = SKEW_MAGIC.to_vec(); - b.extend_from_slice(&BIN_VERSION.to_le_bytes()); - for v in [k.width, k.height] { - b.extend_from_slice(&v.to_le_bytes()); + for ((texture_set, target), map) in &pf.bake_paint { + if map.width == 0 || map.height == 0 || map.values.len() as u64 != u64::from(map.width) * u64::from(map.height) { + return Err(FormatError::Invalid("bake paint map dimensions do not match its values".into())); } - for v in [k.edge_distance, k.edge_contrast] { - b.extend_from_slice(&v.to_le_bytes()); - } - b.push(u8::from(k.per_triangle)); - b.extend(k.values.iter().flat_map(|v| v.to_le_bytes())); - zip.write_all(&b)?; + let target_name = match target { + BakePaintTarget::Cage => "cage", + BakePaintTarget::Skew => "skew", + }; + out.push(Entry { + name: format!("bake_paint/{texture_set}_{target_name}.bin"), + options: deflate, + weight: map.values.len() as u64 * 4, + body: Box::new(move |w| write_baked(w, map.width, map.height, 1, &map.values)), + }); } let mut layers: Vec<_> = pf.pixels.layers.iter().collect(); layers.sort_by_key(|(k, _)| **k); for ((id, c), img) in layers { - zip.start_file(format!("pixels/layer_{}_{}.bin", id.0, c.id()), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { + name: format!("pixels/layer_{}_{}.bin", id.0, c.id()), + options: deflate, + weight, + body: Box::new(move |mut w| write_tiles(&mut w, img)), + }); } let mut masks: Vec<_> = pf.pixels.masks.iter().collect(); masks.sort_by_key(|(k, _)| **k); for (id, img) in masks { - zip.start_file(format!("pixels/mask_{}.bin", id.0), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) }); } for (ts, maps) in &pf.baked { let r = maps.resolution; @@ -214,21 +239,33 @@ fn write_project(out: W, pf: &ProjectFile) -> Result<()> { if h == 0 || data.len() != (r as usize) * (h as usize) * m.components() { continue; } - zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).map_err(zip_err)?; - zip.write_all(&header(r, h, m.components(), 0))?; - let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); - zip.write_all(&bytes)?; + let comps = m.components(); + out.push(Entry { + name: format!("baked/{ts}_{}.bin", m.id()), + options: deflate, + weight: data.len() as u64 * 4, + body: Box::new(move |w| write_baked(w, r, h, comps, data)), + }); } } if let Some(png) = &pf.thumbnail { - zip.start_file("thumbnail.png", stored).map_err(zip_err)?; - zip.write_all(png)?; + out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) }); } used.clear(); for (name, bytes) in &pf.resources { - zip.start_file(unique_entry_name("resources", name, &mut used), stored).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name("resources", name, &mut used), + options: stored, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } + Ok(out) +} + +fn write_project(out: W, pf: &ProjectFile) -> Result<()> { + let mut zip = ZipWriter::new(out); + entries::write_entries(&mut zip, entries(pf)?)?; zip.finish().map_err(zip_err)?; Ok(()) } @@ -246,126 +283,48 @@ pub fn load_project(path: &std::path::Path) -> Result { crate::guard(KIND, || load(std::io::BufReader::new(file))) } -/// Counts decompressed bytes against [`MAX_TOTAL`]. -struct Budget(u64); - -impl Budget { - fn take(&mut self, n: u64) -> Result<()> { - self.0 = self.0.saturating_add(n); - if self.0 > MAX_TOTAL { - return Err(FormatError::TooLarge(format!("project file decompresses to more than {MAX_TOTAL} bytes"))); - } - Ok(()) - } -} - -fn read_all(r: &mut impl Read, cap: u64, budget: &mut Budget, what: &str) -> Result> { +fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &str) -> Result> { let mut out = Vec::new(); - r.take(cap.saturating_add(1)).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?; + + // Read at most one byte beyond either limit to detect overflow without a full entry allocation + let read_limit = cap.min(budget.remaining()).saturating_add(1); + reader.take(read_limit).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?; if out.len() as u64 > cap { return Err(FormatError::TooLarge(format!("{what} is larger than {cap} bytes"))); } - budget.take(out.len() as u64)?; + + budget.take(out.len() as u64).map_err(FormatError::TooLarge)?; Ok(out) } -fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> { - r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}"))) +/// Transfer the bytes charged by the shared codec to this project's one load budget. +fn codec_result(result: std::result::Result, shared: &craft_zip::Budget, budget: &mut LoadBudget, what: &str) -> Result { + budget.take(shared.used()).map_err(FormatError::TooLarge)?; + result.map_err(|error| match error { + craft_tcraft::Error::Budget(_) => FormatError::TooLarge(budget.exceeded_message()), + craft_tcraft::Error::Limit(message) => FormatError::TooLarge(format!("{what}: {message}")), + craft_tcraft::Error::NewerVersion(found) => FormatError::NewerVersion { found, supported: craft_tcraft::VERSION }, + other => malformed(KIND, format!("{what}: {other}")), + }) } -fn u32_at(b: &[u8], i: usize) -> u32 { - b.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).unwrap_or(0) +fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result { + let layout = craft_tcraft::Layout { width: size.0, height: size.1, components }; + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let mut image = None; + let result = craft_tcraft::read_tiles(reader, layout, MAX_TEXELS, &mut shared, |x, y, values| { + image.get_or_insert_with(|| TileImage::new(size.0, size.1, components)).set_tile(x, y, Some(Arc::new(values))); + Ok(()) + }); + codec_result(result, &shared, budget, what)?; + Ok(image.unwrap_or_else(|| TileImage::new(size.0, size.1, components))) } -/// Read and check a `.bin` header: returns (width, height, comps, count). -fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> { - let mut h = [0u8; 24]; - read_exact(r, &mut h, what)?; - if h.get(..4) != Some(MAGIC.as_slice()) { - return Err(malformed(KIND, format!("{what}: bad magic"))); - } - let v = u32_at(&h, 1); - if v > BIN_VERSION { - return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION }); - } - Ok((u32_at(&h, 2), u32_at(&h, 3), u32_at(&h, 4) as usize, u32_at(&h, 5) as usize)) -} - -/// Error unless the entry has no bytes left (also makes the zip reader verify the CRC). -fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { - let mut b = [0u8; 1]; - match r.read(&mut b) { - Ok(0) => Ok(()), - Ok(_) => Err(malformed(KIND, format!("{what}: trailing data"))), - Err(e) => Err(malformed(KIND, format!("{what}: {e}"))), - } -} - -fn read_tiles(r: &mut impl Read, size: (u32, u32), comps: usize, budget: &mut Budget, what: &str) -> Result { - let (w, h, c, count) = read_header(r, what)?; - if (w, h) != size || c != comps { - return Err(malformed(KIND, format!("{what}: {w}×{h}×{c} does not match the texture set ({}×{}×{comps})", size.0, size.1))); - } - let mut img = TileImage::new(w, h, comps); - if count > (img.tiles_x() as usize) * (img.tiles_y() as usize) { - return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds"))); - } - let mut buf = vec![0u8; TILE_AREA * comps * 2]; - let mut pos = [0u8; 8]; - for _ in 0..count { - read_exact(r, &mut pos, what)?; - let (tx, ty) = (u32_at(&pos, 0), u32_at(&pos, 1)); - if tx >= img.tiles_x() || ty >= img.tiles_y() || img.is_allocated(tx, ty) { - return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})"))); - } - read_exact(r, &mut buf, what)?; - budget.take(buf.len() as u64)?; - let data: Vec = buf.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); - img.set_tile(tx, ty, Some(Arc::new(data))); - } - expect_end(r, what)?; - Ok(img) -} - -/// A baked map: (width, height, data). -fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) -> Result<(u32, u32, Vec)> { - let (w, h, c, _) = read_header(r, what)?; - if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_TEXELS || c != comps { - return Err(malformed(KIND, format!("{what}: bad size {w}×{h}×{c}"))); - } - let len = (w as usize) * (h as usize) * comps; - budget.take(len as u64 * 4)?; - let mut bytes = vec![0u8; len * 4]; - read_exact(r, &mut bytes, what)?; - expect_end(r, what)?; - Ok((w, h, bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) -} - -/// The skew map entry: header, then the values. -fn read_skew(r: &mut impl Read, budget: &mut Budget, what: &str) -> Result { - let mut h = [0u8; 25]; - read_exact(r, &mut h, what)?; - if h.get(..4) != Some(SKEW_MAGIC.as_slice()) { - return Err(malformed(KIND, format!("{what}: bad magic"))); - } - let v = u32_at(&h, 1); - if v > BIN_VERSION { - return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION }); - } - let (w, ht) = (u32_at(&h, 2), u32_at(&h, 3)); - let (edge_distance, edge_contrast) = (f32::from_bits(u32_at(&h, 4)), f32::from_bits(u32_at(&h, 5))); - let per_triangle = h.get(24).is_some_and(|b| *b != 0); - if w == 0 || ht == 0 || u64::from(w) * u64::from(ht) > MAX_TEXELS { - return Err(malformed(KIND, format!("{what}: bad size {w}×{ht}"))); - } - let len = (w as usize) * (ht as usize); - budget.take(len as u64 * 4)?; - let mut bytes = vec![0u8; len * 4]; - read_exact(r, &mut bytes, what)?; - expect_end(r, what)?; - let values: Vec = bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); - // A map with a stray number is dropped by the caller's validation; here only the shape is checked. - Ok(SkewData { width: w, height: ht, values, edge_distance, edge_contrast, per_triangle }) +fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec)> { + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let result = craft_tcraft::read_baked(reader, declared_bytes, components, MAX_TEXELS, &mut shared); + let (layout, values) = codec_result(result, &shared, budget, what)?; + Ok((layout.width, layout.height, values)) } /// Texture set holding a paint layer, a content effect or a mask effect id. @@ -375,21 +334,39 @@ fn texture_set_of(project: &Project, id: LayerId) -> Option { } fn load(reader: R) -> Result { - let mut zip = ZipArchive::new(reader).map_err(zip_err)?; - if zip.len() > MAX_ENTRIES { - return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); - } - let mut budget = Budget(0); + let limit_bytes = u64::from(project_open_limit_gib()) << 30; + load_with_budget(reader, LoadBudget::new(limit_bytes)) +} + +fn check_archive(zip: &mut ZipArchive, limit_bytes: u64) -> Result<()> { + craft_zip::inspect_seekable(zip, MAX_ENTRIES, limit_bytes).map_err(|error| match error { + craft_zip::InspectError::TooManyEntries { .. } => FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")), + craft_zip::InspectError::DeclaredBytesExceeded { .. } => FormatError::TooLarge(LoadBudget::new(limit_bytes).exceeded_message()), + craft_zip::InspectError::OverlappingEntries => malformed(KIND, "overlapping ZIP entries are not supported"), + craft_zip::InspectError::Zip(error) => zip_err(error), + }) +} + +fn open_archive(reader: R, metadata_bytes: u64) -> Result>> { + let (reader, indexing) = craft_zip::MetadataReader::new(reader, metadata_bytes)?; + // Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset + let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; + let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?; + indexing.finish(); + Ok(archive) +} + +fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result { + let mut zip = open_archive(reader, MAX_ZIP_METADATA_BYTES)?; + check_archive(&mut zip, budget.remaining())?; + let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; - #[derive(serde::Deserialize)] - struct Version { - format_version: u32, + let version = craft_tcraft::project_version(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; + if version > FORMAT_VERSION { + return Err(FormatError::NewerVersion { found: version, supported: FORMAT_VERSION }); } - let v: Version = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; - if v.format_version > FORMAT_VERSION { - return Err(FormatError::NewerVersion { found: v.format_version, supported: FORMAT_VERSION }); - } - let project: Project = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; + + let (project, mut recovered) = recovery::read_project(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; project.validate()?; let too_large = |t: &texturecraft_core::TextureSet| u64::from(t.size().0) * u64::from(t.size().1) > MAX_TEXELS; if let Some(ts) = project.texture_sets.iter().find(|t| t.resolution == 0 || t.resolution > MAX_IMAGE_SIZE || too_large(t)) { @@ -402,13 +379,16 @@ fn load(reader: R) -> Result { mesh: None, high_poly: Vec::new(), cage: None, - skew: None, + bake_paint: BTreeMap::new(), thumbnail: None, resources: BTreeMap::new(), + warnings: Vec::new(), project, }; + for i in 0..zip.len() { let mut f = zip.by_index(i).map_err(zip_err)?; + let declared_bytes = f.size(); let name = f.name().map_err(zip_err)?.into_owned(); let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size()); if name == "thumbnail.png" { @@ -417,19 +397,33 @@ fn load(reader: R) -> Result { if res_name.is_empty() || sanitize_resource_name(res_name) != res_name { return Err(malformed(KIND, format!("bad resource name {name}"))); } + let bytes = read_all(&mut f, MAX_RESOURCE, &mut budget, &name)?; pf.resources.insert(res_name.to_string(), bytes); } else if let Some((dir, file)) = name.split_once('/').filter(|(d, _)| *d == "highpoly" || *d == "cage") { if file.is_empty() || sanitize_resource_name(file) != file { return Err(malformed(KIND, format!("bad mesh name {name}"))); } + let entry = (file.to_string(), read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?); match dir { "cage" => pf.cage = Some(entry), _ => pf.high_poly.push(entry), } - } else if name == "skew.bin" { - pf.skew = Some(read_skew(&mut f, &mut budget, &name)?); + } else if let Some(rest) = name.strip_prefix("bake_paint/").and_then(|name| name.strip_suffix(".bin")) { + let (texture_set, target) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry {name}")))?; + let texture_set: usize = texture_set.parse().map_err(|_| malformed(KIND, format!("bad entry {name}")))?; + if texture_set >= pf.project.texture_sets.len() { + return Err(malformed(KIND, format!("unknown texture set in {name}"))); + } + + let target = match target { + "cage" => BakePaintTarget::Cage, + "skew" => BakePaintTarget::Skew, + _ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))), + }; + let (width, height, values) = read_baked(&mut f, declared_bytes, 1, &mut budget, &name)?; + pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values }); } else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) { let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?; pf.mesh = Some((ext.to_string(), bytes)); @@ -437,23 +431,30 @@ fn load(reader: R) -> Result { let (id, chan) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let id = LayerId(id.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); let c = Channel::ALL.into_iter().find(|c| c.id() == chan).ok_or_else(|| malformed(KIND, format!("unknown channel in {name}")))?; - // Pixels of layers that are no longer in any stack are dropped. + // Drop pixels of layers that are no longer in any stack let Some(size) = size_of(id) else { continue }; + let img = read_tiles(&mut f, size, c.components() + 1, &mut budget, &name)?; pf.pixels.layers.insert((id, c), img); } else if let Some(rest) = name.strip_prefix("pixels/mask_").and_then(|r| r.strip_suffix(".bin")) { let id = LayerId(rest.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); let Some(size) = size_of(id) else { continue }; + let img = read_tiles(&mut f, size, 2, &mut budget, &name)?; pf.pixels.masks.insert(id, img); } else if let Some(rest) = name.strip_prefix("baked/").and_then(|r| r.strip_suffix(".bin")) { let (ts, map) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let ts: usize = ts.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?; - let m = BakedMap::ALL.into_iter().find(|m| m.id() == map).ok_or_else(|| malformed(KIND, format!("unknown baked map in {name}")))?; + let Some(m) = recovery::baked_map(map) else { + recovered = true; + continue; + }; + if ts >= pf.project.texture_sets.len() { continue; } - let (res, height, data) = read_baked(&mut f, m.components(), &mut budget, &name)?; + + let (res, height, data) = read_baked(&mut f, declared_bytes, m.components(), &mut budget, &name)?; let maps = pf.baked.entry(ts).or_default(); if maps.maps.is_empty() { maps.resolution = res; @@ -462,8 +463,17 @@ fn load(reader: R) -> Result { } maps.maps.insert(m, Arc::new(data)); } - // Other entries (from newer minor revisions) are ignored. + // 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(), + ); + } + Ok(pf) } diff --git a/crates/formats/src/project_file/project_open_limit.rs b/crates/formats/src/project_file/project_open_limit.rs new file mode 100644 index 00000000..3926da27 --- /dev/null +++ b/crates/formats/src/project_file/project_open_limit.rs @@ -0,0 +1,41 @@ +use std::sync::atomic::{AtomicU32, Ordering}; + +/// Default maximum decompressed project size, in GiB. +pub const DEFAULT_PROJECT_OPEN_LIMIT_GIB: u32 = 8; + +static PROJECT_OPEN_LIMIT_GIB: AtomicU32 = AtomicU32::new(DEFAULT_PROJECT_OPEN_LIMIT_GIB); + +/// Set the limit for subsequent project loads, in GiB; zero is clamped to one GiB. +/// An in-progress load keeps the limit it started with. Individual entry limits still apply. +pub fn set_project_open_limit_gib(limit_gib: u32) { + PROJECT_OPEN_LIMIT_GIB.store(limit_gib.max(1), Ordering::Relaxed); +} + +/// Maximum decompressed project size accepted by subsequent loads, in GiB. +pub fn project_open_limit_gib() -> u32 { + PROJECT_OPEN_LIMIT_GIB.load(Ordering::Relaxed) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_file::load_budget::LoadBudget; + + #[test] + fn preferences_apply_to_new_loads_in_gib_without_disabling_existing_guards() { + set_project_open_limit_gib(8); + let mut active_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30); + + set_project_open_limit_gib(16); + let mut next_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30); + + assert!(active_load.take(9 << 30).is_err()); + assert!(next_load.take(9 << 30).is_ok()); + + set_project_open_limit_gib(0); + assert_eq!(project_open_limit_gib(), 1); + set_project_open_limit_gib(u32::MAX); + assert_eq!(u64::from(project_open_limit_gib()) << 30, 4_611_686_017_353_646_080); + set_project_open_limit_gib(DEFAULT_PROJECT_OPEN_LIMIT_GIB); + } +} diff --git a/crates/formats/src/project_file/recovery.rs b/crates/formats/src/project_file/recovery.rs new file mode 100644 index 00000000..8b488051 --- /dev/null +++ b/crates/formats/src/project_file/recovery.rs @@ -0,0 +1,75 @@ +use serde::Deserialize; +use serde_json::Value; +use texturecraft_core::{BakeSettings, BakedMap, Project}; + +pub(super) fn read_project(json: &[u8]) -> serde_json::Result<(Project, bool)> { + let error = match serde_json::from_slice(json) { + Ok(project) => return Ok((project, false)), + Err(error) => error, + }; + + let mut project: Value = serde_json::from_slice(json)?; + let mut recovered = false; + if let Some(texture_sets) = project.get_mut("texture_sets").and_then(Value::as_array_mut) { + for texture_set in texture_sets { + if let Some(bake) = texture_set.get_mut("bake") + && BakeSettings::deserialize(&*bake).is_err() + { + let mut settings = serde_json::to_value(BakeSettings::default())?; + recover_bake_fields(&mut settings, bake, ""); + *bake = settings; + recovered = true; + } + + if let Some(baked) = texture_set.get_mut("baked") { + if let Some(maps) = baked.as_array_mut() { + let count = maps.len(); + maps.retain(|map| BakedMap::deserialize(map).is_ok()); + recovered |= maps.len() != count; + } else { + *baked = Value::Array(Vec::new()); + recovered = true; + } + } + } + } + + if !recovered { + return Err(error); + } + + Ok((serde_json::from_value(project)?, true)) +} + +// Walk the default schema so unknown fields and input nesting cannot expand recovery +fn recover_bake_fields(recovered: &mut Value, original: &Value, path: &str) { + let Some(fields) = recovered.pointer(path).and_then(Value::as_object) else { + return; + }; + + let keys: Vec<_> = fields.keys().cloned().collect(); + for key in keys { + let Some(value) = original.get(&key) else { continue }; + let field_path = format!("{path}/{key}"); + let Some(field) = recovered.pointer_mut(&field_path) else { continue }; + let previous = std::mem::replace(field, value.clone()); + if BakeSettings::deserialize(&*recovered).is_err() { + if let Some(field) = recovered.pointer_mut(&field_path) { + *field = previous; + } + + // A bad nested field must not discard its readable siblings + recover_bake_fields(recovered, value, &field_path); + } + } +} + +pub(super) fn baked_map(name: &str) -> Option { + match name { + "normal_base" => Some(BakedMap::Normal), + "world_space_normals" => Some(BakedMap::WorldNormal), + "ambient_occlusion" => Some(BakedMap::AmbientOcclusion), + "bent_normals" => Some(BakedMap::BentNormal), + _ => BakedMap::parse(name), + } +} diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5832d53c..4fcc0aed 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use texturecraft_core::{Effect, EffectKind, Fill, Layer, LayerKind, Mask, MaskBackground, TextureSet}; +use texturecraft_core::{BakedMap, Effect, EffectKind, Fill, Layer, LayerKind, Mask, MaskBackground, TextureSet}; use super::*; @@ -34,16 +34,11 @@ fn sample() -> Sample { mesh: Some(("glb".into(), vec![1, 2, 3, 4, 5])), high_poly: vec![("b_high.obj".into(), vec![7; 9]), ("a_high.ply".into(), vec![6])], cage: Some(("cage.obj".into(), vec![5, 5])), - skew: Some(SkewData { - width: 3, - height: 2, - values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125], - edge_distance: 0.05, - edge_contrast: 2.0, - per_triangle: true, - }), + bake_paint: [((0, texturecraft_core::BakePaintTarget::Skew), BakePaintData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125] })] + .into(), thumbnail: Some(vec![137, 80, 78, 71]), resources: [("bricks.png".to_string(), vec![9, 8, 7])].into(), + warnings: Vec::new(), }; Sample { pf, paint } } @@ -61,7 +56,7 @@ fn assert_same(a: &ProjectFile, b: &ProjectFile) { assert_eq!(a.baked, b.baked); assert_eq!(a.mesh, b.mesh); assert_eq!((&a.high_poly, &a.cage), (&b.high_poly, &b.cage), "bake meshes keep their order"); - assert_eq!(a.skew, b.skew); + assert_eq!(a.bake_paint, b.bake_paint); assert_eq!(a.thumbnail, b.thumbnail); assert_eq!(a.resources, b.resources); } @@ -75,6 +70,7 @@ fn round_trip_is_identical_and_deterministic() { let s = sample(); let bytes = save_project_bytes(&s.pf).unwrap(); let back = load_project_bytes(&bytes).unwrap(); + assert!(back.warnings.is_empty()); assert_same(&s.pf, &back); assert_eq!(back.pixels.layer(s.paint, Channel::BaseColor).unwrap().get(127, 127), [65535, 0, 9, 65535]); assert_eq!(save_project_bytes(&back).unwrap(), bytes); @@ -86,6 +82,35 @@ fn round_trip_is_identical_and_deterministic() { assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap()); } +#[test] +fn shared_project_schema_round_trips_the_app_document() { + let project = sample().pf.project; + let original = serde_json::to_value(&project).unwrap(); + let document: craft_tcraft::ProjectDocument = serde_json::from_value(original.clone()).unwrap(); + assert_eq!(document.format_version, project.format_version); + assert_eq!(serde_json::to_value(document).unwrap(), original); +} + +#[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() { @@ -172,8 +197,8 @@ fn tiles_are_validated_against_the_texture_set() { let orphan = load_project_bytes(&zip_with(&[("pixels/layer_999_baseColor.bin", tile_bin(128, 4, &[(0, 0)]))])).unwrap(); assert!(orphan.pixels.layers.is_empty()); assert!(load_project_bytes(&zip_with(&[("pixels/layer_x_baseColor.bin", vec![])])).is_err()); - assert!(load_project_bytes(&zip_with(&[("baked/0_ambient_occlusion.bin", header(16, 16, 1, 0))])).is_err()); - assert!(load_project_bytes(&zip_with(&[("baked/0_ambient_occlusion.bin", header(100_000, 100_000, 1, 0))])).is_err()); + assert!(load_project_bytes(&zip_with(&[("baked/0_ambientOcclusion.bin", header(16, 16, 1, 0))])).is_err()); + assert!(load_project_bytes(&zip_with(&[("baked/0_ambientOcclusion.bin", header(100_000, 100_000, 1, 0))])).is_err()); } #[test] @@ -211,3 +236,633 @@ fn duplicate_entry_names_are_made_unique_on_save() { res.sort(); assert_eq!(res, vec![vec![3], vec![4]]); } + +/// Every entry of a zip in file order: (name, method, crc, sizes, the compressed bytes as stored). +/// The zip headers around them (version fields, zip64 size placeholders) are not part of this: +/// copying an entry between zips rewrites them. +#[allow(clippy::type_complexity)] +fn payloads(zip: &[u8]) -> Vec<(String, CompressionMethod, u32, u64, u64, Vec)> { + let mut a = ZipArchive::new(Cursor::new(zip)).unwrap(); + (0..a.len()) + .map(|i| { + let mut f = a.by_index_raw(i).unwrap(); + let mut raw = Vec::new(); + f.read_to_end(&mut raw).unwrap(); + (f.name().unwrap().into_owned(), f.compression(), f.crc32(), f.size(), f.compressed_size(), raw) + }) + .collect() +} + +/// A project with several baked maps and pixel layers, big enough that entries stream in chunks. +fn big_sample() -> ProjectFile { + let mut s = sample(); + let mut x = 12345u32; + let mut noise = |n: usize| -> Vec { + (0..n) + .map(|i| { + x = x.wrapping_mul(1664525).wrapping_add(1013904223); + (i as f32 * 0.001).sin() * 0.5 + 0.5 + (x >> 24) as f32 * 1e-4 + }) + .collect() + }; + let r = 300usize; + let maps = [BakedMap::AmbientOcclusion, BakedMap::Normal, BakedMap::Curvature, BakedMap::Position] + .into_iter() + .map(|m| (m, Arc::new(noise(r * r * m.components())))) + .collect(); + s.pf.baked.insert(1, BakedMaps { resolution: r as u32, maps }); + s.pf.mesh = Some(("obj".into(), noise(5000).iter().map(|v| (v * 200.0) as u8).collect())); + s.pf +} + +fn serial_bytes(pf: &ProjectFile) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::write_serial(&mut zip, entries(pf).unwrap()).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[cfg(not(target_arch = "wasm32"))] +fn parallel_bytes(pf: &ProjectFile, workers: usize, budget: u64) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::parallel::write(&mut zip, entries(pf).unwrap(), workers, budget).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn save_plan_follows_the_reserved_cores_and_the_ram_share() { + // No cap of 8 workers any more, only the entry count and the cores. + assert_eq!(entries::plan(64, 1, 100, 1000, 50), (63, 500)); + assert_eq!(entries::plan(64, 1, 20, 1000, 50).0, 20); + // 0 reserved uses every core; more reserved than cores still leaves one worker. + assert_eq!(entries::plan(16, 0, 100, 1000, 100), (16, 1000)); + assert_eq!(entries::plan(4, 9, 100, 1000, 100).0, 1); + assert_eq!(entries::plan(1, 0, 100, 1000, 100).0, 1); + // The share is of the RAM given, clamped to 1..=100 percent, and never overflows. + assert_eq!(entries::plan(2, 1, 5, 1000, 0).1, 10); + assert_eq!(entries::plan(2, 1, 5, 1000, 250).1, 1000); + assert_eq!(entries::plan(2, 1, 5, u64::MAX, 100).1, u64::MAX); + assert_eq!(entries::plan(2, 1, 5, u64::MAX, 50).1, u64::MAX / 2); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn parallel_save_with_any_reserved_cores_and_ram_share_matches_serial() { + let pf = big_sample(); + let want = payloads(&serial_bytes(&pf)); + let n = want.len(); + // (cpus, reserved cores, available RAM, percent): none reserved, all reserved, a tiny and a huge share. + for (cpus, reserved, ram, percent) in [(8, 0, 1u64 << 40, 100u8), (8, 1, 1 << 40, 50), (8, 99, 1 << 40, 50), (16, 0, 1000, 1), (6, 1, u64::MAX, 100)] { + let (workers, budget) = entries::plan(cpus, reserved, n, ram, percent); + let got = parallel_bytes(&pf, workers, budget); + assert!(payloads(&got) == want, "{cpus} cpus, {reserved} reserved, {ram} bytes at {percent}%"); + assert_same(&pf, &load_project_bytes(&got).unwrap()); + } + // The setting is read by the public save; extreme values still save the same entries. + for (reserved, percent) in [(0, 100), (1000, 1), (1, 50)] { + set_save_resources(reserved, percent); + assert!(payloads(&save_project_bytes(&pf).unwrap()) == want, "{reserved} reserved, {percent}%"); + } + set_save_resources(DEFAULT_RESERVED_CORES, DEFAULT_RAM_PERCENT); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn parallel_save_writes_the_same_entries_as_serial() { + let pf = big_sample(); + let serial = serial_bytes(&pf); + let want = payloads(&serial); + assert!(want.len() > 10); + for (workers, budget) in [(0, 1), (2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { + let got = parallel_bytes(&pf, workers, budget); + assert!(payloads(&got) == want, "{workers} workers, budget {budget}"); + assert_same(&pf, &load_project_bytes(&got).unwrap()); + } + // The public entry point (threads chosen by the machine) agrees too, and loads back. + assert!(payloads(&save_project_bytes(&pf).unwrap()) == want); + assert_same(&pf, &load_project_bytes(&serial).unwrap()); +} + +/// The files written before entries were compressed in parallel: each entry written in one go. +fn reference_one_shot(pf: &ProjectFile) -> Vec { + let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file("project.json", deflate).unwrap(); + zip.write_all(&serde_json::to_vec_pretty(&pf.project).unwrap()).unwrap(); + for (ts, maps) in &pf.baked { + for (m, data) in &maps.maps { + zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).unwrap(); + zip.write_all(&header(maps.resolution, maps.height(*m), m.components(), 0)).unwrap(); + let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); + zip.write_all(&bytes).unwrap(); + } + } + zip.finish().unwrap().into_inner() +} + +/// Streaming a baked map into the compressor in chunks may place deflate block boundaries a few +/// bytes differently than one big write, so the stored bytes can differ slightly; what the entry +/// holds (name, method, CRC, size) must not, and the compressed size stays within 0.01%. +#[test] +fn baked_entries_hold_what_the_one_shot_writer_wrote() { + let mut pf = big_sample(); + (pf.mesh, pf.high_poly, pf.cage, pf.bake_paint, pf.thumbnail, pf.resources) = (None, vec![], None, BTreeMap::new(), None, BTreeMap::new()); + pf.pixels = PixelStore::default(); + let (new, old) = (payloads(&save_project_bytes(&pf).unwrap()), payloads(&reference_one_shot(&pf))); + assert_eq!(new.len(), old.len()); + for (n, o) in new.iter().zip(&old) { + assert_eq!((&n.0, n.1, n.2, n.3), (&o.0, o.1, o.2, o.3)); + assert!(n.4.abs_diff(o.4) <= 64 + o.4 / 10_000, "{}: {} vs {}", n.0, n.4, o.4); + } +} + +#[test] +fn bake_model_options_survive_the_project_archive() { + use texturecraft_core::{BackfaceMode, CageType, HeightNormalization}; + + let mut project_file = sample().pf; + let settings = &mut project_file.project.texture_sets[0].bake; + settings.common.resolution_height = Some(texturecraft_core::BakeResolution::R256); + settings.cage.kind = CageType::CustomFile; + settings.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName; + settings.maps.ao.parameters.rays.min_distance = 0.02; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.maps.curvature.parameters.mesh.sampling_radius = 0.002; + settings.maps.height.parameters.normalization = HeightNormalization::Manual; + settings.maps.height.parameters.scaling_divisor = 4.0; + settings.skew.edge_protection = true; + settings.skew.edge_distance = 0.3; + + let bytes = save_project_bytes(&project_file).unwrap(); + assert_same(&project_file, &load_project_bytes(&bytes).unwrap()); +} + +fn edit_archive(project_file: &ProjectFile, mut edit: impl FnMut(&mut String, &mut Vec)) -> Vec { + let bytes = save_project_bytes(project_file).unwrap(); + let mut source = ZipArchive::new(Cursor::new(bytes)).unwrap(); + let mut output = ZipWriter::new(Cursor::new(Vec::new())); + + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let mut name = entry.name().unwrap().into_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + edit(&mut name, &mut data); + output.start_file(name, SimpleFileOptions::default()).unwrap(); + output.write_all(&data).unwrap(); + } + + output.finish().unwrap().into_inner() +} + +fn edit_project_json(project_file: &ProjectFile, mut edit: impl FnMut(&mut serde_json::Value)) -> Vec { + edit_archive(project_file, |name, data| { + if name == "project.json" { + let mut json = serde_json::from_slice(data).unwrap(); + edit(&mut json); + *data = serde_json::to_vec(&json).unwrap(); + } + }) +} + +#[test] +fn recovery_loads_legacy_bake_settings_and_map_names() { + let mut expected = sample().pf; + let maps = expected.baked.get_mut(&0).unwrap(); + maps.maps.insert(BakedMap::WorldNormal, Arc::new(vec![0.5; 16 * 16 * 3])); + maps.maps.insert(BakedMap::BentNormal, Arc::new(vec![0.5; 16 * 16 * 3])); + expected.project.texture_sets[0].baked = maps.maps.keys().copied().collect(); + expected.project.texture_sets[1].bake.common.dilation = 12; + + let bytes = edit_archive(&expected, |name, data| { + if name == "project.json" { + let mut json: serde_json::Value = serde_json::from_slice(data).unwrap(); + json["texture_sets"][0]["bake"] = serde_json::json!({ + "enabled": true, "resolution": 1024, "antialiasing": 1, "dilation": 16, + "maps": ["Normal", "WorldNormal", "Id", "AmbientOcclusion", "Curvature", "Position", "Thickness"], + "ao": {"rays": 64, "max_distance": 0.1}, "use_low_as_high": true + }); + json["texture_sets"][0]["baked"].as_array_mut().unwrap().extend(serde_json::json!(["ColorMap", "WorldDirection"]).as_array().unwrap().clone()); + *data = serde_json::to_vec(&json).unwrap(); + } + + *name = name + .replace("_normal.bin", "_normal_base.bin") + .replace("_worldNormal.bin", "_world_space_normals.bin") + .replace("_ambientOcclusion.bin", "_ambient_occlusion.bin") + .replace("_bentNormal.bin", "_bent_normals.bin"); + }); + + let recovered = load_project_bytes(&bytes).unwrap(); + assert_eq!(recovered.warnings.len(), 1); + assert_same(&expected, &recovered); + let reopened = load_project_bytes(&save_project_bytes(&recovered).unwrap()).unwrap(); + assert_same(&expected, &reopened); + assert!(reopened.warnings.is_empty()); +} + +#[test] +fn recovery_keeps_readable_bake_fields_and_project_content() { + let mut expected = sample().pf; + let settings = &mut expected.project.texture_sets[0].bake; + settings.common.dilation = 19; + settings.maps.height.is_enabled = true; + settings.maps.ao.parameters.rays.rays = 96; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.high_poly.low_suffix = "_lo".into(); + expected.project.texture_sets[1].bake.common.dilation = 7; + + let bytes = edit_project_json(&expected, |json| { + let bake = &mut json["texture_sets"][0]["bake"]; + bake["common"]["antialiasing"] = serde_json::json!("unknown"); + bake["common"]["resolution_height"] = serde_json::json!(false); + bake["maps"]["normal"] = serde_json::json!("Normal"); + bake["maps"]["ao"]["parameters"]["rays"]["max_distance"] = serde_json::json!("bad"); + bake["maps"]["opacity"]["is_enabled"] = serde_json::json!(null); + bake["cage"] = serde_json::json!([1, 2]); + }); + + assert_same(&expected, &load_project_bytes(&bytes).unwrap()); +} + +#[test] +fn recovery_defaults_unreadable_bake_blocks() { + let expected = sample().pf; + for invalid in [serde_json::Value::Null, serde_json::json!(false), serde_json::json!("old"), serde_json::json!(["Normal"])] { + let bytes = edit_project_json(&expected, |json| json["texture_sets"][0]["bake"] = invalid.clone()); + assert_same(&expected, &load_project_bytes(&bytes).unwrap()); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_failing_entry_is_an_error_not_a_hang() { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + for fail_at in [0usize, 3, 9] { + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| { + if i == fail_at { + return Err(std::io::Error::other("boom")); + } + if i == 5 && fail_at == 9 { + panic!("worker panic"); + } + w.write_all(&[i as u8; 100]) + }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + assert!(entries::parallel::write(&mut zip, list, 4, 25).is_err(), "fail at {fail_at}"); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_late_failing_entry_after_good_ones_is_its_own_error() { + // Only the last entry fails and nothing panics, so the error must come from that entry. + for (workers, budget) in [(4usize, 25u64), (4, u64::MAX), (2, 1)] { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| if i == 9 { Err(std::io::Error::other("late boom")) } else { w.write_all(&[i as u8; 100]) }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + let res = entries::parallel::write(&mut zip, list, workers, budget); + let _ = tx.send(res.map_err(|e| matches!(&e, FormatError::Io(io) if io.to_string() == "late boom"))); + }); + let res = + rx.recv_timeout(std::time::Duration::from_secs(60)).unwrap_or_else(|e| panic!("save did not finish ({e}): {workers} workers, budget {budget}")); + assert_eq!(res, Err(true), "{workers} workers, budget {budget}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn assert_entry_streams_to_destination(method: CompressionMethod, budget: u64) { + use std::sync::atomic::{AtomicBool, Ordering}; + + let path = std::env::temp_dir().join(format!("texturecraft-entry-streaming-{}-{method:?}.zip", std::process::id())); + let destination = std::fs::File::create(&path).unwrap(); + let observed_destination = destination.try_clone().unwrap(); + let reached_destination = AtomicBool::new(false); + let mut random = 12345u32; + let payload: Vec = (0..131_072) + .map(|_| { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + random as u8 + }) + .collect(); + let compressed = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + let mut list: Vec> = (0..2) + .map(|index| Entry { name: format!("before{index}"), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[7; 128])) }) + .collect(); + list.push(Entry { + name: "target".into(), + options: SimpleFileOptions::default().compression_method(method), + weight: payload.len() as u64, + body: Box::new(|writer| { + let before_bytes = observed_destination.metadata()?.len(); + writer.write_all(&payload)?; + writer.flush()?; + reached_destination.store(observed_destination.metadata()?.len() > before_bytes, Ordering::Relaxed); + Ok(()) + }), + }); + list.push(Entry { name: "after".into(), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[9; 128])) }); + let mut writer = ZipWriter::new(destination); + + let result = entries::parallel::write(&mut writer, list, 4, budget); + drop(writer.finish().unwrap()); + drop(observed_destination); + let bytes = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + + result.unwrap(); + assert!(reached_destination.load(Ordering::Relaxed), "{method:?} was buffered instead of streamed"); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + let names: Vec<_> = (0..archive.len()).map(|index| archive.by_index(index).unwrap().name().unwrap().into_owned()).collect(); + assert_eq!(names, ["before0", "before1", "target", "after"]); + let mut actual = Vec::new(); + archive.by_name("target").unwrap().read_to_end(&mut actual).unwrap(); + assert_eq!(actual, payload); + let mut after = Vec::new(); + archive.by_name("after").unwrap().read_to_end(&mut after).unwrap(); + assert_eq!(after, [9; 128]); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn stored_entries_reach_the_destination_during_their_body() { + assert_entry_streams_to_destination(CompressionMethod::Stored, 1 << 20); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn over_budget_entries_reach_the_destination_during_their_body() { + assert_entry_streams_to_destination(CompressionMethod::Deflated, 4096); +} + +#[test] +fn recovery_skips_unsupported_baked_map_entries() { + let expected = sample().pf; + let bytes = edit_archive(&expected, |name, _| { + if name == "thumbnail.png" { + *name = "baked/0_color_map.bin".into(); + } + }); + let mut expected = expected; + expected.thumbnail = None; + let recovered = load_project_bytes(&bytes).unwrap(); + assert_same(&expected, &recovered); + assert_eq!(recovered.warnings.len(), 1); +} + +#[test] +fn recovery_does_not_hide_invalid_project_structure_or_newer_versions() { + let project_file = sample().pf; + for (field, value) in [("resolution", serde_json::json!("bad")), ("stack", serde_json::json!([999])), ("channels", serde_json::json!(null))] { + let bytes = edit_project_json(&project_file, |json| { + json["texture_sets"][0]["bake"] = serde_json::json!("old"); + json["texture_sets"][0][field] = value.clone(); + }); + assert!(load_project_bytes(&bytes).is_err(), "{field}"); + } + + let bytes = edit_project_json(&project_file, |json| { + json["format_version"] = serde_json::json!(FORMAT_VERSION + 1); + json["texture_sets"][0]["bake"] = serde_json::json!("old"); + }); + assert!(matches!(load_project_bytes(&bytes), Err(FormatError::NewerVersion { .. }))); +} + +#[test] +fn recovery_still_rejects_corrupt_pixels() { + let project_file = sample().pf; + let bytes = edit_archive(&project_file, |name, data| { + if name == "project.json" { + let mut json: serde_json::Value = serde_json::from_slice(data).unwrap(); + json["texture_sets"][0]["bake"]["maps"] = serde_json::json!(["Normal"]); + *data = serde_json::to_vec(&json).unwrap(); + } else if name.starts_with("pixels/") { + data.truncate(10); + } + }); + + let error = load_project_bytes(&bytes).unwrap_err(); + assert!(error.to_string().contains("pixels/"), "{error}"); +} + +#[test] +fn recovery_does_not_accept_unrelated_json_errors() { + let bytes = edit_archive(&sample().pf, |name, data| { + if name == "project.json" { + data.splice(1..1, br#""name":"duplicate", "#.iter().copied()); + } + }); + + let error = load_project_bytes(&bytes).unwrap_err(); + assert!(error.to_string().contains("duplicate field"), "{error}"); +} + +#[test] +fn project_open_limit_counts_every_loaded_entry_kind() { + let paint = sample().paint; + let baked = [header(16, 16, 1, 0), vec![0; 16 * 16 * 4]].concat(); + let entries = [ + ("resources/test.bin".to_string(), vec![1; 1024]), + ("mesh.obj".to_string(), vec![2; 1024]), + ("highpoly/test.obj".to_string(), vec![3; 1024]), + ("cage/test.obj".to_string(), vec![4; 1024]), + ("thumbnail.png".to_string(), vec![5; 1024]), + (format!("pixels/layer_{}_baseColor.bin", paint.0), tile_bin(128, 4, &[(0, 0)])), + (format!("pixels/mask_{}.bin", paint.0), tile_bin(128, 2, &[(0, 0)])), + ("baked/0_ambientOcclusion.bin".to_string(), baked.clone()), + ("bake_paint/0_skew.bin".to_string(), baked), + ]; + + for (name, data) in entries { + let bytes = zip_with(&[(&name, data)]); + let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum(); + + let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap(); + let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err(); + let raised_limit = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes + 1)).unwrap(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{name}: {error}"); + assert!(error.to_string().contains(&format!("{} bytes", total_bytes - 1)), "{name}: {error}"); + assert_same(&accepted, &raised_limit); + } +} + +#[test] +fn project_open_limit_is_shared_across_the_whole_archive() { + let project = sample().pf; + let bytes = serial_bytes(&project); + let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum(); + + let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap(); + let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err(); + + assert_same(&project, &accepted); + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); +} + +#[test] +fn entry_reads_stop_at_the_smaller_of_the_entry_and_project_limits() { + for (entry_limit, project_limit, expected_read) in [(8, 100, 9), (100, 8, 9)] { + let mut reader = Cursor::new(vec![1; 1000]); + let mut budget = LoadBudget::new(project_limit); + + let error = read_all(&mut reader, entry_limit, &mut budget, "resource").unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); + assert_eq!(reader.position(), expected_read); + } +} + +#[test] +fn oversized_baked_data_is_rejected_before_reading_its_payload() { + let mut reader = Cursor::new(header(16, 16, 1, 0)); + let mut budget = LoadBudget::new(BIN_HEADER_BYTES as u64 + 16 * 16 * 4 - 1); + + let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64 + 16 * 16 * 4, 1, &mut budget, "baked map").unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "the size guard must run before the truncated read: {error}"); + assert_eq!(reader.position(), BIN_HEADER_BYTES as u64); +} + +#[test] +fn archive_preflight_counts_ignored_entries_and_allows_the_exact_limit() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + for name in ["project.json", "unknown/future-data"] { + writer.start_file(name, options).unwrap(); + writer.write_all(&[0; 16]).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + + check_archive(&mut archive, 32).unwrap(); + let error = check_archive(&mut archive, 31).unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); +} + +#[test] +fn overlapping_archive_entries_are_rejected_before_decompression() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default()).unwrap(); + writer.write_all(&[0; 16]).unwrap(); + writer.shallow_copy_file("resource", "copy").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + + let error = check_archive(&mut archive, 32).unwrap_err(); + + assert!(error.to_string().contains("overlapping ZIP entries"), "{error}"); +} + +#[test] +fn actual_decompression_is_bounded_even_when_the_declared_size_is_small() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Deflated)).unwrap(); + writer.write_all(&vec![0; 1 << 20]).unwrap(); + let mut bytes = writer.finish().unwrap().into_inner(); + let directory = ZipArchive::new(Cursor::new(&bytes)).unwrap().central_directory_start() as usize; + // The central header stores the uncompressed size at byte 24 + bytes.get_mut(directory + 24..directory + 28).unwrap().copy_from_slice(&1u32.to_le_bytes()); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + check_archive(&mut archive, 1024).unwrap(); + let mut entry = archive.by_index(0).unwrap(); + let mut budget = LoadBudget::new(1024); + + let error = read_all(&mut entry, MAX_RESOURCE, &mut budget, "resource").unwrap_err(); + + assert!( + matches!(error, FormatError::TooLarge(_)) || error.to_string().contains("larger than its declared uncompressed size"), + "actual bytes must be bounded independently of ZIP sizes: {error}" + ); +} + +#[test] +fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() { + let mut reader = Cursor::new(header(1024, 1024, 3, 0)); + let mut budget = LoadBudget::new(16 << 20); + + let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64, 3, &mut budget, "baked map").unwrap_err(); + + assert!(error.to_string().contains("24 bytes for a 1024×1024×3 map"), "{error}"); + assert_eq!(budget.remaining(), (16 << 20) - BIN_HEADER_BYTES as u64); + assert_eq!(reader.position(), BIN_HEADER_BYTES as u64); +} + +#[test] +fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() { + let values: Vec = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect(); + let mut bytes = header(values.len() as u32, 1, 1, 0); + bytes.extend(values.iter().flat_map(|bits| bits.to_le_bytes())); + let declared = bytes.len() as u64; + let mut reader = Cursor::new(bytes); + let mut budget = LoadBudget::new(declared); + + let (_, _, decoded) = read_baked(&mut reader, declared, 1, &mut budget, "baked map").unwrap(); + + assert_eq!(decoded.into_iter().map(f32::to_bits).collect::>(), values); + assert_eq!(reader.position(), declared); + assert_eq!(budget.remaining(), 0); +} + +#[test] +fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); + writer.write_all(&vec![7; 1 << 20]).unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + + let mut archive = open_archive(Cursor::new(bytes), 4096).unwrap(); + let mut first_byte = [0; 1]; + archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap(); + + assert_eq!(first_byte, [7]); + + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap(); + writer.write_all(&[7]).unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + + assert!(open_archive(Cursor::new(bytes), 4096).is_err()); +} + +#[test] +fn zip64_entry_counts_remain_supported_and_bounded() { + for count in [65_536, MAX_ENTRIES + 1] { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for index in 0..count { + writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + + let mut archive = open_archive(Cursor::new(bytes), MAX_ZIP_METADATA_BYTES).unwrap(); + let result = check_archive(&mut archive, 0); + + assert_eq!(archive.len(), count); + if count <= MAX_ENTRIES { + result.unwrap(); + } else { + assert!(matches!(result, Err(FormatError::TooLarge(_))), "{result:?}"); + } + } +} diff --git a/crates/geom/src/gbuffer.rs b/crates/geom/src/gbuffer.rs index e26b923f..f18ee092 100644 --- a/crates/geom/src/gbuffer.rs +++ b/crates/geom/src/gbuffer.rs @@ -20,7 +20,7 @@ pub struct UvGBuffer { pub tri: Vec, /// Barycentric weights of the triangle's second and third vertices. pub bary: Vec<[f32; 2]>, - /// Texels written by more than one triangle (overlapping UVs). + /// Covers past the first on texels where any cover has the texel center strictly inside (overlapping UVs; an edge two neighbours share is no overlap) pub overlaps: u32, } @@ -41,74 +41,95 @@ fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) } +/// Twice-areas (in texels²) below this are degenerate triangles, which cover nothing +const MIN_DOUBLE_AREA: f32 = 1e-12; + +/// How far outside a triangle (as a share of its double area) a texel center may sit and still count as covered, so shared edges leave no gaps +const EDGE_TOLERANCE: f32 = 1e-6; + impl UvGBuffer { - /// Rasterize the triangles of material `material` at `width × height`. + /// Rasterize the triangles of material `material` at `width × height` pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer { - let (w, h) = (width.max(1), height.max(1)); - let size = Vec2::new(w as f32, h as f32); - let bands = h.div_ceil(BAND) as usize; - let mut bins: Vec> = vec![Vec::new(); bands]; - for t in mesh.triangles_of(material) { - let Some([a, b, c]) = mesh.tri(t) else { continue }; - let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; - let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; - let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; - if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + let (width, height) = (width.max(1), height.max(1)); + let size = Vec2::new(width as f32, height as f32); + let corner_uvs = |triangle: usize| { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) + }; + + // Sort triangles into bands of rows so each band rasterizes on its own thread + let mut bands: Vec> = vec![Vec::new(); height.div_ceil(BAND) as usize]; + for triangle in mesh.triangles_of(material) { + let Some(uvs) = corner_uvs(triangle) else { continue }; + let top = (uvs.iter().map(|uv| uv.y).fold(f32::INFINITY, f32::min) * size.y).floor().max(0.0) as i64; + let bottom = (uvs.iter().map(|uv| uv.y).fold(f32::NEG_INFINITY, f32::max) * size.y).ceil().min(size.y) as i64; + if bottom <= top || !uvs.iter().all(|uv| uv.is_finite()) { continue; } - let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize); - for bin in bins.iter_mut().take(b1 + 1).skip(b0) { - bin.push(t as u32); + + let (first_band, last_band) = ((top / BAND as i64) as usize, ((bottom - 1).max(0) / BAND as i64) as usize); + for band in bands.iter_mut().take(last_band + 1).skip(first_band) { + band.push(triangle as u32); } } - let n = w as usize * h as usize; - let mut tri = vec![NO_TRI; n]; - let mut bary = vec![[0.0f32; 2]; n]; - let band_len = (BAND * w) as usize; + + let texel_count = width as usize * height as usize; + let mut tri = vec![NO_TRI; texel_count]; + let mut bary = vec![[0.0f32; 2]; texel_count]; + let band_texels = (BAND * width) as usize; let overlaps: u32 = tri - .par_chunks_mut(band_len) - .zip(bary.par_chunks_mut(band_len)) + .par_chunks_mut(band_texels) + .zip(bary.par_chunks_mut(band_texels)) .enumerate() - .map(|(bi, (tri, bary))| { - let mut overlaps = 0u32; - let row0 = bi as u32 * BAND; - let rows = (tri.len() as u32) / w; - 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(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; - let (pa, pb, pc) = (ua * size, ub * size, uc * size); - let area = edge(pa, pb, pc); - if area.abs() < 1e-12 { + .map(|(band_index, (band_tri, band_bary))| { + // Keep cover counts and strict interiors independent of triangle order + let mut covers = vec![0u32; band_tri.len()]; + let mut strict_cover = vec![false; band_tri.len()]; + let first_row = band_index as u32 * BAND; + let band_rows = (band_tri.len() as u32) / width; + for &triangle in bands.get(band_index).map(Vec::as_slice).unwrap_or(&[]) { + let Some(uvs) = corner_uvs(triangle as usize) else { continue }; + let [a, b, c] = uvs.map(|uv| uv * size); + let double_area = edge(a, b, c); + if double_area.abs() < MIN_DOUBLE_AREA { continue; } - let eps = -1e-6 * area.abs(); - let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; - let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); - let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); - let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); - for y in y0..y1 { - for x in x0..x1 { - let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); - let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); - if w0 < eps || w1 < eps || w2 < eps { + + let tolerance = EDGE_TOLERANCE * double_area.abs(); + let (sign, inverse_area) = (double_area.signum(), 1.0 / double_area.abs()); + let left = a.x.min(b.x).min(c.x).floor().max(0.0) as u32; + let right = (a.x.max(b.x).max(c.x).ceil().min(width as f32) as u32).min(width); + let top = (a.y.min(b.y).min(c.y).floor().max(first_row as f32) as u32).max(first_row); + let bottom = (a.y.max(b.y).max(c.y).ceil() as u32).min(first_row + band_rows); + for y in top..bottom { + for x in left..right { + let center = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let weights = [edge(b, c, center) * sign, edge(c, a, center) * sign, edge(a, b, center) * sign]; + if weights.iter().any(|weight| *weight < -tolerance) { continue; } - let i = ((y - row0) * w + x) as usize; - if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { - if *slot != NO_TRI { - overlaps += 1; - } - *slot = t; - let inv = 1.0 / area.abs(); - *bw = [w1 * inv, w2 * inv]; - } + + let index = ((y - first_row) * width + x) as usize; + let (Some(slot), Some(slot_bary), Some(cover_count), Some(strict)) = + (band_tri.get_mut(index), band_bary.get_mut(index), covers.get_mut(index), strict_cover.get_mut(index)) + else { + continue; + }; + + *cover_count += 1; + *strict |= weights.iter().all(|weight| *weight > tolerance); + *slot = triangle; + *slot_bary = [weights[1] * inverse_area, weights[2] * inverse_area]; } } } - overlaps + + // Every cover past the first overlaps, unless all of them only touch the texel center with an edge (neighbours sharing it) + covers.iter().zip(&strict_cover).filter(|(_, strict)| **strict).map(|(count, _)| count.saturating_sub(1)).sum::() }) .sum(); - UvGBuffer { width: w, height: h, tri, bary, overlaps } + + UvGBuffer { width, height, tri, bary, overlaps } } pub fn covered(&self, i: usize) -> bool { @@ -157,7 +178,7 @@ mod tests { #[test] fn half_triangle_covers_texels_with_centers_inside() { - // One triangle covering the lower-left half of UV space (v down: y = v·H). + // UV v increases down, so this triangle covers the lower-left half let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], vec![0, 1, 2], "m") .unwrap(); @@ -171,6 +192,28 @@ mod tests { assert_eq!(g.overlaps, 0); } + #[test] + fn neighbours_sharing_an_edge_through_texel_centers_do_not_overlap() { + // An 8×8 grid of quads at 512 texels: each quad's diagonal runs through 64 texel centers + let grid = primitives::plane(1.0, 8); + let gbuffer = UvGBuffer::new(&grid, 0, 512, 512); + assert_eq!(gbuffer.covered_count(), 512 * 512); + assert_eq!(gbuffer.overlaps, 0); + } + + #[test] + fn an_edge_through_a_covered_texel_center_counts_both_edge_covers() { + // The texel center (0.5, 0.5) lies inside the first triangle and on the diagonal the other two share + let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.2), Vec2::new(0.2, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)]; + let positions = vec![Vec3::ZERO; uv.len()]; + + // In either order: the inside cover first, or the two edge covers first + for indices in [vec![0, 1, 2, 0, 3, 4, 0, 5, 3], vec![0, 3, 4, 0, 5, 3, 0, 1, 2]] { + let m = Mesh::from_parts(positions.clone(), None, uv.clone(), indices.clone(), "m").unwrap(); + assert_eq!(UvGBuffer::new(&m, 0, 1, 1).overlaps, 2, "{indices:?}"); + } + } + #[test] fn overlapping_and_degenerate_triangles() { let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)]; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..b0d311df 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -4,6 +4,12 @@ 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]); + +/// Normals closer than about one degree are the same normal: the edge between them is smooth +const SAME_NORMAL_MIN_COSINE: f32 = 0.9998; + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -82,31 +88,82 @@ impl Mesh { /// split it from its twin), per material in `0..materials.len().max(1)`. pub fn wire_edges(&self) -> Vec> { (0..self.materials.len().max(1)) - .map(|m| { - // Edge → (real in some triangle, triangles using it), in first-seen order. + .map(|material| { + // Keep first-seen edge order while counting its triangle uses let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); - let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); - for t in self.triangles_of(m) { - let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue }; - let hidden = self.diagonals.get(t).copied().unwrap_or(0); - for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() { - let key = (a.min(b), a.max(b)); - let real = hidden >> i & 1 == 0; - let e = *at.entry(key).or_insert_with(|| { + let mut edge_indices: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); + for triangle in self.triangles_of(material) { + let Some(vertices) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + let hidden = self.diagonals.get(triangle).copied().unwrap_or(0); + for (side, (from, to)) in [(vertices[0], vertices[1]), (vertices[1], vertices[2]), (vertices[2], vertices[0])].into_iter().enumerate() { + let key = (from.min(to), from.max(to)); + let is_polygon_edge = hidden >> side & 1 == 0; + let edge_index = *edge_indices.entry(key).or_insert_with(|| { edges.push((key, false, 0)); edges.len() - 1 }); - if let Some((_, r, n)) = edges.get_mut(e) { - *r |= real; - *n = n.saturating_add(1); + if let Some((_, edge_is_polygon_side, triangle_count)) = edges.get_mut(edge_index) { + *edge_is_polygon_side |= is_polygon_edge; + *triangle_count = triangle_count.saturating_add(1); } } } - edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + edges.into_iter().filter(|(_, is_polygon_edge, triangle_count)| *is_polygon_edge || *triangle_count == 1).map(|(edge, ..)| edge).collect() }) .collect() } + /// Hard edges the UV layout does not split, which bake visible lines into the normal map: two triangles meet there with different normals but the same UVs, per material in `0..materials.len().max(1)` + pub fn missing_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(); + + // Imported normals need not be unit length; two missing normals agree + let direction = |index: u32| self.normals.get(index as usize).map_or(Vec3::ZERO, |normal| normal.normalize_or_zero()); + let same_normal = |a: u32, b: u32| { + let (a, b) = (direction(a), direction(b)); + a == b || a.dot(b) >= SAME_NORMAL_MIN_COSINE + }; + for pairs in sides.into_values() { + let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; + + let uv_split = pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))); + let hard = pairs.iter().any(|&(from, to, _)| !same_normal(from, first_from) || !same_normal(to, first_to)); + if hard && !uv_split { + 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; @@ -155,18 +212,19 @@ impl Mesh { /// Area-weighted smooth normals over the index buffer. pub fn compute_normals(&mut self) { - let mut n = vec![Vec3::ZERO; self.positions.len()]; - for t in self.indices.chunks_exact(3) { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + let mut normals = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let face = (*pb - *pa).cross(*pc - *pa); for v in [a, b, c] { - if let Some(x) = n.get_mut(v) { + if let Some(x) = normals.get_mut(v) { *x += face; } } } - self.normals = n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + + self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). @@ -193,25 +251,27 @@ impl Mesh { } fn simple_tangents(&mut self) { - let mut acc = vec![Vec3::ZERO; self.positions.len()]; - for t in self.indices.chunks_exact(3) { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + let mut tangents = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; let (e1, e2) = (*pb - *pa, *pc - *pa); let (d1, d2) = (*ub - *ua, *uc - *ua); - let r = d1.x * d2.y - d2.x * d1.y; - if r.abs() < 1e-12 { + let determinant = d1.x * d2.y - d2.x * d1.y; + if determinant.abs() < 1e-12 { continue; } - let tan = (e1 * d2.y - e2 * d1.y) / r; + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; for v in [a, b, c] { - if let Some(x) = acc.get_mut(v) { - *x += tan; + if let Some(x) = tangents.get_mut(v) { + *x += tangent; } } } - self.tangents = acc.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + + self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); } /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), @@ -236,39 +296,44 @@ impl Mesh { /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then /// place a vertex on a tile border with its own triangle's tile. pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { - let mine: Vec = self.triangles_of(m).collect(); - let mut is_mine = vec![false; self.triangle_count()]; - for t in &mine { - if let Some(x) = is_mine.get_mut(*t) { + let material_triangles: Vec = self.triangles_of(m).collect(); + let mut in_material = vec![false; self.triangle_count()]; + for t in &material_triangles { + if let Some(x) = in_material.get_mut(*t) { *x = true; } } + let mut shared = vec![false; self.positions.len()]; - for (_, tri) in self.indices.chunks_exact(3).enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) { for v in tri { if let Some(s) = shared.get_mut(*v as usize) { *s = true; } } } - let mut copies = std::collections::HashMap::new(); - for k in mine.iter().flat_map(|t| t * 3..t * 3 + 3) { + + let mut duplicates = std::collections::HashMap::new(); + for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { let Some(&v) = self.indices.get(k) else { continue }; - let v = if shared.get(v as usize).copied().unwrap_or(false) { *copies.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; + let v = + if shared.get(v as usize).copied().unwrap_or(false) { *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; if let Some(i) = self.indices.get_mut(k) { *i = v; } } - // (vertex, centroid of its first triangle), each vertex once. - let mut verts = Vec::with_capacity(mine.len() * 3); - for t in &mine { + + // (vertex, centroid of its first triangle), each vertex once + let mut vertices = Vec::with_capacity(material_triangles.len() * 3); + for t in &material_triangles { let Some(tri) = self.tri(*t) else { continue }; let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; - verts.extend(tri.map(|v| (v, centroid))); + vertices.extend(tri.map(|v| (v, centroid))); } - verts.sort_by_key(|(v, _)| *v); - verts.dedup_by_key(|(v, _)| *v); - for (v, centroid) in verts { + + vertices.sort_by_key(|(v, _)| *v); + vertices.dedup_by_key(|(v, _)| *v); + for (v, centroid) in vertices { if let Some(uv) = self.uvs.get_mut(v) { *uv = f(centroid, *uv); } @@ -419,20 +484,79 @@ mod tests { fn wire_edges_leave_out_polygon_diagonals() { let mut m = quad(); assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); - // Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad. + + // Hide the quad's shared diagonal m.diagonals = vec![0b100, 0b001]; assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); - // A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays. + + // Keep the diagonal when a seam splits its twin let mut seam = m.clone(); seam.indices[3] = 4; assert_eq!(seam.wire_edges()[0].len(), 6); - // Appending keeps each side's diagonals on its own triangles. + + // Appending preserves each side's own diagonals let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap(); a.append(&m); assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } + /// `quad` with vertex 4 a copy of vertex 0 at `uv` with `normal`, used by the second triangle: the diagonal (0, 2) / (4, 2) has two sides + fn split_quad(uv: Vec2, normal: Vec3) -> Mesh { + let mut mesh = quad(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(normal); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(uv); + mesh.indices[3] = 4; + mesh + } + + #[test] + fn missing_seams_are_hard_edges_the_uv_layout_does_not_split() { + let none = vec![Vec::<(u32, u32)>::new()]; + assert_eq!(quad().missing_seam_edges(), none, "a smooth quad has no hard edge"); + + let shared_uv = quad().uvs[0]; + let smooth_split = split_quad(shared_uv, Vec3::Z); + assert_eq!(smooth_split.missing_seam_edges(), none, "the same normal on both sides is a smooth edge"); + + let hard = split_quad(shared_uv, Vec3::new(1.0, 0.0, 1.0).normalize()); + assert_eq!(hard.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]], "a hard edge inside one UV island"); + + let seamed = split_quad(Vec2::new(0.9, 0.9), hard.normals[4]); + assert_eq!(seamed.missing_seam_edges(), none, "a hard edge on a UV seam is fine"); + + let mut short_normals = quad(); + short_normals.normals.iter_mut().for_each(|normal| *normal *= 0.5); + assert_eq!(short_normals.missing_seam_edges(), none, "normals shorter than unit length point the same way"); + assert_eq!(split_quad(shared_uv, Vec3::Z * 0.5).missing_seam_edges(), none, "normals of different lengths point the same way"); + + let mut no_normals = quad(); + no_normals.normals.fill(Vec3::ZERO); + assert_eq!(no_normals.missing_seam_edges(), none, "two missing normals agree"); + } + + #[test] + fn missing_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = split_quad(quad().uvs[0], Vec3::X); + mesh.positions[4] = Vec3::new(-0.0, 0.0, 0.0); + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn missing_seams_between_materials_belong_to_both_materials() { + let mut mesh = split_quad(quad().uvs[0], Vec3::X); + 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.missing_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.normals[4] = mesh.normals[0]; + assert_eq!(mesh.missing_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a hard edge"); + } + #[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/brush.rs b/crates/paint/src/brush.rs index 61313d57..2cde78c8 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -130,33 +130,82 @@ pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { t * t * (3.0 - 2.0 * t) } -/// Mirror and radial symmetry through the mesh center. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +/// Largest symmetry offset kept from a command or a file (world units), far beyond any mesh +const MAX_SYMMETRY_OFFSET: f32 = 1.0e6; + +/// Mirror and radial symmetry through the mesh center, optionally moved by `offset` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Symmetry { + /// The toolbar's Symmetry toggle: off keeps the settings below but paints no copies + #[serde(default = "enabled_by_default")] + pub enabled: bool, pub x: bool, pub y: bool, pub z: bool, - /// Radial symmetry: copies spread evenly around `axis` (0 or 1: off; at most 32). + /// Radial copies around `axis`, spread over `angle_span` (0 or 1: off; at most [`MAX_RADIAL_COPIES`]) #[serde(default)] pub radial: u8, - /// Axis of radial symmetry: 0 = X, 1 = Y, 2 = Z. + /// Axis of radial symmetry (0 = X, 1 = Y, 2 = Z), independent of the mirror axes #[serde(default = "radial_axis")] pub axis: u8, + /// Where the mirror planes and the radial axis cross, relative to the mesh center (world units) + #[serde(default)] + pub offset: [f32; 3], + /// Degrees the radial copies spread over: a full turn spaces them evenly, less puts the first and last copy at its ends + #[serde(default = "full_turn")] + pub angle_span: f32, +} + +fn enabled_by_default() -> bool { + true } fn radial_axis() -> u8 { 1 } +fn full_turn() -> f32 { + FULL_TURN_DEGREES +} + +/// [`Symmetry::angle_span`] of a full turn +pub const FULL_TURN_DEGREES: f32 = 360.0; + +/// Most radial copies a brush paints +pub const MAX_RADIAL_COPIES: u8 = 32; + +/// [`Symmetry::axis`] of the last axis, Z +const LAST_AXIS: u8 = 2; + impl Default for Symmetry { fn default() -> Self { - Symmetry { x: false, y: false, z: false, radial: 0, axis: radial_axis() } + Symmetry { enabled: enabled_by_default(), x: false, y: false, z: false, radial: 0, axis: radial_axis(), offset: [0.0; 3], angle_span: full_turn() } } } impl Symmetry { + /// Whether symmetry is on with an axis to mirror on or radial copies pub fn any(&self) -> bool { - self.x || self.y || self.z || self.radial > 1 + self.enabled && (self.x || self.y || self.z || self.radial > 1) + } + + /// Whether radial symmetry is on (see [`Symmetry::radial_on`] for whether it paints copies) + pub fn radial_mode(&self) -> bool { + self.enabled && self.radial > 1 + } + + /// Whether radial copies are painted: with no angle to spread over they would all land on the stroke + pub fn radial_on(&self) -> bool { + self.radial_mode() && self.angle_span > 0.0 + } + + /// Rotation (radians) of radial copy number `copy` (0 = the stroke itself) around the axis + pub fn radial_angle(&self, copy: u8) -> f32 { + if self.angle_span >= FULL_TURN_DEGREES { + f32::from(copy) * std::f32::consts::TAU / f32::from(self.radial.max(1)) + } else { + f32::from(copy) * self.angle_span.to_radians() / f32::from(self.radial.saturating_sub(1).max(1)) + } } /// Mirror scales in stroke order, including identity, without allocating @@ -172,26 +221,39 @@ impl Symmetry { Vec3::NEG_ONE, ] .into_iter() - .filter(|sign| (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z)) + .filter(|sign| *sign == Vec3::ONE || (self.enabled && (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z))) } - /// Linear maps (through the mesh center) taking a point to each of its symmetry copies, - /// the identity first. Mirrors come first, then radial rotations of the point and its mirrors. + /// The point the mirror planes and the radial axis pass through, for a mesh centered at `center` + pub fn origin(&self, center: Vec3) -> Vec3 { + center + Vec3::from(self.offset) + } + + /// [`Symmetry::axis`] as an index (0 = X, 1 = Y, 2 = Z), out-of-range values read as Z + pub fn axis_index(&self) -> usize { + usize::from(self.axis.min(LAST_AXIS)) + } + + /// Axis of radial symmetry as a unit vector + pub fn radial_axis(&self) -> Vec3 { + [Vec3::X, Vec3::Y, Vec3::Z][self.axis_index()] + } + + /// Linear maps `m` taking a point to its copies as `origin + m * (p - origin)`: identity, mirrors, then their radial turns pub fn transforms(&self) -> Vec { - let mut out: Vec = self.mirror_signs().map(Mat3::from_diagonal).collect(); + let mut maps: Vec = self.mirror_signs().map(Mat3::from_diagonal).collect(); - if self.radial > 1 { - let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(self.axis as usize).copied().unwrap_or(Vec3::Y); - let base = out.clone(); - out.reserve(base.len().saturating_mul(usize::from(self.radial - 1))); + if self.radial_on() { + let mirrors = maps.clone(); + maps.reserve(mirrors.len().saturating_mul(usize::from(self.radial - 1))); - for k in 1..self.radial { - let r = Mat3::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(self.radial)); - out.extend(base.iter().map(|m| r * *m)); + for copy in 1..self.radial { + let turn = Mat3::from_axis_angle(self.radial_axis(), self.radial_angle(copy)); + maps.extend(mirrors.iter().map(|mirror| turn * *mirror)); } } - out + maps } } @@ -291,30 +353,44 @@ impl Default for BrushSettings { } impl BrushSettings { - /// Clamp every value into its valid range (input from UI, CLI or agents). + /// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the + /// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it. + pub fn uv_stamp_radius(&self, pressure: f32) -> f32 { + let p = pressure.clamp(0.0, 1.0); + self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 } + } + + /// Clamp every value into its valid range (input from UI, CLI or agents) pub fn sanitized(&self) -> BrushSettings { - let f = |v: f32, lo: f32, hi: f32, d: f32| if v.is_finite() { v.clamp(lo, hi) } else { d }; + let clamp_finite = |value: f32, min: f32, max: f32, default: f32| if value.is_finite() { value.clamp(min, max) } else { default }; + BrushSettings { - size: f(self.size, 0.0005, 0.5, 0.02), - min_size: f(self.min_size, 0.0, 1.0, 0.05), - flow: f(self.flow, 0.0, 1.0, 1.0), - opacity: f(self.opacity, 0.0, 1.0, 1.0), - spacing: f(self.spacing, 0.01, 10.0, 0.1), - hardness: f(self.hardness, 0.0, 0.999, 0.5), - angle: f(self.angle, -360.0, 360.0, 0.0), - angle_fade: (f(self.angle_fade.0, 0.0, 90.0, 70.0), f(self.angle_fade.1, 0.0, 90.0, 85.0)), - lazy: f(self.lazy, 0.0, 500.0, 0.0), - jitter_size: f(self.jitter_size, 0.0, 1.0, 0.0), - jitter_angle: f(self.jitter_angle, 0.0, 1.0, 0.0), - jitter_flow: f(self.jitter_flow, 0.0, 1.0, 0.0), - jitter_position: f(self.jitter_position, 0.0, 4.0, 0.0), - depth: f(self.depth, 0.05, 4.0, 1.0), - symmetry: Symmetry { radial: self.symmetry.radial.min(32), axis: self.symmetry.axis.min(2), ..self.symmetry }, + size: clamp_finite(self.size, 0.0005, 0.5, 0.02), + min_size: clamp_finite(self.min_size, 0.0, 1.0, 0.05), + flow: clamp_finite(self.flow, 0.0, 1.0, 1.0), + opacity: clamp_finite(self.opacity, 0.0, 1.0, 1.0), + spacing: clamp_finite(self.spacing, 0.01, 10.0, 0.1), + hardness: clamp_finite(self.hardness, 0.0, 0.999, 0.5), + angle: clamp_finite(self.angle, -360.0, 360.0, 0.0), + angle_fade: (clamp_finite(self.angle_fade.0, 0.0, 90.0, 70.0), clamp_finite(self.angle_fade.1, 0.0, 90.0, 85.0)), + lazy: clamp_finite(self.lazy, 0.0, 500.0, 0.0), + jitter_size: clamp_finite(self.jitter_size, 0.0, 1.0, 0.0), + jitter_angle: clamp_finite(self.jitter_angle, 0.0, 1.0, 0.0), + jitter_flow: clamp_finite(self.jitter_flow, 0.0, 1.0, 0.0), + jitter_position: clamp_finite(self.jitter_position, 0.0, 4.0, 0.0), + depth: clamp_finite(self.depth, 0.05, 4.0, 1.0), + symmetry: Symmetry { + radial: self.symmetry.radial.min(MAX_RADIAL_COPIES), + axis: self.symmetry.axis.min(LAST_AXIS), + offset: self.symmetry.offset.map(|value| clamp_finite(value, -MAX_SYMMETRY_OFFSET, MAX_SYMMETRY_OFFSET, 0.0)), + angle_span: clamp_finite(self.symmetry.angle_span, 0.0, FULL_TURN_DEGREES, FULL_TURN_DEGREES), + ..self.symmetry + }, particles: Particles { enabled: self.particles.enabled, count: self.particles.count.clamp(1, 16), lifetime: self.particles.lifetime.clamp(1, 128), - gravity: f(self.particles.gravity, 0.0, 2.0, 1.0), + gravity: clamp_finite(self.particles.gravity, 0.0, 2.0, 1.0), }, ..self.clone() } @@ -323,6 +399,15 @@ impl BrushSettings { #[cfg(test)] mod tests { + #[test] + fn uv_stamp_radius_follows_pen_pressure() { + let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() }; + assert!((b.uv_stamp_radius(1.0) - 0.2).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.5) - 0.15).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.0) - 0.1).abs() < 1e-6); + assert!((b.uv_stamp_radius(7.0) - 0.2).abs() < 1e-6, "pressure clamps to 1"); + } + use super::*; #[test] diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..88e68e1d 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -19,14 +19,16 @@ pub mod path; pub mod pickup; pub mod presets; pub mod raster; +pub mod stamp_source; pub mod stroke; pub mod text; pub mod visibility; -pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha}; +pub use brush::{Alignment, BrushAlpha, BrushSettings, FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Particles, Shape, Symmetry, image_alpha}; pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask}; -pub use path::{Lasso, spline}; +pub use path::{Lasso, spline, spline_segments}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; +pub use stamp_source::StampSource; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; -pub use visibility::EyeDepth; +pub use visibility::{EyeDepth, screen_point}; diff --git a/crates/paint/src/particles.rs b/crates/paint/src/particles.rs index 64ec2dde..51c3d53c 100644 --- a/crates/paint/src/particles.rs +++ b/crates/paint/src/particles.rs @@ -78,18 +78,16 @@ mod tests { #[test] fn particles_slide_down_a_wall_deterministically() { - // A vertical wall: the plane rotated to face +Z. - let mut m = primitives::plane(2.0, 8); - for p in &mut m.positions { - *p = Vec3::new(p.x, -p.z, 0.0); + // A vertical wall: the plane rotated to face +Z + let mut mesh = primitives::plane(2.0, 8); + for position in &mut mesh.positions { + *position = Vec3::new(position.x, -position.z, 0.0); } - for n in &mut m.normals { - *n = Vec3::Z; - } - let bvh = Bvh::new(&m); - let cam = OrbitCamera::default(); - let ctx = PickCtx { mesh: &m, bvh: &bvh, camera: &cam, viewport: Vec2::new(100.0, 100.0) }; - let s = Stamp { + mesh.normals.fill(Vec3::Z); + let bvh = Bvh::new(&mesh); + let camera = OrbitCamera::default(); + let context = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(100.0, 100.0) }; + let stamp = Stamp { center: Vec3::ZERO, normal: Vec3::Z, tangent: Vec3::X, @@ -99,14 +97,16 @@ mod tests { hardness: 0.5, depth: 1.0, seed: 3, - copy: false, + source: None, }; - let p = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; - let a = emit(&ctx, &p, &s); - assert_eq!(a, emit(&ctx, &p, &s)); - assert_eq!(a.len(), 80); - let lowest = a.iter().map(|d| d.center.y).fold(f32::MAX, f32::min); + let particles = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; + + let dabs = emit(&context, &particles, &stamp); + + assert_eq!(dabs, emit(&context, &particles, &stamp)); + assert_eq!(dabs.len(), 80); + let lowest = dabs.iter().map(|d| d.center.y).fold(f32::MAX, f32::min); assert!(lowest < -0.4, "{lowest}"); - assert!(a.iter().all(|d| d.center.z.abs() < 1e-3)); + assert!(dabs.iter().all(|d| d.center.z.abs() < 1e-3)); } } diff --git a/crates/paint/src/path.rs b/crates/paint/src/path.rs index fe483ee0..6614857b 100644 --- a/crates/paint/src/path.rs +++ b/crates/paint/src/path.rs @@ -6,30 +6,44 @@ use texturecraft_geom::glam::Vec2; /// Most samples per curve segment. const MAX_SEGMENT_SAMPLES: f32 = 1024.0; -/// A Catmull-Rom spline through `points`, sampled about every `step` units. Closed curves wrap -/// back to the first point; the result starts at the first point. +/// A Catmull-Rom spline through `points`, sampled about every `step` units, starting on the first point (closed curves end there too) pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec { - let n = points.len(); - if n < 2 { - return points.to_vec(); + let mut out: Vec = points.first().copied().into_iter().collect(); + for segment in segment_samples(points, closed, step) { + out.extend(segment); } - let at = |i: isize| { + out +} + +/// [`spline`]'s samples per segment: segment `s` holds those after point `s`, up to and including the next point +pub fn spline_segments(points: &[Vec2], closed: bool, step: f32) -> Vec> { + segment_samples(points, closed, step).map(Iterator::collect).collect() +} + +/// Stream samples so a flat curve does not allocate and retain every segment alongside its output +fn segment_samples(points: &[Vec2], closed: bool, step: f32) -> impl Iterator> + '_ { + let n = points.len(); + let at = move |i: isize| { let i = if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) }; points.get(i as usize).copied().unwrap_or_default() }; let step = if step.is_finite() && step > 1e-6 { step } else { 1.0 }; - let segments = if closed { n } else { n - 1 } as isize; - let mut out = vec![at(0)]; - for s in 0..segments { + let segments = if n < 2 { + 0 + } else if closed { + n + } else { + n - 1 + } as isize; + (0..segments).map(move |s| { let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2)); let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize; - for j in 1..=k { + (1..=k).map(move |j| { let t = j as f32 / k as f32; let (t2, t3) = (t * t, t * t * t); - out.push(0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3)); - } - } - out + 0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3) + }) + }) } /// A closed polygon's coverage: 1 inside, 0 outside, a one-unit ramp across the edge. diff --git a/crates/paint/src/raster.rs b/crates/paint/src/raster.rs index f53fd7fc..b033538b 100644 --- a/crates/paint/src/raster.rs +++ b/crates/paint/src/raster.rs @@ -82,6 +82,28 @@ impl StrokeCanvas { } } +/// Most a texel's eye distance may exceed the nearest surface in its 3×3 pixel neighbourhood, in pixels along the surface +const NEIGHBOUR_REACH: f32 = 1.5; + +/// Facing (cosine) below which the allowance stops growing +const MIN_FACING: f32 = 0.05; + +/// Height of the view in normalized device coordinates (−1 to 1) +const NDC_HEIGHT: f32 = 2.0; + +/// How far toward the eye to test a texel turned `facing` away: at grazing angles the neighbouring pixels of the same surface are much nearer, and the depth test would speckle +fn grazing_allowance(depth: &EyeDepth, point: Vec3, facing: f32, pixels_per_unit: f32) -> f32 { + // Back faces get none, so painting with culling off doesn't reach through thin parts + if facing <= 0.0 { + return 0.0; + } + + let clip_w = (depth.view_proj * point.extend(1.0)).w.max(0.0); + let world_per_pixel = clip_w * NDC_HEIGHT / pixels_per_unit; + let facing = facing.clamp(MIN_FACING, 1.0); + world_per_pixel * NEIGHBOUR_REACH * (1.0 - facing * facing).sqrt() / facing +} + /// What the rasterizer reads. pub struct RasterCtx<'a> { pub mesh: &'a Mesh, @@ -103,28 +125,37 @@ fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { } /// Accumulate `stamps` into `canvas` ("over": `m = a + m·(1 − a)`). -pub fn rasterize(canvas: &mut StrokeCanvas, ctx: &RasterCtx, stamps: &[Stamp]) { - let (w, h) = (ctx.gbuf.width, ctx.gbuf.height); - canvas.fit(ctx.gbuf); - let fade_lo = ctx.angle_fade.1.to_radians().cos(); - let fade_hi = ctx.angle_fade.0.to_radians().cos(); - let mut tris = Vec::new(); - for s in stamps { - if s.radius.is_nan() || s.radius <= 0.0 || !s.center.is_finite() { +pub fn rasterize(canvas: &mut StrokeCanvas, context: &RasterCtx, stamps: &[Stamp]) { + let (width, height) = (context.gbuf.width, context.gbuf.height); + canvas.fit(context.gbuf); + let fade_lo = context.angle_fade.1.to_radians().cos(); + let fade_hi = context.angle_fade.0.to_radians().cos(); + + // The camera scale is shared by every candidate texel in this batch + let pixels_per_unit = context.depth.map_or(1.0, |depth| { + let ndc_per_unit = depth.view_proj.row(1).truncate().length(); + (depth.height as f32 * ndc_per_unit).max(f32::EPSILON) + }); + let mut triangles = Vec::new(); + for stamp in stamps { + if stamp.radius.is_nan() || stamp.radius <= 0.0 || !stamp.center.is_finite() { continue; } - let ext = Vec3::splat(s.radius * s.depth.max(1.0) * 1.42); - tris.clear(); - ctx.bvh.query_box(s.center - ext, s.center + ext, |t| tris.push(t)); - // Each texel belongs to one triangle, so triangles scan independently (in parallel for - // large stamps); stamp alphas combine commutatively, so the order does not matter. - let scan = |&t: &u32| scan_triangle(ctx, s, t, w, h, fade_lo, fade_hi); - let parts: Vec = if tris.len() > 16 { tris.par_iter().filter_map(scan).collect() } else { tris.iter().filter_map(scan).collect() }; - // The stamp center in texels: the footprint texel nearest to it on the surface. + + let extent = Vec3::splat(stamp.radius * stamp.depth.max(1.0) * 1.42); + triangles.clear(); + context.bvh.query_box(stamp.center - extent, stamp.center + extent, |triangle| triangles.push(triangle)); + + // Each texel belongs to one triangle, so large stamps can scan triangles in parallel + let scan = |&triangle: &u32| scan_triangle(context, stamp, triangle, width, height, fade_lo, fade_hi, pixels_per_unit); + let parts: Vec = + if triangles.len() > 16 { triangles.par_iter().filter_map(scan).collect() } else { triangles.iter().filter_map(scan).collect() }; + + // The footprint texel nearest the stamp center supplies the pickup's center let mut center = ([0.0f32; 2], f32::MAX); - for (texels, c) in parts { - if c.1 < center.1 { - center = c; + for (texels, nearest) in parts { + if nearest.1 < center.1 { + center = nearest; } canvas.texels.extend(texels); } @@ -136,69 +167,91 @@ pub fn rasterize(canvas: &mut StrokeCanvas, ctx: &RasterCtx, stamps: &[Stamp]) { type TriTexels = (Vec<(u32, u32, f32)>, ([f32; 2], f32)); #[allow(clippy::too_many_arguments)] -fn scan_triangle(ctx: &RasterCtx, s: &Stamp, t: u32, w: u32, h: u32, fade_lo: f32, fade_hi: f32) -> Option { - if ctx.mesh.material_of(t as usize) != Some(ctx.material) { +fn scan_triangle( + context: &RasterCtx, + stamp: &Stamp, + triangle: u32, + width: u32, + height: u32, + fade_lo: f32, + fade_hi: f32, + pixels_per_unit: f32, +) -> Option { + if context.mesh.material_of(triangle as usize) != Some(context.material) { return None; } - let [a, b, c] = ctx.mesh.tri(t as usize)?; - let (ua, ub, uc) = (ctx.mesh.uvs.get(a)?, ctx.mesh.uvs.get(b)?, ctx.mesh.uvs.get(c)?); - let (pa, pb, pc) = (ctx.mesh.positions.get(a)?, ctx.mesh.positions.get(b)?, ctx.mesh.positions.get(c)?); - let (na, nb, nc) = (ctx.mesh.normals.get(a)?, ctx.mesh.normals.get(b)?, ctx.mesh.normals.get(c)?); - let x0 = (ua.x.min(ub.x).min(uc.x) * w as f32).floor().max(0.0) as u32; - let x1 = ((ua.x.max(ub.x).max(uc.x) * w as f32).ceil().max(0.0) as u32).min(w); - let y0 = (ua.y.min(ub.y).min(uc.y) * h as f32).floor().max(0.0) as u32; - let y1 = ((ua.y.max(ub.y).max(uc.y) * h as f32).ceil().max(0.0) as u32).min(h); - // Stamp radius in texels on this triangle: texel area over world area. - let uv_area = (*ub - *ua).perp_dot(*uc - *ua).abs() * w as f32 * h as f32; - let world_area = (*pb - *pa).cross(*pc - *pa).length(); - let shape = ctx.shape.at_radius(s.radius * (uv_area / world_area).sqrt()); + + let [first, second, third] = context.mesh.tri(triangle as usize)?; + let (uv_a, uv_b, uv_c) = (context.mesh.uvs.get(first)?, context.mesh.uvs.get(second)?, context.mesh.uvs.get(third)?); + let (position_a, position_b, position_c) = (context.mesh.positions.get(first)?, context.mesh.positions.get(second)?, context.mesh.positions.get(third)?); + let (normal_a, normal_b, normal_c) = (context.mesh.normals.get(first)?, context.mesh.normals.get(second)?, context.mesh.normals.get(third)?); + let x0 = (uv_a.x.min(uv_b.x).min(uv_c.x) * width as f32).floor().max(0.0) as u32; + let x1 = ((uv_a.x.max(uv_b.x).max(uv_c.x) * width as f32).ceil().max(0.0) as u32).min(width); + let y0 = (uv_a.y.min(uv_b.y).min(uv_c.y) * height as f32).floor().max(0.0) as u32; + let y1 = ((uv_a.y.max(uv_b.y).max(uv_c.y) * height as f32).ceil().max(0.0) as u32).min(height); + + // Stamp radius in texels on this triangle: texel area over world area + let uv_area = (*uv_b - *uv_a).perp_dot(*uv_c - *uv_a).abs() * width as f32 * height as f32; + let world_area = (*position_b - *position_a).cross(*position_c - *position_a).length(); + let shape = context.shape.at_radius(stamp.radius * (uv_area / world_area).sqrt()); + let mut texels = Vec::new(); let mut center = ([0.0f32; 2], f32::MAX); + for y in y0..y1 { for x in x0..x1 { - let i = (y * w + x) as usize; - if ctx.gbuf.tri.get(i).copied().unwrap_or(NO_TRI) != t { + let texel = (y * width + x) as usize; + if context.gbuf.tri.get(texel).copied().unwrap_or(NO_TRI) != triangle { continue; } - let Some([b1, b2]) = ctx.gbuf.bary.get(i).copied() else { continue }; + + let Some([b1, b2]) = context.gbuf.bary.get(texel).copied() else { continue }; let b0 = 1.0 - b1 - b2; - let p = *pa * b0 + *pb * b1 + *pc * b2; - let d = p - s.center; - let lx = d.dot(s.tangent) / s.radius; - let ly = d.dot(s.bitangent) / s.radius; - if lx * lx + ly * ly > 2.0 { + let position = *position_a * b0 + *position_b * b1 + *position_c * b2; + let offset = position - stamp.center; + let local_x = offset.dot(stamp.tangent) / stamp.radius; + let local_y = offset.dot(stamp.bitangent) / stamp.radius; + if local_x * local_x + local_y * local_y > 2.0 { continue; } - if d.dot(s.normal).abs() > s.radius * s.depth { + + if offset.dot(stamp.normal).abs() > stamp.radius * stamp.depth { continue; } - let dist = d.length_squared(); - if dist < center.1 { - center = ([x as f32 + 0.5, y as f32 + 0.5], dist); + + let distance_squared = offset.length_squared(); + if distance_squared < center.1 { + center = ([x as f32 + 0.5, y as f32 + 0.5], distance_squared); } - let n = (*na * b0 + *nb * b1 + *nc * b2).try_normalize().unwrap_or(s.normal); - let to_eye = (ctx.eye - p).try_normalize().unwrap_or(n); - let facing = n.dot(to_eye); - // Symmetry copies paint where the camera may not see (the back of the model). - let culled = ctx.backface_culling && !s.copy; - if culled && facing <= 0.0 { + + let normal = (*normal_a * b0 + *normal_b * b1 + *normal_c * b2).try_normalize().unwrap_or(stamp.normal); + if normal.dot(stamp.normal) <= 0.0 { continue; } - if n.dot(s.normal) <= 0.0 { + + // Allow half the stamp depth when the mirrored point is off an asymmetric surface + let (seen, seen_normal) = stamp.source.map_or((position, normal), |source| (source.point(position), source.direction(normal))); + let off_surface = if stamp.source.is_some() { stamp.radius * stamp.depth } else { 0.0 }; + let to_eye = (context.eye - seen).try_normalize().unwrap_or(seen_normal); + let facing = seen_normal.dot(to_eye); + if context.backface_culling && facing <= 0.0 { continue; } - if let Some(depth) = ctx.depth.filter(|_| !s.copy) - && !depth.visible(p) + + if let Some(depth) = context.depth + && !depth.visible(seen + to_eye * (grazing_allowance(depth, seen, facing, pixels_per_unit) + off_surface)) { continue; } - let fade = if culled { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 }; - let a = shape.sample(lx, ly, s.hardness, s.seed) * s.flow * fade; - if a > 0.0 { - texels.push((x, y, a)); + + let fade = if context.backface_culling { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 }; + let alpha = shape.sample(local_x, local_y, stamp.hardness, stamp.seed) * stamp.flow * fade; + if alpha > 0.0 { + texels.push((x, y, alpha)); } } } + (center.1 < f32::MAX || !texels.is_empty()).then_some((texels, center)) } @@ -257,7 +310,7 @@ mod tests { hardness: 0.9, depth: 1.0, seed: 0, - copy: false, + source: None, }; rasterize(&mut canvas, &ctx, &[st]); // Plane is 2 units over 128 texels: radius 0.25 = 16 texels around the center (64, 64). diff --git a/crates/paint/src/stamp_source.rs b/crates/paint/src/stamp_source.rs new file mode 100644 index 00000000..5f56e435 --- /dev/null +++ b/crates/paint/src/stamp_source.rs @@ -0,0 +1,24 @@ +//! Where a symmetry copy of a stamp comes from + +use texturecraft_geom::glam::{Mat3, Vec3}; + +/// The map from a symmetry copy back to its source stamp: a copy paints where its source would be painted +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StampSource { + /// The point the symmetry maps turn and mirror about + pub origin: Vec3, + /// The inverse of the copy's linear map (mirrors and turns, so its transpose) + pub to_source: Mat3, +} + +impl StampSource { + /// The source's point for a point of the copy + pub fn point(&self, copy_point: Vec3) -> Vec3 { + self.origin + self.to_source * (copy_point - self.origin) + } + + /// The source's direction for a direction of the copy + pub fn direction(&self, copy_direction: Vec3) -> Vec3 { + self.to_source * copy_direction + } +} diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index 6aacb737..9cc3972b 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -1,11 +1,12 @@ //! From pointer samples to stamps: picking, lazy mouse, spacing along the surface, stamp //! frames, jitter and symmetry. -use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::glam::{Mat3, Quat, Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, surface_at}; use texturecraft_texel::noise::pcg3d; use crate::brush::{Alignment, BrushSettings}; +use crate::stamp_source::StampSource; /// Scene access for picking. pub struct PickCtx<'a> { @@ -37,7 +38,20 @@ pub fn pick(ctx: &PickCtx, screen: Vec2) -> Option { Some(SurfaceHit { pos: s.pos, nrm: s.nrm, tri: hit.tri, uv: s.uv, material: ctx.mesh.material_of(hit.tri as usize).unwrap_or(0), screen }) } -/// One brush dab in world space. +/// Random channels of a stamp's jitters (each draws its own number from the stamp's seed) +const JITTER_ANGLE: u32 = 1; +const JITTER_SIZE: u32 = 2; +const JITTER_ACROSS: u32 = 3; +const JITTER_ALONG: u32 = 4; +const JITTER_FLOW: u32 = 5; + +/// Full angle jitter turns a stamp this far either way (degrees) +const HALF_TURN_DEGREES: f32 = 180.0; + +/// Smallest size jitter leaves a stamp, as a fraction of its radius +const MIN_JITTERED_SIZE: f32 = 0.05; + +/// One brush dab in world space #[derive(Clone, Copy, Debug, PartialEq)] pub struct Stamp { pub center: Vec3, @@ -47,12 +61,12 @@ pub struct Stamp { pub radius: f32, pub flow: f32, pub hardness: f32, - /// Half-depth of the stamp volume relative to the radius. + /// Half-depth of the stamp volume relative to the radius pub depth: f32, - /// Varies procedural alphas per stamp. + /// Varies procedural alphas per stamp pub seed: u32, - /// A symmetry copy: it paints where symmetry puts it, whether the camera sees that or not. - pub copy: bool, + /// A symmetry copy's way back to its source: it paints where the source would, mirrored + pub source: Option, } /// An in-progress stroke. @@ -168,66 +182,87 @@ impl Stroke { self.last = Some(hit); } + /// The next stamp at `hit`: oriented to the surface or the camera, then jittered fn stamp(&mut self, ctx: &PickCtx, hit: &SurfaceHit, radius: f32) -> Stamp { - let s = &self.settings; - let n = self.count; + let settings = &self.settings; + let seed = self.count; self.count = self.count.wrapping_add(1); - let jitter = |k: u32, amount: f32| if amount > 0.0 { (rand01(n, k) * 2.0 - 1.0) * amount } else { 0.0 }; - let normal = match s.alignment { + let jitter = |channel: u32, amount: f32| if amount > 0.0 { (rand01(seed, channel) * 2.0 - 1.0) * amount } else { 0.0 }; + + // Frame: the normal, and an up direction from the camera or the stroke's path + let normal = match settings.alignment { Alignment::Tangent => hit.nrm, Alignment::Camera => -ctx.camera.forward(), }; - let cam_up = { - let f = ctx.camera.forward(); - let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); - right.cross(f) + let camera_up = { + let forward = ctx.camera.forward(); + let right = forward.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + right.cross(forward) }; - let up_src = if s.follow_path { self.last_dir.unwrap_or(cam_up) } else { cam_up }; - let up = (up_src - normal * normal.dot(up_src)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); - let tangent0 = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); - let angle = (s.angle + jitter(1, s.jitter_angle) * 180.0).to_radians(); - let q = Quat::from_axis_angle(normal, angle); - let tangent = q * tangent0; + let up_source = if settings.follow_path { self.last_dir.unwrap_or(camera_up) } else { camera_up }; + let up = (up_source - normal * normal.dot(up_source)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); + let unturned_tangent = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); + + // Jitter: angle, size, position and flow + let angle = (settings.angle + jitter(JITTER_ANGLE, settings.jitter_angle) * HALF_TURN_DEGREES).to_radians(); + let turn = Quat::from_axis_angle(normal, angle); + let tangent = turn * unturned_tangent; let bitangent = normal.cross(tangent); - let r = radius * (1.0 + jitter(2, s.jitter_size)).max(0.05); - let offset = (tangent * jitter(3, 1.0) + bitangent * jitter(4, 1.0)) * s.jitter_position * radius; - let flow = (s.flow * (1.0 - jitter(5, s.jitter_flow).abs())).clamp(0.0, 1.0); - Stamp { center: hit.pos + offset, normal, tangent, bitangent, radius: r, flow, hardness: s.hardness, depth: s.depth, seed: n, copy: false } + let jittered_radius = radius * (1.0 + jitter(JITTER_SIZE, settings.jitter_size)).max(MIN_JITTERED_SIZE); + let offset = (tangent * jitter(JITTER_ACROSS, 1.0) + bitangent * jitter(JITTER_ALONG, 1.0)) * settings.jitter_position * radius; + let flow = (settings.flow * (1.0 - jitter(JITTER_FLOW, settings.jitter_flow).abs())).clamp(0.0, 1.0); + + Stamp { + center: hit.pos + offset, + normal, + tangent, + bitangent, + radius: jittered_radius, + flow, + hardness: settings.hardness, + depth: settings.depth, + seed, + source: None, + } } - /// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and - /// its mirrors. - fn mirrors(&self, s: &Stamp) -> Vec { - let sym = self.settings.symmetry; - if !sym.any() { + /// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and its mirrors + fn mirrors(&self, stamp: &Stamp) -> Vec { + let symmetry = self.settings.symmetry; + if !symmetry.any() { return Vec::new(); } - let mut out = Vec::new(); - for sign in sym.mirror_signs().skip(1) { - let normal = s.normal * sign; - let tangent = s.tangent * sign; - out.push(Stamp { center: self.center + (s.center - self.center) * sign, normal, tangent, bitangent: normal.cross(tangent), copy: true, ..*s }); + let origin = symmetry.origin(self.center); + let mut copies = Vec::new(); + let mut maps = Vec::new(); + for sign in symmetry.mirror_signs().skip(1) { + let normal = stamp.normal * sign; + let tangent = stamp.tangent * sign; + let map = Mat3::from_diagonal(sign); + let source = Some(StampSource { origin, to_source: map.transpose() }); + copies.push(Stamp { center: origin + (stamp.center - origin) * sign, normal, tangent, bitangent: normal.cross(tangent), source, ..*stamp }); + maps.push(map); } - if sym.radial > 1 { - let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(sym.axis as usize).copied().unwrap_or(Vec3::Y); - let base: Vec = std::iter::once(*s).chain(out.iter().copied()).collect(); + if symmetry.radial_on() { + let axis = symmetry.radial_axis(); + let to_turn: Vec<(Stamp, Mat3)> = std::iter::once((*stamp, Mat3::IDENTITY)).chain(copies.iter().copied().zip(maps)).collect(); - for k in 1..sym.radial { - let q = Quat::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(sym.radial)); - out.extend(base.iter().map(|b| Stamp { - center: self.center + q * (b.center - self.center), - normal: q * b.normal, - tangent: q * b.tangent, - bitangent: q * b.bitangent, - copy: true, - ..*b + for copy in 1..symmetry.radial { + let turn = Quat::from_axis_angle(axis, symmetry.radial_angle(copy)); + copies.extend(to_turn.iter().map(|(base, map)| Stamp { + center: origin + turn * (base.center - origin), + normal: turn * base.normal, + tangent: turn * base.tangent, + bitangent: turn * base.bitangent, + source: Some(StampSource { origin, to_source: (Mat3::from_quat(turn) * *map).transpose() }), + ..*base })); } } - out + copies } pub fn last_hit(&self) -> Option { @@ -296,6 +331,61 @@ mod tests { assert_eq!(s.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 8); } + #[test] + fn symmetry_mirrors_about_the_moved_plane() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry.x = true; + settings.symmetry.offset = [0.25, 0.0, 0.0]; + let mut stroke = Stroke::new(&settings, &mesh); + let stamps = stroke.add(&ctx, Vec2::new(250.0, 200.0), 1.0); + assert_eq!(stamps.len(), 2, "one stamp and its copy"); + let (painted, copy) = (stamps[0], stamps[1]); + + // Mirrored about x = 0.25 instead of the mesh center (x = 0) + assert!((painted.center.x + copy.center.x - 0.5).abs() < 1e-4, "{} {}", painted.center, copy.center); + assert!((painted.center.y - copy.center.y).abs() < 1e-4 && (painted.center.z - copy.center.z).abs() < 1e-4); + } + + #[test] + fn default_symmetry_copies_match_the_mesh_centered_formula_bit_for_bit() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry = crate::brush::Symmetry { x: true, y: true, radial: 3, axis: 1, ..settings.symmetry }; + let mut stroke = Stroke::new(&settings, &mesh); + let stamps = stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0); + + // Copies as painting computed them before the plane could move: mirrors, then radial turns of each + let (lo, hi) = mesh.bounds(); + let center = (lo + hi) * 0.5; + let source = stamps[0].center; + let mirrored = [Vec3::new(-1.0, 1.0, 1.0), Vec3::new(1.0, -1.0, 1.0), Vec3::new(-1.0, -1.0, 1.0)].map(|sign| center + (source - center) * sign); + let to_turn: Vec = std::iter::once(source).chain(mirrored).collect(); + let turned = (1..3u8).flat_map(|copy| { + let turn = Quat::from_axis_angle(Vec3::Y, f32::from(copy) * std::f32::consts::TAU / 3.0); + to_turn.iter().map(move |point| center + turn * (*point - center)).collect::>() + }); + let expected: Vec = mirrored.into_iter().chain(turned).collect(); + + let copies: Vec = stamps[1..].iter().map(|stamp| stamp.center).collect(); + assert_eq!(copies, expected); + } + + #[test] + fn a_zero_angle_span_paints_no_radial_copies() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry.radial = 6; + settings.symmetry.angle_span = 0.0; + let mut stroke = Stroke::new(&settings, &mesh); + + // Six copies with no angle between them would all paint over the stroke + assert_eq!(stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 1); + } + #[test] fn radial_symmetry_spreads_copies_around_the_axis() { let (m, b, c) = ctx_parts(); 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/Cargo.toml b/crates/render/Cargo.toml index 080f12ba..ee15b556 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,6 +19,7 @@ bytemuck = { workspace = true } half = { workspace = true } log = { workspace = true } rayon = { workspace = true } +serde = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = "0.4" diff --git a/crates/render/src/bake_overlay.rs b/crates/render/src/bake_overlay.rs new file mode 100644 index 00000000..31d8135d --- /dev/null +++ b/crates/render/src/bake_overlay.rs @@ -0,0 +1,24 @@ +//! One overlay of bake mode's 3D view: whether it shows, its color and its opacity + +/// Whether a part of the bake setup shows in the 3D view, and in which color and opacity +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct BakeOverlay { + pub shown: bool, + /// Linear RGB + pub color: [f32; 3], + /// 0 transparent, 1 opaque; the matching error mixes into the high poly by it + pub opacity: f32, +} + +impl BakeOverlay { + /// A hidden overlay in `color`, fully opaque + pub const fn hidden(color: [f32; 3]) -> Self { + Self { shown: false, color, opacity: 1.0 } + } + + /// The overlay's shader globals: rgb its color, a its opacity (0 while hidden) + pub(crate) fn globals(&self) -> [f32; 4] { + let [red, green, blue] = self.color; + [red, green, blue, if self.shown { self.opacity.clamp(0.0, 1.0) } else { 0.0 }] + } +} diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs new file mode 100644 index 00000000..a03fbfd1 --- /dev/null +++ b/crates/render/src/bake_visualization.rs @@ -0,0 +1,58 @@ +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the missing seams and the low poly + +use crate::bake_overlay::BakeOverlay; +use crate::neutral_material::NeutralMaterial; + +/// Default overlay colors, linear RGB +const HIGH_POLY_COLOR: [f32; 3] = [0.0, 0.216, 0.521]; +const MATCHING_ERROR_COLOR: [f32; 3] = [1.0, 0.0, 0.0]; +const CAGE_SURFACE_COLOR: [f32; 3] = [0.604, 0.451, 0.216]; +const CAGE_WIRE_COLOR: [f32; 3] = [0.604, 0.604, 0.604]; +const MISSING_SEAM_COLOR: [f32; 3] = [0.451, 0.0, 0.451]; +const LOW_POLY_COLOR: [f32; 3] = [0.216, 0.216, 0.216]; + +/// Which parts of the bake setup the 3D view draws, and how +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BakeVisualization { + pub high_poly: BakeOverlay, + /// Tints the high poly where the bake's rays miss it + pub matching_error: BakeOverlay, + pub cage_surface: BakeOverlay, + pub cage_wire: BakeOverlay, + /// The low poly's hard edges that are not UV seams + pub missing_seams: BakeOverlay, + /// The low poly; its color is the neutral material's color + pub low_poly: BakeOverlay, + /// Shade the low poly with this plain material instead of its painted one + pub neutral: Option, + /// Draw the cage and high poly of only this texture set (the high poly's vertices of other sets come marked hidden) + pub only_set: Option, +} + +impl Default for BakeVisualization { + /// Every part hidden, in its default color, the low poly with its painted material + fn default() -> Self { + Self { + high_poly: BakeOverlay::hidden(HIGH_POLY_COLOR), + matching_error: BakeOverlay::hidden(MATCHING_ERROR_COLOR), + cage_surface: BakeOverlay::hidden(CAGE_SURFACE_COLOR), + cage_wire: BakeOverlay::hidden(CAGE_WIRE_COLOR), + missing_seams: BakeOverlay::hidden(MISSING_SEAM_COLOR), + low_poly: BakeOverlay::hidden(LOW_POLY_COLOR), + neutral: None, + only_set: None, + } + } +} + +impl BakeVisualization { + /// Whether any part of the cage shows + pub fn cage_shown(&self) -> bool { + self.cage_surface.shown || self.cage_wire.shown + } + + /// The neutral material while the low poly shows with it + pub fn shown_neutral(&self) -> Option { + self.neutral.filter(|_| self.low_poly.shown) + } +} diff --git a/crates/render/src/cage_geometry.rs b/crates/render/src/cage_geometry.rs new file mode 100644 index 00000000..95b0ec6f --- /dev/null +++ b/crates/render/src/cage_geometry.rs @@ -0,0 +1,13 @@ +//! A texture set's cage as the renderer takes it + +use texturecraft_geom::glam::Vec3; + +/// A cage for [`crate::Renderer::set_bake_cage`]: three corners per low-poly triangle, and lines as corner pairs +#[derive(Clone, Copy, Debug)] +pub struct CageGeometry<'a> { + pub corners: &'a [Vec3], + /// The low poly's polygon edges, for the wireframe + pub edges: &'a [[u32; 2]], + /// The low poly's hard edges without a UV seam + pub missing_seams: &'a [[u32; 2]], +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs new file mode 100644 index 00000000..98b7b15e --- /dev/null +++ b/crates/render/src/cage_gpu.rs @@ -0,0 +1,12 @@ +/// 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, + /// Corner pairs along the low poly's hard edges without a UV seam + pub(crate) missing_seams: wgpu::Buffer, + pub(crate) missing_seam_index_count: u32, +} diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 08fc76eb..f478f77a 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -10,7 +10,8 @@ use std::sync::{Arc, OnceLock}; use bytemuck::{Pod, Zeroable}; use rayon::prelude::*; use texturecraft_bake::BakeError; -use texturecraft_bake::rays::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh, Tracer}; +use texturecraft_bake::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh, Tracer}; +use texturecraft_core::{AmbientOcclusionAttenuation, BackfaceMode}; use texturecraft_geom::Hit; use texturecraft_geom::glam::Vec3; @@ -42,6 +43,10 @@ struct Params { lanes: u32, /// First result row of the pass. out: u32, + min_distance: f32, + attenuation: u32, + ground_height: f32, + backface_mode: u32, } struct Gpu { @@ -152,7 +157,9 @@ impl Tracer for GpuBaker { } let base = ((nodes.len() / 2) as u32, (tris.len() / 4) as u32); roots.push(base.0); - let (n, t) = bvh_rows(m.bvh, base, |o| ([m.keys.get(o).copied().unwrap_or(ANY), 0, 0], [0, 0, 0, o as u32])); + let (n, t) = bvh_rows(m.bvh, base, |o| { + ([m.keys.get(o).copied().unwrap_or(ANY), u32::from(m.backface_culling.get(o).copied().unwrap_or(false)), 0], [0, 0, 0, o as u32]) + }); nodes.extend(n); tris.extend(t); } @@ -232,10 +239,17 @@ impl GpuScene<'_> { } /// Run `pipeline` over `n` items (`items`: their rows) once per pass in one submission, and - /// read back one result row per item and pass (pass after pass). - fn run(&mut self, pipeline: &wgpu::ComputePipeline, items: &[[u32; 4]], n: usize, passes: &[Pass]) -> Result, BakeError> { + /// hand `read` one result row per item and pass (pass after pass). + fn run( + &mut self, + pipeline: &wgpu::ComputePipeline, + items: &[u8], + n: usize, + passes: &[Pass], + read: impl FnOnce(&[[u32; 4]]) -> R, + ) -> Result { if n == 0 || passes.is_empty() { - return Ok(Vec::new()); + return Ok(R::default()); } let g = self.gpu; let max_groups = g.device.limits().max_compute_workgroups_per_dimension as usize; @@ -250,14 +264,14 @@ impl GpuScene<'_> { blocks.resize(blocks.len().next_multiple_of(g.stride), 0); } } - let (in_bytes, out_bytes) = (items.len() as u64 * 16, (n * passes.len()) as u64 * 16); + let (in_bytes, out_bytes) = (items.len() as u64, (n * passes.len()) as u64 * 16); if in_bytes.max(out_bytes) > g.max_buffer() { return Err(err("a batch exceeds this GPU's buffer limit")); } let io = self.io(in_bytes, out_bytes, blocks.len() as u64)?; let dev = &g.device; scoped(dev, "GPU baking: dispatch", || { - g.queue.write_buffer(&io.items, 0, bytemuck::cast_slice(items)); + g.queue.write_buffer(&io.items, 0, items); g.queue.write_buffer(&io.params, 0, &blocks); let mut enc = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_bake") }); { @@ -280,7 +294,7 @@ impl GpuScene<'_> { dev.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).map_err(err)?; rx.recv().map_err(err)?.map_err(err)?; let data = slice.get_mapped_range().map_err(err)?; - let out = bytemuck::try_cast_slice::(&data).map(<[_]>::to_vec).map_err(err); + let out = bytemuck::try_cast_slice::(&data).map(read).map_err(err); drop(data); io.staging.unmap(); out @@ -293,12 +307,16 @@ fn row(v: Vec3, w: u32) -> [u32; 4] { } impl RayScene for GpuScene<'_> { - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> { - let items: Vec<[u32; 4]> = rays.par_iter().flat_map_iter(|r| [row(r.origin, r.tmax.to_bits()), row(r.dir, r.key)]).collect(); - let pass = Pass { params: Params { root: self.root(mesh)?, ..Params::default() }, per_dispatch: RAYS_PER_DISPATCH, per_group: WORKGROUP as usize }; + fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError> { + let pass = Pass { + params: Params { root: self.root(mesh)?, flags: u32::from(ignore_backface) * IGNORE_BACKFACE, ..Params::default() }, + per_dispatch: RAYS_PER_DISPATCH, + per_group: WORKGROUP as usize, + }; let gpu = self.gpu; - let out = self.run(&gpu.transfer, &items, rays.len(), &[pass])?; - Ok(out.into_iter().map(|[t, u, v, tri]| (tri != NONE).then(|| Hit { t: f32::from_bits(t), tri, u: f32::from_bits(u), v: f32::from_bits(v) })).collect()) + self.run(&gpu.transfer, bytemuck::cast_slice(rays), rays.len(), &[pass], |out| { + out.par_iter().map(|&[t, u, v, tri]| (tri != NONE).then(|| Hit { t: f32::from_bits(t), tri, u: f32::from_bits(u), v: f32::from_bits(v) })).collect() + }) } fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> { @@ -316,14 +334,24 @@ impl RayScene for GpuScene<'_> { .map(|h| { // A sample's rays spread over `lanes` threads of a workgroup (a power of two). let lanes = h.rays.clamp(1, WORKGROUP).next_power_of_two(); - let flags = [(h.uniform, UNIFORM), (h.ignore_backface, IGNORE_BACKFACE), (h.same_key, SAME_KEY)] - .iter() - .filter(|(on, _)| *on) - .fold(0, |f, (_, b)| f | b); + let flags = + [(h.uniform, UNIFORM), (h.ground_height.is_some(), 8), (h.same_key, SAME_KEY)].iter().filter(|(on, _)| *on).fold(0, |f, (_, b)| f | b); let params = Params { kind: u32::from(h.kind == RayKind::Thickness), rays: h.rays, dmax: h.dmax, + min_distance: h.min_distance, + attenuation: match h.attenuation { + AmbientOcclusionAttenuation::None => 0, + AmbientOcclusionAttenuation::Linear => 1, + AmbientOcclusionAttenuation::Smooth => 2, + }, + ground_height: h.ground_height.unwrap_or(0.0), + backface_mode: match h.ignore_backface { + BackfaceMode::Never => 0, + BackfaceMode::Always => 1, + BackfaceMode::ByMeshName => 2, + }, eps: h.eps, cos_max: h.cos_max, sin_max: h.sin_max, @@ -335,17 +363,22 @@ impl RayScene for GpuScene<'_> { }) .collect(); let gpu = self.gpu; - let out = self.run(&gpu.hemisphere, &items, queries.len(), &passes)?; - Ok(out.chunks(queries.len().max(1)).map(|c| c.iter().map(|v| v.map(f32::from_bits)).collect()).collect()) + self.run(&gpu.hemisphere, bytemuck::cast_slice(&items), queries.len(), &passes, |out| { + out.chunks(queries.len().max(1)).map(|c| c.iter().map(|v| v.map(f32::from_bits)).collect()).collect() + }) } } #[cfg(test)] mod tests { use std::time::Instant; + use texturecraft_core::{ + AmbientOcclusionSettings, BakeAntialiasing, BakeResolution, BentNormalSettings, CageSettings, CommonBakeSettings, CurvatureSettings, HighPolySettings, + ThicknessSettings, + }; use texturecraft_bake::{BakeOutput, BakeRequest, HighPoly, Progress, bake, bake_on}; - use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, RayDistribution, RaySettings, SelfOcclusion}; + use texturecraft_core::{BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, RayDistribution, RaySettings, SelfOcclusion}; use texturecraft_geom::{Bvh, Mesh, primitives}; use super::*; @@ -364,8 +397,9 @@ mod tests { fn run(low: &Mesh, high: Option<&Mesh>, s: &BakeSettings, tracer: Option<&GpuBaker>) -> BakeOutput { let (lb, hb) = (Bvh::new(low), high.map(Bvh::new)); - let high = high.zip(hb.as_ref()).map(|(mesh, bvh)| HighPoly { mesh, bvh, base_color: &[] }); - let req = BakeRequest { mesh: low, bvh: &lb, material: 0, settings: s, high, cage: None, skew: None, tiles: (1, 1) }; + let high = high.zip(hb.as_ref()).map(|(mesh, bvh)| HighPoly { file_ids: &[], mesh, bvh, base_color: &[] }); + let req = + BakeRequest { low_base_color: &[], mesh: low, bvh: &lb, material: 0, settings: s, high, cage: None, skew: None, cage_paint: None, tiles: (1, 1) }; match tracer { Some(t) => bake_on(&req, &Progress::new(), t).unwrap(), None => bake(&req, &Progress::new()).unwrap(), @@ -387,25 +421,61 @@ mod tests { } } + #[test] + fn gpu_respects_secondary_ray_filters_and_ground_plane() { + let Some(gpu) = gpu() else { return }; + + let mut mesh = primitives::material_ball(); + for part in &mut mesh.submeshes { + part.name.push_str("_ignorebf"); + } + let mut settings = BakeSettings::default(); + settings.common.resolution = BakeResolution::R64; + settings.common.apply_diffusion = false; + settings.maps.select([BakedMap::AmbientOcclusion, BakedMap::BentNormal, BakedMap::Thickness]); + settings.high_poly.ignore_backface_suffix = "_ignorebf".into(); + settings.maps.ao.parameters.rays.min_distance = 0.02; + settings.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName; + settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.maps.ao.parameters.ground_plane.offset = 0.1; + settings.maps.bent_normal.parameters.rays.min_distance = 0.02; + settings.maps.bent_normal.parameters.ignore_backface = BackfaceMode::ByMeshName; + settings.maps.thickness.parameters.rays.min_distance = 0.02; + settings.maps.thickness.parameters.self_occlusion = SelfOcclusion::SameMeshName; + for attenuation in [AmbientOcclusionAttenuation::None, AmbientOcclusionAttenuation::Smooth] { + settings.maps.ao.parameters.attenuation = attenuation; + assert_agree(&run(&mesh, None, &settings, None), &run(&mesh, None, &settings, Some(&gpu))); + } + } + #[test] fn gpu_bake_matches_the_cpu() { - let Some(g) = gpu() else { return }; - // Low poly: the material ball (self-occluding); every ray map with its own settings. + let Some(gpu) = gpu() else { return }; + + // Low poly: the material ball (self-occluding); every ray map with its own settings let ball = primitives::material_ball(); let maps = [BakedMap::AmbientOcclusion, BakedMap::BentNormal, BakedMap::Thickness, BakedMap::Position, BakedMap::Curvature]; - let s = BakeSettings { - resolution: 128, - antialiasing: 2, - dilation: 0, - maps: maps.into_iter().collect(), - ao: RaySettings { rays: 24, max_distance: 0.3, spread: 150.0, distribution: RayDistribution::Uniform }, - ao_ignore_backface: true, - bent_normal: RaySettings { rays: 16, ..RaySettings::default() }, - thickness: RaySettings { rays: 20, spread: 90.0, ..RaySettings::default() }, - ..BakeSettings::default() + let settings = { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R128, antialiasing: BakeAntialiasing::Subsampling2x2, dilation: 0, ..base.common }; + base.maps.select(maps); + base.maps.ao.parameters = AmbientOcclusionSettings { + rays: RaySettings { rays: 24, max_distance: 0.3, spread: 150.0, distribution: RayDistribution::Uniform, ..RaySettings::default() }, + ignore_backface: BackfaceMode::Always, + ..base.maps.ao.parameters + }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters }; + base.maps.bent_normal.parameters = + BentNormalSettings { rays: RaySettings { rays: 16, ..RaySettings::default() }, ..base.maps.bent_normal.parameters }; + base.maps.thickness.parameters = + ThicknessSettings { rays: RaySettings { rays: 20, spread: 90.0, ..RaySettings::default() }, ..base.maps.thickness.parameters }; + base }; - assert_agree(&run(&ball, None, &s, None), &run(&ball, None, &s, Some(&g))); - // A bumpy high poly over a sphere, matched by name: the transfer maps and AO on it. + + assert_agree(&run(&ball, None, &settings, None), &run(&ball, None, &settings, Some(&gpu))); + + // A bumpy high poly over a sphere, matched by name: the transfer maps and AO on it let low = primitives::sphere(1.0, 32, 16); let mut high = primitives::sphere(1.0, 128, 64); for p in &mut high.positions { @@ -414,22 +484,35 @@ mod tests { high.compute_normals(); high.compute_tangents(); high.submeshes[0].name = format!("{}_high", low.submeshes[0].name); - let s = BakeSettings { - resolution: 128, - dilation: 0, - maps: [BakedMap::Normal, BakedMap::Height, BakedMap::Id, BakedMap::Opacity, BakedMap::AmbientOcclusion, BakedMap::WorldNormal] - .into_iter() - .collect(), - max_frontal: 0.02, - max_rear: 0.02, - matching: BakeMatch::ByMeshName, - low_suffix: String::new(), - ao: RaySettings { rays: 16, ..RaySettings::default() }, - ao_self_occlusion: SelfOcclusion::SameMeshName, - use_low_as_high: false, - ..BakeSettings::default() + let settings = { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R128, dilation: 0, ..base.common }; + base.maps.select([ + BakedMap::Normal, + BakedMap::Height, + BakedMap::Id, + BakedMap::Opacity, + BakedMap::AmbientOcclusion, + BakedMap::WorldNormal, + BakedMap::Curvature, + ]); + base.cage = CageSettings { max_frontal: 0.02, max_rear: 0.02, ..base.cage }; + base.high_poly = HighPolySettings { + match_mode: texturecraft_core::MeshMatchMode::ByMeshName, + low_suffix: String::new(), + use_low_as_high: false, + ..base.high_poly + }; + base.maps.ao.parameters = AmbientOcclusionSettings { + rays: RaySettings { rays: 16, ..RaySettings::default() }, + self_occlusion: SelfOcclusion::SameMeshName, + ..base.maps.ao.parameters + }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters }; + base }; - assert_agree(&run(&low, Some(&high), &s, None), &run(&low, Some(&high), &s, Some(&g))); + + assert_agree(&run(&low, Some(&high), &settings, None), &run(&low, Some(&high), &settings, Some(&gpu))); } /// `cargo test -p texturecraft-render --release -- --ignored --nocapture gpu_bake_speed` @@ -439,8 +522,24 @@ mod tests { let Some(g) = gpu() else { return }; let ball = primitives::material_ball(); let rays = RaySettings { rays: 64, ..RaySettings::default() }; - let s = BakeSettings { resolution: 2048, ao: rays, thickness: rays, bent_normal: rays, ..BakeSettings::default() }; - run(&ball, None, &BakeSettings { resolution: 64, ..s.clone() }, Some(&g)); + let s = { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R2048, ..base.common }; + base.maps.ao.parameters = AmbientOcclusionSettings { rays, ..base.maps.ao.parameters }; + base.maps.thickness.parameters = ThicknessSettings { rays, ..base.maps.thickness.parameters }; + base.maps.bent_normal.parameters = BentNormalSettings { rays, ..base.maps.bent_normal.parameters }; + base + }; + run( + &ball, + None, + &{ + let mut base = s.clone(); + base.common = CommonBakeSettings { resolution: BakeResolution::R64, ..base.common }; + base + }, + Some(&g), + ); let time = |t: Option<&GpuBaker>| { let start = Instant::now(); let out = run(&ball, None, &s, t); @@ -452,16 +551,20 @@ mod tests { println!("GPU again (warm clocks): {gpu_t2:.2?}"); println!( "material ball 2048², {} maps, 64 rays: CPU {cpu_t:.2?}, {} {gpu_t:.2?}, {:.1}x", - s.maps.len(), + s.maps.enabled().count(), gpu.tracer, cpu_t.as_secs_f64() / gpu_t.as_secs_f64() ); assert_agree(&cpu, &gpu); for maps in [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness]] { - let s = BakeSettings { maps: maps.into_iter().collect(), ..s.clone() }; + let s = { + let mut base = s.clone(); + base.maps.select(maps); + base + }; let start = Instant::now(); run(&ball, None, &s, Some(&g)); - println!("{:?}: {:.2?}", s.maps, start.elapsed()); + println!("{:?}: {:.2?}", s.maps.enabled().collect::>(), start.elapsed()); } } } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 775fc026..601e097e 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -113,6 +113,11 @@ pub struct GpuTracer { env: Option, materials: Option, acc: Option, + /// Keep the preceding size so motion/full-resolution switches can reuse allocations. + spare_acc: Option, + /// How many sets of accumulation buffers were allocated (for tests). + #[cfg(test)] + acc_allocations: u32, scene: Option, bind: Option, samples: u32, @@ -309,6 +314,9 @@ impl GpuTracer { env: None, materials: None, acc: None, + spare_acc: None, + #[cfg(test)] + acc_allocations: 0, scene: None, bind: None, samples: 0, @@ -323,6 +331,7 @@ impl GpuTracer { /// Free the scene and accumulation memory, keeping the compiled pipelines. pub fn release(&mut self) { (self.geometry, self.env, self.materials, self.acc, self.scene, self.bind) = (None, None, None, None, None, None); + self.spare_acc = None; self.samples = 0; } @@ -498,24 +507,42 @@ impl GpuTracer { Ok(true) } - /// Start over at `width × height` (the accumulation buffers are cleared or reallocated). + /// Start over at `width × height`, keeping the active render intact if allocation fails. pub fn reset(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, width: u32, height: u32) -> Result<(), String> { - let (w, h) = (width.clamp(1, 8192), height.clamp(1, 8192)); - self.samples = 0; - if let Some(a) = self.acc.as_ref().filter(|a| (a.width, a.height) == (w, h)) { - for b in &a.acc { - encoder.clear_buffer(b, 0, None); + let (width, height) = (width.clamp(1, 8192), height.clamp(1, 8192)); + let bytes = u64::from(width) * u64::from(height) * 16; + let limits = device.limits(); + + // Reject unsupported sizes before invalidating the displayed render + if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + return Err(format!("a {width}×{height} render exceeds this GPU's buffer limit")); + } + + if let Some(accumulation) = self.acc.as_ref().filter(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { + for buffer in &accumulation.acc { + encoder.clear_buffer(buffer, 0, None); } + + self.samples = 0; return Ok(()); } - self.acc = None; - self.bind = None; - let bytes = u64::from(w) * u64::from(h) * 16; - let limits = device.limits(); - if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { - return Err(format!("a {w}×{h} render exceeds this GPU's buffer limit")); + + // Reused buffers must not retain samples from the previous view + if let Some(spare) = self.spare_acc.take_if(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { + for buffer in spare.acc.iter().chain(&spare.illum) { + encoder.clear_buffer(buffer, 0, None); + } + + self.spare_acc = self.acc.replace(spare); + self.bind = None; + self.samples = 0; + return Ok(()); } - let buf = |label| { + + // Retire the obsolete spare before allocating, but keep the active render until success + self.spare_acc = None; + + let create_buffer = |label| { device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, @@ -523,12 +550,20 @@ impl GpuTracer { mapped_at_creation: false, }) }; - self.acc = Some(scoped(device, "GPU path tracing: accumulation buffers", || Accum { - width: w, - height: h, - acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(buf), - illum: ["tc_illum_a", "tc_illum_b"].map(buf), - })?); + let accumulation = scoped(device, "GPU path tracing: accumulation buffers", || Accum { + width, + height, + acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(create_buffer), + illum: ["tc_illum_a", "tc_illum_b"].map(create_buffer), + })?; + self.spare_acc = self.acc.replace(accumulation); + self.bind = None; + self.samples = 0; + #[cfg(test)] + { + self.acc_allocations += 1; + } + Ok(()) } @@ -800,22 +835,87 @@ mod tests { /// The radiance accumulation, read back. fn accumulation(h: &Headless, t: &GpuTracer) -> Vec<[f32; 4]> { - let acc = t.acc.as_ref().unwrap(); - let bytes = acc.width as u64 * acc.height as u64 * 16; - let staging = h.device.create_buffer(&wgpu::BufferDescriptor { + read_buffer(h, &t.acc.as_ref().unwrap().acc[0]) + } + + /// Read a completed buffer to check its contents across resets and reuse. + fn read_buffer(headless: &Headless, buffer: &wgpu::Buffer) -> Vec<[f32; 4]> { + let bytes = buffer.size(); + let staging = headless.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false, }); - let mut enc = h.device.create_command_encoder(&Default::default()); - enc.copy_buffer_to_buffer(&acc.acc[0], 0, &staging, 0, bytes); - h.queue.submit([enc.finish()]); + let mut encoder = headless.device.create_command_encoder(&Default::default()); + encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, bytes); + headless.queue.submit([encoder.finish()]); staging.slice(..).map_async(wgpu::MapMode::Read, |_| {}); - h.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap(); + headless.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap(); + bytemuck::cast_slice(&staging.slice(..).get_mapped_range().unwrap()).to_vec() } + /// Two cached sizes reuse cleared buffers, and leaving Rendering mode releases both. + #[test] + fn switching_between_two_sizes_reuses_the_accumulation_buffers() { + let Some((headless, mut tracer)) = gpu() else { return }; + + for (width, height) in [(64, 48), (32, 24), (64, 48), (32, 24), (64, 48)] { + let mut encoder = headless.device.create_command_encoder(&Default::default()); + tracer.reset(&headless.device, &mut encoder, width, height).unwrap(); + headless.queue.submit([encoder.finish()]); + + let accumulation = tracer.acc.as_ref().unwrap(); + assert_eq!((accumulation.width, accumulation.height), (width, height)); + assert_eq!(tracer.samples(), 0); + for buffer in accumulation.acc.iter().chain(&accumulation.illum) { + assert!(read_buffer(&headless, buffer).iter().all(|pixel| *pixel == [0.0; 4]), "reused buffers must be cleared"); + + // Leave nonzero contents to detect stale pixels on the next reuse + let pixels = vec![[1.0f32; 4]; (width * height) as usize]; + headless.queue.write_buffer(buffer, 0, bytemuck::cast_slice(&pixels)); + } + tracer.samples = 7; + } + + assert_eq!(tracer.acc_allocations, 2, "two sizes, two allocations, however often it switches"); + let mut encoder = headless.device.create_command_encoder(&Default::default()); + tracer.reset(&headless.device, &mut encoder, 16, 16).unwrap(); + headless.queue.submit([encoder.finish()]); + assert_eq!(tracer.acc_allocations, 3, "a third size allocates (and drops the oldest set)"); + + tracer.release(); + assert!(tracer.acc.is_none() && tracer.spare_acc.is_none(), "leaving Rendering mode frees both sizes"); + } + + /// Rejecting an oversized render preserves the image and lets tracing continue. + #[test] + fn failed_reset_retains_the_active_render() { + let Some((mut headless, mut tracer)) = gpu() else { return }; + let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); + let camera = camera(); + let settings = TraceSettings::default(); + let display = TraceDisplay::from_display(&Default::default()); + tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera, &settings, &display, [32, 24], 2).unwrap(); + let before = accumulation(&headless, &tracer); + + let mut encoder = headless.device.create_command_encoder(&Default::default()); + let error = tracer.reset(&headless.device, &mut encoder, 8192, 8192).unwrap_err(); + + assert!(error.contains("exceeds this GPU's buffer limit")); + assert!(tracer.acc.is_some(), "a rejected resize must keep the active buffers"); + assert!(tracer.bind.is_some(), "a rejected resize must keep the active bindings"); + assert_eq!(tracer.samples(), 2, "a rejected resize must keep the accumulated samples"); + assert_eq!(accumulation(&headless, &tracer), before); + assert!(tracer.pass(&headless.device, &headless.queue, &mut encoder, &camera, &settings, 1)); + let output = GpuTracer::output_texture(&headless.device, 32, 24); + assert!(tracer.resolve(&headless.device, &headless.queue, &mut encoder, &display, &output.create_view(&Default::default()))); + headless.queue.submit([encoder.finish()]); + assert!(crate::readback::Readback::blocking(&headless.device, &headless.queue, &output).is_some()); + assert_eq!(tracer.samples(), 3); + } + const WHITE: [(Channel, [f32; 3]); 3] = [(Channel::BaseColor, [1.0; 3]), (Channel::Metallic, [0.0; 3]), (Channel::Roughness, [0.5; 3])]; #[test] 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..fc777e80 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,18 +13,33 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_overlay; +pub mod bake_visualization; +pub mod cage_geometry; +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; +mod missing_seam_gpu; +pub mod neutral_material; +pub mod overlay_quad; pub mod readback; pub mod renderer; +pub mod set_highlight; mod subdivide; pub mod trace; +pub use bake_overlay::BakeOverlay; +pub use bake_visualization::BakeVisualization; +pub use cage_geometry::CageGeometry; +pub use neutral_material::NeutralMaterial; +pub use overlay_quad::OverlayQuad; 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 e9ed9424..9e720c6c 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -1,30 +1,59 @@ //! 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 }; - // `sample` scales both axes by the width: rows of a UV tile atlas map through its aspect. - let (w, h) = (u64::from(b.resolution.max(1)), u64::from(b.height(m))); + for y in 0..size { - let sy = (u64::from(y) * h / w) as u32; for x in 0..size { - let v = b.sample(m, x, sy, 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 } + +/// RGBA8 of the neutral value of map `m` (what a map not baked yet shows during a bake: flat +/// normals, white occlusion, mid-gray height ...), `size × size`, encoded like [`mesh_map_rgba`]. +pub fn neutral_rgba(m: BakedMap, size: u32) -> Vec { + let value = m.neutral(); + let pixel = [0, 1, 2].map(|k| (value[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + let size = size.max(1); + let mut out = Vec::with_capacity((size * size * 4) as usize); + for _ in 0..size * size { + out.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 255]); + } + 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/missing_seam_gpu.rs b/crates/render/src/missing_seam_gpu.rs new file mode 100644 index 00000000..07a69168 --- /dev/null +++ b/crates/render/src/missing_seam_gpu.rs @@ -0,0 +1,8 @@ +/// The low poly's hard edges without a UV seam, as a line list over its vertex buffer +pub(crate) struct MissingSeamGpu { + /// 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/src/neutral_material.rs b/crates/render/src/neutral_material.rs new file mode 100644 index 00000000..d3331185 --- /dev/null +++ b/crates/render/src/neutral_material.rs @@ -0,0 +1,75 @@ +//! The plain material bake mode can show the low poly with, so the bake reads without the painted colours + +/// The highest Quality: reflection samples per pixel +pub const MAX_SAMPLES_PER_PIXEL: u32 = 256; + +/// A plain material for the low poly in bake mode: its color comes from the low poly's overlay; its normal and occlusion are the texture set's as shown (the bake under any painted normal, height or AO) +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct NeutralMaterial { + pub roughness: f32, + pub metallic: f32, + /// How much the texture set's ambient occlusion (baked × painted) darkens the material (0 none, 1 fully) + pub ao_intensity: f32, + /// Environment reflection samples per pixel, taken by every frame so a moving view looks like a still one + pub samples_per_pixel: u32, + /// Light the material along the baked bent normal: the open direction above each point + pub bent_normal: bool, + /// How far the diffuse light turns to the bent normal, and how much reflections facing away from it dim (0..1) + pub bent_normal_diffuse: f32, + pub bent_normal_specular: f32, +} + +impl Default for NeutralMaterial { + /// Low quality (16 samples per pixel), a slightly rough half metal, most of the baked occlusion, no bent normal + fn default() -> Self { + Self { + roughness: 0.3, + metallic: 0.6, + ao_intensity: 0.75, + samples_per_pixel: 16, + bent_normal: false, + bent_normal_diffuse: 1.0, + bent_normal_specular: 1.0, + } + } +} + +impl NeutralMaterial { + /// The material's shader globals: x roughness, y metallic, z AO intensity, w 1 (on) + pub(crate) fn globals(&self) -> [f32; 4] { + [self.roughness, self.metallic, self.ao_intensity, 1.0] + } + + /// Reflection samples each frame takes: the whole quality, from 1 to [`MAX_SAMPLES_PER_PIXEL`] (a damaged settings file can't stall the GPU) + pub(crate) fn samples_per_frame(&self) -> u32 { + self.samples_per_pixel.clamp(1, MAX_SAMPLES_PER_PIXEL) + } + + /// The bent normal's shader globals: x diffuse amount, y specular amount (both 0 while off), zw - + pub(crate) fn bent_normal_globals(&self) -> [f32; 4] { + if self.bent_normal { [self.bent_normal_diffuse, self.bent_normal_specular, 0.0, 0.0] } else { [0.0; 4] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_frame_takes_the_whole_quality() { + let quality = |samples_per_pixel| NeutralMaterial { samples_per_pixel, ..NeutralMaterial::default() }; + assert_eq!(quality(16).samples_per_frame(), 16); + assert_eq!(quality(256).samples_per_frame(), 256); + assert_eq!(quality(u32::MAX).samples_per_frame(), MAX_SAMPLES_PER_PIXEL, "a damaged file is held to the highest quality"); + assert_eq!(quality(0).samples_per_frame(), 1); + } + + #[test] + fn the_bent_normal_reaches_the_shader_only_when_on() { + let off = NeutralMaterial::default(); + assert_eq!(off.bent_normal_globals(), [0.0; 4]); + let on = NeutralMaterial { bent_normal: true, bent_normal_diffuse: 0.5, bent_normal_specular: 0.25, ..off }; + assert_eq!(on.bent_normal_globals(), [0.5, 0.25, 0.0, 0.0]); + } +} diff --git a/crates/render/src/overlay_quad.rs b/crates/render/src/overlay_quad.rs new file mode 100644 index 00000000..c813bb42 --- /dev/null +++ b/crates/render/src/overlay_quad.rs @@ -0,0 +1,11 @@ +//! See-through quads drawn into the 3D view and hidden where the mesh is in front (the symmetry plane and lines) + +use texturecraft_geom::glam::Vec3; + +/// A flat quad with its corners in order, in a screen color (linear RGB) and opacity +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OverlayQuad { + pub corners: [Vec3; 4], + pub color: [f32; 3], + pub opacity: f32, +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index ea4757d5..4c62d450 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,8 +30,15 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::bake_visualization::BakeVisualization; +use crate::cage_geometry::CageGeometry; +use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; +use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; +use crate::missing_seam_gpu::MissingSeamGpu; +use crate::overlay_quad::OverlayQuad; +use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; pub const MSAA: u32 = 4; @@ -76,6 +83,16 @@ struct GlobalsRaw { fwd: [f32; 4], disp: [f32; 4], refr: [f32; 4], + highlight: [f32; 4], + highlight_shift: [f32; 4], + bake_high: [f32; 4], + bake_matching_error: [f32; 4], + bake_cage: [f32; 4], + bake_cage_wire: [f32; 4], + bake_missing_seam: [f32; 4], + bake_neutral_color: [f32; 4], + bake_neutral: [f32; 4], + bake_bent_normal: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -96,6 +113,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 +160,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 +187,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 +265,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 +275,7 @@ impl Default for Shade { sss_blur: None, refraction: false, displacement: false, + bake: None, } } } @@ -267,6 +299,8 @@ pub struct Frame { pub shade: Shade, /// Visibility per texture set. pub visible: Vec, + /// See-through quads in the 3D view, hidden behind the mesh + pub overlay: Vec, } struct Tex { @@ -477,6 +511,9 @@ struct ViewTargets { behind: Option, blit_buf: wgpu::Buffer, blit_bg: wgpu::BindGroup, + /// The frame's overlay triangles and how many vertices of the buffer they use + overlay: Option, + overlay_vertices: u32, /// Set by [`Renderer::prepare`]: the view has content to blit. ready: bool, } @@ -513,6 +550,17 @@ pub struct Renderer { uv_pipeline: wgpu::RenderPipeline, wire_pipeline: wgpu::RenderPipeline, wire3d_pipeline: wgpu::RenderPipeline, + overlay_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, + missing_seam_pipeline: wgpu::RenderPipeline, + /// The missing seams along the cage, and in the 2D view + cage_missing_seam_pipeline: wgpu::RenderPipeline, + uv_missing_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -546,6 +594,10 @@ pub struct Renderer { /// accumulation. content_rev: u64, mesh: Option, + bake_high: Option, + /// Each texture set's cage, by set index + cages: Vec>, + missing_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 +843,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 +884,49 @@ 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. + + // RGBA8 fallback clips bright highlights and dark gradients 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 +934,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 +945,127 @@ 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 cage_missing_seam_pipeline = pipeline( + device, + "tc_cage_missing_seam", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_cage_missing_seam", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_missing_seam_pipeline = + pipeline(device, "tc_uv_missing_seam", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire_missing_seam", blend), MSAA, always()); + let missing_seam_pipeline = pipeline( + device, + "tc_missing_seam", + &layout, + &module, + "vs_wire3d", + &vertex_layout, + hdr_target("fs_wire_missing_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 overlay_pipeline = + pipeline(device, "tc_overlay", &background_layout, &module, "vs_overlay", &vertex_layout, hdr_target("fs_overlay", blend), MSAA, wire3d_depth); 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 +1079,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 +1103,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 +1122,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 +1137,48 @@ 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, + overlay_pipeline, + highlight_pipeline, + bake_high_pipeline, + cage_pipeline, + cage_wire_pipeline, + missing_seam_pipeline, + cage_missing_seam_pipeline, + uv_missing_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 +1198,16 @@ impl Renderer { sh: [[0.0; 4]; 9], content_rev: 0, mesh: None, + bake_high: None, + cages: Vec::new(), + missing_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 { @@ -1078,6 +1261,7 @@ impl Renderer { if self.mesh.as_ref().is_some_and(|m| m.id == id) { return; } + let verts = subdivide::vertices(mesh); let mk = |label: &str, data: &[u8], usage: wgpu::BufferUsages| upload_buffer(device, queue, label, data, usage); let mut idx_bytes = bytemuck::cast_slice::(&mesh.indices).to_vec(); @@ -1085,7 +1269,8 @@ impl Renderer { let vb = mk("tc_vb", bytemuck::cast_slice(&verts), wgpu::BufferUsages::VERTEX); let ib = mk("tc_ib", &idx_bytes, wgpu::BufferUsages::INDEX); let draws: Vec<(u32, u32, usize)> = mesh.submeshes.iter().map(|s| (s.start, s.count, s.material)).collect(); - // Mesh edges per material (polygons, not their triangles), for the wireframes. + + // Use polygon edges for each material's wireframe let mut line_idx: Vec = Vec::new(); let mut line_draws = Vec::new(); for (m, edges) in mesh.wire_edges().into_iter().enumerate() { @@ -1104,6 +1289,96 @@ 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; `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>, 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(cage), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == cage.corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(cage.corners)); + } + (Some(cage), _) => { + *slot = Some(CageGpu { + topology, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(cage.corners), wgpu::BufferUsages::VERTEX), + corner_count: cage.corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(cage.edges), wgpu::BufferUsages::INDEX), + edge_index_count: (cage.edges.len() * 2) as u32, + missing_seams: upload_buffer(device, queue, "tc_cage_seam_ib", bytemuck::cast_slice(cage.missing_seams), wgpu::BufferUsages::INDEX), + missing_seam_index_count: (cage.missing_seams.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 hard edges without a UV seam as vertex pairs per material ([`Mesh::missing_seam_edges`]) for mesh `mesh_id` + pub fn set_missing_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_missing_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.missing_seams = Some(MissingSeamGpu { 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 }; @@ -1452,6 +1727,8 @@ impl Renderer { behind: None, blit_buf, blit_bg, + overlay: None, + overlay_vertices: 0, ready: false, } } @@ -1531,13 +1808,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 @@ -1629,10 +1900,11 @@ impl Renderer { if sample >= TAA_SAMPLES { return; } + let aspect = frame.size[0].max(1) as f32 / frame.size[1].max(1) as f32; let mut vp = frame.camera.view_proj(aspect); if sample > 0 { - // Sub-pixel jitter in clip space: a box filter over the pixel once averaged. + // Sub-pixel jitter averages into a box filter let (jx, jy) = (halton(sample, 2) - 0.5, halton(sample, 3) - 0.5); vp = Mat4::from_translation(Vec3::new(2.0 * jx / frame.size[0].max(1) as f32, 2.0 * jy / frame.size[1].max(1) as f32, 0.0)) * vp; } @@ -1644,13 +1916,13 @@ impl Renderer { (1.0, [sx, sy, pan[0], pan[1]]) } }; - // Data views (channels, mesh maps, UV checker, the 2D view) show values as they are: no - // exposure, tone mapping, effects or shadows. + + // Data views bypass exposure, tone mapping, effects and shadows let data = uv_view > 0.5 || s.view_mode != 0; let fx = |v: f32| if s.post_effects && !data { v.clamp(0.0, 1.0) } else { 0.0 }; let bloom = fx(s.bloom) > 0.0; - // The key light lives in the environment: turn it with it (the inverse of env_rotate in - // mesh.wgsl maps environment directions to world directions). + + // Turn the key light with the environment let (sin, cos) = s.env_rotation_deg.to_radians().sin_cos(); let [lx, ly, lz, lw] = s.light; let light = Vec3::new(cos * lx + sin * lz, ly, cos * lz - sin * lx); @@ -1659,19 +1931,19 @@ impl Renderer { self.ensure_dense(device, queue); } let disp = match self.mesh.as_ref().filter(|_| displace) { - // Height-to-normal's slope: strength 1 tilts 45° for a height change of 1 over 1/16 of - // the UV square; the vertex shader samples the mip whose texels match the vertex spacing. + // A unit height across 1/16 of UV space tilts 45°; use the mip nearest vertex spacing Some(m) => [1.0, m.world_per_uv / 16.0, 1.0 / (m.dense.as_ref().unwrap_or(&m.geo).triangles.max(1) as f32 * 0.5).sqrt(), 0.0], None => [0.0; 4], }; let shadow_disp = [disp[0], disp[1] * s.height_strength, disp[2], 0.0]; let shadow_vp = if !data && s.shadows && lw > 0.0 { self.update_shadow(device, queue, encoder, light, shadow_disp, &frame.visible) } else { None }; let radius = self.mesh.as_ref().map_or(1.0, |m| m.radius); - // Background rays come from a perspective camera even in orthographic views (an ortho - // ray grid would show a single flat environment color). + + // Perspective background rays prevent flat color in orthographic views let bg_vp = OrbitCamera { ortho: false, ..frame.camera }.view_proj(aspect); let e = frame.camera.eye(); - // Scene effects (3D material view; they need float targets for depths and signed light). + + // Scene effects need float targets for depths and signed light let scene_fx = !data && frame.kind == ViewKind::Scene && self.hdr_format == HDR_FORMAT && self.mesh.is_some(); let dof = s.dof.filter(|_| scene_fx); let sss = s.sss_blur.filter(|m| scene_fx && m.iter().any(|v| *v > 0.0)); @@ -1680,7 +1952,8 @@ impl Renderer { let cam = &frame.camera; let half_h = (cam.fov.clamp(5.0, 150.0).to_radians() * 0.5).tan(); let height = frame.size[1].max(1) as f32; - // Pixels per world unit at view depth z: k / z in perspective, k in orthographic views. + + // Perspective pixels per world unit vary with depth let k = if cam.ortho { height / (2.0 * cam.distance.max(1e-6) * half_h) } else { height / (2.0 * half_h) }; let ppw = |z: f32| if cam.ortho { k } else { k / z.max(1e-6) }; let dof_c = dof.map_or([0.0; 4], |[focus, aperture]| { @@ -1700,13 +1973,16 @@ impl Renderer { uv_xform, light: [light.x, light.y, light.z, lw], light_vp: shadow_vp.unwrap_or(Mat4::IDENTITY).to_cols_array_2d(), - // Normal offset: 1.5 shadow texels of the light frustum (2 × radius wide). + // Offset by 1.5 shadow texels to avoid self-shadowing shadow: [if shadow_vp.is_some() { 1.0 } else { 0.0 }, 1.0 / SHADOW_SIZE as f32, radius * 3.0 / SHADOW_SIZE as f32, 0.0], material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior], scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }], 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), + ..bake_globals(s.bake) }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; let post = PostRaw { @@ -1719,6 +1995,7 @@ impl Renderer { let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return }; queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw)); queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post)); + upload_overlay(device, queue, v, &frame.overlay, (!data).then_some(s.exposure_ev)); v.ready = true; v.history = Some((frame.clone(), rev)); v.samples = sample; @@ -1729,9 +2006,7 @@ impl Renderer { } let weight = 1.0 / f64::from(sample + 1); match v.fx.as_ref().filter(|_| fx_on) { - // The effects run on every frame before it joins the average, so idle accumulation - // also smooths the depth of field's sampling pattern (turned each frame). Their - // G-buffer (unjittered) stays valid while the view accumulates. + // Effects run before averaging; the unjittered G-buffer remains valid Some(f) => { self.scene_pass(encoder, v, &v.hdr, globals_bg, frame); if sample == 0 { @@ -1805,7 +2080,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); @@ -1867,34 +2142,37 @@ impl Renderer { None => (&self.mesh_pipeline, frame.shade.wireframe_3d.then_some(&self.wire3d_pipeline)), Some(_) => (&self.uv_pipeline, frame.shade.wireframe.then_some(&self.wire_pipeline)), }; - // Transmissive surfaces refract what the behind pass rendered this frame. + + // Transmissive surfaces refract the current behind pass 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 +2180,118 @@ 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.shown); + let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_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, uv_set, 1), + (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_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); + } + if let Some(texture_set) = uv_set + && frame.shade.bake.is_some_and(|bake| bake.missing_seams.shown) + && let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == mesh.id) + { + pass.set_pipeline(&self.uv_missing_seam_pipeline); + pass.set_vertex_buffer(0, mesh.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } } + + // Overlay quads last, so the mesh's depth hides what is behind it + if uv_set.is_none() + && let Some(overlay) = targets.overlay.as_ref().filter(|_| targets.overlay_vertices > 0) + { + pass.set_pipeline(&self.overlay_pipeline); + pass.set_vertex_buffer(0, overlay.slice(..)); + pass.draw(0..targets.overlay_vertices, 0..1); + } + } + + /// Bake mode's high poly, missing 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.shown + && 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.missing_seams.shown + && let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + { + pass.set_pipeline(&self.missing_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, None) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..1); + } + } + + 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 + if bake.cage_surface.shown { + 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); + } + } + + if bake.cage_wire.shown { + 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); + } + } + + if bake.missing_seams.shown && bake.cage_shown() { + pass.set_pipeline(&self.cage_missing_seam_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.missing_seams.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.missing_seam_index_count, 0, 0..1); + } + } } /// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h). @@ -1963,11 +2332,126 @@ 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)) + }) +} + +/// A quad's two triangles, as corner indices +const QUAD_TRIANGLES: [usize; 6] = [0, 1, 2, 0, 2, 3]; + +/// Write `quads` into the view's overlay buffer, colors divided by the exposure only (undoing ACES makes saturated colors overshoot) +fn upload_overlay(device: &wgpu::Device, queue: &wgpu::Queue, view: &mut ViewTargets, quads: &[OverlayQuad], exposure_ev: Option) { + view.overlay_vertices = 0; + let Some(vertex_count) = quads.len().checked_mul(QUAD_TRIANGLES.len()).and_then(|count| u32::try_from(count).ok()) else { + log::warn!("Symmetry overlay has too many vertices; hide the intersection or use a simpler mesh"); + return; + }; + + // A valid imported mesh can produce more intersection vertices than the GPU accepts + let byte_count = u64::from(vertex_count) * std::mem::size_of::() as u64; + if byte_count > device.limits().max_buffer_size { + log::warn!("Symmetry overlay exceeds the GPU buffer limit; hide the intersection or use a simpler mesh"); + return; + } + + if vertex_count == 0 { + return; + } + + let vertices: Vec = quads + .iter() + .flat_map(|quad| { + let [r, g, b] = exposure_ev.map_or(quad.color, |exposure_ev| crate::set_highlight::scene_color_showing(quad.color, exposure_ev, false)); + let vertex = |corner: Vec3| Vertex { pos: corner.to_array(), nrm: [0.0; 3], tan: [r, g, b, quad.opacity], uv: [0.0; 2] }; + QUAD_TRIANGLES.map(|corner| vertex(quad.corners[corner])) + }) + .collect(); + let bytes: &[u8] = bytemuck::cast_slice(&vertices); + if view.overlay.as_ref().is_none_or(|buffer| buffer.size() < bytes.len() as u64) { + view.overlay = Some(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_overlay"), + size: bytes.len() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + if let Some(buffer) = &view.overlay { + queue.write_buffer(buffer, 0, bytes); + view.overlay_vertices = vertex_count; + } +} + +/// 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] +} + +/// The globals of bake mode's overlays and neutral material for `bake` (all zero without it) +fn bake_globals(bake: Option) -> GlobalsRaw { + let Some(bake) = bake else { return GlobalsRaw::zeroed() }; + + let [red, green, blue] = bake.low_poly.color; + let neutral = bake.shown_neutral(); + let samples_per_frame = neutral.map_or(0, |neutral| neutral.samples_per_frame()); + GlobalsRaw { + bake_high: bake.high_poly.globals(), + bake_matching_error: bake.matching_error.globals(), + bake_cage: bake.cage_surface.globals(), + bake_cage_wire: bake.cage_wire.globals(), + bake_missing_seam: bake.missing_seams.globals(), + bake_neutral_color: [red, green, blue, samples_per_frame as f32], + bake_neutral: neutral.map_or([0.0; 4], |neutral| neutral.globals()), + bake_bent_normal: neutral.map_or([0.0; 4], |neutral| neutral.bent_normal_globals()), + ..GlobalsRaw::zeroed() + } +} + +/// 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::*; use crate::headless::Headless; + #[test] + fn oversized_overlays_leave_the_view_usable() { + let Ok(mut headless) = Headless::new() else { return }; + let limit = headless.device.limits().max_buffer_size as usize; + let count = limit / (QUAD_TRIANGLES.len() * std::mem::size_of::()) + 1; + let quad = OverlayQuad { corners: [Vec3::ZERO; 4], color: [1.0, 0.0, 0.0], opacity: 0.5 }; + let quads = vec![quad; count]; + let view = headless.renderer.targets(&headless.device, 1, [32, 32], false, false, false).unwrap(); + upload_overlay(&headless.device, &headless.queue, view, &[quad], None); + + upload_overlay(&headless.device, &headless.queue, view, &quads, None); + + assert_eq!(view.overlay_vertices, 0, "skip overlays beyond the device limit"); + upload_overlay(&headless.device, &headless.queue, view, &[quad], None); + assert_eq!(view.overlay_vertices, 6, "the next frame can draw its overlay"); + } + /// A headless renderer with one 256² texture set, and the base color slot's full-size /// texture handed over as WebGPU would: allocated, with its verdict still to come. fn awaiting() -> Option<(Headless, std::sync::mpsc::Sender>)> { @@ -2026,6 +2510,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..cc29879e --- /dev/null +++ b/crates/render/src/set_highlight.rs @@ -0,0 +1,66 @@ +//! 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] { + scene_color_showing(self.color, exposure_ev, aces) + } +} + +/// The scene color that exposure `exposure_ev` and the tone curve (ACES when `aces`) show as `screen` (linear RGB) +pub(crate) fn scene_color_showing(screen: [f32; 3], exposure_ev: f32, aces: bool) -> [f32; 3] { + let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); + + screen.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.wgsl b/crates/render/src/shaders/bake.wgsl index f321bc84..8c96d490 100644 --- a/crates/render/src/shaders/bake.wgsl +++ b/crates/render/src/shaders/bake.wgsl @@ -1,4 +1,4 @@ -// GPU mesh-map baking: the ray casts of `texturecraft_bake::rays` (the CPU oracle) as compute +// GPU mesh-map baking: the ray casts of `texturecraft_bake::tracing` (the CPU oracle) as compute // shaders, concatenated after rays.wgsl. `transfer_main` finds the closest high-poly hit of each // transfer ray; `hemisphere_main` casts a query's secondary rays (ambient occlusion and bent // normal, or thickness) in the same directions as `Hemisphere::direction`, spread over `lanes` @@ -24,6 +24,10 @@ struct Params { root: u32, // transfer: BVH root node of the high poly lanes: u32, // hemisphere: threads per query, a power of two dividing the workgroup out: u32, // first result row of this pass + min_distance: f32, + attenuation: u32, + ground_height: f32, + backface_mode: u32, }; @group(0) @binding(0) var P: Params; @@ -36,12 +40,13 @@ struct Params { var want_key: u32; var skip_back: bool; +var backface_by_name: bool; fn accept(i: u32, d: vec3) -> bool { if (want_key != NONE && tris[i * 4u].w != want_key) { return false; } - if (skip_back) { + if (skip_back || (backface_by_name && tris[i * 4u + 1u].w != 0u)) { let p0 = tri_p(i, 0u); return dot(cross(tri_p(i, 1u) - p0, tri_p(i, 2u) - p0), d) <= 0.0; } @@ -57,7 +62,8 @@ fn transfer_main(@builtin(global_invocation_id) gid: vec3) { let a = items[k * 2u]; let b = items[k * 2u + 1u]; want_key = b.w; - skip_back = false; + skip_back = (P.flags & IGNORE_BACKFACE) != 0u; + backface_by_name = false; let h = traverse_from(P.root, bitcast>(a.xyz), bitcast>(b.xyz), bitcast(a.w), false); var out = vec4(0u, 0u, 0u, NONE); if (h.idx != NONE) { @@ -88,8 +94,9 @@ fn hemisphere_main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocati let o = bitcast>(r0.xyz) + geo * P.eps; let t = onb_t(axis); let b = onb_b(axis); - want_key = select(NONE, r2.w, occlusion && (P.flags & SAME_KEY) != 0u); - skip_back = occlusion && (P.flags & IGNORE_BACKFACE) != 0u; + want_key = select(NONE, r2.w, (P.flags & SAME_KEY) != 0u); + skip_back = P.backface_mode == 1u; + backface_by_name = P.backface_mode == 2u; var sum = 0.0; var bent = vec3(0.0); var n = 0u; @@ -110,15 +117,26 @@ fn hemisphere_main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocati if (dot(d, geo) <= 0.0) { continue; } - let h = traverse_from(root, o, d, P.dmax, false); - let hit = h.idx != NONE; + let h = traverse_from(root, o + d * P.min_distance, d, max(0.0, P.dmax - P.min_distance), false); + var hit = h.idx != NONE; + var distance = select(P.dmax, h.t + P.min_distance, hit); + if ((P.flags & 8u) != 0u && d.y < -1e-8) { + let ground_distance = (P.ground_height - o.y) / d.y; + if (ground_distance >= P.min_distance && ground_distance <= P.dmax) { + distance = min(distance, ground_distance); + hit = true; + } + } if (occlusion) { - let f = h.t / P.dmax; - let v = select(0.0, 1.0 - f * f, hit); + let fraction = clamp((distance - P.min_distance) / max(P.dmax - P.min_distance, 1.1920929e-7), 0.0, 1.0); + var attenuation = 1.0; + if (P.attenuation == 1u) { attenuation = 1.0 - fraction; } + if (P.attenuation == 2u) { attenuation = 1.0 - fraction * fraction * (3.0 - 2.0 * fraction); } + let v = select(0.0, attenuation, hit); sum += v; bent += d * (1.0 - v); } else { - sum += select(P.dmax, h.t, hit); + sum += distance; } n += 1u; } @@ -142,8 +160,8 @@ fn hemisphere_main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocati let l2 = dot(bent, bent); let bn = select(nrm, bent * inverseSqrt(l2), l2 > 1e-30); out = vec4(select(1.0, clamp(1.0 - sum / f32(n), 0.0, 1.0), n > 0u), bn); - } else if (n > 0u) { - out.x = clamp(sum / f32(n) / P.dmax, 0.0, 1.0); + } else { + out.x = select(P.dmax, sum / f32(n), n > 0u); } results[P.out + k] = bitcast>(out); } diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl new file mode 100644 index 00000000..0720e318 --- /dev/null +++ b/crates/render/src/shaders/bake_view.wgsl @@ -0,0 +1,221 @@ +// Bake mode's 3D view: the high poly, the cage around the low poly, the missing seams and the neutral material + +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, negative where another texture set owns it (hidden) + @location(2) missed: f32, +}; + +// Reflectance of the neutral material's dielectric part facing the camera +const NEUTRAL_F0: f32 = 0.04; + +// Lowest roughness the neutral material shades with: below it the GGX lobe is too narrow for its samples +const MIN_NEUTRAL_ROUGHNESS: f32 = 0.045; + +// How fast reflections fade as they dip below the mesh surface (larger = sooner) +const HORIZON_FADE: f32 = 1.3; + +// Floor of the cosines that divide the reflection terms, so grazing angles stay finite +const MIN_COSINE: f32 = 1e-4; + +// A normal closer than this to +-Z builds its tangent frame from X, where the cross product with Z would vanish +const TANGENT_HELPER_MAX_Z: f32 = 0.999; + +// One mip coarser than each sample's share of the lobe: hides the gaps between few samples (filtered importance sampling) +const FILTERED_SAMPLING_LOD_BIAS: f32 = 1.0; + +// A packed bent normal shorter than this is the unbaked gray, not a direction +const BENT_NORMAL_MIN_LENGTH: f32 = 0.5; + +// Cosines between a reflection and the bent normal over which the reflection goes from occluded to open +const BENT_OCCLUSION_START: f32 = -0.25; +const BENT_OCCLUSION_END: f32 = 0.75; + +// Floor of the GGX distribution's denominator, which reaches 0 at the peak of a mirror-like lobe +const MIN_GGX_DENOMINATOR: f32 = 1e-6; + +// Fractional part of the golden ratio: shifts each accumulated frame's samples around the lobe +const GOLDEN_RATIO_FRACTION: f32 = 0.618034; + +// High-poly surface where the interpolated `missed` falls below this belongs to a hidden texture set +const HIDDEN_BELOW: f32 = -0.5; + +// 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 { + if (surface.missed < HIDDEN_BELOW) { + discard; + } + + let color = mix(g.bake_high.rgb, g.bake_matching_error.rgb, max(surface.missed, 0.0) * g.bake_matching_error.a); + 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(g.bake_cage.rgb, face_normal, surface.world_position), g.bake_cage.a); +} + +// 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 g.bake_cage_wire; +} + +@fragment +fn fs_wire_missing_seam(surface: VOut) -> @location(0) vec4 { + return g.bake_missing_seam; +} + +// The missing seams along the cage, whose vertices carry the bake view's outputs +@fragment +fn fs_wire_cage_missing_seam(surface: BakeViewOut) -> @location(0) vec4 { + return g.bake_missing_seam; +} + +// Shade the neutral material using the texture set's normal, occlusion and optional bent normal +fn neutral_color(n: vec3, n_geo: vec3, v: vec3, world_position: vec3, ao_channel: f32, packed_bent: vec3) -> vec4 { + let albedo = g.bake_neutral_color.rgb; + let rough = clamp(g.bake_neutral.x, MIN_NEUTRAL_ROUGHNESS, 1.0); + let metal = g.bake_neutral.y; + let ao = mix(1.0, ao_channel, g.bake_neutral.z); + let f0 = mix(vec3(NEUTRAL_F0), albedo, metal); + let diffuse_col = albedo * (1.0 - metal); + let nov = clamp(abs(dot(n, v)), MIN_COSINE, 1.0); + + // An unbaked bent normal reads as the neutral gray (length 0): the surface normal stands in + var bent = packed_bent * 2.0 - 1.0; + bent = select(n, normalize(bent), dot(bent, bent) > BENT_NORMAL_MIN_LENGTH * BENT_NORMAL_MIN_LENGTH); + let diffuse = sh_irradiance(normalize(mix(n, bent, g.bake_bent_normal.x)), vec3(0.0)) * diffuse_col * ao; + let r = reflect(-v, n); + let horizon = clamp(1.0 + HORIZON_FADE * dot(r, n_geo), 0.0, 1.0); + + // Reflections pointing away from the open direction are occluded + let bent_occlusion = mix(1.0, smoothstep(BENT_OCCLUSION_START, BENT_OCCLUSION_END, dot(bent, r)), g.bake_bent_normal.y); + let spec = sampled_reflection(n, v, rough, f0, nov) * ao * bent_occlusion * horizon * horizon; + + var direct = vec3(0.0); + if (g.light.w > 0.0) { + let l = normalize(g.light.xyz); + let h = normalize(l + v); + let nol = clamp(dot(n, l), 0.0, 1.0); + let f = f0 + (vec3(1.0) - f0) * pow(1.0 - clamp(dot(v, h), 0.0, 1.0), 5.0); + direct = ((vec3(1.0) - f) * diffuse_col / PI + ggx_dv(rough * rough, nov, nol, clamp(dot(n, h), 0.0, 1.0)) * f) * nol * g.light.w; + if (g.shadow.x > 0.5 && nol > 0.0) { + direct *= shadow_factor(world_position, n_geo); + } + } + let color = diffuse + spec + direct; + return vec4(select(color, vec3(0.0), any(color != color)), 1.0); +} + +// Importance sample the environment's GGX reflection with a new sequence each frame +fn sampled_reflection(n: vec3, v: vec3, rough: f32, f0: vec3, nov: f32) -> vec3 { + let count = max(u32(g.bake_neutral_color.w), 1u); + let a = rough * rough; + let a2 = a * a; + let env_size = vec2(textureDimensions(env_tex)); + let texel_solid_angle = 4.0 * PI / (env_size.x * env_size.y); + let side = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), abs(n.z) < TANGENT_HELPER_MAX_Z); + let tangent = normalize(cross(side, n)); + let bitangent = cross(n, tangent); + let frame_offset = u32(g.material.z) * count; + + // Schlick-GGX geometry term at k = a / 2 + let k = a * 0.5; + let view_visibility = nov / (nov * (1.0 - k) + k); + + var sum = vec3(0.0); + for (var index = 0u; index < count; index++) { + let xi = vec2(fract((f32(index) + 0.5) / f32(count) + f32(g.material.z) * GOLDEN_RATIO_FRACTION), radical_inverse(index + frame_offset)); + let phi = 2.0 * PI * xi.x; + + // Clamp cosine before computing its sine to avoid NaN near zero roughness + let cos_theta = clamp(sqrt((1.0 - xi.y) / (1.0 + (a2 - 1.0) * xi.y)), 0.0, 1.0); + let sin_theta = sqrt(1.0 - cos_theta * cos_theta); + let h = normalize(tangent * (cos(phi) * sin_theta) + bitangent * (sin(phi) * sin_theta) + n * cos_theta); + let l = reflect(-v, h); + let nol = min(dot(n, l), 1.0); + if (nol <= 0.0) { + continue; + } + + // Capped at 1: a dot product rounding past it makes pow(1 - voh, 5) NaN on GPUs that compute pow through log2 + let noh = clamp(dot(n, h), MIN_COSINE, 1.0); + let voh = clamp(dot(v, h), MIN_COSINE, 1.0); + let denominator = max(noh * noh * (a2 - 1.0) + 1.0, MIN_GGX_DENOMINATOR); + let pdf = a2 / (PI * denominator * denominator) * noh / (4.0 * voh); + + // Filtered importance sampling: each sample reads the mip that covers its share of the lobe + let lod = clamp(0.5 * log2(1.0 / (f32(count) * pdf * texel_solid_angle)) + FILTERED_SAMPLING_LOD_BIAS, 0.0, g.env.y); + let light = textureSampleLevel(env_tex, env_samp, env_uv(l), lod).rgb; + let fresnel = f0 + (vec3(1.0) - f0) * pow(1.0 - voh, 5.0); + let visibility = view_visibility * nol / (nol * (1.0 - k) + k); + let contribution = light * fresnel * (visibility * voh / (noh * nov)); + + // Drop NaN samples before they contaminate the frame average + sum += select(contribution, vec3(0.0), any(contribution != contribution)); + } + return sum / f32(count); +} + +// Van der Corput: the bits of `index` mirrored behind the binary point (swapped by hand: WebGL2 lacks a bit reverse) +fn radical_inverse(index: u32) -> f32 { + var bits = (index << 16u) | (index >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return f32(bits) / 4294967296.0; +} diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index cd2e8d80..aac1d147 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -24,6 +24,16 @@ 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 - + bake_high: vec4, // bake mode: rgb high poly color, a - + bake_matching_error: vec4, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden) + bake_cage: vec4, // rgb cage surface color, a opacity + bake_cage_wire: vec4, // rgb cage wireframe color, a opacity + bake_missing_seam: vec4, // rgb color of hard edges without a UV seam, a opacity + bake_neutral_color: vec4, // rgb the neutral material's color, a its reflection samples this frame + bake_neutral: vec4, // x roughness, y metallic, z AO intensity of the neutral material, w on (1) + bake_bent_normal: vec4, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw - }; @group(0) @binding(0) var g: Globals; @@ -401,8 +411,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let hu = textureSample(t_height, samp, uv - vec2(0.0, ts.y)).r; let hd = textureSample(t_height, samp, uv + vec2(0.0, ts.y)).r; - // Tangent-space normal: height gradient (+Y = up the image) combined with the normal channel. - // Same slope rule as texture export: strength 1 tilts 45° for a height change of 1 over 1/16 of the width. + // Match export: a unit height over 1/16 of the width tilts 45° + // Combine the height gradient with the tangent-space normal let k = g.mode.z * dims.x / 16.0 * tile_scale(uv); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); var n_detail = snorm8(nrm_s); @@ -416,6 +426,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { if (ch >= 11) { return unlit(lobe_view(ch, lobes, sheen_t, nrm_t.a, emis_t.a, extra)); } + switch ch { case 0: { return unlit(data_out(base_s.rgb)); } case 1: { return unlit(data_out(vec3(orm.b))); } @@ -433,6 +444,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { if (mode == 2) { return unlit(raw_out(aux.rgb)); } + if (mode == 3) { let c = floor(uv * 32.0); let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5); @@ -444,7 +456,11 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { return unlit(data_out((col + tint) * diff)); } - // Opacity: dithered alpha test (a new pattern per accumulated frame, so it averages out). + if (g.bake_neutral.w > 0.5) { + return Shaded(neutral_color(n, n_geo, v, i.wpos, orm.r, aux.rgb), vec3(0.0)); + } + + // Change the alpha dither each frame so accumulation smooths it if (base_s.a < hash12(i.clip.xy + g.material.z * vec2(17.0, 59.0))) { discard; } @@ -457,25 +473,27 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { var f0 = mix(vec3(0.08 * orm.a), albedo, metal); var diffuse_col = albedo * (1.0 - metal); if (g.material.x > 0.5) { - // Specular/glossiness: the Specular color is F0 and base color the diffuse color, with - // the energy the specular takes removed (roughness already is 1 - glossiness). + // Specular color gives F0; remove its energy from diffuse f0 = hgt.gba; diffuse_col = albedo * (1.0 - max(f0.r, max(f0.g, f0.b))); } - // Transmission: that part of the dielectric base refracts instead of reflecting diffusely. + + // Transmission removes energy from the dielectric diffuse base let trans = extra.b * (1.0 - metal); diffuse_col *= 1.0 - trans; - // The extra lobes; their defaults (weights 0) leave the base shading as it is. + // Zero lobe weights preserve the base shading let coat_w = lobes.r; let coat_rough = clamp(lobes.g, 0.045, 1.0); let aniso = lobes.b; let sheen_col = sheen_t.rgb * sheen_t.a; let sheen_max = max3(sheen_col); let sheen_rough = clamp(nrm_t.a, 0.07, 1.0); - // Subsurface scattering: wrapped diffuse, wider for the channels the scatter color carries further. + + // Scatter color controls each channel's diffuse wrap let wrap = emis_t.a * g.scatter.xyz; - // Anisotropy: GGX roughness stretched along the mesh tangent turned by the angle (0..1 → 0..π). + + // Stretch GGX along the tangent rotated by 0..π let a = rough * rough; let at = max(a * (1.0 + aniso), 0.002); let ab = max(a * (1.0 - aniso), 0.002); @@ -484,8 +502,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let ta1 = ta0 - n * dot(n, ta0); let ta = ta1 * inverseSqrt(max(dot(ta1, ta1), 1e-8)); let ba = cross(n, ta); - // The clear coat follows the mesh normal (not the normal and height channels), turned by the - // coat normal channel where it is painted (the flat default keeps the mesh normal exactly). + + // Coat normals perturb the geometric normal independently of base detail var n_c = n_geo; let cn = coat_normal_ts(extra); if (coat_w > 0.0 && max(abs(cn.x), abs(cn.y)) > 0.004) { @@ -493,7 +511,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { } let nov_c = clamp(abs(dot(n_c, v)), 1e-4, 1.0); let coat_t = 1.0 - coat_w * schlick(0.04, nov_c); - // What reaches the layers below: the coat's transmission and the sheen albedo scaling. + + // Coat transmission and sheen albedo limit energy reaching the base var base_scale = coat_t; var sheen_e = 0.0; if (sheen_max > 0.0) { @@ -504,12 +523,13 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let diffuse = sh_irradiance(n, wrap) * diffuse_col * ao; var r = reflect(-v, n); if (aniso > 0.0) { - // Bent reflection vector: the standard real-time approximation of anisotropic IBL. + // Bend the reflection to approximate anisotropic IBL let bent = cross(cross(ba, v), ba); r = reflect(-v, normalize(mix(n, bent, aniso * clamp(5.0 * rough, 0.0, 1.0)))); } let pre = textureSampleLevel(env_tex, env_samp, env_uv(r), rough * g.env.y).rgb; - // Horizon fading: reflections that point below the geometric surface are dimmed. + + // Fade reflections below the geometric surface let horizon = clamp(1.0 + 1.3 * dot(r, n_geo), 0.0, 1.0); let spec = pre * env_brdf(f0, rough, nov) * ao * horizon * horizon; var layers = vec3(0.0); @@ -523,16 +543,14 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { } if (trans > 0.0) { - // shortcut: one refraction interface (no exit); the path tracer refracts through the - // whole mesh. + // Approximate one refraction interface; the path tracer also handles the exit var td = refract(-v, n, 1.0 / max(g.material.w, 1.0)); if (dot(td, td) < 1e-6) { td = reflect(-v, n); } var behind = textureSampleLevel(env_tex, env_samp, env_uv(td), rough * g.env.y).rgb; if (g.refr.x > 0.5) { - // Screen-space refraction: the opaque scene where the refracted ray lands on screen, - // over the environment where that shows nothing (or the ray leaves the view). + // Composite the refracted screen sample over the environment fallback let p = g.view_proj * vec4(i.wpos + td * g.refr.z, 1.0); let s = p.xy / max(p.w, 1e-6); let suv = vec2(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5); @@ -561,7 +579,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { dv = ggx_dv(a, nov, nol, noh); } let f = f0 + (vec3(1.0) - f0) * pow(1.0 - voh, 5.0); - // Energy-conserving wrapped Lambert (plain Lambert where nothing scatters). + + // Normalize wrapped Lambert to conserve energy let diff_nol = max((nol_raw + wrap) / ((1.0 + wrap) * (1.0 + wrap)), vec3(0.0)); direct_diffuse = (vec3(1.0) - f) * diffuse_col / PI * diff_nol * (g.light.w * base_scale); direct = ((vec3(1.0) - f) * diffuse_col / PI * diff_nol + dv * f * nol) * (g.light.w * base_scale); @@ -659,8 +678,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 +689,46 @@ 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); } + +// How far overlay quads move toward the eye, as a fraction of their distance (as the wireframe does) +const OVERLAY_TOWARD_EYE: f32 = 0.002; + +// See-through overlay quads (the symmetry plane and the lines on the mesh): the color comes in the tangent slot, nudged toward the eye like the wireframe so lines on the surface win the depth test +@vertex +fn vs_overlay(v: VIn) -> VOut { + var o: VOut; + o.wpos = v.pos; + o.nrm = v.nrm; + o.tan = v.tan; + o.uv = v.uv; + o.clip = g.view_proj * vec4(v.pos + (g.eye.xyz - v.pos) * OVERLAY_TOWARD_EYE, 1.0); + return o; +} + +@fragment +fn fs_overlay(i: VOut) -> @location(0) vec4 { + return i.tan; +} + +// 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/subdivide.rs b/crates/render/src/subdivide.rs index d08a82f2..283759a4 100644 --- a/crates/render/src/subdivide.rs +++ b/crates/render/src/subdivide.rs @@ -65,29 +65,31 @@ fn on_edge(verts: &[Vertex], (p, q): (u32, u32), k: u32, n: u32) -> Option (Vec, Vec, Vec) { - let n = 1u32 << level.min(MAX_LEVEL); - let (mut out_v, mut out_i, mut out_d) = (Vec::new(), Vec::new(), Vec::new()); +pub(crate) fn subdivide(vertices: &[Vertex], indices: &[u32], draws: &[Draw], level: u32) -> (Vec, Vec, Vec) { + let segments = 1u32 << level.min(MAX_LEVEL); + let (mut output_vertices, mut output_indices, mut output_draws) = (Vec::new(), Vec::new(), Vec::new()); + for &(start, count, material) in draws { - let first = out_i.len() as u32; - let tris = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); - for t in tris.chunks_exact(3) { - let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; - let base = out_v.len() as u32; - // Grid point (i, j), i + j <= n, row by row: row j holds n + 1 - j points. Points on - // the edges are computed the same way from both triangles sharing the edge (no cracks). - for j in 0..=n { - for i in 0..=n - j { + let first = output_indices.len() as u32; + let triangles = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); + for t in triangles.as_chunks::<3>().0 { + let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue }; + let base = output_vertices.len() as u32; + + // Row j holds segments + 1 - j points inside the triangle + // Shared edges use identical interpolation in both triangles to prevent cracks + for j in 0..=segments { + for i in 0..=segments - j { let edge = match (i, j) { (_, 0) => Some(((t[0], t[1]), i)), (0, _) => Some(((t[0], t[2]), j)), - _ if i + j == n => Some(((t[1], t[2]), j)), + _ if i + j == segments => Some(((t[1], t[2]), j)), _ => None, }; - let p = match edge.and_then(|(ends, k)| on_edge(verts, ends, k, n)) { + let p = match edge.and_then(|(ends, k)| on_edge(vertices, ends, k, segments)) { Some(p) => p, None => { - let w = [1.0 - (i + j) as f32 / n as f32, i as f32 / n as f32, j as f32 / n as f32]; + let w = [1.0 - (i + j) as f32 / segments as f32, i as f32 / segments as f32, j as f32 / segments as f32]; Vertex { pos: mix(a.pos, b.pos, c.pos, w), nrm: mix(a.nrm, b.nrm, c.nrm, w), @@ -96,39 +98,42 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level } } }; - out_v.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p }); + output_vertices.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p }); } } - let at = |i: u32, j: u32| base + j * (n + 1) - j * j.saturating_sub(1) / 2 + i; - for j in 0..n { - for i in 0..n - j { - out_i.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]); - if i + j + 1 < n { - out_i.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]); + + let at = |i: u32, j: u32| base + j * (segments + 1) - j * j.saturating_sub(1) / 2 + i; + for j in 0..segments { + for i in 0..segments - j { + output_indices.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]); + if i + j + 1 < segments { + output_indices.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]); } } } } - out_d.push((first, out_i.len() as u32 - first, material)); + output_draws.push((first, output_indices.len() as u32 - first, material)); } - (out_v, out_i, out_d) + + (output_vertices, output_indices, output_draws) } /// World length per unit of UV over the whole mesh (the square root of their area ratio): how /// far a height change moves the surface for the slope height-to-normal shows. -pub(crate) fn world_per_uv(verts: &[Vertex], indices: &[u32]) -> Option { - let (mut world, mut uv) = (0.0f64, 0.0f64); - for t in indices.chunks_exact(3) { - let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; +pub(crate) fn world_per_uv(vertices: &[Vertex], indices: &[u32]) -> Option { + let (mut world_area, mut uv_area) = (0.0f64, 0.0f64); + for t in indices.as_chunks::<3>().0 { + let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue }; let d = |p: [f32; 3], q: [f32; 3]| [f64::from(q[0] - p[0]), f64::from(q[1] - p[1]), f64::from(q[2] - p[2])]; let (e1, e2) = (d(a.pos, b.pos), d(a.pos, c.pos)); let cross = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; - world += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5; + world_area += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5; let (u1, u2) = ([b.uv[0] - a.uv[0], b.uv[1] - a.uv[1]], [c.uv[0] - a.uv[0], c.uv[1] - a.uv[1]]); - uv += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5; + uv_area += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5; } - let r = (world / uv).sqrt() as f32; - (uv > 1e-12 && r.is_finite() && r > 0.0).then_some(r) + + let scale = (world_area / uv_area).sqrt() as f32; + (uv_area > 1e-12 && scale.is_finite() && scale > 0.0).then_some(scale) } #[cfg(test)] diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index a823a031..36a1c087 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -66,6 +66,9 @@ pub struct TraceScene { pub lens: Option<[f32; 2]>, } +/// Width of the built-in environments traced (texels). +const ENV_SIZE: u32 = 1024; + impl TraceScene { pub fn new(mesh: Arc, bvh: Arc, sets: Vec, env: Arc, env_rotation: f32) -> TraceScene { let mut tri_set = vec![usize::MAX; mesh.triangle_count()]; @@ -114,13 +117,24 @@ impl TraceScene { /// The scene as `display` shows it: the imported environment `env_image` (when the display /// names a resource and it decodes) or the built-in one, its rotation and the shading mode. pub fn for_display(mesh: Arc, bvh: Arc, sets: Vec, display: &DisplaySettings, env_image: Option<&ImageRes>) -> TraceScene { + TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(TraceScene::display_env(display, env_image))) + } + + /// The environment [`TraceScene::for_display`] traces under (building it takes a while: a + /// caller that rebuilds scenes often keeps it and passes it to [`TraceScene::for_display_env`]). + pub fn display_env(display: &DisplaySettings, env_image: Option<&ImageRes>) -> EnvImage { let imported = env_image.and_then(|i| EnvImage::from_rgba(i.width, i.height, &i.rgba, i.srgb)); - let env = imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, 1024)); - let mut scene = TraceScene::new(mesh, bvh, sets, Arc::new(env), display.env_rotation.to_radians()); + imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, ENV_SIZE)) + } + + /// [`TraceScene::for_display`] under `env`, from [`TraceScene::display_env`] of the same display. + pub fn for_display_env(mesh: Arc, bvh: Arc, sets: Vec, display: &DisplaySettings, env: Arc) -> TraceScene { + let mut scene = TraceScene::new(mesh, bvh, sets, env, display.env_rotation.to_radians()); scene.spec_gloss = display.spec_gloss; scene.set_scatter(display.scatter_color, display.scatter_radius); scene.ior = display.ior; scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]); + scene } diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 864c70c3..f6c25615 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::{BakeOverlay, BakeVisualization, CageGeometry, Frame, NeutralMaterial, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -42,19 +43,24 @@ 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(); cam.frame(lo, hi); - let frame = Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true] }; + let frame = + Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true], overlay: Vec::new() }; Some((h, frame)) } @@ -220,6 +226,248 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +/// `overlay` shown +fn shown(overlay: BakeOverlay) -> BakeOverlay { + BakeOverlay { shown: true, ..overlay } +} + +#[test] +fn bake_neutral_material_shades_the_low_poly_in_its_settings() { + const COLOR_LEAD: i32 = 30; + let Some((mut h, frame)) = setup() else { return }; + + let neutral = NeutralMaterial { roughness: 0.5, metallic: 0.0, ao_intensity: 1.0, samples_per_pixel: 16, ..NeutralMaterial::default() }; + let low_poly = BakeOverlay { color: [0.0, 0.0, 0.8], ..shown(BakeVisualization::default().low_poly) }; + let painted_parts = BakeVisualization { low_poly, ..BakeVisualization::default() }; + let neutral_parts = BakeVisualization { neutral: Some(neutral), ..painted_parts }; + let painted = render(&mut h, &shaded(&frame, |s| s.bake = Some(painted_parts)), "bake_neutral_off"); + let blue = render(&mut h, &shaded(&frame, |s| s.bake = Some(neutral_parts)), "bake_neutral_blue"); + let center = (frame.size[0] / 2, frame.size[1] / 2); + let [red, green, blue_channel] = blue.at(center.0, center.1).map(i32::from); + assert!( + blue_channel > red + COLOR_LEAD && blue_channel > green + COLOR_LEAD, + "the neutral material takes the project mesh's color: {:?}", + [red, green, blue_channel] + ); + assert_ne!(blue.px, painted.px, "the painted material is replaced"); + + let metal = BakeVisualization { neutral: Some(NeutralMaterial { metallic: 1.0, roughness: 0.1, ..neutral }), ..neutral_parts }; + assert_ne!(render(&mut h, &shaded(&frame, |s| s.bake = Some(metal)), "bake_neutral_metal").px, blue.px, "roughness and metallic reach the shader"); + + let hidden_low_poly = BakeVisualization { low_poly: BakeOverlay { shown: false, ..low_poly }, ..neutral_parts }; + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_neutral_background"); + assert_same( + &render(&mut h, &shaded(&frame, |s| s.bake = Some(hidden_low_poly)), "bake_neutral_hidden"), + &background, + "a hidden project mesh draws nothing", + ); +} + +#[test] +fn bake_neutral_material_looks_the_same_moving_as_still() { + // Full quality keeps the first frame near settled; one sample missed by 6.6 levels + const MAX_MEAN_LEVELS: f32 = 4.0; + let Some((mut h, frame)) = setup() else { return }; + + let neutral = NeutralMaterial { roughness: 0.5, metallic: 1.0, ..NeutralMaterial::default() }; + let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() }; + let still = shaded(&frame, |s| { + s.taa = true; + s.bake = Some(parts); + }); + let first = render(&mut h, &still, "bake_neutral_first_frame"); + for _ in 1..TAA_SAMPLES { + render(&mut h, &still, "bake_neutral_settling"); + } + let settled = render(&mut h, &still, "bake_neutral_settled"); + + // Compared on the ball in the middle of the view, where the reflections are + let (width, height) = (frame.size[0], frame.size[1]); + let ball = (width * 3 / 8..width * 5 / 8).flat_map(|x| (height / 4..height / 2).map(move |y| (x, y))); + let differences: Vec = ball.map(|(x, y)| (first.luma(x, y) - settled.luma(x, y)).abs()).collect(); + let mean_difference = differences.iter().sum::() / differences.len() as f32; + assert!(mean_difference < MAX_MEAN_LEVELS, "the first frame is {mean_difference} levels off the settled one on average"); +} + +#[test] +fn bake_neutral_material_stays_lit_at_any_roughness_once_settled() { + // Near roughness 0 a bad sample gave NaN, and the settled average of all frames went black + const MIN_BALL_LUMA: f32 = 20.0; + let Some((mut h, frame)) = setup() else { return }; + + for roughness in [0.0, 0.05, 0.1] { + let neutral = NeutralMaterial { roughness, ..NeutralMaterial::default() }; + let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() }; + let still = shaded(&frame, |s| { + s.taa = true; + s.bake = Some(parts); + }); + for _ in 0..TAA_SAMPLES { + render(&mut h, &still, "bake_neutral_mirror_settling"); + } + let settled = render(&mut h, &still, "bake_neutral_mirror_settled"); + let (width, height) = (frame.size[0], frame.size[1]); + let ball = settled.mean(width * 3 / 8, height / 4, width * 5 / 8, height / 2); + assert!(ball > MIN_BALL_LUMA, "roughness {roughness}: the settled ball is black ({ball})"); + } +} + +#[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(CageGeometry { corners: &corners, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY); + let bake = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), ..BakeVisualization::default() }; + 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 high_only = BakeVisualization { high_poly: shown(bake.high_poly), matching_error: shown(bake.matching_error), ..BakeVisualization::default() }; + let caged_parts = BakeVisualization { cage_surface: shown(bake.cage_surface), cage_wire: shown(bake.cage_wire), ..bake }; + let hidden = only(&mut h, BakeVisualization::default(), "bake_low_hidden"); + let high_poly = only(&mut h, high_only, "bake_high_poly"); + let caged = only(&mut h, caged_parts, "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, high_only, "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]); + let no_error = only(&mut h, BakeVisualization { matching_error: bake.matching_error, ..high_only }, "bake_high_missed_hidden"); + assert_same(&no_error, &high_poly, "with the matching error hidden the missed vertices keep the high poly's color"); + let green_error = BakeOverlay { color: [0.0, 1.0, 0.0], ..high_only.matching_error }; + let [red, green, blue] = + only(&mut h, BakeVisualization { matching_error: green_error, ..high_only }, "bake_high_missed_green").at(center.0, center.1).map(i32::from); + assert!(green > red + COLOR_LEAD && green > blue + COLOR_LEAD, "the matching error's color reaches the shader: {:?}", [red, green, blue]); + + // Show for selected texture set only filters the cage (only set 0 has one here), never the low poly + let first_set = only(&mut h, BakeVisualization { only_set: Some(0), ..caged_parts }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { only_set: Some(1), ..caged_parts }, "bake_only_second_set"); + assert_same(&first_set, &caged, "set 0's cage stays and both sets' low poly draws"); + assert_same(&second_set, &low_only, "set 0's cage drops out, the low poly stays"); + + // The cage's surface and wireframe show apart, in their own color and opacity + let surface_only = only(&mut h, BakeVisualization { cage_surface: shown(bake.cage_surface), ..bake }, "bake_cage_surface"); + let wire_only = only(&mut h, BakeVisualization { cage_wire: shown(bake.cage_wire), ..bake }, "bake_cage_wire"); + assert!(surface_only.px != low_only.px && wire_only.px != low_only.px && surface_only.px != wire_only.px, "each part of the cage draws on its own"); + let opaque_blue = BakeOverlay { color: [0.0, 0.0, 1.0], opacity: 1.0, ..caged_parts.cage_surface }; + let [red, green, blue] = + only(&mut h, BakeVisualization { cage_surface: opaque_blue, ..bake }, "bake_cage_surface_blue").at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green + COLOR_LEAD, "an opaque blue cage hides the ball: {:?}", [red, green, blue]); + let clear = only(&mut h, BakeVisualization { cage_surface: BakeOverlay { opacity: 0.0, ..opaque_blue }, ..bake }, "bake_cage_surface_clear"); + assert_same(&clear, &low_only, "a fully transparent cage leaves the ball as it is"); + + // High-poly vertices another set owns are left out + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![-1.0; high.positions.len()]); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_high_hidden_background"); + assert_same(&only(&mut h, high_only, "bake_high_other_set"), &background, "a high poly owned by other sets draws nothing"); + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![0.0; high.positions.len()]); + + // The missing seams draw over the low poly in their color + h.renderer.set_missing_seams(&h.device, &h.queue, MESH_ID, &ball.wire_edges()); + let seams = only(&mut h, BakeVisualization { missing_seams: shown(bake.missing_seams), ..bake }, "bake_missing_seams"); + assert_ne!(seams.px, low_only.px, "the seams show"); + let green_seams = BakeOverlay { color: [0.0, 1.0, 0.0], ..shown(bake.missing_seams) }; + assert_ne!( + only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_green").px, + seams.px, + "the seams' color reaches the shader" + ); + let uv = Frame { view_id: 2, kind: ViewKind::Uv { ts: 0, zoom: 1.0, pan: [0.0, 0.0] }, ..frame.clone() }; + let uv_plain = render(&mut h, &shaded(&uv, |s| s.bake = Some(bake)), "bake_missing_seams_uv_off"); + let uv_seams = render(&mut h, &shaded(&uv, |s| s.bake = Some(BakeVisualization { missing_seams: green_seams, ..bake })), "bake_missing_seams_uv"); + assert_ne!(uv_seams.px, uv_plain.px, "the seams show in the 2D view too"); + let caged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..caged_parts }, "bake_missing_seams_cage"); + let uncaged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_no_cage"); + let caged_plain = only(&mut h, caged_parts, "bake_cage_no_seams"); + assert_ne!(caged_seams.px, caged_plain.px, "the seams show with the cage"); + assert_ne!(caged_seams.px, uncaged_seams.px); + + // 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(CageGeometry { corners: &grown, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY); + let bigger = only(&mut h, caged_parts, "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: shown(BakeVisualization::default().high_poly), ..BakeVisualization::default() }; + 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_but_not_by_selected_set() { + let Some((mut headless, frame)) = setup() else { return }; + + let bake = BakeVisualization::default(); + 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: shown(bake.low_poly), 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 = shaded(&selected, |shade| shade.bake = Some(BakeVisualization { only_set: None, ..shade.bake.unwrap_or(bake) })); + 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 selected-set filter leaves the low poly, its wireframe and highlight alone"); + } +} + #[test] fn ortho_background_matches_perspective() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/texel/src/dilate.rs b/crates/texel/src/dilate.rs index d1f8aeb2..c1c24fce 100644 --- a/crates/texel/src/dilate.rs +++ b/crates/texel/src/dilate.rs @@ -23,9 +23,13 @@ impl DilationMap { /// [`DilationMap::new`] that never pads across the borders of `block × block` squares (the /// UV tiles of an atlas); 0 means one block. pub fn in_blocks(covered: &[bool], width: u32, height: u32, max_dist: Option, block: u32) -> DilationMap { + Self::in_rectangular_blocks(covered, width, height, max_dist, (block, block)) + } + + pub fn in_rectangular_blocks(covered: &[bool], width: u32, height: u32, max_dist: Option, block: (u32, u32)) -> DilationMap { let n = (width as usize).saturating_mul(height as usize); let mut src = vec![NONE; n]; - let bsz = if block == 0 { u32::MAX } else { block }; + let bsz = (if block.0 == 0 { u32::MAX } else { block.0 }, if block.1 == 0 { u32::MAX } else { block.1 }); let is_covered = |i: usize| covered.get(i).copied().unwrap_or(false); // Breadth first, one distance at a time; only island borders seed it (interior texels // have nothing to spread to, so the result is the same at a fraction of the work). @@ -89,12 +93,12 @@ impl DilationMap { /// The 8-neighbours of texel `i` of a `w × h` image inside the image and inside its `bsz` /// square block. -fn neighbours(i: usize, w: u32, h: u32, bsz: u32) -> impl Iterator { +fn neighbours(i: usize, w: u32, h: u32, bsz: (u32, u32)) -> impl Iterator { let (wu, x, y) = (w as usize, (i % w.max(1) as usize) as u32, (i / w.max(1) as usize) as u32); - let left = x > 0 && x % bsz != 0; - let right = x + 1 < w && (x + 1) % bsz != 0; - let up = y > 0 && y % bsz != 0; - let down = y + 1 < h && (y + 1) % bsz != 0; + let left = x > 0 && x % bsz.0 != 0; + let right = x + 1 < w && (x + 1) % bsz.0 != 0; + let up = y > 0 && y % bsz.1 != 0; + let down = y + 1 < h && (y + 1) % bsz.1 != 0; [ (left, i.wrapping_sub(1)), (right, i + 1), @@ -200,3 +204,19 @@ mod tests { assert_eq!(data, [3u16; 16]); } } + +#[cfg(test)] +mod rectangular_test { + use super::*; + #[test] + fn rectangular_tiles_keep_padding_within_both_axes() { + let mut covered = vec![false; 8 * 6]; + covered[2 * 8 + 3] = true; + let padding = DilationMap::in_rectangular_blocks(&covered, 8, 6, None, (4, 3)); + for y in 0..6 { + for x in 0..8 { + assert_eq!(padding.source(x, y).is_some(), x < 4 && y < 3); + } + } + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 7887bf26..c6e42c38 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -14,7 +14,10 @@ texturecraft-render = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] } egui = { workspace = true } craft-ui = { workspace = true } +craft-i18n = { 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 +25,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,15 +32,21 @@ 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). [build-dependencies] +craft-i18n = { workspace = true } skera = "0.8" 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" @@ -49,4 +57,6 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H eframe = { workspace = true, features = ["x11"] } # Offscreen pictures of the whole window (tests/ui_snapshots.rs). egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } +# Fallible setup of the exact GPU device used by rendering regression tests. +pollster = "0.4" image = { workspace = true } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 86168323..322d3297 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -4,6 +4,8 @@ //! recipe follows craft-fonts' `docs/integration.md`; no font file is committed here. The Latin //! faces are embedded without their Private Use Area ([`without_private_use`]). +mod i18n_build; + use std::fmt::Write as _; use std::path::PathBuf; @@ -11,7 +13,7 @@ use std::path::PathBuf; /// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB). const MANIFESTS: &[(&str, Faces, Faces)] = &[ ("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]), - // The interface font, regular and semibold (0.8 MB). + // The interface font has regular and semibold faces (LATIN_MANIFEST, LATIN, LATIN), ]; /// The Arabic face (0.8 MB, so the web build has it too). @@ -23,6 +25,7 @@ const LATIN: Faces = &[("Inter", "Regular"), ("Inter", "SemiBold")]; type Faces = &'static [(&'static str, &'static str)]; fn main() { + i18n_build::embed(); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); @@ -35,6 +38,7 @@ fn main() { Err(e) => println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {e}", dir.display()), } } + src.push_str("];\n"); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); if let Err(e) = std::fs::write(&out, src) { @@ -49,6 +53,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: if rel == LATIN_MANIFEST && !manifest.exists() { return Ok(String::new()); } + let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); let wanted = if wasm { web } else { desktop }; @@ -58,9 +63,11 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let [family, style, file, scripts, ..] = f.as_slice() else { return Err(format!("malformed manifest line: {line}")); }; + if !wanted.contains(&(*family, *style)) { continue; } + let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); if rel == LATIN_MANIFEST { @@ -69,6 +76,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: std::fs::write(&out, without_private_use(&bytes).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{}: {e}", out.display()))?; path = out; } + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, @@ -77,6 +85,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: path.display().to_string(), ); } + Ok(out) } diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs new file mode 100644 index 00000000..cf6ba7e4 --- /dev/null +++ b/crates/ui-egui/i18n_build.rs @@ -0,0 +1,98 @@ +//! Optional shared translation catalogs, embedded at build time. +use std::fmt::Write as _; +use std::path::Path; + +/// Generate Rust includes for the optional catalog checkout; required input must contain app catalogs. +/// Paths are escaped as Rust strings so Windows separators and spaces remain valid. +pub fn generate(dir: Option<&Path>, required: bool) -> Result { + let mut source = String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"); + let Some(dir) = dir else { + if required { + return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into()); + } + source.push_str("];\n"); + return Ok(source); + }; + + if !dir.is_absolute() { + return Err("CRAFT_I18N_DIR must be an absolute path".into()); + } + + let locales = dir.join("locales"); + let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?; + println!("cargo::rerun-if-changed={}", locales.display()); + let mut paths = Vec::new(); + for entry in entries { + let entry = entry.map_err(|e| e.to_string())?; + if entry.file_type().map_err(|e| e.to_string())?.is_dir() { + paths.push(entry.path()); + } + } + + paths.sort(); + let mut count = 0; + let mut catalogs = Vec::new(); + for path in paths { + // Watch directories so adding or removing an app catalog rebuilds the embedding + println!("cargo::rerun-if-changed={}", path.display()); + let app = path.join("texturecraft.tsv"); + if !app.is_file() { + continue; + } + + let locale = path.file_name().and_then(|n| n.to_str()).ok_or("non-UTF-8 locale")?; + let common = path.join("common.tsv"); + let embed = |file: &Path| -> Result<(String, &'static str), String> { + let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; + let name = file.to_str().ok_or("non-UTF-8 catalog path")?; + println!("cargo::rerun-if-changed={name}"); + + // The shared runtime needs static inputs for this short-lived build process + Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str()))) + }; + let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") }; + let (app, app_text) = embed(&app)?; + let code: &'static str = Box::leak(locale.to_owned().into_boxed_str()); + catalogs.push((code, shared_text, app_text)); + let _ = writeln!(source, " ({locale:?}, {shared}, {app}),"); + count += 1; + } + if required && count == 0 { + return Err("no TextureCraft translation catalogs found".into()); + } + + // Reject rows the runtime would skip before required builds can ship English fallbacks + let (runtime, mut problems) = craft_i18n::I18n::new(Box::leak(catalogs.into_boxed_slice()), &[]); + problems.extend(runtime.check_all()); + if !problems.is_empty() { + return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; "))); + } + + source.push_str("];\n"); + Ok(source) +} + +/// Write the embedding for both desktop and wasm, reporting optional failures as warnings. +/// Required input errors stop Cargo instead of silently shipping an English-only release. +pub fn embed() { + println!("cargo::rerun-if-env-changed=CRAFT_I18N_DIR"); + println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED"); + let dir = std::env::var_os("CRAFT_I18N_DIR").map(std::path::PathBuf::from); + let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v == "1"); + let source = match generate(dir.as_deref(), required) { + Ok(source) => source, + Err(error) => { + if required { + println!("cargo::error={error}"); + } else { + println!("cargo::warning=building without craft-i18n: {error}"); + } + "pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into() + } + }; + + let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs"); + if let Err(error) = std::fs::write(&out, source) { + println!("cargo::error=writing {}: {error}", out.display()); + } +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs new file mode 100644 index 00000000..4b60f6f0 --- /dev/null +++ b/crates/ui-egui/src/bake_job.rs @@ -0,0 +1,10 @@ +use crate::RunningBake; + +/// A background bake of one or more texture sets. +pub struct BakeJob { + pub queue: Vec, + pub current: Option, + pub total: usize, + /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. + pub mesh_id: u64, +} diff --git a/crates/ui-egui/src/bake_mode/bake_checks.rs b/crates/ui-egui/src/bake_mode/bake_checks.rs new file mode 100644 index 00000000..36b91298 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_checks.rs @@ -0,0 +1,223 @@ +//! Problems the next bake would have, listed above the bake bar before Bake is pressed + +use std::sync::{Arc, Weak}; + +use egui_phosphor::regular as icon; +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; + +use crate::TextureCraftApp; +use crate::i18n::trf; +use crate::theme::Tokens; + +/// Share of a texture set's UV layout that may overlap before it is listed (as mesh import warns) +const UV_OVERLAP_WARNING: f32 = 0.01; + +/// How many part names a warning spells out before "and N more" +const NAMES_SHOWN: usize = 3; + +/// The warnings' gap above the bake bar +const WARNINGS_GAP: f32 = 8.0; + +/// The warnings above bake mode's bake bar in the 3D view `viewport`, until a bake starts +pub(crate) fn bake_warnings(app: &TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { + if app.bake_progress().is_some() { + return; + } + + let warnings = cached_warnings(ctx, &app.session); + if warnings.is_empty() { + return; + } + + let tokens = Tokens::get(ctx); + let above_bar = super::BAKE_BAR_MARGIN + ctx.global_style().spacing.interact_size.y + WARNINGS_GAP; + egui::Area::new(egui::Id::unique("bake_warnings")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -above_bar)).show( + ctx, + |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| { + for warning in warnings.iter() { + ui.label(egui::RichText::new(format!("{} {warning}", icon::WARNING)).color(tokens.warning)); + } + }); + }, + ); +} + +/// The warnings for the texture sets the next bake includes, worked out again only when what they read changes +pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc> { + let id = egui::Id::unique("bake_check_warnings"); + let key = inputs_key(session); + + // A handle, not an address: a rebuilt high poly could reuse a dropped one's address + let high = session.bake_meshes.merged_high().map_or_else(Weak::new, |high| Arc::downgrade(&high.mesh)); + if let Some((cached_key, cached_high, cached)) = ctx.data(|data| data.get_temp::<(String, Weak, Arc>)>(id)) + && cached_key == key + && cached_high.ptr_eq(&high) + { + return cached; + } + + let fresh = Arc::new(warnings(session)); + ctx.data_mut(|data| data.insert_temp(id, (key, high, fresh.clone()))); + fresh +} + +/// Everything the warnings read or show apart from the high poly (cached as a handle): the low poly, the UI language, and per included set its name, material, high-poly settings, UV tile resolutions and the tiles left out of the bake +fn inputs_key(session: &Session) -> String { + let sets: Vec<_> = baked_sets(session) + .filter_map(|index| { + let set = session.doc.project.texture_sets.get(index)?; + Some((index, &set.name, set.material, &set.bake.high_poly, &set.tile_resolutions, &set.bake_excluded_tiles)) + }) + .collect(); + + format!("{}|{}|{sets:?}", session.mesh_id, crate::i18n::current().code) +} + +/// The texture sets the next bake includes +fn baked_sets(session: &Session) -> impl Iterator + '_ { + session.doc.project.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.common.is_enabled && set.has_enabled_bake_tiles()).map(|(index, _)| index) +} + +/// Overlapping UVs per included set, its low-poly parts "By Mesh Name" pairs with nothing, then the high-poly parts no included set bakes from +pub(crate) fn warnings(session: &Session) -> Vec { + let mut lines = Vec::new(); + let included: Vec = baked_sets(session).collect(); + for &index in &included { + let Some(set) = session.doc.project.texture_sets.get(index) else { continue }; + + let overlap = session.bake_uv_overlap(index).unwrap_or(0.0); + if overlap > UV_OVERLAP_WARNING { + let percent = format!("{:.1}", overlap * 100.0); + lines.push(trf( + "{set}: {percent}% of the UV layout overlaps, so those texels bake one place for several", + &[("set", &set.name), ("percent", &percent)], + )); + } + + let Ok(Some(pairs)) = session.bake_name_pairs(index) else { continue }; + + let unpaired_low: Vec<&str> = pairs.iter().filter(|pair| pair.high.is_none()).filter_map(|pair| pair.low.as_deref()).collect(); + if !unpaired_low.is_empty() { + lines.push(trf("{set}: no high poly part matches {names}", &[("set", &set.name), ("names", &listed(&unpaired_low))])); + } + } + + let unpaired_high = session.bake_unpaired_high_parts(&included).unwrap_or_default(); + if !unpaired_high.is_empty() { + let names: Vec<&str> = unpaired_high.iter().map(String::as_str).collect(); + lines.push(trf("No low poly part matches {names}", &[("names", &listed(&names))])); + } + + lines +} + +/// `names` joined, the first few spelled out and the rest counted +fn listed(names: &[&str]) -> String { + let shown = names.iter().take(NAMES_SHOWN).copied().collect::>().join(", "); + match names.len().checked_sub(NAMES_SHOWN).filter(|more| *more > 0) { + Some(more) => trf("{names} and {count} more", &[("names", &shown), ("count", &more)]), + None => shown, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::MeshMatchMode; + + /// Part `index` named `name` (an OBJ object): a quad at x offset `x` whose UVs span `u` to `u` + 0.2 + fn quad(name: &str, index: usize, x: f32, u: f32) -> String { + let first = index * 4 + 1; + format!( + "o {name}\nv {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\nvt {u} 0\nvt {} 0\nvt {} 1\nvt {u} 1\nf {first}/{first} {}/{} {}/{} {}/{}\n", + x + 1.0, + x + 1.0, + u + 0.2, + u + 0.2, + first + 1, + first + 1, + first + 2, + first + 2, + first + 3, + first + 3 + ) + } + + fn session(overlapping: bool) -> Session { + let names = ["Box_low", "Lid_low", "Bolt_low", "Nut_low", "Pin_low"]; + let obj: String = + names.iter().enumerate().map(|(index, name)| quad(name, index, index as f32 * 2.0, if overlapping { 0.0 } else { index as f32 * 0.2 })).collect(); + Session::from_mesh_bytes("parts.obj", obj.as_bytes(), 128, "parts").unwrap() + } + + #[test] + fn a_clean_setup_lists_nothing() { + let mut session = session(false); + assert_eq!(warnings(&session), Vec::::new()); + session.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + assert_eq!(warnings(&session), Vec::::new(), "\"Always\" pairs every part"); + } + + #[test] + fn renaming_a_set_refreshes_the_cached_warnings() { + let mut session = session(true); + let ctx = egui::Context::default(); + let before = cached_warnings(&ctx, &session); + assert!(before.iter().any(|line| line.starts_with(&session.doc.project.texture_sets[0].name)), "{before:?}"); + + session.doc.project.texture_sets[0].name = "Renamed".into(); + let after = cached_warnings(&ctx, &session); + assert!(after.iter().any(|line| line.starts_with("Renamed:")), "{after:?}"); + } + + #[test] + fn swapping_the_high_poly_refreshes_the_cached_warnings() { + let mut session = session(false); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + session.add_high_poly_bytes("spare.obj", b"o Spare_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let ctx = egui::Context::default(); + assert!(cached_warnings(&ctx, &session).contains(&"No low poly part matches Spare_high".to_owned())); + + // The new high poly's mesh may take the dropped one's address + drop(session.remove_high_poly(0).unwrap()); + session.add_high_poly_bytes("box.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let after = cached_warnings(&ctx, &session); + assert!(!after.iter().any(|line| line.contains("Spare_high")), "{after:?}"); + } + + #[test] + fn leaving_the_overlapping_tile_out_refreshes_the_cached_warnings() { + // One quad in tile 1001, two on the same UVs in tile 1002 + let obj = [quad("First_low", 0, 0.0, 0.0), quad("Second_low", 1, 2.0, 1.0), quad("Third_low", 2, 4.0, 1.0)].concat(); + let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap(); + let ctx = egui::Context::default(); + assert_eq!(cached_warnings(&ctx, &session).len(), 1, "tile 1002 overlaps"); + + session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002); + assert_eq!(*cached_warnings(&ctx, &session), Vec::::new(), "tile 1001 alone has no overlap"); + } + + #[test] + fn overlapping_uvs_and_unpaired_parts_are_listed() { + let mut session = session(true); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Spare_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let set = session.doc.project.texture_sets[0].name.clone(); + + assert_eq!( + warnings(&session), + [ + format!("{set}: 100.0% of the UV layout overlaps, so those texels bake one place for several"), + format!("{set}: no high poly part matches Lid_low, Bolt_low, Nut_low and 1 more"), + "No low poly part matches Spare_high".to_owned(), + ] + ); + + session.doc.project.texture_sets[0].bake.common.is_enabled = false; + assert_eq!(warnings(&session), Vec::::new(), "a set the bake leaves out is not checked"); + } +} diff --git a/crates/ui-egui/src/bake_mode/bake_paint_brush.rs b/crates/ui-egui/src/bake_mode/bake_paint_brush.rs new file mode 100644 index 00000000..ee2c977a --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_paint_brush.rs @@ -0,0 +1,17 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_engine::core::BakePaintTarget; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct BakePaintBrush { + pub on: bool, + pub target: BakePaintTarget, + pub radius: f32, + pub value: f32, + pub hardness: f32, +} + +impl Default for BakePaintBrush { + fn default() -> Self { + Self { on: false, target: BakePaintTarget::Skew, radius: 0.03, value: 1.0, hardness: 0.5 } + } +} 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..5c4d02cc --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -0,0 +1,194 @@ +use egui::collapsing_header::CollapsingState; +use egui::{Rect, Ui, vec2}; +use egui_phosphor::regular as icon; +use texturecraft_render::BakeOverlay; + +use super::BakeVisualizationToggles; +use super::section_opening::SectionOpening; +use crate::TextureCraftApp; +use crate::i18n::{n_, tr, trf}; +use crate::screen_color_pick::eyedropper; +use crate::theme::Tokens; +use crate::widgets::{color_swatch, combo, icon_button, section_chevron, slider}; + +/// 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; + +/// Opacity of the panel's backing +const PANEL_OPACITY: f32 = 0.92; + +/// Size of the panel's eye button, and of the smaller buttons on its rows +const EYE_BUTTON_SIZE: f32 = 22.0; +const ROW_BUTTON_SIZE: f32 = 18.0; + +/// Width of an overlay's color swatch +const SWATCH_WIDTH: f32 = 44.0; + +/// The neutral material's quality steps: samples per pixel and their names +const QUALITIES: [(u32, &str); 6] = [ + (4, n_("Very Low (4 spp)")), + (16, n_("Low (16 spp)")), + (32, n_("Medium (32 spp)")), + (64, n_("High (64 spp)")), + (128, n_("Very High (128 spp)")), + (256, n_("Ultra (256 spp)")), +]; + +/// 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; + let tokens = Tokens::get(ui.ctx()); + 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| { + // Its own backing, so the panel reads in every theme over whatever the 3D view shows + egui::Frame::popup(ui.style()).fill(tokens.panel.gamma_multiply(PANEL_OPACITY)).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + + // Ids renamed with the reference defaults, so open/closed states saved by earlier builds don't carry over + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("baking_visualization_open"), true); + if header(ui, toggles, collapsing_state.is_open()).clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles)); + }); + }, + ); +} + +/// The panel's sections below its header +fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { + ui.horizontal(|ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(egui::RichText::new(icon::INFO).color(Tokens::get(ui.ctx()).text_dim)) + .on_hover_text(tr("Only the cage and the high poly meshes of the selected texture set show.")); + }); + }); + + // The eye greys what it hides, and holds the project mesh shown + let meshes_editable = !toggles.hide_baking_meshes; + if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| { + overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh); + overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error); + }) { + toggles.reset_high_poly(); + } + + if collapsible(ui, "cage", tr("Cage"), SectionOpening::Open, true, meshes_editable, |ui| { + overlay_row(ui, "bake_cage_surface_color", tr("Cage Surface"), &mut toggles.cage_surface); + ui.add_enabled_ui(toggles.cage_surface.shown, |ui| slider(ui, tr("Cage Surface Opacity"), &mut toggles.cage_surface.opacity, 0.0..=1.0, 2)); + overlay_row(ui, "bake_cage_wire_color", tr("Cage Wireframe"), &mut toggles.cage_wire); + ui.add_enabled_ui(toggles.cage_wire.shown, |ui| slider(ui, tr("Cage Wireframe Opacity"), &mut toggles.cage_wire.opacity, 0.0..=1.0, 2)); + }) { + toggles.reset_cage(); + } + + if collapsible(ui, "seams", tr("UV Seams"), SectionOpening::Closed, true, true, |ui| { + overlay_row(ui, "bake_missing_seam_color", tr("Missing Seams on Hard Edges"), &mut toggles.missing_seams); + }) { + toggles.reset_seams(); + } + + if collapsible(ui, "project_mesh", tr("Project Mesh (LP)"), SectionOpening::Closed, true, true, |ui| { + ui.add_enabled_ui(meshes_editable, |ui| overlay_row(ui, "bake_project_mesh_color", tr("Project Mesh"), &mut toggles.project_mesh)); + ui.add_enabled_ui(toggles.project_mesh.shown, |ui| { + collapsible(ui, "neutral_material", tr("Neutral Material"), SectionOpening::Open, false, true, |ui| neutral_material(ui, toggles)) + }); + }) { + toggles.reset_project_mesh(); + } +} + +/// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal +fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { + ui.add_enabled_ui(toggles.neutral_shown, |ui| { + let neutral = &mut toggles.neutral; + let selected = QUALITIES.iter().find(|(samples, _)| *samples == neutral.samples_per_pixel).map_or("", |(_, name)| tr(name)); + combo(ui, tr("Quality"), selected, |ui| { + for (samples, name) in QUALITIES { + ui.selectable_value(&mut neutral.samples_per_pixel, samples, tr(name)); + } + }); + slider(ui, tr("Roughness"), &mut neutral.roughness, 0.0..=1.0, 2); + slider(ui, tr("Metallic"), &mut neutral.metallic, 0.0..=1.0, 2); + slider(ui, tr("AO intensity"), &mut neutral.ao_intensity, 0.0..=1.0, 2); + ui.checkbox(&mut neutral.bent_normal, tr("Bent Normal")); + ui.add_enabled_ui(neutral.bent_normal, |ui| { + slider(ui, tr("Bent Normal Diffuse Amount"), &mut neutral.bent_normal_diffuse, 0.0..=1.0, 2); + slider(ui, tr("Bent Normal Specular Amount"), &mut neutral.bent_normal_specular, 0.0..=1.0, 2); + }); + }); +} + +/// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked +fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool { + let tokens = Tokens::get(ui.ctx()); + let mut collapsing_state = + CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open); + let (header, reset) = ui + .horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = egui::RichText::new(format!("{} {title}", section_chevron(ui, collapsing_state.is_open()).text())).strong().color(tokens.text_strong); + let header = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); + + // Dimmed while the section is closed, as the reference draws it + let reset = resettable.then(|| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(collapsing_state.is_open() && editable, |ui| { + icon_button(ui, icon::CLOCK_COUNTER_CLOCKWISE, &trf("Reset {section}", &[("section", &title)]), false, ROW_BUTTON_SIZE) + }) + .inner + }) + .inner + }); + (header, reset) + }) + .inner; + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_indented(&header, ui, |ui| { + ui.add_enabled_ui(editable, body); + }); + reset.is_some_and(|reset| reset.clicked()) +} + +/// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right +fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) { + ui.horizontal(|ui| { + ui.checkbox(&mut overlay.shown, label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(overlay.shown, |ui| { + eyedropper( + ui, + ui.make_persistent_id(id), + &mut overlay.color, + &trf("Pick the {overlay} Color from the Screen", &[("overlay", &label)]), + ROW_BUTTON_SIZE, + ); + color_swatch(ui, id, &mut overlay.color, SWATCH_WIDTH); + }); + }); + }); +} + +/// The panel's title with a chevron showing whether the panel is `open`, and the eye that hides the baking meshes; returns the title's response +fn header(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, open: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = egui::RichText::new(format!("{} {}", section_chevron(ui, open).text(), tr("Baking Visualization"))).color(tokens.text_strong); + let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button(ui, icon::EYE_SLASH, tr("Hide Baking Meshes"), toggles.hide_baking_meshes, EYE_BUTTON_SIZE).clicked() { + toggles.toggle_hiding(); + } + }); + 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..bb99e09b --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -0,0 +1,140 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial}; + +/// Opacity of the cage's surface and wireframe until changed +const CAGE_OPACITY: f32 = 0.4; + +/// The Baking Visualization panel's settings for bake mode's 3D view (view state, not saved in the project) +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeVisualizationToggles { + /// The panel's eye: hides the high poly and the cage, whatever their own switches say + pub hide_baking_meshes: bool, + pub selected_set_only: bool, + pub high_poly_mesh: BakeOverlay, + pub matching_error: BakeOverlay, + pub cage_surface: BakeOverlay, + pub cage_wire: BakeOverlay, + pub missing_seams: BakeOverlay, + pub project_mesh: BakeOverlay, + /// Show the project mesh with [`Self::neutral`] instead of its painted material + pub neutral_shown: bool, + pub neutral: NeutralMaterial, +} + +impl Default for BakeVisualizationToggles { + fn default() -> Self { + let parts = BakeVisualization::default(); + let shown = |overlay: BakeOverlay| BakeOverlay { shown: true, ..overlay }; + Self { + hide_baking_meshes: false, + selected_set_only: false, + high_poly_mesh: shown(parts.high_poly), + matching_error: shown(parts.matching_error), + cage_surface: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_surface) }, + cage_wire: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_wire) }, + missing_seams: shown(parts.missing_seams), + project_mesh: shown(parts.low_poly), + neutral_shown: true, + neutral: NeutralMaterial::default(), + } + } +} + +impl BakeVisualizationToggles { + /// What the renderer draws with these settings while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> BakeVisualization { + let unless_hidden = |overlay: BakeOverlay| BakeOverlay { shown: overlay.shown && !self.hide_baking_meshes, ..overlay }; + BakeVisualization { + high_poly: unless_hidden(self.high_poly_mesh), + matching_error: self.matching_error, + cage_surface: unless_hidden(self.cage_surface), + cage_wire: unless_hidden(self.cage_wire), + missing_seams: self.missing_seams, + low_poly: self.project_mesh, + neutral: self.neutral_shown.then_some(self.neutral), + only_set: self.selected_set_only.then_some(selected_set), + } + } + + /// Whether the project mesh shows the neutral material lit along the bent normal, which the 3D view then reads in place of a mesh map + pub fn bent_normal_shown(&self) -> bool { + self.project_mesh.shown && self.neutral_shown && self.neutral.bent_normal + } + + /// Switch the panel's eye; hiding the baking meshes shows the project mesh, so the view never goes empty + pub fn toggle_hiding(&mut self) { + self.hide_baking_meshes = !self.hide_baking_meshes; + self.project_mesh.shown |= self.hide_baking_meshes; + } + + /// Put the High Definition Mesh section back to its defaults + pub fn reset_high_poly(&mut self) { + let defaults = Self::default(); + (self.high_poly_mesh, self.matching_error) = (defaults.high_poly_mesh, defaults.matching_error); + } + + /// Put the Cage section back to its defaults + pub fn reset_cage(&mut self) { + let defaults = Self::default(); + (self.cage_surface, self.cage_wire) = (defaults.cage_surface, defaults.cage_wire); + } + + /// Put the UV Seams section back to its defaults + pub fn reset_seams(&mut self) { + self.missing_seams = Self::default().missing_seams; + } + + /// Put the Project Mesh section back to its defaults + pub fn reset_project_mesh(&mut self) { + let defaults = Self::default(); + (self.project_mesh, self.neutral_shown, self.neutral) = (defaults.project_mesh, defaults.neutral_shown, defaults.neutral); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn panel_settings_saved_by_earlier_builds_start_over_from_the_defaults() { + let mut saved = serde_json::to_value(crate::state::UiState::default()).unwrap(); + let fields = saved.as_object_mut().unwrap(); + fields.remove("baking_visualization"); + fields.insert( + "bake_visualization".into(), + serde_json::json!({"hide_baking_meshes": false, "missing_seams": {"shown": false, "color": [1, 0, 0], "opacity": 1}}), + ); + let state: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(state.bake_visualization, BakeVisualizationToggles::default()); + } + + #[test] + fn the_settings_reach_the_renderer() { + let mut toggles = BakeVisualizationToggles::default(); + toggles.cage_wire.color = [0.1, 0.2, 0.3]; + toggles.neutral_shown = false; + let visualization = toggles.visualization(2); + assert_eq!(visualization.cage_wire, toggles.cage_wire); + assert_eq!(visualization.neutral, None); + assert_eq!(visualization.only_set, None); + toggles.selected_set_only = true; + assert_eq!(toggles.visualization(2).only_set, Some(2)); + } + + #[test] + fn the_eye_hides_the_baking_meshes_and_keeps_the_project_mesh() { + let mut toggles = BakeVisualizationToggles::default(); + let shown = toggles.visualization(0); + assert!(shown.high_poly.shown && shown.cage_surface.shown && shown.cage_wire.shown, "the eye starts off, as in the reference"); + + toggles.project_mesh.shown = false; + toggles.toggle_hiding(); + let hidden = toggles.visualization(0); + assert!(!hidden.high_poly.shown && !hidden.cage_surface.shown && !hidden.cage_wire.shown); + assert!(hidden.low_poly.shown, "hiding the baking meshes brings the project mesh back"); + + toggles.toggle_hiding(); + assert!(toggles.visualization(0).high_poly.shown, "the eye switches back"); + } +} 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 new file mode 100644 index 00000000..1953d2d3 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -0,0 +1,275 @@ +use super::controls::{choice, hint, integer, number, section, text_input}; +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::icon_button; +use egui::Ui; +use egui_phosphor::regular as icon; +use serde_json::{Map, Value, json}; +use texturecraft_engine::core::{ + BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, +}; + +/// How many rows the high poly list box is tall +const HIGH_POLY_LIST_ROWS: f32 = 5.0; + +/// Space between the panel's sections, in points +const SECTION_GAP: f32 = 8.0; + +/// Widest dilation the slider offers, in texels (the bake settings command accepts the same) +const MAX_DILATION_WIDTH: u32 = 128; + +/// The output and high-poly sections, then cage and skew, greyed with the reason when they can't apply +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"), |ui| { + output_size(ui, &mut settings.common); + choice( + ui, + tr("Antialiasing"), + &mut settings.common.antialiasing, + &[ + (BakeAntialiasing::None, tr("None")), + (BakeAntialiasing::Subsampling2x2, tr("Subsampling 2x2")), + (BakeAntialiasing::Subsampling4x4, tr("Subsampling 4x4")), + (BakeAntialiasing::Subsampling8x8, tr("Subsampling 8x8")), + ], + ); + integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); + 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); + } + }); + + // Without a high poly the reference shows everything that needs one greyed, not hidden + let has_high = !app.session.bake_meshes.high.is_empty(); + ui.add_space(SECTION_GAP); + ui.push_id("high_poly", |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_scene(app, ui); + ui.add_enabled_ui(has_high, |ui| { + ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); + choice( + ui, + tr("Match"), + &mut settings.high_poly.match_mode, + &[(MeshMatchMode::Always, tr("Always")), (MeshMatchMode::ByMeshName, tr("By Mesh Name"))], + ); + text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); + text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); + text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); + }); + }) { + settings.high_poly = Default::default(); + reset.insert("high_poly".into(), json!(settings.high_poly)); + } + }); + + ui.add_space(SECTION_GAP); + ui.push_id("cage", |ui| { + if section(ui, tr("Cage"), |ui| { + // The cage steers rays toward a separate high poly, so it has nothing to do without one + let cage_applies = has_high && !settings.high_poly.use_low_as_high; + if !has_high { + hint(ui, tr("The cage applies once a high poly mesh is loaded.")); + } else if !cage_applies { + hint(ui, tr("The cage is not used while the low poly mesh is used as the high poly mesh.")); + } + ui.add_enabled_ui(cage_applies, |ui| { + choice( + ui, + tr("Cage Type"), + &mut settings.cage.kind, + &[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))], + ); + if settings.cage.kind == CageType::DistanceBased { + paint_brush(app, ui, BakePaintTarget::Cage); + number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); + number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); + ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); + ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); + } + }); + if settings.cage.kind == CageType::CustomFile { + cage_file(app, ui, cage_applies); + } + }) { + settings.cage = Default::default(); + reset.insert("cage".into(), json!(settings.cage)); + } + }); + + // Shown greyed when it can't apply, as the reference does, with the reason on top + let skew_applies = has_high && settings.skew_applies(); + ui.add_space(SECTION_GAP); + ui.push_id("skew", |ui| { + if section(ui, tr("Skew Correction"), |ui| { + if !skew_applies { + hint(ui, skew_unavailable_reason(settings, has_high)); + } + ui.add_enabled_ui(skew_applies, |ui| { + choice( + ui, + tr("Skew Correction Method"), + &mut settings.skew.method, + &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], + ); + paint_brush(app, ui, BakePaintTarget::Skew); + ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); + number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); + 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)) +} + +/// Why Skew Correction can't apply: no high poly (`has_high` false), or `settings` rule it out (see [`BakeSettings::skew_applies`]) +fn skew_unavailable_reason(settings: &BakeSettings, has_high: bool) -> &'static str { + if !has_high { + tr("Skew Correction applies once a high poly mesh is loaded.") + } else if settings.high_poly.use_low_as_high { + tr("Skew Correction is not available while the low poly mesh is used as the high poly mesh.") + } else if settings.cage.kind == CageType::CustomFile { + tr("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself.") + } else { + tr("Skew Correction needs Average Normals turned on in the cage settings.") + } +} + +fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { + ui.label(tr("Output Size")); + ui.horizontal(|ui| { + 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 { + ui.selectable_value(value, resolution, resolution.pixels().to_string()); + } + }); + }; + + resolution(ui, "output_width", &mut settings.resolution); + let locked = settings.resolution_height.is_none(); + let mut height = settings.resolution_height.unwrap_or(settings.resolution); + ui.add_enabled_ui(!locked, |ui| resolution(ui, "output_height", &mut height)); + 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, button_size).clicked() { + settings.resolution_height = if locked { Some(settings.resolution) } else { None }; + } + }); +} + +/// The high poly meshes as a list box, with + to add some and − to remove the selected one +fn high_poly_scene(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let names: Vec = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); + let selected_id = ui.make_persistent_id("high_poly_selected"); + let mut selected = ui.data(|data| data.get_temp::(selected_id)).filter(|index| *index < names.len()); + + ui.label(tr("High Poly Scene")); + let (mut add, mut remove) = (false, false); + ui.horizontal_top(|ui| { + let button_size = ui.spacing().interact_size.y; + let list_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); + let list_height = HIGH_POLY_LIST_ROWS * ui.spacing().interact_size.y; + egui::Frame::NONE.fill(tokens.field).stroke(egui::Stroke::new(1.0, tokens.field_border)).corner_radius(tokens.cr()).show(ui, |ui| { + ui.set_min_size(egui::vec2(list_width, list_height)); + ui.set_max_width(list_width); + egui::ScrollArea::both().id_salt("high_poly_list").max_height(list_height).auto_shrink([false; 2]).show(ui, |ui| { + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(selected == Some(index), name).on_hover_text(name).clicked() { + selected = Some(index); + } + } + }); + }); + ui.vertical(|ui| { + add = icon_button(ui, icon::PLUS, tr("Add High-Poly Meshes"), false, button_size).clicked(); + remove = ui.add_enabled_ui(selected.is_some(), |ui| icon_button(ui, icon::MINUS, tr("Remove"), false, button_size)).inner.clicked(); + }); + }); + + if let (true, Some(index)) = (remove, selected) { + app.run("bake.highPoly.remove", json!({ "index": index })); + selected = None; + } + ui.data_mut(|data| { + if let Some(index) = selected { + data.insert_temp(selected_id, index); + } else { + data.remove_temp::(selected_id); + } + }); + if add { + crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false); + } +} + +/// The cage file row; while the cage can't `apply` only removing a loaded one stays available, so a saved cage can still be dropped +fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui, apply: bool) { + ui.add_enabled(apply, egui::Label::new(tr("Cage Scene"))); + let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); + ui.horizontal(|ui| { + 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_enabled_ui(apply, |ui| { + 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, button_size).clicked() { + app.run("bake.cage.clear", json!({})); + } + }); +} + +fn paint_brush(app: &mut TextureCraftApp, ui: &mut Ui, target: BakePaintTarget) { + let (label, clear_label, clear_command) = match target { + BakePaintTarget::Cage => ("Paint Cage", "Reset Painted Cage", "bake.cage.reset"), + BakePaintTarget::Skew => ("Paint Skew Correction", "Remove Skew Correction", "bake.skew.clear"), + }; + let mut brush = app.ui.bake_paint_brush; + let active = brush.on && brush.target == target; + if ui.add(egui::Button::new(tr(label)).selected(active)).clicked() { + brush.on = !active; + if brush.target != target { + brush.value = match target { + BakePaintTarget::Cage => 0.5, + BakePaintTarget::Skew => 1.0, + }; + } + brush.target = target; + } + if brush.on && brush.target == target { + number(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3); + number(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2); + number(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); + if app.ui.layout == crate::state::ViewLayout::Only3D { + app.ui.layout = crate::state::ViewLayout::Split; + } + } + app.ui.bake_paint_brush = brush; + if app.session.doc.bake_paint.contains_key(&(app.session.ts(), target)) && ui.button(tr(clear_label)).clicked() { + app.run(clear_command, json!({})); + } +} diff --git a/crates/ui-egui/src/bake_mode/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs new file mode 100644 index 00000000..f260bf7c --- /dev/null +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -0,0 +1,88 @@ +use crate::i18n::tr; +use crate::theme::{Tokens, caption}; +use egui::collapsing_header::CollapsingState; +use egui::{RichText, Ui}; + +/// 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 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); + 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 + }); + + let response = ui.interact(header.response.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(header.inner, egui::Label::new(chevron).selectable(false)); +} + +/// 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); + section_header(ui, title, &mut collapsing_state); + + collapsing_state + .show_body_unindented(ui, |ui| { + egui::Frame::NONE + .inner_margin(egui::Margin::same(8)) + .show(ui, |ui| { + contents(ui); + ui.add_space(6.0); + ui.button(tr("Restore Defaults")).clicked() + }) + .inner + }) + .is_some_and(|response| response.inner) +} + +pub(super) fn choice(ui: &mut Ui, label: &str, value: &mut T, options: &[(T, &str)]) { + let caption = ui.label(label); + let selected = options.iter().find(|(option, _)| option == value).map_or("", |(_, label)| *label); + egui::ComboBox::from_id_salt(label) + .width(ui.available_width()) + .selected_text(selected) + .show_ui(ui, |ui| { + for (option, label) in options { + ui.selectable_value(value, *option, *label); + } + }) + .response + .labelled_by(caption.id); +} + +pub(super) fn number(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) { + let response = crate::widgets::slider(ui, label, value, range.clone(), decimals); + if response.changed() && (response.dragged() || response.clicked()) { + let scale = 10_f32.powi(decimals as i32); + *value = ((*value * scale).round() / scale).clamp(*range.start(), *range.end()); + } +} + +pub(super) fn integer(ui: &mut Ui, label: &str, value: &mut u32, range: std::ops::RangeInclusive) { + let mut number_value = *value as f32; + let response = crate::widgets::slider(ui, label, &mut number_value, *range.start() as f32..=*range.end() as f32, 0); + if response.changed() { + *value = (number_value.round() as u32).clamp(*range.start(), *range.end()); + } +} + +pub(super) fn text_input(ui: &mut Ui, label: &str, value: &mut String) { + ui.label(label); + ui.add(egui::TextEdit::singleline(value).desired_width(ui.available_width())); +} + +pub(super) fn hint(ui: &mut Ui, text: &str) { + ui.label(RichText::new(text).color(Tokens::get(ui.ctx()).text_dim).size(11.0)); +} diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs new file mode 100644 index 00000000..5168d341 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -0,0 +1,193 @@ +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, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, + RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, +}; + +/// 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 => { + hint(ui, tr("No Parameters")); + None + } + 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), + } +} + +/// 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) { + choice( + ui, + tr("Color Source"), + &mut settings.source, + &[ + (IdColorSource::VertexColor, tr("Vertex Color")), + (IdColorSource::MaterialColor, tr("Material Color")), + (IdColorSource::FileId, tr("File ID")), + (IdColorSource::MeshId, tr("Mesh ID")), + (IdColorSource::Submesh, tr("Submesh")), + ], + ); + if matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh) { + choice( + ui, + tr("Color Generator"), + &mut settings.generator, + &[(IdColorGenerator::Random, tr("Random")), (IdColorGenerator::HueShift, tr("Hue Shift")), (IdColorGenerator::Grayscale, tr("Grayscale"))], + ); + } +} + +fn rays(ui: &mut Ui, settings: &mut RaySettings) { + integer(ui, tr("Secondary Rays"), &mut settings.rays, 1..=256); + number(ui, tr("Min Occluder Distance"), &mut settings.min_distance, 0.00001..=1.0, 5); + number(ui, tr("Max Occluder Distance"), &mut settings.max_distance, 0.00001..=if settings.relative_to_bounding_box { 1.0 } else { 10.0 }, 5); + if ui.checkbox(&mut settings.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && settings.relative_to_bounding_box { + settings.max_distance = settings.max_distance.min(1.0); + } + number(ui, tr("Spread Angle"), &mut settings.spread, 0.0..=180.0, 0); + choice(ui, tr("Distribution"), &mut settings.distribution, &[(RayDistribution::Uniform, tr("Uniform")), (RayDistribution::Cosine, tr("Cosine"))]); +} + +fn backface(ui: &mut Ui, settings: &mut BackfaceMode) { + choice( + ui, + tr("Ignore Backface"), + settings, + &[(BackfaceMode::Never, tr("Never")), (BackfaceMode::Always, tr("Always")), (BackfaceMode::ByMeshName, tr("By Mesh Name"))], + ); +} + +fn occlusion(ui: &mut Ui, label: &str, settings: &mut SelfOcclusion) { + choice(ui, label, settings, &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only Same Mesh Name"))]); +} + +fn ambient_occlusion(ui: &mut Ui, settings: &mut AmbientOcclusionSettings) { + rays(ui, &mut settings.rays); + backface(ui, &mut settings.ignore_backface); + occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); + choice( + ui, + tr("Attenuation"), + &mut settings.attenuation, + &[ + (AmbientOcclusionAttenuation::None, tr("None")), + (AmbientOcclusionAttenuation::Smooth, tr("Smooth")), + (AmbientOcclusionAttenuation::Linear, tr("Linear")), + ], + ); + ui.checkbox(&mut settings.ground_plane.enabled, tr("Ground Plane")); + if settings.ground_plane.enabled { + number(ui, tr("Ground Plane Offset"), &mut settings.ground_plane.offset, 0.0..=100.0, 2); + } +} + +fn curvature(ui: &mut Ui, settings: &mut CurvatureSettings) { + choice( + ui, + tr("Method"), + &mut settings.method, + &[(CurvatureMethod::NormalMap, tr("Generate from Normal Map")), (CurvatureMethod::Mesh, tr("Generate from Mesh"))], + ); + match settings.method { + CurvatureMethod::NormalMap => { + number(ui, tr("Details"), &mut settings.normal_map.details, 0.0..=1.0, 2); + ui.checkbox(&mut settings.normal_map.enable_seams, tr("Enable Seams")); + if settings.normal_map.enable_seams { + number(ui, tr("Seams Intensity"), &mut settings.normal_map.seams_intensity, 0.0..=1.0, 2); + } + } + CurvatureMethod::Mesh => { + let mesh = &mut settings.mesh; + integer(ui, tr("Secondary Rays"), &mut mesh.rays, 1..=256); + number(ui, tr("Sampling Radius"), &mut mesh.sampling_radius, 0.00001..=if mesh.relative_to_bounding_box { 10.0 } else { 1.0 }, 5); + if ui.checkbox(&mut mesh.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && !mesh.relative_to_bounding_box { + mesh.sampling_radius = mesh.sampling_radius.min(1.0); + } + occlusion(ui, tr("Self Intersection"), &mut mesh.self_intersection); + ui.checkbox(&mut mesh.auto_tonemapping, tr("Auto Tonemapping")); + if !mesh.auto_tonemapping { + number(ui, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); + number(ui, tr("Value Bounds Max"), &mut mesh.value_max, -10.0..=10.0, 2); + } + } + } +} + +fn position(ui: &mut Ui, settings: &mut PositionSettings) { + choice(ui, tr("Axis"), &mut settings.axis, &[(PositionAxis::All, tr("All")), (PositionAxis::X, "X"), (PositionAxis::Y, "Y"), (PositionAxis::Z, "Z")]); + choice( + ui, + tr("Normalization Type"), + &mut settings.normalization, + &[(PositionMode::BoundingBox, tr("BBox")), (PositionMode::BoundingSphere, tr("BSphere")), (PositionMode::None, tr("None"))], + ); + choice( + ui, + tr("Normalization Scale"), + &mut settings.scale, + &[(PositionNormalizationScale::PerMaterial, tr("Per Material")), (PositionNormalizationScale::FullScene, tr("Full Scene"))], + ); +} + +fn thickness(ui: &mut Ui, settings: &mut ThicknessSettings) { + rays(ui, &mut settings.rays); + occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); + choice( + ui, + tr("Normalization"), + &mut settings.normalization, + &[ + (ThicknessNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), + (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (ThicknessNormalization::None, tr("None")), + ], + ); +} + +fn height(ui: &mut Ui, settings: &mut HeightSettings) { + choice( + ui, + tr("Normalization"), + &mut settings.normalization, + &[ + (HeightNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), + (HeightNormalization::RelativeToLowMesh, tr("Relative to Low Mesh")), + (HeightNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (HeightNormalization::Manual, tr("Manual")), + ], + ); + if settings.normalization == HeightNormalization::Manual { + number(ui, tr("Scaling Divisor"), &mut settings.scaling_divisor, 0.00001..=100.0, 5); + } +} + +fn bent_normal(ui: &mut Ui, settings: &mut BentNormalSettings) { + rays(ui, &mut settings.rays); + backface(ui, &mut settings.ignore_backface); + occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +} 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..2ae7f095 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -0,0 +1,298 @@ +//! Bake Mode presentation; persisted settings live in core and edits use engine commands + +mod bake_checks; +mod bake_paint_brush; +mod bake_visualization_panel; +mod bake_visualization_toggles; +mod breadcrumb; +mod common_settings; +mod section_opening; +pub(crate) use bake_checks::bake_warnings; +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 })); + } + + // The name takes the room the resolution leaves, so it only shortens when the row is too narrow + let resolution_text = format!("{resolution}x{resolution}"); + let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0); + let name_size = egui::vec2(name_width, ui.spacing().interact_size.y); + let name_button = ui.allocate_ui_with_layout(name_size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(name_width); + ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()) + }); + if name_button.inner.on_hover_text(&name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + } + if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), resolution_text, resolution, None) + && selected != resolution + { + app.start_resize(set_index, selected); + } + }); + + 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}x{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})); + } + }); + }) + }); + } + }); + } + }); + } + }); +} + +/// How wide [`resolution_menu`] draws `text`, with a button's padding on both sides +fn resolution_menu_width(ui: &Ui, text: &str) -> f32 { + let font = egui::TextStyle::Button.resolve(ui.style()); + ui.painter().layout_no_wrap(text.to_owned(), font, ui.visuals().text_color()).size().x + ui.spacing().button_padding.x * 2.0 +} + +fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option) -> Option { + let effective_size = format!("{resolution}x{resolution}"); + let measured = if text.is_empty() { &effective_size } else { &text }; + let font = egui::TextStyle::Button.resolve(ui.style()); + let width = resolution_menu_width(ui, measured); + 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}x{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 })); +} + +/// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material +fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::PreviewShow; + + let Some(preview) = app.session.bake_preview.as_ref() else { return }; + + let show = preview.show; + + // Finished maps of the set baking now can be pinned; the others are still neutral + let rows: Vec<(BakedMap, bool)> = + preview.current_set().map(|set| set.order.iter().map(|&map| (map, set.baked.maps.contains_key(&map))).collect()).unwrap_or_default(); + let text = match show { + PreviewShow::Follow => tr("Follow Newest Map").to_owned(), + PreviewShow::Material => tr("Material").to_owned(), + PreviewShow::Pin(map) => trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]), + }; + + let mut choice = None; + egui::ComboBox::from_id_salt("bake_preview_show") + .selected_text(text) + .show_ui(ui, |ui| { + if ui.selectable_label(show == PreviewShow::Follow, tr("Follow Newest Map")).clicked() { + choice = Some(PreviewShow::Follow); + } + for (map, done) in rows { + let label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.add_enabled(done, egui::Button::selectable(show == PreviewShow::Pin(map), label)).clicked() { + choice = Some(PreviewShow::Pin(map)); + } + } + if ui.selectable_label(show == PreviewShow::Material, tr("Material")).clicked() { + choice = Some(PreviewShow::Material); + } + }) + .response + .on_hover_text(tr( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + )); + + if let Some(show) = choice { + app.run("bake.preview", json!({ "show": show.id() })); + } +} + +/// How many maps baking `texture_sets` makes, counted as the reference's Bake button counts them: checked maps × included UV tiles, per set +fn maps_to_bake(app: &TextureCraftApp, texture_sets: &[usize]) -> usize { + texture_sets + .iter() + .filter_map(|index| app.session.doc.project.texture_sets.get(*index)) + .map(|set| { + let tiles = if set.uv_tiles.is_empty() { 1 } else { set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).count() }; + set.bake.maps.enabled().count() * tiles + }) + .sum() +} + +/// The bake bar's gap from the bottom of the 3D view, in points (the pre-bake warnings sit above it) +pub(super) const BAKE_BAR_MARGIN: f32 = 16.0; + +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, -BAKE_BAR_MARGIN)) + .default_width(0.0) + .show(ctx, |ui| { + if let Some(status) = app.bake_status() { + ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong())); + } + 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(); + } + preview_control(app, ui); + } 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 maps = maps_to_bake(app, &texture_sets); + let label = trf("Bake ({n})", &[("n", &maps)]); + if ui.add_enabled(maps > 0, 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/section_opening.rs b/crates/ui-egui/src/bake_mode/section_opening.rs new file mode 100644 index 00000000..8428a7f7 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/section_opening.rs @@ -0,0 +1,6 @@ +/// Whether a Baking Visualization section starts open, as the reference shows the panel at first launch (HP and Cage open, UV seams and Project mesh closed) +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SectionOpening { + Open, + Closed, +} 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..766a43c2 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -0,0 +1,295 @@ +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 missing 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.shown { + 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); + } else if self.high_sent { + // Drop the hidden GPU mesh but keep its id so its reach can be reused + out.bake_high = Some((None, self.high_id)); + self.high_sent = false; + self.reach.resend(); + } + + if visualization.missing_seams.shown && self.seams_mesh_id != Some(session.mesh_id) { + self.seams_mesh_id = Some(session.mesh_id); + out.missing_seams = Some((session.mesh_id, session.mesh.missing_seam_edges())); + } + + if visualization.cage_shown() { + 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); + let mut shared_edges = 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| { + let result = if inputs.uses_mesh(&session.mesh) { + let (wire_edges, missing_seam_edges) = + shared_edges.get_or_insert_with(|| (session.mesh.wire_edges(), session.mesh.missing_seam_edges())); + inputs.cage_shell_with_edges(wire_edges, missing_seam_edges) + } else { + inputs.cage_shell() + }; + result.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; + + /// Every part of the visualization shown + fn everything() -> BakeVisualization { + let parts = BakeVisualization::default(); + let shown = |overlay: texturecraft_render::BakeOverlay| texturecraft_render::BakeOverlay { shown: true, ..overlay }; + BakeVisualization { + high_poly: shown(parts.high_poly), + matching_error: shown(parts.matching_error), + cage_surface: shown(parts.cage_surface), + cage_wire: shown(parts.cage_wire), + missing_seams: shown(parts.missing_seams), + low_poly: shown(parts.low_poly), + ..parts + } + } + + /// 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.missing_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.missing_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.missing_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_hidden_high_poly_leaves_the_gpu_and_comes_back_without_a_new_reach() { + let (session, mut link) = (session(), BakeSceneLink::default()); + let sent = |out: SceneSync| out.bake_high.map(|(high, id)| (high.is_some(), id)); + let hidden = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() }; + let first = sent(sync(&mut link, &session, everything())); + red_share(&mut link, &session, everything()); + let dropped = sent(sync(&mut link, &session, hidden)); + assert!(sync(&mut link, &session, hidden).bake_high.is_none(), "dropped once"); + let back = sync(&mut link, &session, everything()); + assert!(!link.busy(), "showing it again starts no new reach"); + assert!(back.bake_high_missed.is_some(), "its colours are sent again with it"); + + let (Some((true, first_id)), Some((false, dropped_id)), Some((true, back_id))) = (first, dropped, sent(back)) else { + panic!("the high poly is sent, dropped, then sent again") + }; + + assert_eq!((dropped_id, back_id), (first_id, first_id)); + } + + #[test] + fn a_reach_finishes_while_nothing_is_drawn() { + let session = session(); + let no_high_poly = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..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() }; + let hidden = texturecraft_engine::bake::HIDDEN_HIGH_POLY_VERTEX; + assert_eq!(red_share(&mut link, &session, no_set), hidden, "a filter that keeps no set hides the whole high poly"); + } +} 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..f94ed3d5 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -0,0 +1,170 @@ +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 { + // The GPU keeps displayed colors; stale CPU arrays need not overlap the rebuild + self.reach.clear(); + + 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 rebuilding_reach_releases_previous_vertex_arrays_before_starting_work() { + const PREVIOUS_SET_COUNT: usize = 2; + const PREVIOUS_VERTEX_COUNT: usize = 64; + + 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 mut link = ReachLink { + reach: (0..PREVIOUS_SET_COUNT).map(|_| Some(HighPolyReach { vertices: vec![None; PREVIOUS_VERTEX_COUNT], ..Default::default() })).collect(), + ..Default::default() + }; + let mut out = SceneSync::default(); + + link.sync(&session, 1, None, &mut out); + + let retained_slots: usize = link.reach.iter().flatten().map(|reach| reach.vertices.capacity()).sum(); + assert_eq!(retained_slots, 0, "obsolete CPU arrays must not overlap their replacements"); + assert!(out.bake_high_missed.is_none(), "the GPU keeps its displayed colors until the replacement arrives"); + } + + #[test] + fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() { + const WAIT_FRAMES: usize = 2000; + const WAIT_FRAME_PAUSE: Duration = Duration::from_millis(5); + + 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..WAIT_FRAMES { + link.poll(); + if !link.busy() { + break; + } + + std::thread::sleep(WAIT_FRAME_PAUSE); + } + + 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/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs new file mode 100644 index 00000000..f8d76d78 --- /dev/null +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -0,0 +1,138 @@ +//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab + +use egui::Ui; +use serde_json::json; +use std::path::Path; +use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// The preset name field's width in points +const NAME_WIDTH: f32 = 110.0; + +/// A name field and a button that saves the current brush under that name +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { + let dir = crate::user_dir("brushes"); + let name_id = ui.make_persistent_id("brush_preset_name"); + let confirm_id = ui.make_persistent_id("brush_preset_overwrite"); + let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); + let mut pending_path: Option = ui.data_mut(|data| data.get_temp(confirm_id)); + + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH)); + + if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { + let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim()))); + match std::fs::symlink_metadata(&path) { + Ok(_) => pending_path = Some(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + } + Err(_) => pending_path = Some(path), + } + } + }); + + if let Some(path) = pending_path.clone() { + let mut replace = false; + let mut cancel = false; + egui::Window::new(tr("Replace")) + .id(ui.make_persistent_id("brush_preset_replace_dialog")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ui.ctx(), |ui| { + ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default()); + ui.horizontal(|ui| { + replace = ui.button(tr("Replace")).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + if replace { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + pending_path = None; + } else if cancel { + pending_path = None; + } + } + + ui.data_mut(|data| { + data.insert_temp(name_id, new_name); + data.insert_temp(confirm_id, pending_path); + }); +} + +/// Preserve Unicode names and encode filename punctuation without collisions +fn preset_file_stem(name: &str) -> String { + let mut stem = String::new(); + + // Six digits cover every Unicode scalar and separate adjacent escapes + for character in name.chars() { + if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' { + stem.push(character); + } else { + stem.push_str(&format!("~{:06X}", character as u32)); + } + } + let uppercase = stem.to_ascii_uppercase(); + if matches!( + uppercase.as_str(), + "CON" + | "PRN" + | "AUX" + | "NUL" + | "COM1" + | "COM2" + | "COM3" + | "COM4" + | "COM5" + | "COM6" + | "COM7" + | "COM8" + | "COM9" + | "LPT1" + | "LPT2" + | "LPT3" + | "LPT4" + | "LPT5" + | "LPT6" + | "LPT7" + | "LPT8" + | "LPT9" + ) { + stem.insert_str(0, "brush-"); + } + stem +} + +/// Save a preset and invalidate cached tiles only when the write succeeds +fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool { + // A folder that cannot be made is reported by the save command + let _ = std::fs::create_dir_all(dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() { + return false; + } + + app.brushes = None; + app.thumbs.forget_saved_files(); + true +} + +#[cfg(test)] +mod tests { + use super::preset_file_stem; + + #[test] + fn distinct_unicode_brush_names_have_distinct_safe_file_stems() { + assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画")); + assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb")); + assert_eq!(preset_file_stem("水彩"), "水彩"); + assert!(!preset_file_stem("a/b").contains('/')); + assert_eq!(preset_file_stem("CON"), "brush-CON"); + } +} 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/control.rs b/crates/ui-egui/src/control.rs index 167b9754..b95788d3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -73,6 +73,7 @@ pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec) -> Option<(u32, u32, Vec } pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value { + app.ui.prefs.apply_resource_limits(); match method { "ping" => ok(json!("pong")), "ui.resize" => { @@ -110,9 +111,46 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & "uiMs": app.ui_ms, "titleBar": app.title_bar.name(), "baking": app.bake_progress(), + "bakeStatus": app.bake_status(), + "bakePreview": texturecraft_engine::bake_preview::preview_json(&app.session), "toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::>(), })) } + "ui.bake.start" => { + // Bake in the background like the Bake button: the 3D view shows the maps as they finish + let count = app.session.doc.project.texture_sets.len(); + let sets: Vec = match p.get("ts") { + Some(value) => match serde_json::from_value::>(if value.is_array() { value.clone() } else { json!([value]) }) { + Ok(list) if list.iter().all(|&index| index < count) => list, + _ => return err(format!("`ts` must be texture set indices below {count}")), + }, + None => app + .session + .doc + .project + .texture_sets + .iter() + .enumerate() + .filter(|(_, texture_set)| texture_set.bake.common.is_enabled) + .map(|(index, _)| index) + .collect(), + }; + if app.bake.is_some() { + return err("a bake is already running"); + } + + if sets.is_empty() { + return err("no texture set to bake: tick one in Bake mode or pass `ts`"); + } + + app.ui.mode = crate::state::Mode::Baking; + app.start_bake(sets); + ok(texturecraft_engine::bake_preview::preview_json(&app.session)) + } + "ui.bake.cancel" => { + app.cancel_bake(); + ok(Value::Null) + } "ui.menu.list" => ok(json!( crate::menus::CATALOG .iter() @@ -141,6 +179,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & match serde_json::from_value(cur) { Ok(ui) => { app.ui = ui; + app.ui.prefs.apply_resource_limits(); ok(Value::Null) } Err(e) => err(format!("invalid UI state: {e}")), diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs new file mode 100644 index 00000000..2071ceb6 --- /dev/null +++ b/crates/ui-egui/src/decal_drop.rs @@ -0,0 +1,130 @@ +//! A shelf image dropped on the 3D view waits for a menu pick at the drop point: a mask, or a channel of the texture set under it + +use egui::{Id, Pos2, Ui, Vec2}; +use serde_json::json; +use texturecraft_engine::geom::OrbitCamera; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// What the menu offers besides the texture set's channels: a new fill layer masked by the image +const MASK_CHOICE: &str = "mask"; + +/// The most of the window's height the channel list takes before it scrolls +const MENU_MAX_HEIGHT_SHARE: f32 = 0.6; + +/// An image dropped on the 3D view, placed as a decal once the menu at the drop point is picked +#[derive(Clone)] +pub struct DecalDrop { + /// The image resource + pub image: String, + /// The texture set under the drop point + pub texture_set: usize, + /// The drop point in view pixels + pub view_position: Vec2, + /// The 3D view's size in pixels + pub view_size: Vec2, + /// The camera used to pick the drop point + pub camera: OrbitCamera, + /// The drop point on screen, where the menu opens + pub screen_position: Pos2, +} + +impl DecalDrop { + /// Where the waiting drop and its menu's state are kept + fn menu_id() -> Id { + Id::unique("decal_drop_menu") + } + + /// Open the menu for this drop (replacing any other waiting drop): it stays open while the drop waits + pub fn open(self, ui: &Ui) { + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), (self, frame))); + } + + /// Keep input out of both views while the menu waits and for the rest of its closing frame + pub fn blocks_input(ctx: &egui::Context) -> bool { + Self::current(ctx).is_some() || ctx.data(|data| data.get_temp::(Self::menu_id().with("closed_frame"))) == Some(ctx.cumulative_frame_nr()) + } + + /// The waiting drop; one whose menu went undrawn for a frame (the 3D view was hidden) is dropped instead of blocking the views + fn current(ctx: &egui::Context) -> Option { + let frame = ctx.cumulative_frame_nr(); + let (drop, menu_frame) = ctx.data(|data| data.get_temp::<(DecalDrop, u64)>(Self::menu_id()))?; + if frame > menu_frame + 1 { + ctx.data_mut(|data| data.remove::<(DecalDrop, u64)>(Self::menu_id())); + return None; + } + + Some(drop) + } + + /// Close the menu and consume the rest of this frame's input + fn close(ctx: &egui::Context) { + let id = Self::menu_id(); + let frame = ctx.cumulative_frame_nr(); + + // The 2D view reads input after this menu closes in the 3D view + ctx.data_mut(|data| { + data.remove::<(DecalDrop, u64)>(id); + data.insert_temp(id.with("closed_frame"), frame); + }); + } + + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing + pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { + let id = Self::menu_id(); + let Some(drop) = Self::current(ui.ctx()) else { return }; + + // Saved view pixels must not be picked through a different camera + if drop.camera != app.session.camera { + Self::close(ui.ctx()); + return; + } + + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(id, (drop.clone(), frame))); + + let channels = app.session.doc.project.texture_set(drop.texture_set).map(|set| set.channel_list()).unwrap_or_default(); + let mut picked = None; + let shown = egui::Popup::new(id, ui.ctx().clone(), egui::PopupAnchor::Position(drop.screen_position), response.layer_id) + .kind(egui::PopupKind::Menu) + .layout(egui::Layout::top_down_justified(egui::Align::Min)) + .style(egui::containers::menu::menu_style) + .open(true) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + if ui.button(tr("Mask")).clicked() { + picked = Some(MASK_CHOICE); + } + ui.separator(); + + // Many channels scroll instead of running off the window + let max_height = ui.ctx().content_rect().height() * MENU_MAX_HEIGHT_SHARE; + egui::ScrollArea::vertical().max_height(max_height).show(ui, |ui| { + for channel in channels { + if ui.button(tr(channel.label())).clicked() { + picked = Some(channel.id()); + } + } + }); + }); + + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + Self::close(ui.ctx()); + } + + let Some(channel) = picked else { return }; + + app.run( + "layer.add.decal", + json!({ + "image": drop.image, + "channel": channel, + "x": drop.view_position.x, + "y": drop.view_position.y, + "viewport": [drop.view_size.x, drop.view_size.y], + }), + ); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 471f164d..2d0bbdd4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1,23 +1,33 @@ -//! Panel bodies of the right column: Texture Set List, Layers, Texture Set Settings, Properties +//! Panel bodies of the right column: Texture Sets, Layers, Texture Set Settings, Properties //! (hosted as dock tabs by `docking`). use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; -use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::filter_lib::scalar_params; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; +use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::shelf::{Asset, ShelfDrag}; 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}; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, section_with_reset, 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), @@ -131,9 +141,10 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - // Wraps in a narrow column instead of widening the rows below past the panel. + + // Wrap in a narrow column so rows stay within the panel ui.horizontal_wrapped(|ui| { - // The menu buttons as compact as the icon buttons beside them. + // Keep menu buttons as compact as the adjacent icon buttons ui.spacing_mut().button_padding.x = 4.0; ui.spacing_mut().item_spacing.x = 4.0; let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); @@ -168,11 +179,15 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(2.0); let ts = app.session.ts(); let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); + let now = ui.input(|i| i.time); + app.layer_panel.begin(&app.session, now); egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { + let mut count = 0; for id in stack { - layer_tree(app, ui, id, 0); + layer_tree(app, ui, id, 0, &mut count); } - // Click on empty space deselects nothing; the space below the rows drops at the bottom. + + // Empty space keeps the selection and drops below the rows let free = ui.available_height(); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if free.is_finite() { free.max(24.0) } else { 24.0 }), Sense::hover()); if let Some(dragged) = dnd_release::(&resp) { @@ -195,6 +210,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); } }); + app.layer_panel.end(ui.ctx(), &app.session); } /// Whether the selection targets the layer content (the content or one of its effects) rather @@ -208,128 +224,509 @@ 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) { +/// Layer rows alternate between two shades so neighbours read as separate items. +fn row_shade(tokens: &Tokens, index: usize) -> Color32 { + if index.is_multiple_of(2) { tokens.row } else { tokens.row.lerp_to_gamma(tokens.row_hover, ALTERNATE_LAYER_SHADE) } +} + +/// Width of the blend mode / opacity column at the right of a layer row. +const RIGHT_COLUMN: f32 = 58.0; +/// Indent per folder level, and per level of the effect tree. +const INDENT: f32 = 14.0; +/// Edge of the small icon buttons in the properties panel. +const ICON_BUTTON_SIZE: f32 = 22.0; +/// Height of a blend mode menu or opacity field in a stack row, and the rounding of its hover fill. +const ROW_CONTROL_HEIGHT: f32 = 17.0; +const ROW_CONTROL_ROUNDING: f32 = 2.0; +/// Gap between the controls at the right of a stack row, and between them and the row's edge. +const ROW_CONTROL_GAP: f32 = 4.0; +/// Space before an effect row's eye and after its name. +const ROW_LEFT_PADDING: f32 = 7.0; +const ROW_RIGHT_PADDING: f32 = 6.0; +/// Width of the selected row's accent edge. +const SELECTED_EDGE_WIDTH: f32 = 3.0; +/// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. +const THUMBNAIL_ROUNDING: f32 = 2.0; +const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; +const HIDDEN_STRIKE_WIDTH: f32 = 1.5; +const DROP_LINE_WIDTH: f32 = 2.0; +/// The eye's size and the column it sits in (the eye and a gap before the thumbnail). +const EYE_SIZE: f32 = 16.0; +const EYE_COLUMN_WIDTH: f32 = 22.0; +/// Gap between an effect's thumbnail and its name, and the narrowest name worth showing. +const THUMBNAIL_GAP: f32 = 8.0; +const MIN_NAME_WIDTH: f32 = 20.0; +/// Font sizes in an effect row: the eye, the name, the blend mode and its caret. +const EYE_FONT_SIZE: f32 = 12.0; +const EFFECT_NAME_FONT_SIZE: f32 = 11.5; +const ROW_SMALL_FONT_SIZE: f32 = 11.0; +const CARET_FONT_SIZE: f32 = 8.0; +/// Room for the caret at the right of the blend mode's name. +const CARET_WIDTH: f32 = 10.0; +/// The blend mode menu's width, wide enough for the longest mode name. +const BLEND_MENU_MIN_WIDTH: f32 = 190.0; +/// Padding inside a row's opacity field, and the percent it moves per point dragged. +const ROW_FIELD_PADDING: f32 = 4.0; +const OPACITY_DRAG_SPEED: f64 = 0.5; +/// A layer row's eye: its hit area, its glyph size and the column it sits in. +const LAYER_EYE_SIZE: f32 = 18.0; +const LAYER_EYE_FONT_SIZE: f32 = 13.0; +const LAYER_EYE_COLUMN_WIDTH: f32 = 20.0; +/// A folder's caret: its size (the space it takes before the thumbnail) and its center from where it starts. +const FOLDER_CARET_SIZE: f32 = 14.0; +const FOLDER_CARET_CENTER: f32 = 6.0; +/// A thumbnail's border while it is the layer's target, and how far outside it the mask-view and drop outlines sit. +const TARGET_BORDER_WIDTH: f32 = 1.5; +const HIGHLIGHT_OUTSET: f32 = 2.0; +/// The gap between a layer row's stacked blend mode and opacity, either side of the row's middle. +const ROW_STACK_GAP: f32 = 1.0; +/// Width of a layer's colour tag beside the accent edge. +const TAG_WIDTH: f32 = 3.0; +/// Space between a layer's content and mask thumbnails, and the size of the empty mask slot. +const THUMBNAIL_SPACING: f32 = 4.0; +const MASK_SLOT_SIZE: f32 = 18.0; +/// Grays of a white or black mask before its thumbnail arrives. +const WHITE_MASK_GRAY: u8 = 225; +const BLACK_MASK_GRAY: u8 = 18; +/// A layer's name and subtitle font sizes, and their distance from the row's middle. +const LAYER_NAME_FONT_SIZE: f32 = 12.5; +const LAYER_SUBTITLE_FONT_SIZE: f32 = 10.0; +const NAME_LINE_GAP: f32 = 2.0; +/// Folder lines: their width, how faded they are, how far an indent must reach past one, and where the branch starts. +const FOLDER_LINE_WIDTH: f32 = 1.0; +const FOLDER_LINE_FADE: f32 = 0.6; +const FOLDER_LINE_CLEARANCE: f32 = 8.0; +const FOLDER_BRANCH_OFFSET: f32 = 15.0; +/// The share of a folder row's height, either side of its middle, where a drop goes inside it. +const FOLDER_DROP_ZONE: f32 = 0.25; +/// How far each alternating effect row shade goes from the panel towards the hover colour. +const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; +/// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. +const EFFECT_BLEND_WIDTH: f32 = 82.0; +const EFFECT_OPACITY_WIDTH: f32 = 36.0; +/// Height of the "Content effects" / "Mask effects" header rows. +const GROUP_HEADER_H: f32 = 20.0; + +// Group header spacing leaves room for the label and effect count +const GROUP_HEADER_CARET_OFFSET: f32 = 15.0; +const GROUP_HEADER_LABEL_GAP: f32 = 10.0; +const GROUP_HEADER_LABEL_RESERVE: f32 = 28.0; +const GROUP_HEADER_COUNT_PADDING: f32 = 8.0; +const GROUP_HEADER_LABEL_FONT_SIZE: f32 = 10.5; +/// Hover tint of alternating layer rows +const ALTERNATE_LAYER_SHADE: f32 = 0.45; +/// Maximum layer-tree nesting shown by the dock +const MAX_LAYER_TREE_DEPTH: usize = 12; +/// Checkerboard cells along each thumbnail edge +const THUMB_CHECKER_CELLS: usize = 4; +/// Keep the group label and count readable when the panel is narrow +const GROUP_HEADER_MIN_REMAINING_WIDTH: f32 = 90.0; + +/// Keep both thumbnail targets inside the row before spending space on indentation +fn layer_thumbnail_layout(width: f32, depth: usize, folder: bool, preferred_size: f32) -> (f32, f32) { + let controls = ROW_LEFT_PADDING + LAYER_EYE_COLUMN_WIDTH + if folder { FOLDER_CARET_SIZE } else { 0.0 }; + let thumbnail_space = (width - controls - THUMBNAIL_SPACING - ROW_CONTROL_GAP).max(0.0); + let size = preferred_size.min(thumbnail_space * 0.5); + let indent = (depth as f32 * INDENT).min((thumbnail_space - size * 2.0).max(0.0)); + (indent, size) +} + +/// Drop secondary controls before allowing them to cover thumbnail targets or the name +fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { + let right = rect.right() - ROW_CONTROL_GAP; + let show_blend = right - RIGHT_COLUMN - ROW_CONTROL_GAP - left >= MIN_NAME_WIDTH; + let name_right = if show_blend { right - RIGHT_COLUMN - ROW_CONTROL_GAP } else { right }; + (Rect::from_min_max(pos2(left, rect.top() + 4.0), pos2(name_right.max(left), rect.bottom() - 4.0)), show_blend) +} + +/// Preserve the effect eye, preview and a readable name before spending space on nesting. +fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) +} + +/// X of the centre of the eye column at indent `level` in a row spanning from `left`. +fn level_x(left: f32, level: usize) -> f32 { + left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5 +} + +fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) { let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; - layer_row(app, ui, &layer, depth); - for e in layer.content_effects.iter().rev() { - effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE); + + let index = *count; + *count += 1; + layer_row(app, ui, &layer, depth, index); + let mask_effects = layer.mask.as_ref().map_or(0, |mask| mask.effects.len()); + if !layer.content_effects.is_empty() { + effect_group(app, ui, &layer, depth, false, mask_effects > 0); } - if let Some(m) = &layer.mask { - for e in m.effects.iter().rev() { - effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND); - } + if mask_effects > 0 { + effect_group(app, ui, &layer, depth, true, false); } + + // A line under the layer and its effects separates it from the next layer + let tokens = Tokens::get(ui.ctx()); + let available = ui.available_rect_before_wrap(); + ui.painter().hline(available.x_range(), available.top() - 0.5, Stroke::new(1.0, tokens.separator)); if let LayerKind::Group { children, collapsed } = &layer.kind && !collapsed - && depth < 12 + && depth < MAX_LAYER_TREE_DEPTH { - for c in children.iter().rev() { - layer_tree(app, ui, *c, depth + 1); + for child in children.iter().rev() { + layer_tree(app, ui, *child, depth + 1, count); } } } -fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize) { - let tk = Tokens::get(ui.ctx()); +/// The picture for `target` inside `rect` (drawn over the well), whether there is one yet. +fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter(); + painter.rect_filled(rect, THUMBNAIL_ROUNDING, tokens.field); + + // A checkerboard shows through where the layer has nothing (transparent texels) + let cell_size = rect.width() / THUMB_CHECKER_CELLS as f32; + let check = tokens.field.lerp_to_gamma(tokens.row_hover, 0.6); + for y in 0..THUMB_CHECKER_CELLS { + for x in (0..THUMB_CHECKER_CELLS).filter(|x| (x + y) % 2 == 0) { + painter.rect_filled(Rect::from_min_size(rect.min + vec2(x as f32 * cell_size, y as f32 * cell_size), vec2(cell_size, cell_size)), 0.0, check); + } + } + + // Only rows on screen ask for a picture + if ui.is_rect_visible(rect) + && let Some(texture) = app.layer_panel.texture(ui.ctx(), &app.session, target) + { + let tint = if dim { Color32::WHITE.gamma_multiply(0.4) } else { Color32::WHITE }; + painter.image(texture, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); + return true; + } + + false +} + +/// The row of `layer` at folder depth `depth`, the `index`th row of the stack (rows alternate shades). +fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { + let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); - let h = 38.0; - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); - let p = ui.painter().clone(); - let bg = if selected && app.session.target == StackTarget::Content { - tk.row_selected - } else if resp.hovered() { - tk.row_hover + let content_target = selected && targets_content(app); + let preferred_size = layer_preview_size(app); + let row_height = layer_row_height(preferred_size); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); + + // Background, folder lines, the selected row's accent edge and the colour tag + let painter = ui.painter().clone(); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover } else { - tk.row + row_shade(&tokens, index) }; - p.rect_filled(rect.shrink2(vec2(0.0, 1.0)), 2.0, bg); + painter.rect_filled(rect, 0.0, background); + let (indent, thumbnail_size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), preferred_size); + + // Folder contents hang off lines down the left without crossing compact row controls + let line = Stroke::new(FOLDER_LINE_WIDTH, tokens.button_border.gamma_multiply(FOLDER_LINE_FADE)); + for level in 0..depth { + if level as f32 * INDENT + FOLDER_LINE_CLEARANCE < indent { + painter.vline(level_x(rect.left(), level), rect.y_range(), line); + } + } + if depth > 0 && indent >= INDENT { + let x = rect.left() + FOLDER_BRANCH_OFFSET + indent - INDENT; + painter.hline(x..=x + INDENT * 0.5, rect.center().y, line); + } if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, row_height)), 0.0, tokens.accent); } - if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(0.0, 1.0), vec2(3.0, h - 2.0)), 0.0, *tag); + if let Some(tag) = layer.color_tag.and_then(|tag| TAG_COLORS.get(tag as usize)) { + painter.rect_filled(Rect::from_min_size(rect.min + vec2(SELECTED_EDGE_WIDTH, 0.0), vec2(TAG_WIDTH, row_height)), 0.0, *tag); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; - // Eye. - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); - let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); - p.text( + + // The eye + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(LAYER_EYE_SIZE, LAYER_EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); + painter.text( eye.center(), egui::Align2::CENTER_CENTER, if layer.visible { ic::EYE } else { ic::EYE_SLASH }, - egui::FontId::proportional(13.0), - if layer.visible { tk.text } else { tk.text_dim }, + egui::FontId::proportional(LAYER_EYE_FONT_SIZE), + if layer.visible { tokens.text } else { tokens.text_dim }, ); - if eye_resp.clicked() { + if eye_response.clicked() { app.run("layer.visible", json!({"layer": layer.id.0})); } - // Group caret. - let mut x = x0 + 20.0; + + // A folder's caret + let mut x = content_left + LAYER_EYE_COLUMN_WIDTH; if let LayerKind::Group { collapsed, .. } = layer.kind { - let caret = Rect::from_center_size(pos2(x + 6.0, rect.center().y), vec2(14.0, 14.0)); - let cr = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); - p.text( + let caret = Rect::from_center_size(pos2(x + FOLDER_CARET_CENTER, rect.center().y), vec2(FOLDER_CARET_SIZE, FOLDER_CARET_SIZE)); + let caret_response = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); + painter.text( caret.center(), egui::Align2::CENTER_CENTER, if collapsed { ic::CARET_RIGHT } else { ic::CARET_DOWN }, - egui::FontId::proportional(11.0), - tk.text_dim, + egui::FontId::proportional(ROW_SMALL_FONT_SIZE), + tokens.text_dim, ); - if cr.clicked() - && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|l| &mut l.kind) + if caret_response.clicked() + && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|edited| &mut edited.kind) { *collapsed = !*collapsed; } - x += 14.0; + + x += FOLDER_CARET_SIZE; } - // Thumbnail. - let thumb = Rect::from_min_size(pos2(x, rect.top() + 5.0), vec2(28.0, 28.0)); - p.rect_filled(thumb, 2.0, tk.field); + + // Content thumbnail: the layer's own result in the displayed channel + let channel = app.ui.layer_channel; + let thumbnail = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { + content_glyph(&painter, &tokens, thumbnail, layer); + } + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); + let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_response.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); + } + x = thumbnail.right() + THUMBNAIL_SPACING; + + // An instance draws its source's content, blending and (unless it has its own) mask + let project = &app.session.doc.project; + let source = layer.instance_source().map(|source| { + let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); + project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name)) + }); + let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); + let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); + + // Mask thumbnail, selectable on its own; or the slot that adds one + let mask_rect; + if let Some(mask) = &mask { + let mask_target = selected && !targets_content(app); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask.enabled) { + let white = mask.background == texturecraft_engine::core::MaskBackground::White; + painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); + if !mask.effects.is_empty() { + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(LAYER_EYE_FONT_SIZE), tokens.text_dim); + } + } + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); + if !mask.enabled { + painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); + } + let mask_response = ui + .interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()) + .on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)")); + if mask_response.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); + if ui.input(|input| input.modifiers.alt) { + let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); + let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; + app.run("viewport.view", view); + } + } + if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { + painter.rect_stroke( + mask_rect.expand(HIGHLIGHT_OUTSET), + THUMBNAIL_ROUNDING, + Stroke::new(TARGET_BORDER_WIDTH, tokens.warning), + egui::StrokeKind::Outside, + ); + } + } else { + // The empty slot adds a mask to this layer + let slot_size = thumbnail_size.min(MASK_SLOT_SIZE); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size)); + let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); + let slot_color = if slot.hovered() { tokens.accent } else { tokens.field_border }; + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, slot_color), egui::StrokeKind::Inside); + if slot.hovered() { + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text); + } + egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); + } + x = mask_rect.right() + THUMBNAIL_GAP; + + // Name (or rename editor) with the quieter subtitle under it + let (name_rect, show_blend) = layer_name_layout(rect, x); + let show_name = name_rect.width() >= MIN_NAME_WIDTH; + if !show_name { + row.clone().on_hover_text(&layer.name); + if app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0) { + app.ui.rename = None; + } + } + let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0); + if renaming { + let mut editor_ui = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + if let Some((_, text)) = app.ui.rename.as_mut() { + // Escape reaches us instead of just unfocusing the field, so it can cancel + let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; + let editor = editor_ui.add(egui::TextEdit::singleline(text).desired_width(name_rect.width()).event_filter(filter)); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) { + app.ui.rename = None; + } else if editor.lost_focus() { + // Enter or a click elsewhere + let name = text.trim().to_string(); + app.ui.rename = None; + if !name.is_empty() && name != layer.name { + app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); + } + } else if !editor.has_focus() { + // Only until the field has focus: asking every frame trapped the editor open and blocked every shortcut + editor.request_focus(); + } + } + } else if show_name { + let name_color = if layer.visible { tokens.text_strong } else { tokens.text_dim }; + let galley = elided(&painter, layer.name.clone(), LAYER_NAME_FONT_SIZE, name_color, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y - NAME_LINE_GAP - galley.size().y), galley, tokens.text); + let kind = tr(match &layer.kind { + LayerKind::Paint => "Paint layer", + LayerKind::Fill(_) => "Fill layer", + LayerKind::Group { .. } => "Folder", + LayerKind::Instance { .. } => "Instance", + }); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |mask| mask.effects.len()); + let subtitle = match (source, effects) { + (Some(source), _) => format!("{kind} · {} {source}", ic::LINK_SIMPLE), + (None, 0) => kind.to_string(), + (None, 1) => format!("{kind} · {}", tr("1 effect")), + (None, count) => format!("{kind} · {}", trf("{count} effects", &[("count", &count)])), + }; + let subtitle = elided(&painter, subtitle, LAYER_SUBTITLE_FONT_SIZE, tokens.text_dim, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y + NAME_LINE_GAP), subtitle, tokens.text_dim); + } + + // Blend mode and opacity of the displayed channel, stacked at the right + let mode_rect = Rect::from_min_size( + pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y - ROW_CONTROL_HEIGHT - ROW_STACK_GAP), + vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT), + ); + let opacity_rect = + Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y + ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT)); + if let Some(channel_blend) = blend.filter(|_| show_blend) { + let id = ui.scope_id().with(("blend", layer.id.0)); + let (mode, opacity) = blend_controls( + ui, + id, + (mode_rect, opacity_rect), + (channel_blend.mode, channel_blend.opacity), + (tr("Blending mode of the displayed channel"), &layer.name), + ); + if let Some(mode) = mode { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "mode": format!("{mode:?}")})); + } + if let Some((opacity, merge)) = opacity { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "opacity": opacity, "merge": merge})); + } + } else if show_blend { + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(ROW_SMALL_FONT_SIZE), tokens.text_dim); + } + + // Interaction: select, rename, drag & drop, context menu + let on_control = eye_response.clicked() || content_response.clicked(); + if row.clicked() && !on_control && !renaming { + app.run("layer.select", json!({"layer": layer.id.0})); + } + if row.double_clicked() && !on_control && !renaming && show_name { + app.ui.rename = Some((layer.id.0, layer.name.clone())); + } + if row.drag_started() && !renaming { + row.dnd_set_drag_payload(layer.id.0); + } + + // Drops: a layer or a shelf material lands above this row (inside a folder on its middle); a shelf smart mask replaces the mask + let inside = layer.is_group() + && ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| (pointer.y - rect.center().y).abs() < row_height * FOLDER_DROP_ZONE); + let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); + let moving = row.dnd_hover_payload::().is_some_and(|dragged| *dragged != layer.id.0); + let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); + if moving || shelf.as_ref().is_some_and(Asset::is_material) { + if inside { + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); + } else { + painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); + } + } else if matches!(shelf, Some(Asset::SmartMask(_))) { + painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside); + } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); + } + if let Some(dragged) = dnd_release::(&row) + && *dragged != layer.id.0 + { + app.run("layer.move", json!({"layer": *dragged, "above": layer.id.0, "inside": inside})); + } + match dnd_release::(&row).map(|drag| drag.asset.clone()) { + Some(Asset::Material(material)) => { + app.run("material.apply", json!({"material": material, "above": layer.id.0, "inside": inside})); + } + Some(Asset::Library(path)) => { + app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside})); + } + Some(Asset::SmartMask(smart_mask)) => { + app.run("mask.smart.apply", json!({"name": smart_mask, "layer": layer.id.0})); + } + Some(Asset::Filter(filter)) => { + app.run("layer.select", json!({"layer": layer.id.0})); + app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": filter, "target": "content"})); + } + Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {} + } + row.context_menu(|ui| layer_context_menu(app, ui, layer)); +} + +/// The border of a content or mask thumbnail: the accent while it is the layer's target. +fn target_stroke(tokens: &Tokens, target: bool) -> Stroke { + if target { Stroke::new(TARGET_BORDER_WIDTH, tokens.accent) } else { Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border) } +} + +/// What a content thumbnail shows until its picture arrives (or where the layer has none). +fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) { match &layer.kind { LayerKind::Fill(f) => { let c = match f.source(Channel::BaseColor) { @@ -337,270 +734,289 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5], Source::Image { .. } | Source::Anchor { .. } => [0.5; 3], }; - crate::thumbs::paint_sphere(&p, thumb.center(), 12.0, c); + crate::thumbs::paint_sphere(p, thumb.center(), thumb.width() * 0.34, c); } LayerKind::Paint => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(15.0), tk.text); + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(thumb.width() * 0.45), tk.text_dim); } LayerKind::Group { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(16.0), tk.text); + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(thumb.width() * 0.5), tk.text); } LayerKind::Instance { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(16.0), tk.accent); + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(thumb.width() * 0.45), tk.accent); } } - x = thumb.right() + 8.0; - // An instance draws its source's content, blending and (unless it has its own) mask. - let project = &app.session.doc.project; - let source = layer.instance_source().map(|src| { - let set = project.locate(src).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(|t| t.name.as_str()).unwrap_or("?"); - project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) - }); - let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(app.ui.layer_channel)); - // Mask thumbnail. - let right_w = 46.0; - let mask_rect = Rect::from_min_size(pos2(rect.right() - right_w - 30.0, rect.top() + 7.0), vec2(24.0, 24.0)); - if let Some(m) = &mask { - let mask_sel = selected && !targets_content(app); - p.rect_filled( - mask_rect, - 1.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); - p.rect_stroke( - mask_rect, - 1.0, - Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(11.0), tk.text_dim); - } - if !m.enabled { - p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); - } - let mr = ui - .interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()) - .on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)")); - if mr.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); - if ui.input(|i| i.modifiers.alt) { - let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); - let p = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; - app.run("viewport.view", p); - } - } - if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 1.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); - } - } else { - // The empty slot adds a mask to this layer. - let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); - if slot.hovered() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); - } - egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); +} + +/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows +/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on. +fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) { + let tokens = Tokens::get(ui.ctx()); + let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |layer_mask| &layer_mask.effects) } else { &layer.content_effects }; + let key = (layer.id.0, mask); + let folded = app.layer_panel.folded.contains(&key); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click()); + let label = if mask { tr("Mask effects") } else { tr("Content effects") }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let painter = ui.painter().clone(); + painter.rect_filled(rect, 0.0, if response.hovered() { tokens.row_hover } else { tokens.panel }); + let indent = ((depth + 1) as f32 * INDENT).min((rect.width() - GROUP_HEADER_MIN_REMAINING_WIDTH).max(0.0)); + tree_lines(&painter, &tokens, rect, indent, &[], more_below); + let x = rect.left() + GROUP_HEADER_CARET_OFFSET + indent; + painter.text( + pos2(x, rect.center().y), + egui::Align2::CENTER_CENTER, + if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, + egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE), + tokens.text_dim, + ); + let galley = elided( + &painter, + label.to_string(), + GROUP_HEADER_LABEL_FONT_SIZE, + tokens.text_dim, + (rect.right() - GROUP_HEADER_LABEL_RESERVE - x - GROUP_HEADER_LABEL_GAP).max(0.0), + ); + painter.galley(pos2(x + GROUP_HEADER_LABEL_GAP, rect.center().y - galley.size().y * 0.5), galley, tokens.text_dim); + painter.text( + pos2(rect.right() - GROUP_HEADER_COUNT_PADDING, rect.center().y), + egui::Align2::RIGHT_CENTER, + stack.len().to_string(), + egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE), + tokens.text_dim, + ); + if response.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) { + app.layer_panel.folded.insert(key); } - // Name (or rename editor). - let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2(mask_rect.left() - 4.0, rect.bottom() - 4.0)); - let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); - if renaming { - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); - if let Some((_, buf)) = app.ui.rename.as_mut() { - // Escape reaches us instead of just unfocusing the field, so it can cancel. - let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; - let r = child.add(egui::TextEdit::singleline(buf).desired_width(name_rect.width()).event_filter(filter)); - if ui.input(|i| i.key_pressed(egui::Key::Escape)) { - app.ui.rename = None; - } else if r.lost_focus() { - // Enter or a click elsewhere. - let name = buf.trim().to_string(); - app.ui.rename = None; - if !name.is_empty() && name != layer.name { - app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); - } - } else if !r.has_focus() { - // Only until the field has focus: requesting it every frame kept it from ever - // losing focus, which trapped the editor open and blocked every shortcut. - r.request_focus(); - } - } - } else { - let galley = elided(&p, layer.name.clone(), 12.0, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - let y = if source.is_some() { rect.center().y - 7.0 } else { rect.center().y }; - p.galley(pos2(name_rect.left(), y - galley.size().y * 0.5), galley, tk.text); - if let Some(src) = source { - let src = elided(&p, format!("{} {src}", ic::LINK_SIMPLE), 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 7.0 - src.size().y * 0.5), src, tk.text_dim); + if folded { + return; + } + + let trunks: Vec = if more_below { vec![depth] } else { Vec::new() }; + for (row_index, effect) in stack.iter().rev().enumerate() { + effect_row(app, ui, layer, stack, effect, row_index, depth + 2, &trunks, row_index + 1 == stack.len(), mask); + } +} + +/// Tree connector of a row at the clamped `indent`: a line down from the parent's column (to the middle +/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with +/// lines straight through for the `trunks` of ancestors that continue. +fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: &[usize], more: bool) { + if indent < INDENT { + return; + } + let stroke = Stroke::new(1.0, tk.button_border); + for t in trunks { + if *t as f32 * INDENT + 8.0 < indent { + p.vline(level_x(rect.left(), *t), rect.y_range(), stroke); } } - // Blend mode and opacity of the displayed channel. - let ch = app.ui.layer_channel; - let blend_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 3.0), vec2(right_w, 16.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 19.0), vec2(right_w, 16.0)); - if let Some(b) = blend { - let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); - p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); - egui::Popup::menu(&br).show(|ui| { - ui.set_min_width(190.0); - for m in BlendMode::MENU { - match m { - Some(m) => { - if ui.selectable_label(m == b.mode, tr(m.label())).clicked() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "mode": format!("{m:?}")})); - ui.close(); - } - } - None => { - ui.separator(); - } - } - } - }); - let mut op = (b.opacity * 100.0).round(); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); - // As tall as its slot in the row (the style's fields are taller), in the row's small print. - child.spacing_mut().interact_size.y = op_rect.height(); - child.spacing_mut().button_padding = vec2(4.0, 0.0); - child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0)); - if r.changed() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); - } - } else { - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); - } - // Interaction: select, rename, drag & drop, context menu. - if resp.clicked() && !eye_resp.clicked() && !renaming { - app.run("layer.select", json!({"layer": layer.id.0})); - } - if resp.double_clicked() && !eye_resp.clicked() && !renaming { - app.ui.rename = Some((layer.id.0, layer.name.clone())); - } - if resp.drag_started() && !renaming { - resp.dnd_set_drag_payload(layer.id.0); - } - // Drops: a layer or a shelf material lands above this row (inside a folder when dropped on - // its middle); a shelf smart mask replaces this layer's mask. - let inside = layer.is_group() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| (p.y - rect.center().y).abs() < h * 0.25); - let shelf = resp.dnd_hover_payload::().map(|d| d.asset.clone()); - let moving = resp.dnd_hover_payload::().is_some_and(|src| *src != layer.id.0); - if moving || shelf.as_ref().is_some_and(Asset::is_material) { - if inside { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); - } else { - p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); - } - } else if matches!(shelf, Some(Asset::SmartMask(_))) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Outside); - } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); - } - if let Some(src) = dnd_release::(&resp) - && *src != layer.id.0 - { - app.run("layer.move", json!({"layer": *src, "above": layer.id.0, "inside": inside})); - } - match dnd_release::(&resp).map(|d| d.asset.clone()) { - Some(Asset::Material(m)) => { - app.run("material.apply", json!({"material": m, "above": layer.id.0, "inside": inside})); - } - Some(Asset::Library(path)) => { - app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside})); - } - Some(Asset::SmartMask(m)) => { - app.run("mask.smart.apply", json!({"name": m, "layer": layer.id.0})); - } - Some(Asset::Filter(f)) => { - app.run("layer.select", json!({"layer": layer.id.0})); - app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": f, "target": "content"})); - } - Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {} - } - resp.context_menu(|ui| layer_context_menu(app, ui, layer)); + let x = rect.left() + 15.0 + indent - INDENT; + let end = if more { rect.bottom() } else { rect.center().y }; + p.vline(x, rect.top()..=end, stroke); + p.hline(x..=x + INDENT * 0.6, rect.center().y, stroke); } /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects. -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) { - let tk = Tokens::get(ui.ctx()); - let (eid, visible) = (e.id, e.visible); - let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); - let p = ui.painter().clone(); - p.rect_filled( - rect.shrink2(vec2(0.0, 1.0)), - 2.0, - if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover - } else { - tk.panel - }, - ); +/// A stack row's blend mode menu and opacity field (percent, named after row `row_name`): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. +fn blend_controls( + ui: &mut Ui, + id: egui::Id, + (mode_rect, opacity_rect): (Rect, Rect), + (mode, opacity): (BlendMode, f32), + (hover, row_name): (&str, &str), +) -> (Option, Option<(f32, bool)>) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter().clone(); + + let mut picked = None; + let menu = ui.interact(mode_rect, id, Sense::click()).on_hover_text(hover); + if menu.hovered() { + painter.rect_filled(mode_rect, ROW_CONTROL_ROUNDING, tokens.row_hover); + } + let mode_font = egui::FontId::proportional(ROW_SMALL_FONT_SIZE); + painter.text(mode_rect.right_center() - vec2(CARET_WIDTH, 0.0), egui::Align2::RIGHT_CENTER, mode.short(), mode_font, tokens.text); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_FONT_SIZE), tokens.text_dim); + egui::Popup::menu(&menu).show(|ui| { + ui.set_min_width(BLEND_MENU_MIN_WIDTH); + for item in BlendMode::MENU { + match item { + Some(item) => { + if ui.selectable_label(item == mode, tr(item.label())).clicked() { + picked = Some(item); + ui.close(); + } + } + None => { + ui.separator(); + } + } + } + }); + + let mut percent = (opacity * 100.0).round(); + let mut field_ui = ui.new_child(egui::UiBuilder::new().max_rect(opacity_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); + // As tall as its slot in the row (the style's fields are taller), in the row's small print + field_ui.spacing_mut().interact_size.y = opacity_rect.height(); + field_ui.spacing_mut().button_padding = vec2(ROW_FIELD_PADDING, 0.0); + field_ui.style_mut().override_text_style = Some(egui::TextStyle::Small); + + // Plain text like the blend mode beside it: no field box, only the hover fill + let widgets = &mut field_ui.visuals_mut().widgets; + for state in [&mut widgets.inactive, &mut widgets.noninteractive] { + state.weak_bg_fill = Color32::TRANSPARENT; + state.bg_fill = Color32::TRANSPARENT; + state.bg_stroke = Stroke::NONE; + } + for state in [&mut widgets.hovered, &mut widgets.active] { + state.weak_bg_fill = tokens.row_hover; + state.bg_stroke = Stroke::NONE; + } + let field = field_ui.add(egui::DragValue::new(&mut percent).range(0.0..=100.0).speed(OPACITY_DRAG_SPEED).max_decimals(0).suffix("%")); + field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, true, trf("Opacity of {name}", &[("name", &row_name)]))); + + // A drag's first change starts an undo step and its later changes continue it (a drag can start without a change) + let drag_changed_id = id.with("opacity_drag_changed"); + let drag_changed = !field.drag_started() && ui.data(|data| data.get_temp::(drag_changed_id)).unwrap_or(false); + let merge = field.dragged() && drag_changed; + if field.changed() || field.drag_started() { + ui.data_mut(|data| data.insert_temp(drag_changed_id, field.changed() && field.dragged())); + } + (picked, field.changed().then_some((percent / 100.0, merge))) +} + +/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +#[allow(clippy::too_many_arguments)] +fn effect_row( + app: &mut TextureCraftApp, + ui: &mut Ui, + layer: &Layer, + stack: &[Effect], + effect: &Effect, + row_index: usize, + level: usize, + trunks: &[usize], + last: bool, + in_mask: bool, +) { + let tokens = Tokens::get(ui.ctx()); + let (effect_id, visible) = (effect.id, effect.visible); + let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id); + let layer_preview = layer_preview_size(app); + let preview_size = effect_preview_size(layer_preview); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview)), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name)); + + // Background, tree lines and the selected row's accent edge + let painter = ui.painter().clone(); + + // Effect rows alternate two shades just above the panel, counted from the top of their list + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover + } else { + tokens.panel.lerp_to_gamma(tokens.row_hover, EFFECT_ROW_SHADES[row_index % EFFECT_ROW_SHADES.len()]) + }; + painter.rect_filled(rect, 0.0, background); + let indent = effect_row_indent(rect.width(), level, preview_size); + tree_lines(&painter, &tokens, rect, indent, trunks, !last); if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); - let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); - p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); - if er.clicked() { - app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); - } else if resp.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + + // The eye, then the stack as it is up to and including this effect (a hidden one shows what it bypasses) + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(EYE_SIZE, EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eff_eye", effect_id.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); + let eye_glyph = if visible { ic::EYE } else { ic::EYE_SLASH }; + painter.text(eye.center(), egui::Align2::CENTER_CENTER, eye_glyph, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text_dim); + let thumbnail = Rect::from_min_size(pos2(content_left + EYE_COLUMN_WIDTH, rect.center().y - preview_size * 0.5), vec2(preview_size, preview_size)); + let channel = app.ui.layer_channel; + if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) { + let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; + painter.text(thumbnail.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(preview_size * 0.5), tokens.text_dim); } - // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. - if resp.drag_started() { - resp.dnd_set_drag_payload(EffectDrag(eid.0)); + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border), egui::StrokeKind::Outside); + if !visible { + painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); - let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); - if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + + // The name, then the blend mode and opacity side by side at the right when the name keeps room to be read + let name_left = thumbnail.right() + THUMBNAIL_GAP; + let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; + let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; + let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; + let name_color = if visible { tokens.text } else { tokens.text_dim }; + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); + painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + if show_blend { + let mode_width = EFFECT_BLEND_WIDTH - ROW_CONTROL_GAP - EFFECT_OPACITY_WIDTH; + let mode_rect = Rect::from_center_size(pos2(controls_left + mode_width * 0.5, rect.center().y), vec2(mode_width, ROW_CONTROL_HEIGHT)); + let opacity_center = pos2(mode_rect.right() + ROW_CONTROL_GAP + EFFECT_OPACITY_WIDTH * 0.5, rect.center().y); + let opacity_rect = Rect::from_center_size(opacity_center, vec2(EFFECT_OPACITY_WIDTH, ROW_CONTROL_HEIGHT)); + let id = ui.scope_id().with(("eff_blend", effect_id.0)); + let (mode, opacity) = + blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), (tr("Blending mode of the effect"), &effect.name)); + if let Some(mode) = mode { + app.run("effect.set", json!({"effect": effect_id.0, "blend": format!("{mode:?}")})); + } + if let Some((opacity, merge)) = opacity { + app.run("effect.set", json!({"effect": effect_id.0, "opacity": opacity, "merge": merge})); + } + } + + if eye_response.clicked() { + app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if row.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); + } + + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half + if row.drag_started() { + row.dnd_set_drag_payload(EffectDrag(effect_id.0)); + } + let position = |id: u64| stack.iter().position(|other| other.id.0 == id); + let below = ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| pointer.y > rect.center().y); + if row.dnd_hover_payload::().is_some_and(|dragged| dragged.0 != effect_id.0 && position(dragged.0).is_some()) { let y = if below { rect.bottom() } else { rect.top() }; - p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + painter.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(DROP_LINE_WIDTH, tokens.accent)); } - if let Some(src) = dnd_release::(&resp) - && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + if let Some(dragged) = dnd_release::(&row) + && let (Some(from), Some(to)) = (position(dragged.0), position(effect_id.0)) && from != to { - // Rows list the stack top first, so above this row is the next index up. + // Rows list the stack top first, so above this row is the next index up let index = match (from < to, below) { (true, false) | (false, true) => to, (true, true) => to - 1, (false, false) => to + 1, }; - app.run("effect.move", json!({"effect": src.0, "index": index})); + app.run("effect.move", json!({"effect": dragged.0, "index": index})); } - resp.context_menu(|ui| { + + row.context_menu(|ui| { let keymap = app.ui.keymap.clone(); - // The row is selected before the paste runs, so a copied effect is all it needs. + // The row is selected before the paste runs, so a copied effect is all it needs let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); - // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. - for (label, id, keys, enabled) in [ + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect + for (label, command, keys, enabled) in [ (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), (tr("Duplicate effect"), "effect.duplicate", None, true), (tr("Remove effect"), "effect.remove", None, true), ] { - let mut b = egui::Button::new(label); - if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { - b = b.shortcut_text(sc); + let mut button = egui::Button::new(label); + if let Some(shortcut) = keys.and_then(|key| crate::keymap::shortcut_of(&keymap, key)) { + button = button.shortcut_text(shortcut); } - if ui.add_enabled(enabled, b).clicked() { - // Selected first: a paste lands above it, a duplicate takes the selection. - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); - app.run(id, json!({"effect": eid.0})); + if ui.add_enabled(enabled, button).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); + app.run(command, json!({"effect": effect_id.0})); ui.close(); } } @@ -667,7 +1083,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.close(); } }; - // An instance without a mask of its own edits its source's; adding one overrides it. + // An instance edits its source mask until it gets its own let project = &app.session.doc.project; let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.is_some()); run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": lid}), layer.mask.is_none()); @@ -754,7 +1170,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { app.run("textureSet.uvTiles", json!({"ts": ts, "enabled": tiled})); } ui.end_row(); - // Each tile's own size (per-tile resolution). + // Each tile's own size (per-tile resolution) for &udim in &set.uv_tiles { let r = set.tile_resolution(udim); ui.label(RichText::new(format!(" {udim}")).color(tk.text_dim)); @@ -827,14 +1243,14 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover()); ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button }); ui.vertical(|ui| { - ui.label(RichText::new(tr(m.label())).strong()); + ui.label(RichText::new(tr(crate::i18n::baked_map_label(m))).strong()); ui.label( RichText::new(if present { format!("{}_{}", set.name, m.id()) } else { tr("Missing (bake to create)").into() }) .size(10.5) .color(tk.text_dim), ); }); - // An image resource instead of a bake, or no map. + // An image resource instead of a bake, or no map ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { if let Some(name) = image_menu(app, ui) { @@ -848,7 +1264,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { }); }); }); - // A shelf image dropped on the row becomes this mesh map. + // A shelf image dropped on the row becomes this mesh map let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); if let Some(name) = image_drop(ui, &resp) { app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); @@ -858,10 +1274,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } /// Menu items listing the image resources, then Import...: the image picked, if any. -fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { +pub(crate) fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { ui.label(caption(tr("Images"))); let mut picked = None; - // Bounded, so Import... and the items after it stay on screen with many images. + // Bounded so Import... and later items stay on screen with many images egui::ScrollArea::vertical().id_salt("image_menu").max_height(240.0).show(ui, |ui| { for name in app.session.doc.resources.keys() { if ui.button(name.as_str()).clicked() { @@ -881,7 +1297,7 @@ fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { /// An image from the Assets panel dropped on `resp`, outlined while one hovers it. Other assets /// are left for the drop targets around it. -fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { +pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { if !resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { return None; } @@ -892,8 +1308,8 @@ fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } } -fn mesh_map_color(m: BakedMap) -> Color32 { - match m { +pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 { + match map { BakedMap::Normal => Color32::from_rgb(128, 128, 255), BakedMap::WorldNormal => Color32::from_rgb(120, 200, 140), BakedMap::Id => Color32::from_rgb(220, 60, 60), @@ -904,45 +1320,65 @@ fn mesh_map_color(m: BakedMap) -> Color32 { BakedMap::Height => Color32::from_gray(128), BakedMap::BentNormal => Color32::from_rgb(140, 170, 230), BakedMap::Opacity => Color32::from_gray(230), - BakedMap::ColorMap => Color32::from_rgb(200, 150, 90), - BakedMap::WorldDirection => Color32::from_gray(180), } } // --------------------------------------------------------------------------------------------- // Properties -/// The Properties tab title: what the panel edits. +/// 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(), - _ => tr(app.session.tool.tool.label()).to_string(), + let project = &app.session.doc.project; + let tool = app.session.tool.tool; + let tool_usable = app.session.tool_usable(tool); + let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { + // Polygon fill keeps its own properties wherever it can fill + _ if tool == Tool::PolygonFill && tool_usable => tr(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(), + (Some(_), StackTarget::Mask) if !tool_usable => tr("Mask").to_string(), + (None, _) if !tool_usable => return tr("Properties").to_string(), + _ => tr(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)); + // A floating scroll bar would cover the right-aligned slider values and section reset icons + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + 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, instance or mask, else the tool (or a hint to select a layer when it can't act) +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()); + let tool = app.session.tool.tool; + let tool_usable = app.session.tool_usable(tool); + + match (&selected, app.session.target) { + // Polygon fill shows its own settings and says what it fills into, wherever it can fill + _ if tool == Tool::PolygonFill && tool_usable => 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); - ui.separator(); - tool_properties(app, ui); + (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); + if tool_usable { + ui.separator(); + tool_properties(app, ui); + } + } + (None, _) if !tool_usable => { + ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); } _ => tool_properties(app, ui), - }); + } } /// An instance draws its source: point there for edits. @@ -992,38 +1428,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), @@ -1036,6 +1477,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), @@ -1135,104 +1577,232 @@ 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)])) + } + } + } +} + +/// Font size of the dim hint line under the Brush caption +const HINT_TEXT_SIZE: f32 = 10.5; + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let b = &mut app.session.tool.brush; + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); ui.label(caption(tr("Brush"))); let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); - ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim)); - section(ui, "sec_size", tr("Size"), true, |ui| { - let mut size = b.size / 0.25 * 100.0; - if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() { - b.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); + ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); + + // Each section's reset puts back only the fields it shows + let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); + if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| { + let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; + if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() { + brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - let mut ms = b.min_size * 100.0; - if slider(ui, tr("Minimum size (%)"), &mut ms, 0.0..=100.0, 0).changed() { - b.min_size = ms / 100.0; + + let mut min_size_percent = brush.min_size * 100.0; + if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() { + brush.min_size = min_size_percent / 100.0; } - ui.checkbox(&mut b.screen_space, tr("Size in screen space")); - }); - section(ui, "sec_flow", tr("Flow and opacity"), true, |ui| { - let mut f = b.flow * 100.0; - if slider(ui, tr("Flow"), &mut f, 0.0..=100.0, 0).changed() { - b.flow = f / 100.0; + + ui.checkbox(&mut brush.screen_space, tr("Size in screen space")); + }) { + (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); + } + + let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing, settings.hardness); + if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { + let mut flow_percent = brush.flow * 100.0; + if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { + brush.flow = flow_percent / 100.0; } - let mut o = b.opacity * 100.0; - if slider(ui, tr("Stroke opacity"), &mut o, 0.0..=100.0, 0).changed() { - b.opacity = o / 100.0; + + let mut opacity_percent = brush.opacity * 100.0; + if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() { + brush.opacity = opacity_percent / 100.0; } - let mut s = b.spacing * 100.0; - if slider(ui, tr("Spacing"), &mut s, 1.0..=1000.0, 0).changed() { - b.spacing = s / 100.0; + + let mut spacing_percent = brush.spacing * 100.0; + if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { + brush.spacing = spacing_percent / 100.0; } - let mut h = b.hardness * 100.0; - if slider(ui, tr("Hardness"), &mut h, 0.0..=99.9, 0).changed() { - b.hardness = h / 100.0; + + let mut hardness_percent = brush.hardness * 100.0; + if slider(ui, tr("Hardness"), &mut hardness_percent, 0.0..=99.9, 0).changed() { + brush.hardness = hardness_percent / 100.0; } - }); - section(ui, "sec_angle", tr("Angle"), false, |ui| { - slider(ui, tr("Angle"), &mut b.angle, -180.0..=180.0, 0); - ui.checkbox(&mut b.follow_path, tr("Follow path")); - }); - section(ui, "sec_jitter", tr("Jitters"), false, |ui| { - for (label, v) in [(tr("Size jitter"), &mut b.jitter_size), (tr("Angle jitter"), &mut b.jitter_angle), (tr("Flow jitter"), &mut b.jitter_flow)] { - let mut x = *v * 100.0; - if slider(ui, label, &mut x, 0.0..=100.0, 0).changed() { - *v = x / 100.0; + }) { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = flow_fields(&defaults); + } + + let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); + if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| { + slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0); + ui.checkbox(&mut brush.follow_path, tr("Follow path")); + }) { + (brush.angle, brush.follow_path) = angle_fields(&defaults); + } + + let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position); + if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| { + let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)]; + for (label, jitter) in jitters { + let mut jitter_percent = *jitter * 100.0; + if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() { + *jitter = jitter_percent / 100.0; } } - let mut pj = b.jitter_position * 100.0; - if slider(ui, tr("Position jitter"), &mut pj, 0.0..=400.0, 0).changed() { - b.jitter_position = pj / 100.0; + + let mut position_jitter_percent = brush.jitter_position * 100.0; + if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() { + brush.jitter_position = position_jitter_percent / 100.0; } - }); - section(ui, "sec_align", tr("Alignment and culling"), false, |ui| { + }) { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults); + } + + let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth); + if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| { use texturecraft_engine::paint::Alignment; let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))]; - let shown = alignments.iter().find(|(a, _)| *a == b.alignment).map_or("", |(_, l)| l); + let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label); combo(ui, tr("Alignment"), shown, |ui| { - for (a, l) in alignments { - ui.selectable_value(&mut b.alignment, a, l); + for (alignment, label) in alignments { + ui.selectable_value(&mut brush.alignment, alignment, label); } }); - ui.checkbox(&mut b.backface_culling, tr("Backface culling")); - slider(ui, tr("Angle fade from"), &mut b.angle_fade.0, 0.0..=90.0, 0); - slider(ui, tr("Angle fade to"), &mut b.angle_fade.1, 0.0..=90.0, 0); - slider(ui, tr("Stamp depth"), &mut b.depth, 0.05..=4.0, 2); - }); - section(ui, "sec_particles", tr("Particles"), false, |ui| { - let pt = &mut b.particles; - ui.checkbox(&mut pt.enabled, tr("Particle brush (slides down the surface)")); - let mut count = pt.count as f32; + + ui.checkbox(&mut brush.backface_culling, tr("Backface culling")); + slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0); + slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0); + slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2); + }) { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults); + } + + if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| { + let particles = &mut brush.particles; + ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)")); + + let mut count = particles.count as f32; if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() { - pt.count = count as u32; + particles.count = count as u32; } - let mut life = pt.lifetime as f32; - if slider(ui, tr("Lifetime (steps)"), &mut life, 1.0..=128.0, 0).changed() { - pt.lifetime = life as u32; + + let mut lifetime_steps = particles.lifetime as f32; + if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() { + particles.lifetime = lifetime_steps as u32; } - slider(ui, tr("Gravity"), &mut pt.gravity, 0.0..=2.0, 2); - }); - section(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, |ui| { - slider(ui, tr("Lazy mouse distance"), &mut b.lazy, 0.0..=200.0, 0); - ui.horizontal(|ui| { - ui.checkbox(&mut b.symmetry.x, tr("Mirror X")); - ui.checkbox(&mut b.symmetry.y, tr("Mirror Y")); - ui.checkbox(&mut b.symmetry.z, tr("Mirror Z")); - }); - let mut copies = f32::from(b.symmetry.radial); - if slider(ui, tr("Radial copies"), &mut copies, 0.0..=32.0, 0).changed() { - b.symmetry.radial = copies as u8; - } - ui.add_enabled_ui(b.symmetry.radial > 1, |ui| { - ui.horizontal(|ui| { - ui.label(tr("Radial axis")); - for (k, name) in ["X", "Y", "Z"].into_iter().enumerate() { - ui.selectable_value(&mut b.symmetry.axis, k as u8, name); - } - }); - }); - }); - *b = b.sanitized(); + + slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2); + }) { + brush.particles = defaults.particles; + } + + if section_with_reset(ui, "sec_lazy", tr("Lazy mouse"), false, brush.lazy == defaults.lazy, |ui| { + slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0); + }) { + brush.lazy = defaults.lazy; + } + + *brush = brush.sanitized(); + + // Presets are files, which the browser doesn't have + #[cfg(not(target_arch = "wasm32"))] + section(ui, "sec_brush_preset", tr("Preset"), false, |ui| crate::brush_preset_save::row(app, ui)); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. @@ -1356,59 +1926,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)); } } @@ -1469,7 +2048,8 @@ fn link_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, link: app.cook_link(layer); } if ui.button(tr("Open in MaterialCraft")).clicked() { - let path = std::env::temp_dir().join(format!("{}.mcraft", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let ext = texturecraft_engine::link_cmds::source_extension(&link.package); + let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); let opened = app .session .link_package(layer) @@ -1551,7 +2131,7 @@ fn with(base: &Value, extra: Value) -> Value { } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). -fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { +pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { let p = &app.session.doc.project; let Some((ts, _, _)) = p.locate(reader) else { return Vec::new() }; p.walk(ts) @@ -1563,51 +2143,61 @@ fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String .collect() } -fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { +pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); 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")), @@ -1615,55 +2205,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(_) => {} } } @@ -1837,74 +2435,23 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu } } }); - // A shelf image dropped on the channel becomes its source. + // A shelf image dropped on the channel becomes its source if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { app.run("layer.fill.set", set(json!({"image": name}))); } } } -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 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:?}")})); - } - } - }); - }); - 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})); - } - 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) => { - 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]; - 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)); - } - 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})); - } - } +/// The properties of effect `effect_id` of `layer`: each kind's own settings. +fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { + let tokens = Tokens::get(ui.ctx()); + let Some(effect) = app.session.doc.project.effect(effect_id).map(|(_, effect)| effect.clone()) else { return }; + + let id = effect_id.0; + + match &effect.kind { + EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), + EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); let anchors = anchors_below(app, layer.id); @@ -1918,195 +2465,171 @@ 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()})); } } }); - ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } _ => {} } if anchors.is_empty() { - ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.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"))); ui.label( RichText::new(tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); } 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 == effect_id) { 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.") }; - ui.label(RichText::new(hint).color(tk.text_dim)); - tool_properties(app, ui); + ui.label(RichText::new(hint).color(tokens.text_dim)); + if app.session.tool_usable(app.session.tool.tool) { + tool_properties(app, ui); + } } EffectKind::Path(paths) => { ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) - .color(tk.text_dim), + .color(tokens.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((effect_id, 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})); + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { + app.run("path.remove", json!({"effect": id, "index": index})); } }); } - tool_properties(app, ui); - } - EffectKind::Filter(f) => filter_properties(app, ui, id, f), - other => { - ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); - } - } -} - -/// 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. -fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) { - let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor); - if layer.content_effects.iter().any(|e| e.id == eid) { - let pick = egui::Id::unique(("levels_channel", eid.0)); - let chans: Vec = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect(); - channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel); - combo(ui, tr("Channel"), tr(channel.label()), |ui| { - for c in chans { - if ui.selectable_label(c == channel, tr(c.label())).clicked() { - ui.data_mut(|d| d.insert_temp(pick, c)); - } + if app.session.tool_usable(app.session.tool.tool) { + tool_properties(app, ui); } - }); - } - let key = egui::Id::unique(("levels_histogram", eid.0, channel)); - let rev = app.session.revision; - let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc>)>(key)) { - Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h), - _ => app.session.effect_histogram(eid, channel, 64).map(|h| { - let h = std::sync::Arc::new(h); - ui.data_mut(|d| d.insert_temp(key, (rev, h.clone()))); - h - }), - }; - if let Some(counts) = counts { - histogram(ui, &counts, range); + } + EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), + other => { + ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); + } } } -/// 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 { .. } @@ -2117,8 +2640,69 @@ 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)); } _ => {} } } + +#[cfg(test)] +mod layer_layout_tests { + use super::*; + + #[test] + fn narrow_nested_rows_keep_thumbnail_and_secondary_controls_separate() { + for width in [120.0, 180.0, 260.0, 400.0] { + for depth in 0..=12 { + for folder in [false, true] { + let row = Rect::from_min_size(pos2(100.0, 20.0), vec2(width, 48.0)); + let (indent, size) = layer_thumbnail_layout(width, depth, folder, 36.0); + let content_left = row.left() + 7.0 + indent + 20.0 + if folder { 14.0 } else { 0.0 }; + let content = Rect::from_min_size(pos2(content_left, row.top() + 6.0), vec2(size, size)); + let mask = content.translate(vec2(size + 4.0, 0.0)); + let (name, show_blend) = layer_name_layout(row, mask.right() + 8.0); + + assert!(size >= 35.0, "minimum-width panels retain usable thumbnail targets"); + assert!(row.contains_rect(content) && row.contains_rect(mask), "width={width}, depth={depth}, folder={folder}"); + assert!(!content.intersects(mask)); + if name.width() >= 20.0 { + assert!(row.contains_rect(name)); + assert!(name.left() > mask.right()); + } + if show_blend { + let blend_left = row.right() - RIGHT_COLUMN - 4.0; + assert!(name.right() + 4.0 <= blend_left); + assert!(mask.right() < blend_left); + } + } + } + } + } + + #[test] + fn narrow_effect_rows_keep_the_eye_preview_and_name_inside() { + for width in [120.0, 180.0, 260.0, 400.0] { + for level in 0..=14 { + for preview in [18.0, 21.6, 28.0] { + let indent = effect_row_indent(width, level, preview); + let eye_right = 7.0 + indent + 16.0; + let preview_left = 7.0 + indent + 22.0; + let name_left = preview_left + preview + 8.0; + assert!(eye_right < preview_left); + assert!(name_left + 20.0 <= width - 6.0 + 0.001); + } + } + } + } + + #[test] + fn ordinary_rows_keep_preferred_sizes_and_secondary_controls() { + let row = Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 48.0)); + let (indent, size) = layer_thumbnail_layout(row.width(), 2, false, 36.0); + let (_, show_blend) = layer_name_layout(row, 7.0 + indent + 20.0 + size * 2.0 + 4.0 + 8.0); + + assert_eq!(indent, 28.0); + assert_eq!(size, 36.0); + assert!(show_blend); + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index ed23f88a..62bfa427 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -24,6 +24,12 @@ use crate::theme::Tokens; pub enum Panel { Viewport, Assets, + // Saved layouts name the bake panels by their earlier names + #[serde(rename = "BakeMaps")] + MeshMapSettings, + #[serde(rename = "BakeSettings")] + CommonSettings, + MeshMapBakers, TextureSetList, Layers, TextureSetSettings, @@ -35,12 +41,15 @@ pub enum Panel { } /// Window ▸ Views items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 9] = [ +pub const VIEWS: [(&str, Panel); 12] = [ ("ui.view.assets", Panel::Assets), + ("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), @@ -53,9 +62,20 @@ pub fn view_panel(id: &str) -> Option { } impl Panel { - pub const ALL: [Panel; 10] = [ + pub(crate) fn available_in(self, mode: crate::state::Mode) -> bool { + match self { + 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; 13] = [ Panel::Viewport, Panel::Assets, + Panel::MeshMapSettings, + Panel::CommonSettings, + Panel::MeshMapBakers, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, @@ -70,7 +90,10 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", - Panel::TextureSetList => "Texture Set List", + 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", Panel::Properties => "Properties", @@ -106,36 +129,63 @@ 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 -/// set settings) and properties down the right. Ratios match the 1600x960 window. Display, -/// shader, history and log are closed and open as floating windows. +/// The default: assets (4 tile columns at 1920 px) left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties 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)); + + // The Assets split keeps four tiles visible at the reference window width + const ASSETS_SPLIT_RATIO: f32 = 0.16; + const VIEWPORT_SPLIT_RATIO: f32 = 0.80; + const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; + const LAYERS_SPLIT_RATIO: f32 = 0.57; + + let column = split( + SplitAxis::Vertical, + SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO), + tabs(&[TextureSetList]), + split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + ); + let root = split( + SplitAxis::Horizontal, + SplitSize::Ratio(ASSETS_SPLIT_RATIO), + tabs(&[Assets]), + split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), 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() { - let location = Location { - floating: Some(rect), - anchor: None, + workspace.hidden.push((panel, floating_location(rect))); + } + } + + for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { + workspace.hidden.push(( + panel, + Location { + floating: None, + anchor: Some(TextureSetList), placement: Placement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None, - }; - workspace.hidden.push((panel, location)); - } + }, + )); } + workspace } +/// Where a closed panel reopens as its own floating window at `rect` (`[x, y, width, height]`) +fn floating_location(rect: [f32; 4]) -> Location { + Location { floating: Some(rect), anchor: None, placement: Placement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None } +} + /// craft-ui's checks plus the viewport's: a saved or hand-edited file cannot hide, float, group /// or collapse it. pub fn validate(workspace: &Workspace) -> Result<(), String> { @@ -176,17 +226,31 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { // --------------------------------------------------------------------------------------------- // The live dock +/// Height of a panel group's tab strip, in points +pub(crate) const TAB_HEIGHT: f32 = 30.0; + +/// Width of the bake layout's texture set and mesh map bakers column in points: the reference's scaled to our larger font +const BAKERS_COLUMN_WIDTH: f32 = 232.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 } } } @@ -210,16 +274,47 @@ 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] { + if let Ok(location) = workspace.layout.location(&panel) { + workspace.hidden.push((panel, location)); + } + } + + 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 { @@ -260,6 +355,13 @@ impl Dock { } } + /// Open the closed `panel` as a floating window at `rect` (`[x, y, width, height]`) + pub(crate) fn float_at(&mut self, panel: Panel, rect: [f32; 4]) { + self.workspace.hidden.retain(|(hidden_panel, _)| *hidden_panel != panel); + self.workspace.hidden.push((panel, floating_location(rect))); + self.focus(panel); + } + /// One change from the dock area's gestures. A change that is rejected leaves the layout as /// it was. fn apply(&mut self, action: Action) { @@ -279,97 +381,140 @@ fn area_id() -> Id { Id::unique("texturecraft-docking") } -/// The dock look: every panel group is a card on the window's frame colour, its tab strip -/// without hard lines, the shown tab a pill. -fn style(ui: &Ui, t: &Tokens) -> DockStyle { - let mut s = DockStyle::from_ui(ui); - s.gap = f32::from(crate::theme::GUTTER); - // Smallest panel extent a divider drag leaves. - s.min_pane = 60.0; - s.background = t.panel; - s.tab_background = t.panel; - s.active_background = t.button; - s.text = t.text_strong; - s.inactive_text = t.text_dim; - s.border = egui::Stroke::NONE; - s.accent = t.accent; - s.floating_background = t.panel; - s.floating_stroke = egui::Stroke::new(1.0, t.button_border); - s.font = egui::FontId::proportional(12.5); - s.min_tab_width = 54.0; - s.tab_height = 30.0; - // Panels arrange in a split tree around the viewport; floating title bars only move windows. - s.new_dock_zones = false; - s.title_bar_docks = false; - s +/// Smallest panel extent a divider drag leaves, in points +const MIN_PANE_EXTENT: f32 = 60.0; + +/// Border width of a floating panel, in points +const FLOATING_BORDER_WIDTH: f32 = 1.0; + +/// Text size of the panel tabs, in points +const TAB_TEXT_SIZE: f32 = 12.5; + +/// Narrowest panel tab, in points +const MIN_TAB_WIDTH: f32 = 54.0; + +/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill +fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { + let mut dock_style = DockStyle::from_ui(ui); + dock_style.gap = f32::from(crate::theme::GUTTER); + dock_style.min_pane = MIN_PANE_EXTENT; + + dock_style.background = tokens.panel; + dock_style.tab_background = tokens.panel; + dock_style.active_background = tokens.button; + dock_style.text = tokens.text_strong; + dock_style.inactive_text = tokens.text_dim; + dock_style.border = egui::Stroke::NONE; + dock_style.accent = tokens.accent; + dock_style.floating_background = tokens.panel; + dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border); + + dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE); + dock_style.min_tab_width = MIN_TAB_WIDTH; + dock_style.tab_height = TAB_HEIGHT; + + // Panels arrange in a split tree around the viewport; floating title bars only move windows + dock_style.new_dock_zones = false; + dock_style.title_bar_docks = false; + dock_style +} + +/// 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) { - let ctx = ui.ctx().clone(); - let tk = Tokens::get(&ctx); - let style = style(ui, &tk); + for panel in Panel::ALL { + if !panel.available_in(app.ui.mode) && app.ui.dock.is_open(panel) { + app.ui.dock.close(panel); + } + } + + let context = ui.ctx().clone(); + let tokens = Tokens::get(&context); + let style = style(ui, &tokens); let layout = app.ui.dock.workspace.layout.clone(); - let mut area = DockArea::new(area_id()).input_blocked(ctx.memory(|m| m.top_modal_layer()).is_some()); + let mut area = DockArea::new(area_id()).input_blocked(input_blocked(app, &context)); if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tk }); + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens }); + crate::rail_popup::hand_drag_to_dock(&context, area_id()); + + // After the dock, which records the viewport the popup reaches into, and before a changed layout returns early + crate::rail_popup::show(app, &context); + #[cfg(not(target_arch = "wasm32"))] - crate::menus::forwarded_shortcuts(app, &ctx, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default()); + crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default()); if let Some(error) = &output.error { log::warn!("docking: {error}"); } - // A body that changed the layout (a panel opened from its own menu) wins over this frame's - // gestures, which were made against the old one. + + // A layout changed by a panel takes priority over gestures from the old layout if app.ui.dock.workspace.layout != layout { - craft_ui::docking::cancel_drag::(&ctx, area_id()); + craft_ui::docking::cancel_drag::(&context, area_id()); return; } + for action in output.actions { app.ui.dock.apply(action); } } -/// The panels' contents, names and limits for the dock area. +/// The panels' contents, names and limits for the dock area struct Panels<'a> { app: &'a mut TextureCraftApp, - tk: Tokens, + tokens: Tokens, +} + +/// Room between a panel's edges and its contents +const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); + +/// The body of every panel except the viewport, in the dock or on the rail +pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { + egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel { + Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), + Panel::Assets => crate::shelf::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), + Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), + Panel::Properties => crate::dock::properties(app, ui), + // Display and Shader Settings scroll here, as tall as their contents; History and Log scroll their own lists + Panel::Display => egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, true]).show(ui, |ui| crate::windows::display(app, ui)).inner, + Panel::Shader => egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, true]).show(ui, |ui| crate::windows::shader(app, ui)).inner, + Panel::History => crate::windows::history(app, ui), + Panel::Log => crate::windows::log(app, ui), + Panel::Viewport => {} + }); } impl DockContent for Panels<'_> { fn body(&mut self, ui: &mut Ui, panel: &Panel) { let app = &mut *self.app; if *panel == Panel::Viewport { - ui.painter().rect_filled(ui.max_rect(), 0.0, self.tk.viewport); + crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); + ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); crate::viewport::central(app, ui); return; } - egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel { - Panel::Assets if app.ui.mode == crate::state::Mode::Baking => crate::windows::bake_body(app, ui), - Panel::Assets => crate::shelf::body(app, ui), - Panel::TextureSetList => crate::dock::texture_set_list(app, ui), - Panel::Layers => crate::dock::layers(app, ui), - Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), - Panel::Properties => crate::dock::properties(app, ui), - // The other panels scroll their own lists. - Panel::Display => { - egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, false]).show(ui, |ui| crate::windows::display(app, ui)).inner - } - Panel::Shader => { - egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, false]).show(ui, |ui| crate::windows::shader(app, ui)).inner - } - Panel::History => crate::windows::history(app, ui), - Panel::Log => crate::windows::log(app, ui), - Panel::Viewport => {} - }); + + panel_body(app, ui, *panel); } fn logical_label(&self, panel: &Panel) -> String { match panel { Panel::Properties => crate::dock::properties_title(self.app), - // Bake mode shows its settings where the shelf lives. - Panel::Assets if self.app.ui.mode == crate::state::Mode::Baking => tr("Bake Mesh Maps").to_string(), p => tr(p.name()).to_string(), } } @@ -418,6 +563,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 c0aee844..5d5ddafc 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -70,7 +70,7 @@ static PALETTE: LazyLock = LazyLock::new(|| { [ (n_("Texture set channels"), Channel::ALL.iter().map(|&channel| (channel.label(), SourceRef::Channel { channel, component: 0 })).collect()), (n_("Converted maps"), VirtualMap::ALL.iter().map(|&map| (map.label(), SourceRef::Virtual { map, component: 0 })).collect()), - (n_("Mesh maps"), BakedMap::ALL.iter().map(|&map| (map.label(), SourceRef::Baked { map, component: 0 })).collect()), + (n_("Mesh maps"), BakedMap::ALL.iter().map(|&map| (crate::i18n::baked_map_label(map), SourceRef::Baked { map, component: 0 })).collect()), (n_("Constants"), vec![(n_("Black"), SourceRef::Constant(0.0)), (n_("Gray 50%"), SourceRef::Constant(0.5)), (n_("White"), SourceRef::Constant(1.0))]), ] }); @@ -79,7 +79,7 @@ fn source_label(s: &SourceRef) -> &'static str { match s { SourceRef::Channel { channel, .. } => channel.label(), SourceRef::Virtual { map, .. } => map.label(), - SourceRef::Baked { map, .. } => map.label(), + SourceRef::Baked { map, .. } => crate::i18n::baked_map_label(*map), SourceRef::Constant(_) => n_("Constant"), } } @@ -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/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs new file mode 100644 index 00000000..63fe8008 --- /dev/null +++ b/crates/ui-egui/src/generator_panel.rs @@ -0,0 +1,394 @@ +//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs. + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source}; + +use crate::TextureCraftApp; +use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::theme::{Tokens, caption}; +use crate::widgets::{combo, section, slider_edit}; + +/// Random seeds stay below this, short enough to read and type. +const SEED_RANGE: u32 = 10_000; +/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range. +const SEED_MIX: u32 = 2_654_435_761; + +/// Font size of the notes under a control. +const NOTE_FONT_SIZE: f32 = 10.5; + +/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. +const INPUT_TILE_SIZE: f32 = 32.0; +const INPUT_TILE_ROUNDING: f32 = 2.0; +const INPUT_TILE_ICON_SIZE: f32 = 16.0; + +/// Width of the names in the Attributes section, so their values line up. +const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; + +/// The settings of generator effect `id`. +pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { + let tokens = 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() && kind != generator.kind { + app.run("effect.set", json!({"effect": id, "generator": format!("{kind:?}")})); + } + } + }); + + section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); + section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); + section(ui, "generator_parameters", tr("Parameters"), true, |ui| { + global_adjustments(app, ui, id, generator); + ramp_parameters(app, ui, id, generator); + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + app.run("effect.set", defaults_of(id, generator.kind)); + } + }); + }); + }); + if !generator.kind.inputs().is_empty() { + section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + for map in generator.kind.inputs() { + input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); + } + }); + } + 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(tokens.warning), + ); + } +} + +/// What a generator kind makes, its category and its tags (read only). +fn attributes(ui: &mut Ui, kind: GeneratorKind) { + let tokens = Tokens::get(ui.ctx()); + let (description, tags) = match kind { + GeneratorKind::EdgeWear => ( + tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::Dirt => ( + tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")], + ), + GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), + GeneratorKind::Curvature => ( + tr("Convex edges, cavities or both from the curvature map, at several detail sizes."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::AmbientOcclusion => { + (tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) + } + GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + }; + + // Wrapped rows: a long line must not widen the panel past its edge + let tags = tags.join(", "); + for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] { + ui.horizontal_top(|ui| { + ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); + ui.add(egui::Label::new(value).wrap()); + }); + } +} + +/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to. +fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) { + let tokens = Tokens::get(ui.ctx()); + combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| { + for mode in ResolutionMode::ALL { + if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")})); + } + } + }) + .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); + if resolution.mode == ResolutionMode::Custom { + combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| { + for size in OutputResolution::CUSTOM_SIZES { + if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() { + app.run("effect.set", json!({"effect": id, "customResolution": size})); + } + } + }); + } + combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| { + for factor in OutputResolution::FACTORS { + if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() { + app.run("effect.set", json!({"effect": id, "resolutionFactor": factor})); + } + } + }) + .on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up.")); + + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return }; + + let (smallest, largest) = texture_set + .uv_tiles + .iter() + .map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution)) + .fold((u32::MAX, 0), |(smallest, largest), size| (smallest.min(size), largest.max(size))); + let (smallest, largest) = if largest == 0 { + let size = resolution.output_size(texture_set.resolution, texture_set.resolution); + (size, size) + } else { + (smallest, largest) + }; + let size_label = if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") }; + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label)); + }) + .response + .on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution.")); +} + +/// The most powers of two a resolution factor scales by, either way. +const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); + +/// "Same as context", or the fraction or multiple a resolution factor stands for. +fn factor_label(factor: i8) -> String { + match factor { + 0 => tr("Same as context").to_string(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + } +} + +/// Global invert, blur, balance and contrast: what every generator applies to its finished value. +fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut invert, mut global) = (generator.invert, generator.global); + let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); + let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); + let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); + if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) { + app.run( + "effect.set", + json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), + ); + } +} + +/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. +fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); + 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 offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), + ); + } + seed_row(app, ui, id, generator.seed); +} + +/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference. +fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { + let typing_id = ui.make_persistent_id(("generator_seed_typing", id)); + let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); + ui.horizontal(|ui| { + ui.label(tr("Seed")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { + typing = !typing; + } + if typing { + let mut typed = seed; + let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); + if field.changed() { + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge})); + } + } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() { + app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)})); + } + }); + }); + ui.data_mut(|data| data.insert_temp(typing_id, typing)); +} + +/// A seed different from `current`, from the clock. +fn random_seed(current: u32) -> u32 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); + let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; + if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } +} + +/// The `effect.set` params that put generator effect `id` back to the defaults of its kind. +fn defaults_of(id: u64, kind: GeneratorKind) -> Value { + let defaults = Generator::new(kind); + let mut params = json!({ + "effect": id, + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + "seed": defaults.seed, + "direction": defaults.direction, + "invert": defaults.invert, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + if let Some(detail) = defaults.detail { + params["mode"] = json!(format!("{:?}", detail.mode)); + params["sizes"] = json!(detail.weights); + } + params +} + +/// 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 tokens = 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(tokens.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"), + } +} + +/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { + let tokens = Tokens::get(ui.ctx()); + let input = map.id(); + let current = match source { + None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), + Some(Source::Uniform(_)) => tr("Uniform value").to_string(), + Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel), + Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + }; + let group = ui.group(|ui| { + ui.horizontal(|ui| { + input_tile(app, ui, map, source); + ui.vertical(|ui| { + ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + }); + }); + combo(ui, tr("Source"), current.clone(), |ui| { + let anchors = anchors_below(app, layer); + if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + } + for (anchor, label) in &anchors { + if ui + .selectable_label( + matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), + trf("Anchor: {name}", &[("name", label)]), + ) + .clicked() + { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + }); + if let Some(Source::Uniform(value)) = source { + let mut value = value[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); + } + } + if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + ui.label( + RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) + .size(NOTE_FONT_SIZE) + .color(tokens.text_dim), + ); + } + }); + if let Some(name) = image_drop(ui, &group.response) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } +} + +/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); + let painter = ui.painter(); + let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + match source { + Some(Source::Image { name, .. }) => match app.session.images.get(name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), name, image); + painter.image(texture.id(), rect, whole, egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + } + }, + Some(Source::Uniform(value)) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + } + Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); + } + None => { + let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); + painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); + } + } + painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside); +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 77db5727..ef362d63 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, CageGeometry, 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 hard edges without a UV seam (vertex pairs) per material +pub type MissingSeamEdges = 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 hard edges without a UV seam per material, for mesh id + pub missing_seams: Option<(u64, MissingSeamEdges)>, } /// 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,157 @@ 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() { + // While a bake shows, its streamed maps (neutral where not baked yet) replace the document's + let preview = session.bake_preview_baked(texture_set); + let baked = preview.or_else(|| session.doc.baked.get(&texture_set)); + let have = baked.and_then(|baked| baked.maps.get(&map)); + let revision = have.map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}{}", if preview.is_some() { "~" } else { "" }), 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); + let rgba = if preview.is_some() && have.is_none() { + texturecraft_render::mesh_maps::neutral_rgba(map, resolution) + } else { + texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, resolution, cache.size, &cache.composite.block_scales) + }; + out.aux.push((texture_set, resolution, rgba)); + 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 +337,69 @@ 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| CageGeometry { + corners: &upload.corners, + edges: &upload.shell.edges, + missing_seams: &upload.shell.missing_seams, + }); + gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); + } + if let Some((mesh_id, seams)) = &sync.missing_seams { + gpu.renderer.set_missing_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/grid_tile.rs b/crates/ui-egui/src/grid_tile.rs new file mode 100644 index 00000000..45fd9bf6 --- /dev/null +++ b/crates/ui-egui/src/grid_tile.rs @@ -0,0 +1,9 @@ +//! A grid tile's measurements in the shelf's small, medium and large views + +/// A grid tile's size and its thumbnail's size and center below the tile's top, in points +pub(crate) struct GridTile { + pub(crate) width: f32, + pub(crate) height: f32, + pub(crate) thumbnail_size: f32, + pub(crate) thumbnail_center_y: f32, +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f9106d57..f1aaa9b8 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,22 +1,32 @@ -//! UI text lookup. Keys are the English strings, so English needs no table and a missing -//! translation falls back to English. Every user-visible literal goes through [`tr`] (or [`trf`] -//! for text with `{name}` placeholders); each language is a static `(English, translation)` -//! table, indexed into a hash map the first time the language is used. `Prefs::language` picks it. +//! UI text lookup over the optional shared craft-i18n catalogs. +//! Missing translations and builds without catalogs use the English source text. -use std::collections::HashMap; use std::fmt::Display; -use std::sync::OnceLock; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{LazyLock, OnceLock}; -mod ar; -mod de; -mod es; -mod fr; -mod it; -mod ja; -mod ko; -mod pt_br; -mod zh_hans; +include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); + +static I18N: LazyLock = LazyLock::new(|| { + let offered: Vec<_> = LANGUAGES.iter().map(|l| l.code).collect(); + let (i18n, problems) = craft_i18n::I18n::new(CRAFT_I18N, &offered); + for problem in problems { + log::warn!("translation catalog: {problem}"); + } + i18n +}); + +static SHARED_LANGUAGES: OnceLock<[craft_i18n::Lang; COUNT]> = OnceLock::new(); + +/// Resolve the fixed picker codes once; hot text lookups only load the cached language handle. +fn shared_languages() -> &'static [craft_i18n::Lang; COUNT] { + SHARED_LANGUAGES.get_or_init(|| LANGUAGES.each_ref().map(|l| I18N.from_code(l.code).unwrap_or(craft_i18n::Lang::EN))) +} + +/// Whether this build embeds a catalog for a supported language. +pub fn available(code: &str) -> bool { + I18N.from_code(code).is_some() +} pub struct Language { /// BCP 47 code ("en", "pt-BR", "zh-Hans"). @@ -25,31 +35,46 @@ pub struct Language { pub name: &'static str, /// Its English name (the picker's fallback when no font can draw `name`). pub english: &'static str, - /// `(English, translation)` pairs, in any order. - pub table: &'static [(&'static str, &'static str)], } const COUNT: usize = 10; pub static LANGUAGES: [Language; COUNT] = [ - Language { code: "en", name: "English", english: "English", table: &[] }, - Language { code: "fr", name: "Français", english: "French", table: fr::TABLE }, - Language { code: "de", name: "Deutsch", english: "German", table: de::TABLE }, - Language { code: "es", name: "Español", english: "Spanish", table: es::TABLE }, - Language { code: "pt-BR", name: "Português (Brasil)", english: "Portuguese (Brazil)", table: pt_br::TABLE }, - Language { code: "it", name: "Italiano", english: "Italian", table: it::TABLE }, - Language { code: "ja", name: "日本語", english: "Japanese", table: ja::TABLE }, - Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)", table: zh_hans::TABLE }, - Language { code: "ko", name: "한국어", english: "Korean", table: ko::TABLE }, - Language { code: "ar", name: "العربية", english: "Arabic", table: ar::TABLE }, + Language { code: "en", name: "English", english: "English" }, + Language { code: "fr", name: "Français", english: "French" }, + Language { code: "de", name: "Deutsch", english: "German" }, + Language { code: "es", name: "Español", english: "Spanish" }, + Language { code: "pt-BR", name: "Português (Brasil)", english: "Portuguese (Brazil)" }, + Language { code: "it", name: "Italiano", english: "Italian" }, + Language { code: "ja", name: "日本語", english: "Japanese" }, + Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" }, + Language { code: "ko", name: "한국어", english: "Korean" }, + Language { code: "ar", name: "العربية", english: "Arabic" }, ]; -static MAPS: [OnceLock>; COUNT] = [const { OnceLock::new() }; COUNT]; static CURRENT: AtomicUsize = AtomicUsize::new(0); +/// Display labels belong to the UI; the model exposes only map identities +pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'static str { + use texturecraft_engine::core::BakedMap; + + match map { + BakedMap::Normal => n_("Normal"), + BakedMap::WorldNormal => n_("World Space Normal"), + BakedMap::Id => n_("ID"), + BakedMap::AmbientOcclusion => n_("Ambient Occlusion"), + BakedMap::Curvature => n_("Curvature"), + BakedMap::Position => n_("Position"), + BakedMap::Thickness => n_("Thickness"), + BakedMap::Height => n_("Height"), + BakedMap::BentNormal => n_("Bent Normals"), + BakedMap::Opacity => n_("Opacity"), + } +} + /// Switch the UI language (unknown codes fall back to English). pub fn set_language(code: &str) { - CURRENT.store(LANGUAGES.iter().position(|l| l.code == code).unwrap_or(0), Ordering::Relaxed); + CURRENT.store(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0), Ordering::Relaxed); } /// The current UI language. @@ -59,12 +84,8 @@ pub fn current() -> &'static Language { /// `text` in the current language (unchanged when it has no translation). pub fn tr(text: &str) -> &str { - let i = CURRENT.load(Ordering::Relaxed); - let (Some(lang), Some(map)) = (LANGUAGES.get(i), MAPS.get(i)) else { return text }; - if lang.table.is_empty() { - return text; - } - map.get_or_init(|| lang.table.iter().copied().collect()).get(text).copied().unwrap_or(text) + let lang = shared_languages().get(CURRENT.load(Ordering::Relaxed)).copied().unwrap_or(craft_i18n::Lang::EN); + I18N.t(lang, text) } /// Marks a static string for translation where it is defined (gettext's `N_`); it is translated @@ -75,25 +96,9 @@ pub const fn n_(text: &'static str) -> &'static str { /// `template` translated, with each `{name}` replaced by its value in `args`. pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String { - let mut out = String::with_capacity(template.len() + 16); - let mut rest = tr(template); - while let Some(open) = rest.find('{') { - out.push_str(&rest[..open]); - let after = &rest[open + 1..]; - match after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (close, v))) { - Some((close, v)) => { - use std::fmt::Write as _; - let _ = write!(out, "{v}"); - rest = &after[close + 1..]; - } - None => { - out.push('{'); - rest = after; - } - } - } - out.push_str(rest); - out + let values: Vec<_> = args.iter().map(|(name, value)| (*name, value.to_string())).collect(); + let args: Vec<_> = values.iter().map(|(name, value)| (*name, value.as_str())).collect(); + craft_i18n::fmt(tr(template), &args) } /// The supported language for a locale such as "de-AT", "pt_BR.UTF-8" or "zh-Hant-TW" ("en" when @@ -116,22 +121,30 @@ 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(()); + use std::collections::{BTreeSet, HashMap}; /// 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 { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut keys = Vec::new(); - for entry in std::fs::read_dir(&dir).unwrap() { - let path = entry.unwrap().path(); - if path.extension().is_some_and(|e| e == "rs") { - literals(&std::fs::read_to_string(&path).unwrap(), &mut keys); + let mut directories = vec![dir]; + while let Some(directory) = directories.pop() { + for entry in std::fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() && path.file_name().is_some_and(|name| name != "i18n") { + directories.push(path); + } else if path.extension().is_some_and(|extension| extension == "rs") { + literals(&std::fs::read_to_string(path).unwrap(), &mut keys); + } } } keys.extend(catalog_keys().into_iter().map(str::to_owned)); @@ -143,38 +156,38 @@ mod tests { /// The labels of the menu catalog, panels, shortcuts, shelf tabs and engine enums that are /// translated where they are shown. fn catalog_keys() -> Vec<&'static str> { - use texturecraft_engine::core::{BakedMap, BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind}; + use texturecraft_engine::core::{BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind}; use texturecraft_engine::filter_lib::{FILTERS, build, scalar_params}; - let mut k: Vec<&'static str> = Vec::new(); - k.extend(crate::menus::TOP); - for i in crate::menus::CATALOG.iter().filter(|i| i.label != "-") { - k.push(i.label); - k.extend(i.sub); + let mut keys: Vec<&'static str> = Vec::new(); + keys.extend(crate::menus::TOP); + for item in crate::menus::CATALOG.iter().filter(|item| item.label != "-") { + keys.push(item.label); + keys.extend(item.sub); } - k.extend(crate::docking::VIEWS.iter().map(|(_, p)| p.name())); - for b in crate::keymap::bindings() { - k.push(b.label); - k.push(b.group); + keys.extend(crate::docking::VIEWS.iter().map(|(_, panel)| panel.name())); + for binding in crate::keymap::bindings() { + keys.push(binding.label); + keys.push(binding.group); } - k.extend(crate::shelf::TABS.iter().map(|t| t.2)); - k.extend(Channel::ALL.iter().flat_map(|c| [c.label(), c.short()])); - k.extend(BlendMode::all().map(|m| m.label())); - k.extend(BakedMap::ALL.iter().map(|m| m.label())); - k.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|m| m.label())); - k.extend(texturecraft_engine::Tool::ALL.iter().map(|t| t.label())); - k.extend(ProceduralKind::ALL.iter().map(|p| p.label())); - k.extend(GeneratorKind::ALL.iter().map(|g| g.label())); - k.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|a| a.label())); - k.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, l)| *l)); - for f in FILTERS { - k.extend([f.label, f.group]); - if let Ok(EffectKind::Filter(x)) = build(f.id, &serde_json::Value::Null) { - k.push(x.label()); - k.extend(scalar_params(&x).into_iter().map(|p| p.1)); + keys.extend(crate::shelf::TABS.iter().map(|tab| tab.2)); + keys.extend(Channel::ALL.iter().flat_map(|channel| [channel.label(), channel.short()])); + keys.extend(BlendMode::all().map(|mode| mode.label())); + keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label())); + keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label())); + keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); + keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); + keys.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|alpha| alpha.label())); + keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label)); + for filter in FILTERS { + keys.extend([filter.label, filter.group]); + if let Ok(EffectKind::Filter(effect)) = build(filter.id, &serde_json::Value::Null) { + keys.push(effect.label()); + keys.extend(scalar_params(&effect).into_iter().map(|parameter| parameter.1)); } } - // Effect, view and camera names the engine gives. - k.extend([ + + // Include effect, view and camera names supplied by the engine + keys.extend([ "Paint", "Path", "Fill", @@ -187,8 +200,8 @@ mod tests { texturecraft_engine::camera_cmds::DEFAULT_CAMERA, crate::dock::SOLO_HINT, ]); - k.retain(|s| !s.is_empty() && !UNTRANSLATED.contains(s)); - k + keys.retain(|key| !key.is_empty() && !UNTRANSLATED.contains(key)); + keys } /// String literals passed straight to `tr(` or `trf(` in `src`. @@ -228,43 +241,52 @@ mod tests", } } - fn placeholders(s: &str) -> Vec<&str> { - let mut v: Vec<&str> = s.split('{').skip(1).filter_map(|p| p.split_once('}').map(|(name, _)| name)).collect(); - v.sort_unstable(); - v + #[test] + fn embedded_catalogs_are_valid() { + assert!(I18N.check_all().is_empty(), "{:?}", I18N.check_all()); } + /// Translation work never blocks a feature: report missing/stale keys without failing. #[test] - fn every_key_is_translated_in_every_language() { + fn translation_coverage_report() { let keys = keys(); assert!(keys.len() > 300, "found only {} keys", keys.len()); - let mut missing = Vec::new(); - for l in LANGUAGES.iter().skip(1) { - let map: HashMap<&str, &str> = l.table.iter().copied().collect(); - assert_eq!(map.len(), l.table.len(), "{}: duplicate keys", l.code); - for k in &keys { - if !map.contains_key(k.as_str()) { - missing.push(format!("{}: {k:?}", l.code)); + let used: BTreeSet<_> = keys.iter().map(String::as_str).collect(); + for &(locale, common, app) in CRAFT_I18N { + let Some(lang) = I18N.from_code(locale) else { continue }; + let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect(); + + // Decode TSV escapes to compare with literal source strings + let mut rows = HashMap::new(); + for text in [common, app] { + for line in text.lines().filter(|l| !l.starts_with('#')) { + let columns: Vec<_> = line.split('\t').collect(); + if let ["", source, _] = columns.as_slice() { + let mut decoded = String::new(); + let mut chars = source.chars(); + while let Some(c) = chars.next() { + decoded.push(if c == '\\' { + match chars.next() { + Some('n') => '\n', + Some('t') => '\t', + Some(c) => c, + None => '\\', + } + } else { + c + }); + } + rows.insert(decoded, ()); + } } } + let stale: Vec<_> = rows.keys().filter(|key| !used.contains(key.as_str())).collect(); + eprintln!("{locale}: missing {} {missing:?}; unused/shared {} {stale:?}", missing.len(), stale.len()); } - assert!(missing.is_empty(), "{} missing translations:\n{}", missing.len(), missing.join("\n")); } - /// Catalog labels that read the same in every language (names and formats). const UNTRANSLATED: &[&str] = &["RGB", "RGBA"]; - #[test] - fn translations_keep_placeholders_and_are_not_empty() { - for l in &LANGUAGES { - for (en, t) in l.table { - assert!(!t.trim().is_empty(), "{}: empty translation of {en:?}", l.code); - assert_eq!(placeholders(en), placeholders(t), "{}: placeholders of {en:?} in {t:?}", l.code); - assert_eq!(en.ends_with("..."), t.ends_with("...") || t.ends_with('…'), "{}: ellipsis of {en:?} in {t:?}", l.code); - } - } - } - #[test] fn lookup_formatting_and_fallbacks() { let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -280,27 +302,53 @@ mod tests", assert_eq!(language_for_locale(locale), code, "{locale}"); } set_language("de"); - assert_eq!(current().code, "de"); + assert_eq!(current().code, if available("de") { "de" } else { "en" }); assert_eq!(tr("not a key"), "not a key"); set_language("en"); } + #[test] + fn shared_lookup_overrides_and_missing_translations() { + static CATALOGS: &craft_i18n::Embedded = &[("es", "\tSave\tGuardar\n\tOpen\tAbrir\n", "\tSave\tGuardar proyecto\n")]; + let (runtime, problems) = craft_i18n::I18n::new(CATALOGS, &["es"]); + assert!(problems.is_empty()); + assert!(runtime.check_all().is_empty()); + let lang = runtime.from_code("es").unwrap(); + assert_eq!(runtime.t(lang, "Save"), "Guardar proyecto"); + assert_eq!(runtime.t(lang, "Open"), "Abrir"); + assert_eq!(runtime.t(lang, "New feature"), "New feature"); + assert_eq!(runtime.t(craft_i18n::Lang::EN, "Save"), "Save"); + } + + #[test] + fn saved_language_codes_and_spanish_lookup() { + let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for language in &LANGUAGES { + set_language(language.code); + assert_eq!(current().code, if available(language.code) { language.code } else { "en" }); + } + set_language("es"); + assert_eq!(tr("Layers"), if available("es") { "Capas" } else { "Layers" }); + set_language("en"); + } + #[test] fn lookup_is_fast() { let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let keys = keys(); set_language("ja"); - let t = std::time::Instant::now(); - let mut n = 0usize; + let started = std::time::Instant::now(); + let mut total_chars = 0usize; for _ in 0..100 { - for k in &keys { - n += tr(k).len(); + for key in &keys { + total_chars += tr(key).len(); } } - let per = t.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64; + let ns_per_lookup = started.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64; set_language("en"); - assert!(n > 0); - // A frame looks up a few hundred strings: well under a microsecond each. - assert!(per < 1000.0, "{per:.0} ns per lookup"); + assert!(total_chars > 0); + + // A frame looks up a few hundred strings, each expected below one microsecond + assert!(ns_per_lookup < 1000.0, "{ns_per_lookup:.0} ns per lookup"); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 939b0b3c..b63df18c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1,6 +1,17 @@ //! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "جارٍ خبز {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "جارٍ خبز {map} ({n}/{total})، مجموعة الخامات {set} من {sets}"), + ("Follow Newest Map", "تتبّع أحدث خريطة"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "الرسم متوقف مؤقتًا أثناء عرض عملية الخبز. ألغِ الخبز أو انتظر حتى ينتهي.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ما يعرضه العرض ثلاثي الأبعاد أثناء الخبز: أحدث خريطة مكتملة، أو أي خريطة مكتملة تختارها، أو الخامة. الخرائط التي لم تُخبز بعد تعرض قيمة محايدة.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), ("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"), ("2D view only", "عرض ثنائي الأبعاد فقط"), @@ -22,15 +33,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)", "إضافة كملصق (مركز العرض)"), @@ -44,7 +46,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "إضافة مرشح"), ("Add folder", "إضافة مجلد"), ("Add generator", "إضافة مولّد"), - ("Add high definition meshes", "إضافة مجسمات عالية الدقة"), ("Add levels", "إضافة مستويات"), ("Add mask", "إضافة قناع"), ("Add mask with color selection", "إضافة قناع مع تحديد لوني"), @@ -52,20 +53,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", "تعديلات"), ( @@ -80,8 +69,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "مرتبط أيضاً بـ {item} ({menu})"), ("Alt + LMB drag", "سحب بـ Alt + زر الفأرة الأيسر"), ("Always", "دائماً"), + ("Ambient Occlusion", "الانسداد المحيطي (AO)"), ("Ambient occlusion", "الانسداد المحيطي (AO)"), - ("Ambient occlusion intensity", "شدة الانسداد المحيطي"), ("Amount", "المقدار"), ("Anchor point", "نقطة ارتكاز"), ("Anchor: {name}", "نقطة ارتكاز: {name}"), @@ -96,27 +85,25 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "تنعيم الحواف"), ("Aperture", "فتحة العدسة"), ("Apply", "تطبيق"), - ("Apply to all texture sets", "تطبيق على جميع مجموعات الخامات"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), + ("Auto", "تلقائي"), ("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"), ("Autosave every", "حفظ تلقائي كل"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "تُحفظ النسخ التلقائية والمواد الذكية والإعدادات المسبقة والقوالب وتخطيطات الواجهة في مجلد البيانات. يُطبَّق المجلد الجديد عند إعادة التشغيل، وتبقى الملفات المحفوظة في مكانها.", ), - ("Average normals", "توسيط النواظم"), ("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) للمولدات المعتمدة على الانحناء والانسداد المحيطي والسماكة.", ), - ("Bake selected textures ({n})", "خبز الخامات المحددة ({n})"), - ("Bake with \"Bake selected textures\"", "اخبز باستخدام \"خبز الخامات المحددة\""), ("Baked Lighting", "إضاءة مخبوزة"), ("Baking", "الخبز"), ("Base color", "اللون الأساسي"), @@ -127,10 +114,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "اللون الأساسي، المعدنية، الخشونة ومستوى اللمعان."), ("Based on each texture set's size", "بناءً على حجم كل مجموعة خامات"), ("Basic settings", "الإعدادات الأساسية"), - ("Bent normals", "النواظم المنحنية"), + ("Bent Normals", "النواظم المنحنية"), ("Bevel", "شطف الحواف"), ("Black", "أسود"), - ("Blend sharpness", "حدة المزج"), ("Blending", "الدمج"), ("Blending mode of the displayed channel", "نمط الدمج للقناة المعروضة"), ("Blur", "تمويه"), @@ -145,9 +131,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "مدمج (للقراءة فقط): انسخه لتعديله"), ("Built-in templates are read-only: duplicate one to edit it", "القوالب المدمجة للقراءة فقط: انسخ قالباً لتعديله"), ("Built-in: {mesh}", "مدمج: {mesh}"), - ("By mesh name", "حسب اسم المجسم"), ("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", "إلغاء ضربة الفرشاة"), @@ -156,6 +151,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "القناة"), ("Channel source: uniform value, procedural, image or anchor", "مصدر القناة: قيمة موحدة، إجرائي، صورة أو نقطة ارتكاز"), ("Channels", "القنوات"), + ("Check for Updates...", "التحقق من وجود تحديثات..."), ("Checker", "رقعة شطرنج"), ("Clamp", "تقييد القيم"), ("Clear", "مسح"), @@ -177,7 +173,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "توازن الألوان"), ("Color burn", "حرق لوني (Color Burn)"), ("Color dodge", "تفتيح لوني (Color Dodge)"), - ("Color map", "خريطة الألوان"), ("Color of the light that travels under the surface (each channel goes as far as its value)", "لون الضوء المنتقل تحت السطح (تصل كل قناة بقدر قيمتها)"), ("Color picker", "منتقي الألوان"), ("Color selection", "تحديد لوني"), @@ -185,7 +180,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Colors near the first shift towards the second, keeping their shading.", "الألوان القريبة من الأولى تتحول نحو الثانية مع الحفاظ على تظليلها."), ("Colors read as gray. Add a levels or blur effect above to shape the result.", "تُقرأ الألوان كرمادي. أضف تأثير مستويات أو تمويه في الأعلى لتشكيل النتيجة."), ("Combine with the layer's height", "الدمج مع ارتفاع الطبقة"), - ("Common parameters", "المعلمات المشتركة"), ("Compare mask", "قناع مقارنة"), ("Compositing", "التركيب"), ("Constant", "ثابت"), @@ -198,7 +192,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "نسخ من"), ("Copy layer(s)", "نسخ الطبقة (الطبقات)"), ("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"), - ("Copy these bake settings to every texture set", "نسخ إعدادات الخبز هذه إلى كل مجموعة خامات"), ("Copy to all texture sets", "نسخ إلى جميع مجموعات الخامات"), ("Copy what the texture set shows", "نسخ ما تعرضه مجموعة الخامات"), ("Couldn't encode the render", "تعذر ترميز التصيير"), @@ -246,8 +239,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "تمديد + لون الخلفية الافتراضي"), ("Dilation + transparent", "تمديد + شفاف"), ("Dilation infinite", "تمديد لا نهائي"), - ("Dilation width", "عرض التمديد"), - ("Direction {axis}", "الاتجاه {axis}"), ("DirectX normal map", "خريطة نواظم DirectX"), ("Dirt", "أوساخ"), ("Disable", "تعطيل"), @@ -327,10 +318,14 @@ 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", "ضوضاء دقيقة"), ("Fingerprints", "بصمات أصابع"), + ("Enter a finite number", "أدخل عددًا محدودًا"), + ("Double-click or press Enter to edit", "انقر نقرًا مزدوجًا أو اضغط Enter للتعديل"), + ("Fit the input range to the histogram", "ملاءمة نطاق الإدخال مع المدرج التكراري"), ("Flatten layer", "تسطيح الطبقة"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -348,11 +343,6 @@ pub const TABLE: &[(&str, &str)] = &[ "للمشروع كله: طريقة قراءة صور خرائط النواظم المعيَّنة كخرائط للمجسم (أعد تعيينها بعد التغيير) والقيمة الافتراضية للتصدير", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "مجاني ومفتوح المصدر (MIT أو Apache-2.0)، كُتب بلغة Rust."), - ("From normal map", "من خريطة النواظم"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "من خريطة النواظم: انحناء تفاصيل خريطة النواظم المخبوزة بدلاً من المجسم.", - ), ("From template", "من قالب"), ("From template / project", "من قالب / مشروع"), ("Full", "كامل"), @@ -392,12 +382,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "مساعدة"), ("Hide UI", "إخفاء واجهة المستخدم"), ("High", "عالي"), - ("High definition meshes", "مجسمات عالية الدقة"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "ارتفاع المجسم عالي الدقة بين المسافة الخلفية القصوى (أسود) والأمامية القصوى (أبيض).", - ), - ("High poly mesh suffix", "لاحقة المجسم عالي الدقة"), ("High poly: {name}", "عالي الدقة: {name}"), ("Highlights", "المناطق المضيئة"), ("Histogram Range", "نطاق المدرج التكراري"), @@ -428,7 +412,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "استيراد HDR..."), ("Import a template (.json)", "استيراد قالب (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "استورد صورة (ملف > استيراد الموارد) لإسقاطها على المجسم."), - ("Import images to use them in fills and masks", "استورد الصور لاستخدامها في التعبئة والأقنعة"), ("Import resources...", "استيراد الموارد..."), ("Import MaterialX material...", "استيراد مادة MaterialX..."), ("MaterialX materials", "مواد MaterialX"), @@ -450,6 +433,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "عكس"), ("Invert mask", "عكس القناع"), ("Invert mask background", "عكس خلفية القناع"), + ("Invert mask value", "عكس قيمة القناع"), ("Invert quick mask", "عكس القناع السريع"), ("Jitters", "اضطرابات (Jitters)"), ("Join the ArtCraft community on Discord", "انضم إلى مجتمع ArtCraft على Discord"), @@ -466,7 +450,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "ذاكرة الطبقات: {mb} ميغابايت"), ("Layers", "الطبقات"), ("Lazy mouse", "الفأرة الكسولة (Lazy mouse)"), - ("Lazy mouse and symmetry", "الفأرة الكسولة والتناظر"), ("Lazy mouse distance", "مسافة الفأرة الكسولة"), ("Leather grain", "حبيبات جلدية"), ("Lens size: how quickly things blur away from the focus distance", "حجم العدسة: سرعة تمويه العناصر البعيدة عن مسافة التركيز"), @@ -482,17 +465,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "ضوء خطي (Linear Light)"), ("List of exports", "قائمة الصادرات"), ("Load UI Layout", "تحميل تخطيط الواجهة"), - ("Load a cage (the low poly, inflated)", "تحميل القفص (مجسم منخفض الدقة منتفخ)"), ("Loaded UI layout {path}", "تم تحميل تخطيط الواجهة {path}"), ("Log", "السجل"), ("Low", "منخفض"), - ("Low poly mesh suffix", "لاحقة المجسم منخفض الدقة"), ("Luminosity", "اللمعان (Luminosity)"), ("MMB drag / Alt + MMB", "سحب بزر الفأرة الأوسط / Alt + زر الفأرة الأوسط"), ("Made by the ArtCraft team and community.", "صُنع بواسطة فريق ArtCraft والمجتمع."), ("Magenta / green", "أرجواني / أخضر"), ("Main shader", "المظلل الرئيسي"), ("Marble veins", "عروق الرخام"), + ("Mask", "قناع"), ("Mask Editor: Edge wear", "محرر الأقنعة: تآكل الحواف"), ("Mask value (gray)", "قيمة القناع (رمادي)"), ("Mask with height", "قناع بالارتفاع"), @@ -500,17 +482,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "إنهاء المادة: مطروق"), ("MatFinish Raw", "إنهاء المادة: خام"), ("MatFinish Sanded", "إنهاء المادة: مصنفر"), - ("Match", "مطابقة"), ("Material", "المادة"), ("Material ball", "كرة المادة"), ("Material finish", "إنهاء المادة"), ("Materials", "المواد"), - ("Max frontal distance", "أقصى مسافة أمامية"), - ("Max occluder distance", "أقصى مسافة للحاجب"), - ("Max rear distance", "أقصى مسافة خلفية"), ("Maximum", "الحد الأقصى"), ("Mesh fill", "تعبئة المجسم"), - ("Mesh map bakers", "خَبّازو خرائط المجسم"), ("Mesh map: {map}", "خريطة المجسم: {map}"), ("Mesh maps", "خرائط المجسم"), ("Mesh maps baked", "تم خبز خرائط المجسم"), @@ -519,9 +496,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "درجات الإضاءة المتوسطة"), ("Minimum", "الحد الأدنى"), ("Minimum size (%)", "الحد الأدنى للحجم (%)"), - ("Mirror X", "مرآة X"), - ("Mirror Y", "مرآة Y"), - ("Mirror Z", "مرآة Z"), ("Missing (bake to create)", "مفقود (اخبز للإنشاء)"), ("Mixed AO", "انسداد محيطي مختلط"), ("Mode", "النمط"), @@ -546,7 +520,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "كمية الضوضاء"), ("Noise scale", "مقياس الضوضاء"), ("None", "بلا"), - ("None: the low poly is its own high poly.", "بلا: المجسم منخفض الدقة هو نفسه عالي الدقة."), ("Normal", "عادي"), ("Normal DirectX", "ناظم DirectX"), ("Normal Invert", "عكس الناظم"), @@ -575,7 +548,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Offset {axis}", "إزاحة {axis}"), ("Offsets the textures by the height channel, at the height to normal strength", "يزيح الخامات وفق قناة الارتفاع، بقوة تحويل الارتفاع إلى ناظم"), ("On", "مفعل"), - ("One color per mesh part.", "لون واحد لكل جزء من المجسم."), ("Opacity", "العتامة"), ("Open sample project...", "فتح مشروع نموذجي..."), ("Open...", "فتح..."), @@ -586,15 +558,16 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "مدار"), ("Orthographic", "متوازي (إملائي)"), + ("Perspective", "منظوري"), ("Output directory", "دليل الإخراج"), ("Output high", "المخرج العالي"), ("Output low", "المخرج المنخفض"), - ("Output size", "حجم المخرج"), ("Output template", "قالب الإخراج"), ("Output templates", "قوالب الإخراج"), ("Overlay", "تراكب (Overlay)"), ("Overlay opacity", "عتامة التراكب"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - خشونة ومعدنية (TextureCraft)"), + ("Pick color", "التقاط لون"), ("PNG image", "صورة PNG"), ("Padding", "الحشو (Padding)"), ("Paint", "رسم"), @@ -604,7 +577,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "ارسم على المجسم لتعديل هذا القناع. استخدم قيمة القناع في لسان تبويب المادة للتدرج الرمادي.", ), - ("Paint the path with the brush (Enter)", "رسم المسار بالفرشاة (Enter)"), ("Paint with the current tool", "الرسم بالأداة الحالية"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -623,7 +595,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "لصق الطبقة (الطبقات)"), ("Path", "مسار"), ("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "المسار: النقر يضيف نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "المسار: النقر يضيف نقطة، والنقر على المنحنى يُدرج نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي", + ), ("Pattern scale", "مقياس النمط"), ("Perlin noise", "ضوضاء بيرلن (Perlin)"), ("Pick focus in the viewport", "اختر نقطة التركيز في منفذ العرض"), @@ -639,7 +614,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "اضطراب الموضع"), ("Posterize", "تبسيط الألوان (Posterize)"), ("Press a key...", "اضغط على مفتاح..."), - ("Procedurals", "إجرائيات"), ("Project", "المشروع"), ("Project Configuration...", "تكوين المشروع..."), ("Project opened", "تم فتح المشروع"), @@ -650,8 +624,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "ربع"), ("Quick mask", "قناع سريع"), ("Quit", "إنهاء"), - ("Radial axis", "المحور الدائري"), - ("Radial copies", "نُسخ دائرية"), ("Radius (texels at 2K)", "نصف القطر (تكسل بدقة 2K)"), ("RENDERING", "التصيير"), ("Range", "النطاق"), @@ -663,7 +635,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "إعادة"), ("Reimport mesh", "إعادة استيراد المجسم"), - ("Relative to the bounding box diagonal.", "نسبة إلى قطر المربع المحيط."), ("Remove", "إزالة"), ("Remove channel", "إزالة القناة"), ("Remove effect", "إزالة التأثير"), @@ -671,9 +642,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "إزالة الطبقة"), ("Remove layer(s)", "إزالة الطبقة (الطبقات)"), ("Remove mask", "إزالة القناع"), + ("Remove point", "إزالة النقطة"), ("Remove resource", "إزالة المورد"), - ("Remove the cage", "إزالة القفص"), - ("Remove the path (Esc)", "إزالة المسار (Esc)"), ("Remove the shortcut", "إزالة الاختصار"), ("Remove this output", "إزالة هذا المخرج"), ("Remove unused resources...", "إزالة الموارد غير المستخدمة..."), @@ -686,22 +656,17 @@ 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", "إعادة فحص مجلد المكتبة"), + ("Reset", "إعادة تعيين"), ("Reset UI", "إعادة ضبط واجهة المستخدم"), ("Reset all", "إعادة ضبط الكل"), + ("Reset to defaults", "إعادة الضبط إلى الإعدادات الافتراضية"), ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), - ("Return to painting mode", "العودة إلى نمط الرسم"), ("Return to this step", "العودة إلى هذه الخطوة"), - ("Auto-rebake", "إعادة الخبز تلقائيًا"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "يعيد خبز هذه الخريطة تلقائيًا عند تغيّر إعدادات الخبز أو المجسّم منخفض الدقة أو المجسّمات عالية الدقة", - ), ("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"), ("Rotation", "التدوير"), ("Rotation (degrees)", "التدوير (بالدرجات)"), @@ -729,9 +694,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "خدوش"), ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), - ("Search all assets", "البحث في جميع الأصول"), + ("Search", "بحث"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), - ("Secondary rays", "أشعة ثانوية"), ("Seed", "البذرة العشوائية (Seed)"), ("Select a layer", "تحديد طبقة"), ("Select an output template", "تحديد قالب إخراج"), @@ -796,16 +760,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "استعيان فرعي 8×8"), ("Subsurface scattering", "تشتت تحت السطح (SSS)"), ("Subtract", "طرح"), - ("Symmetry (X)", "تناظر (X)"), - ("Symmetry (Y)", "تناظر (Y)"), ("Tangent | Wrap", "مماس | التفاف"), - ("Tangent-space normals of the high definition meshes.", "نواظم فضاء المماس للمجسمات عالية الدقة."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "تنعيم حواف زمني (يحسّن العرض ثلاثي الأبعاد أثناء ثباته)"), - ("Texture Set List", "قائمة مجموعات الخامات"), + ("Texture Sets", "مجموعات الخامات"), ("Texture Set Settings", "إعدادات مجموعة الخامات"), ("Texture resolution", "دقة الخامة"), ("Texture set channels", "قنوات مجموعة الخامات"), - ("Texture set list", "قائمة مجموعات الخامات"), ("Texture sets", "مجموعات الخامات"), ("TextureCraft had to close:", "اضطر TextureCraft إلى الإغلاق:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - خشونة ومعدنية"), @@ -850,14 +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 low poly mesh as high poly mesh", "استخدام المجسم منخفض الدقة كمجسم عالي الدقة"), ("Use the control channel or `texturecraft-cli render` for screenshots", "استخدم قناة التحكم أو الأمر `texturecraft-cli render` لالتقاط لقطات الشاشة"), ("Value", "القيمة"), ("Version {version}", "الإصدار {version}"), @@ -878,15 +837,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "العجلة / سحب بـ Alt + زر الفأرة الأيمن"), ("White", "أبيض"), - ("White where the surface faces the direction, black where it faces away.", "أبيض حيث يواجه السطح الاتجاه، وأسود حيث يتجه بعيداً عنه."), ("Width", "العرض"), ("Width (texels at 2K)", "العرض (تكسل بدقة 2K)"), ("Window", "نافذة"), ("Wood grain", "حبيبات الخشب"), ("Works in texture space, like the blur: it does not cross UV seams.", "يعمل في فضاء الخامات، مثل التمويه: لا يعبر درزات UV."), - ("World space direction", "اتجاه الفضاء العالمي"), - ("World space normal", "ناظم الفضاء العالمي"), - ("World-space normals of the high poly (or the low poly).", "نواظم الفضاء العالمي للمجسم عالي الدقة (أو منخفض الدقة)."), + ("World Space Normal", "ناظم الفضاء العالمي"), ("Yellow / blue", "أصفر / أزرق"), ("Zoom", "تكبير/تصغير"), ("a missing layer", "طبقة مفقودة"), @@ -923,7 +879,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: إضافة فوق الطبقة المحددة (أو اسحبها إلى مكدس الطبقات أو إلى منفذ العرض)", ), - ("{name} ({n} triangles)", "{name} ({n} مثلث)"), ("{name} copy", "نسخة من {name}"), ("{n} bits", "{n} بت"), ( @@ -934,28 +889,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (المقياس {scale}، البذرة {seed})"), ("Template name", "اسم القالب"), ("Save current project as template", "حفظ المشروع الحالي كقالب"), - ("Spread angle", "زاوية الانتشار"), ("Distribution", "التوزيع"), ("Cosine", "جيب التمام (Cosine)"), ("Uniform", "موحد (Uniform)"), - ("Ignore backface", "تجاهل الوجه الخلفي"), - ("Self occlusion", "انسداد ذاتي"), - ("Only same mesh name", "نفس اسم المجسم فقط"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "أشعة النواظم المنحنية تتبع إعدادات حاجب الانسداد المحيطي."), - ("Sampling radius", "نصف قطر العينات"), - ("0 picks a radius from the output size.", "0 يختار نصف القطر تلقائياً من حجم المخرج."), - ("Encoding", "الترميز"), - ("Signed (-1..1)", "ذو إشارة (-1..1)"), - ("Positive (0..1)", "موجب (0..1)"), ("Normalization", "تسوية (Normalization)"), - ("Bounding box", "المربع المحيط"), - ("Bounding sphere", "الكرة المحيطة"), - ("Position normalized to the low poly's bounding box or sphere.", "الموضع مُسوّى بالنسبة للمربع أو الكرة المحيطة للمجسم منخفض الدقة."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "الألوان الأساسية (الخامات، المعاملات) وألوان الرؤوس للمجسمات عالية الدقة.", - ), - ("White where the high poly covers the low poly, times its alpha.", "أبيض حيث يغطي المجسم عالي الدقة المجسم منخفض الدقة، مضروباً في قيمة ألفا."), ("Brightness", "السطوع"), ("Dark", "داكن"), ("Medium dark", "متوسط الدكنة"), @@ -979,8 +916,6 @@ pub const TABLE: &[(&str, &str)] = &[ "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), ("Brushes", "الفرش"), - ("My brushes", "فرشي"), - ("Use this brush (keeps its size)", "استخدام هذه الفرشاة (مع الحفاظ على حجمها)"), ("Brush name", "اسم الفرشاة"), ("Save current brush", "حفظ الفرشاة الحالية"), ("Start window", "نافذة البدء"), @@ -1001,12 +936,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "تغييرات غير محفوظة"), ("Don't save", "عدم الحفظ"), ("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"), - ("Skew correction", "تصحيح الانحراف"), - ("Paint skew in the 2D view", "ارسم الانحراف في العرض ثنائي الأبعاد"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "اسحب في العرض ثنائي الأبعاد لرسم المواضع التي تنعطف فيها أشعة الخَبْز نحو الناظم الأساسي؛ ارسم بالقيمة 0 للمسح", - ), ("Radius", "نصف القطر"), ("Remove skew correction", "إزالة تصحيح الانحراف"), ("Twill weave", "نسيج مائل"), @@ -1026,4 +955,194 @@ pub const TABLE: &[(&str, &str)] = &[ "فُتحت في MaterialCraft: استخدم هناك ملف > إرسال إلى TextureCraft لإعادة تغييراتك", ), ("Parameters change in the desktop app, with MaterialCraft installed", "تتغير المعلمات في تطبيق سطح المكتب مع تثبيت MaterialCraft"), + ("Add High-Poly Meshes", "إضافة مجسمات عالية التفاصيل"), + ("All", "الكل"), + ("Apply Diffusion", "تطبيق الانتشار"), + ("Attenuation", "التوهين"), + ("Auto Tonemapping", "تعيين درجات الألوان تلقائيًا"), + ("Average Normals", "توسيط النواظم"), + ("BBox", "صندوق الإحاطة"), + ("BSphere", "كرة الإحاطة"), + ("Mesh Map Bakers", "مُخبِزات خرائط المجسم"), + ("Common Settings", "الإعدادات المشتركة"), + ("Mesh Map Settings", "إعدادات خرائط المجسم"), + ("Check All", "تحديد الكل"), + ("No Parameters", "لا توجد معلمات"), + ("Bake Selected Textures ({n})", "خبز الخامات المحددة ({n})"), + ("By Mesh Name", "حسب اسم المجسم"), + ("Cage", "القفص"), + ("Cage Scene", "مشهد القفص"), + ("Cage Type", "نوع القفص"), + ("Color Generator", "مولد الألوان"), + ("Color Source", "مصدر اللون"), + ("Common Parameters", "المعلمات المشتركة"), + ("Custom File", "ملف مخصص"), + ("Details", "التفاصيل"), + ("Dilation Width", "عرض التمديد"), + ("Distance-Based", "حسب المسافة"), + ("Edge Contrast", "تباين الحواف"), + ("Edge Distance", "مسافة الحواف"), + ("Edge Protection", "حماية الحواف"), + ("Enable Seams", "تفعيل الوصلات"), + ("File ID", "معرّف الملف"), + ("Full Scene", "المشهد الكامل"), + ("Generate from Mesh", "إنشاء من المجسم"), + ("Generate from Normal Map", "إنشاء من خريطة المتجهات العمودية"), + ("Ground Plane", "مستوى الأرض"), + ("Ground Plane Offset", "إزاحة مستوى الأرض"), + ("High Poly Mesh Suffix", "لاحقة المجسم عالي الدقة"), + ("High Poly Scene", "مشهد عالي التفاصيل"), + ("High-Poly Parameters", "معلمات المجسم عالي التفاصيل"), + ("Hue Shift", "إزاحة تدرج اللون"), + ("Ignore Backface", "تجاهل الوجه الخلفي"), + ("Ignore Backface Suffix", "لاحقة تجاهل الوجه الخلفي"), + ("Include in Bake", "تضمين في الخبز"), + ("Load Cage", "تحميل القفص"), + ("Lock Output Size", "قفل حجم الإخراج"), + ("Low Poly Mesh Suffix", "لاحقة المجسم منخفض الدقة"), + ("Manual", "يدوي"), + ("Material Color", "لون المادة"), + ("Max Frontal Distance", "أقصى مسافة أمامية"), + ("Max Occluder Distance", "أقصى مسافة للحاجب"), + ("Max Rear Distance", "أقصى مسافة خلفية"), + ("Mesh ID", "معرّف المجسم"), + ("Method", "الطريقة"), + ("Min Occluder Distance", "أدنى مسافة للحاجب"), + ("Never", "أبدًا"), + ("No High-Poly Meshes", "لا توجد مجسمات عالية التفاصيل"), + ("Normalization Scale", "نطاق التطبيع"), + ("Normalization Type", "نوع التطبيع"), + ("Only Same Mesh Name", "نفس اسم المجسم فقط"), + ("Output Size", "حجم المخرج"), + ("Match", "المطابقة"), + ("Skew Correction Method", "طريقة تصحيح الانحراف"), + ("Mesh Normals Based", "استنادًا إلى متجهات الشبكة العمودية"), + ("Face Normals Based", "استنادًا إلى متجهات الأوجه العمودية"), + ("Reset Painted Cage", "إعادة تعيين القفص المرسوم"), + ("Paint Cage", "رسم القفص"), + ("Paint Skew Correction", "رسم تصحيح الميل"), + ("Per Material", "لكل مادة"), + ("Random", "عشوائي"), + ("Relative to Bounding Box", "بالنسبة إلى صندوق الإحاطة"), + ("Relative to Low Mesh", "بالنسبة إلى المجسم منخفض التفاصيل"), + ("Relative to Min/Max", "بالنسبة إلى الحد الأدنى والأقصى"), + ("Relative to Ray Distances", "بالنسبة إلى مسافات الأشعة"), + ("Remove Cage", "إزالة القفص"), + ("Remove Skew Correction", "إزالة تصحيح الانحراف"), + ("Restore Defaults", "استعادة الإعدادات الافتراضية"), + ("Return to Painting Mode", "العودة إلى نمط الرسم"), + ("Sampling Radius", "نصف قطر العينات"), + ("Scaling Divisor", "قاسم المقياس"), + ("Seams Intensity", "شدة الوصلات"), + ("Secondary Rays", "أشعة ثانوية"), + ("Self Intersection", "التقاطع الذاتي"), + ("Self Occlusion", "انسداد ذاتي"), + ("Skew Correction", "تصحيح الانحراف"), + ("Smooth", "ناعم"), + ("Spread Angle", "زاوية الانتشار"), + ("Submesh", "مجسم فرعي"), + ("Use Low Poly Mesh as High Poly Mesh", "استخدام المجسم منخفض الدقة كمجسم عالي الدقة"), + ("Value Bounds Max", "الحد الأقصى للقيمة"), + ("Value Bounds Min", "الحد الأدنى للقيمة"), + ("Vertex Color", "لون الرأس"), + ("Select the layer content", "تحديد محتوى الطبقة"), + ("Paint layer", "طبقة رسم"), + ("Fill layer", "طبقة تعبئة"), + ("1 effect", "تأثير واحد"), + ("{count} effects", "{count} تأثيرات"), + ("Mask effects", "تأثيرات القناع"), + ("Content effects", "تأثيرات المحتوى"), + ("Fold or unfold these effects", "طيّ هذه التأثيرات أو فردها"), + ("Remove resolution override", "إزالة تجاوز الدقة"), + ("Texture set resolution", "دقة مجموعة الخامات"), + ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Angle span", "مدى الزاوية"), + ("Axis position", "موضع المحور"), + ("Count", "العدد"), + ("Display", "العرض"), + ("Hide while painting", "إخفاء أثناء الرسم"), + ("Manipulator size", "حجم أداة التحريك"), + ("Mirror symmetry", "تناظر مرآوي"), + ("Radial settings", "إعدادات التناظر الدائري"), + ("Radial symmetry", "تناظر دائري"), + ("Show axis", "إظهار المحور"), + ("Show axis position manipulator", "إظهار أداة تحريك موضع المحور"), + ("Show cursor", "إظهار المؤشر"), + ("Show intersection", "إظهار التقاطع"), + ("Show plane", "إظهار المستوى"), + ("Symmetry", "التناظر"), + ("Symmetry color display", "لون عرض التناظر"), + ("Symmetry settings", "إعدادات التناظر"), + ("Type", "النوع"), + ("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", "أقصى ذاكرة عند الحفظ"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "يستخدم الحفظ الأنوية الأخرى وحدًا أقصى بهذه النسبة من الذاكرة الحرة. يعمل نواة واحدة على الأقل دائمًا.", + ), + ("Max project size on open", "الحد الأقصى لحجم المشروع عند الفتح"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", + ), + ("Filter by type", "تصفية حسب النوع"), + ("All libraries", "كل المكتبات"), + ("Browse folders", "تصفح المجلدات"), + ("Starter assets", "الأصول المضمّنة"), + ("Your assets", "أصولك"), + ("Reset query", "إعادة تعيين الاستعلام"), + ("Refresh", "تحديث"), + ("Saved searches", "عمليات البحث المحفوظة"), + ("Save the current search", "حفظ البحث الحالي"), + ("Delete", "حذف"), + ("Filter by path", "تصفية حسب المسار"), + ("Hide non-applicable folders", "إخفاء المجلدات غير المطابقة"), + ("Thumbnail size", "حجم الصورة المصغّرة"), + ("Small", "صغير"), + ("Medium", "متوسط"), + ("Large", "كبير"), + ("List", "قائمة"), + ("Procedurals", "إجرائيات"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ae02fbd2..81e62b2c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1,6 +1,17 @@ //! German UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} wird gebacken ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} wird gebacken ({n}/{total}), Texturset {set} von {sets}"), + ("Follow Newest Map", "Neueste Map verfolgen"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "Das Malen ist pausiert, solange ein Bake angezeigt wird. Brich den Bake ab oder warte, bis er fertig ist.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Was die 3D-Ansicht während des Backens zeigt: die zuletzt fertige Map, eine fertige Map deiner Wahl oder das Material. Noch nicht gebackene Maps zeigen einen neutralen Wert.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), ("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"), ("2D view only", "Nur 2D-Ansicht"), @@ -22,15 +33,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.", @@ -47,7 +49,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Filter hinzufügen"), ("Add folder", "Ordner hinzufügen"), ("Add generator", "Generator hinzufügen"), - ("Add high definition meshes", "Hochauflösende Meshes hinzufügen"), ("Add levels", "Tonwertkorrektur hinzufügen"), ("Add mask", "Maske hinzufügen"), ("Add mask with color selection", "Maske mit Farbauswahl hinzufügen"), @@ -55,20 +56,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"), ( @@ -83,8 +72,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Auch belegt für {item} ({menu})"), ("Alt + LMB drag", "Alt + LMT ziehen"), ("Always", "Immer"), - ("Ambient occlusion", "Ambient Occlusion"), - ("Ambient occlusion intensity", "Ambient-Occlusion-Intensität"), + ("Ambient Occlusion", "Ambient Occlusion"), + ("Ambient occlusion", "Ambient occlusion"), ("Amount", "Stärke"), ("Anchor point", "Ankerpunkt"), ("Anchor: {name}", "Anker: {name}"), @@ -99,24 +88,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Kantenglättung"), ("Aperture", "Blende"), ("Apply", "Anwenden"), - ("Apply to all texture sets", "Auf alle Textursets anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"), ("Autosave every", "Automatisch speichern alle"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Automatische Sicherungen, Smart-Materialien, Vorgaben, Vorlagen und UI-Layouts werden im Datenordner gespeichert. Ein neuer Ordner gilt nach einem Neustart; bereits gespeicherte Dateien bleiben, wo sie sind.", ), - ("Average normals", "Normalen mitteln"), ("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."), - ("Bake selected textures ({n})", "Ausgewählte Texturen backen ({n})"), - ("Bake with \"Bake selected textures\"", "Backen mit „Ausgewählte Texturen backen“"), ("Baked Lighting", "Gebackene Beleuchtung"), ("Baking", "Backen"), ("Base color", "Grundfarbe"), @@ -127,10 +114,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Grundfarbe, Metallisch, Rauheit und Specular-Stärke."), ("Based on each texture set's size", "Basierend auf der Größe jedes Textursets"), ("Basic settings", "Grundeinstellungen"), - ("Bent normals", "Gebogene Normalen"), + ("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"), @@ -145,9 +131,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Integriert (schreibgeschützt): zum Bearbeiten duplizieren"), ("Built-in templates are read-only: duplicate one to edit it", "Integrierte Vorlagen sind schreibgeschützt: zum Bearbeiten eine duplizieren"), ("Built-in: {mesh}", "Integriert: {mesh}"), - ("By mesh name", "Nach Mesh-Name"), ("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"), @@ -156,6 +151,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"), @@ -180,7 +176,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Farbbalance"), ("Color burn", "Farbig nachbelichten"), ("Color dodge", "Farbig abwedeln"), - ("Color map", "Farb-Map"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Farbe des Lichts, das unter der Oberfläche wandert (jeder Kanal reicht so weit wie sein Wert)", @@ -197,7 +192,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Farben werden als Grau gelesen. Darüber eine Tonwertkorrektur oder einen Weichzeichnen-Effekt hinzufügen, um das Ergebnis zu formen.", ), ("Combine with the layer's height", "Mit der Höhe der Ebene kombinieren"), - ("Common parameters", "Gemeinsame Parameter"), ("Compare mask", "Vergleichsmaske"), ("Compositing", "Compositing"), ("Constant", "Konstante"), @@ -210,7 +204,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Kopieren aus"), ("Copy layer(s)", "Ebene(n) kopieren"), ("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"), - ("Copy these bake settings to every texture set", "Diese Back-Einstellungen in jedes Texturset kopieren"), ("Copy to all texture sets", "In alle Textursets kopieren"), ("Copy what the texture set shows", "Kopieren, was das Texturset anzeigt"), ("Couldn't encode the render", "Das Rendering konnte nicht kodiert werden"), @@ -261,8 +254,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatation + Standard-Hintergrundfarbe"), ("Dilation + transparent", "Dilatation + transparent"), ("Dilation infinite", "Dilatation unendlich"), - ("Dilation width", "Dilatationsbreite"), - ("Direction {axis}", "Richtung {axis}"), ("DirectX normal map", "DirectX-Normal-Map"), ("Dirt", "Schmutz"), ("Disable", "Deaktivieren"), @@ -351,10 +342,14 @@ 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"), ("Fingerprints", "Fingerabdrücke"), + ("Enter a finite number", "Eine endliche Zahl eingeben"), + ("Double-click or press Enter to edit", "Doppelklicken oder Eingabetaste zum Bearbeiten drücken"), + ("Fit the input range to the histogram", "Eingabebereich an das Histogramm anpassen"), ("Flatten layer", "Ebene reduzieren"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -372,11 +367,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Für das ganze Projekt: wie Normal-Map-Bilder als Mesh-Maps gelesen werden (nach einer Änderung neu zuweisen), und die Vorgabe für den Export", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Frei und quelloffen (MIT OR Apache-2.0), geschrieben in Rust."), - ("From normal map", "Aus Normal-Map"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Aus Normal-Map: Krümmung der Details der gebackenen Normal-Map statt des Meshs.", - ), ("From template", "Aus Vorlage"), ("From template / project", "Aus Vorlage / Projekt"), ("Full", "Voll"), @@ -416,12 +406,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Hilfe"), ("Hide UI", "UI ausblenden"), ("High", "Hoch"), - ("High definition meshes", "Hochauflösende Meshes"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "High-Poly-Höhe zwischen maximaler hinterer (schwarz) und maximaler vorderer (weiß) Distanz.", - ), - ("High poly mesh suffix", "Suffix für High-Poly-Mesh"), ("High poly: {name}", "High-Poly: {name}"), ("Highlights", "Lichter"), ("Histogram Range", "Histogrammbereich"), @@ -455,7 +439,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Ein Bild importieren (Datei > Ressourcen importieren), um es auf das Mesh zu projizieren.", ), - ("Import images to use them in fills and masks", "Bilder importieren, um sie in Füllungen und Masken zu verwenden"), ("Import resources...", "Ressourcen importieren..."), ("Import MaterialX material...", "MaterialX-Material importieren..."), ("MaterialX materials", "MaterialX-Materialien"), @@ -477,6 +460,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Invertieren"), ("Invert mask", "Maske invertieren"), ("Invert mask background", "Maskenhintergrund invertieren"), + ("Invert mask value", "Maskenwert invertieren"), ("Invert quick mask", "Schnellmaske invertieren"), ("Jitters", "Streuung"), ("Join the ArtCraft community on Discord", "Der ArtCraft-Community auf Discord beitreten"), @@ -493,7 +477,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Ebenenspeicher: {mb} MB"), ("Layers", "Ebenen"), ("Lazy mouse", "Lazy Mouse"), - ("Lazy mouse and symmetry", "Lazy Mouse und Symmetrie"), ("Lazy mouse distance", "Lazy-Mouse-Distanz"), ("Leather grain", "Ledernarbung"), ("Lens size: how quickly things blur away from the focus distance", "Linsengröße: wie schnell Objekte außerhalb der Fokusdistanz unscharf werden"), @@ -509,17 +492,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Lineares Licht"), ("List of exports", "Exportliste"), ("Load UI Layout", "UI-Layout laden"), - ("Load a cage (the low poly, inflated)", "Cage laden (das aufgeblähte Low-Poly)"), ("Loaded UI layout {path}", "UI-Layout {path} geladen"), ("Log", "Protokoll"), ("Low", "Niedrig"), - ("Low poly mesh suffix", "Suffix für Low-Poly-Mesh"), ("Luminosity", "Luminanz"), ("MMB drag / Alt + MMB", "MMT ziehen / Alt + MMT"), ("Made by the ArtCraft team and community.", "Entwickelt vom ArtCraft-Team und der Community."), ("Magenta / green", "Magenta / Grün"), ("Main shader", "Haupt-Shader"), ("Marble veins", "Marmoradern"), + ("Mask", "Maske"), ("Mask Editor: Edge wear", "Masken-Editor: Kantenabnutzung"), ("Mask value (gray)", "Maskenwert (Grau)"), ("Mask with height", "Mit Höhe maskieren"), @@ -527,17 +509,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Gehämmert"), ("MatFinish Raw", "MatFinish Roh"), ("MatFinish Sanded", "MatFinish Geschmirgelt"), - ("Match", "Zuordnung"), ("Material", "Material"), ("Material ball", "Materialkugel"), ("Material finish", "Materialoberfläche"), ("Materials", "Materialien"), - ("Max frontal distance", "Max. vordere Distanz"), - ("Max occluder distance", "Max. Verdeckerdistanz"), - ("Max rear distance", "Max. hintere Distanz"), ("Maximum", "Maximum"), ("Mesh fill", "Mesh-Füllung"), - ("Mesh map bakers", "Mesh-Map-Baker"), ("Mesh map: {map}", "Mesh-Map: {map}"), ("Mesh maps", "Mesh-Maps"), ("Mesh maps baked", "Mesh-Maps gebacken"), @@ -546,9 +523,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Mitteltöne"), ("Minimum", "Minimum"), ("Minimum size (%)", "Mindestgröße (%)"), - ("Mirror X", "Spiegeln X"), - ("Mirror Y", "Spiegeln Y"), - ("Mirror Z", "Spiegeln Z"), ("Missing (bake to create)", "Fehlt (zum Erstellen backen)"), ("Mixed AO", "Gemischte AO"), ("Mode", "Modus"), @@ -576,7 +550,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Rauschstärke"), ("Noise scale", "Rauschskalierung"), ("None", "Keine"), - ("None: the low poly is its own high poly.", "Keine: Das Low-Poly ist sein eigenes High-Poly."), ("Normal", "Normale"), ("Normal DirectX", "Normale DirectX"), ("Normal Invert", "Normale invertieren"), @@ -608,7 +581,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Verschiebt die Texturen anhand des Höhenkanals, mit der Stärke Höhe zu Normale", ), ("On", "Ein"), - ("One color per mesh part.", "Eine Farbe pro Mesh-Teil."), ("Opacity", "Deckkraft"), ("Open sample project...", "Beispielprojekt öffnen..."), ("Open...", "Öffnen..."), @@ -619,15 +591,16 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbit"), ("Orthographic", "Orthografisch"), + ("Perspective", "Perspektivisch"), ("Output directory", "Ausgabeverzeichnis"), ("Output high", "Ausgabe hoch"), ("Output low", "Ausgabe tief"), - ("Output size", "Ausgabegröße"), ("Output template", "Ausgabevorlage"), ("Output templates", "Ausgabevorlagen"), ("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"), @@ -637,7 +610,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Auf das Mesh malen, um diese Maske zu bearbeiten. Für Grau den Maskenwert im Tab Material verwenden.", ), - ("Paint the path with the brush (Enter)", "Pfad mit dem Pinsel malen (Eingabe)"), ("Paint with the current tool", "Mit dem aktuellen Werkzeug malen"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -660,8 +632,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Pfad"), ("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Pfad: Klicken fügt einen Punkt hinzu, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Pfad: Klicken fügt einen Punkt hinzu, Klicken auf die Kurve fügt einen ein, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", ), ("Pattern scale", "Musterskalierung"), ("Perlin noise", "Perlin-Rauschen"), @@ -678,7 +650,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Positionsstreuung"), ("Posterize", "Tontrennung"), ("Press a key...", "Taste drücken..."), - ("Procedurals", "Prozedurale"), ("Project", "Projekt"), ("Project Configuration...", "Projektkonfiguration..."), ("Project opened", "Projekt geöffnet"), @@ -689,8 +660,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Viertel"), ("Quick mask", "Schnellmaske"), ("Quit", "Beenden"), - ("Radial axis", "Radiale Achse"), - ("Radial copies", "Radiale Kopien"), ("Radius (texels at 2K)", "Radius (Texel bei 2K)"), ("RENDERING", "RENDERING"), ("Range", "Bereich"), @@ -702,7 +671,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Wiederholen"), ("Reimport mesh", "Mesh neu importieren"), - ("Relative to the bounding box diagonal.", "Relativ zur Diagonale des Begrenzungsrahmens."), ("Remove", "Entfernen"), ("Remove channel", "Kanal entfernen"), ("Remove effect", "Effekt entfernen"), @@ -710,9 +678,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Ebene entfernen"), ("Remove layer(s)", "Ebene(n) entfernen"), ("Remove mask", "Maske entfernen"), + ("Remove point", "Punkt entfernen"), ("Remove resource", "Ressource entfernen"), - ("Remove the cage", "Cage entfernen"), - ("Remove the path (Esc)", "Pfad entfernen (Esc)"), ("Remove the shortcut", "Tastenkürzel entfernen"), ("Remove this output", "Diese Ausgabe entfernen"), ("Remove unused resources...", "Unbenutzte Ressourcen entfernen..."), @@ -725,25 +692,17 @@ 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"), + ("Reset", "Zurücksetzen"), ("Reset UI", "UI zurücksetzen"), ("Reset all", "Alle zurücksetzen"), + ("Reset to defaults", "Auf Standardwerte zurücksetzen"), ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), - ("Return to painting mode", "Zurück zum Malmodus"), ("Return to this step", "Zu diesem Schritt zurückkehren"), - ("Auto-rebake", "Automatisch neu backen"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Diese Map automatisch neu backen, wenn sich ihre Bake-Einstellungen, das Low-Poly- oder die High-Poly-Meshes ändern", - ), ("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"), ("Rotation", "Drehung"), ("Rotation (degrees)", "Drehung (Grad)"), @@ -771,9 +730,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Kratzer"), ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), - ("Search all assets", "Alle Assets durchsuchen"), + ("Search", "Suchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), - ("Secondary rays", "Sekundärstrahlen"), ("Seed", "Startwert"), ("Select a layer", "Ebene auswählen"), ("Select an output template", "Ausgabevorlage auswählen"), @@ -838,16 +796,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Subsampling 8x8"), ("Subsurface scattering", "Subsurface Scattering"), ("Subtract", "Subtrahieren"), - ("Symmetry (X)", "Symmetrie (X)"), - ("Symmetry (Y)", "Symmetrie (Y)"), ("Tangent | Wrap", "Tangente | Umhüllen"), - ("Tangent-space normals of the high definition meshes.", "Tangentenraum-Normalen der hochauflösenden Meshes."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Temporale Kantenglättung (verfeinert die 3D-Ansicht im Stillstand)"), - ("Texture Set List", "Texturset-Liste"), + ("Texture Sets", "Textursets"), ("Texture Set Settings", "Texturset-Einstellungen"), ("Texture resolution", "Texturauflösung"), ("Texture set channels", "Texturset-Kanäle"), - ("Texture set list", "Texturset-Liste"), ("Texture sets", "Textursets"), ("TextureCraft had to close:", "TextureCraft musste beendet werden:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metallisch/Rauheit"), @@ -892,17 +846,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 low poly mesh as high poly mesh", "Low-Poly-Mesh als High-Poly-Mesh verwenden"), ("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}"), @@ -923,10 +873,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Mausrad / Alt + RMT ziehen"), ("White", "Weiß"), - ( - "White where the surface faces the direction, black where it faces away.", - "Weiß, wo die Oberfläche in die Richtung zeigt, schwarz, wo sie abgewandt ist.", - ), ("Width", "Breite"), ("Width (texels at 2K)", "Breite (Texel bei 2K)"), ("Window", "Fenster"), @@ -935,9 +881,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Works in texture space, like the blur: it does not cross UV seams.", "Arbeitet im Texturraum wie das Weichzeichnen: UV-Nähte werden nicht überschritten.", ), - ("World space direction", "Richtung (Weltkoordinaten)"), - ("World space normal", "Normale (Weltkoordinaten)"), - ("World-space normals of the high poly (or the low poly).", "Normalen des High-Poly (oder Low-Poly) in Weltkoordinaten."), + ("World Space Normal", "Normale (Weltkoordinaten)"), ("Yellow / blue", "Gelb / Blau"), ("Zoom", "Zoomen"), ("a missing layer", "eine fehlende Ebene"), @@ -974,7 +918,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel bzw. in das Ansichtsfenster ziehen)", ), - ("{name} ({n} triangles)", "{name} ({n} Dreiecke)"), ("{name} copy", "{name} Kopie"), ("{n} bits", "{n} Bit"), ( @@ -985,34 +928,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (Skalierung {scale}, Startwert {seed})"), ("Template name", "Vorlagenname"), ("Save current project as template", "Aktuelles Projekt als Vorlage speichern"), - ("Spread angle", "Streuwinkel"), ("Distribution", "Verteilung"), ("Cosine", "Kosinus"), ("Uniform", "Gleichmäßig"), - ("Ignore backface", "Rückseiten ignorieren"), - ("Self occlusion", "Eigenverdeckung"), - ("Only same mesh name", "Nur gleicher Mesh-Name"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Strahlen der gebogenen Normalen folgen den Verdecker-Einstellungen der Ambient Occlusion.", - ), - ("Sampling radius", "Abtastradius"), - ("0 picks a radius from the output size.", "0 wählt den Radius anhand der Ausgabegröße."), - ("Encoding", "Kodierung"), - ("Signed (-1..1)", "Vorzeichenbehaftet (-1..1)"), - ("Positive (0..1)", "Positiv (0..1)"), ("Normalization", "Normalisierung"), - ("Bounding box", "Begrenzungsrahmen"), - ("Bounding sphere", "Begrenzungskugel"), - ( - "Position normalized to the low poly's bounding box or sphere.", - "Position, normalisiert auf den Begrenzungsrahmen oder die Begrenzungskugel des Low-Poly.", - ), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Grundfarben (Texturen, Faktoren) und Vertexfarben der hochauflösenden Meshes.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Weiß, wo das High-Poly das Low-Poly bedeckt, mal dessen Alpha."), // Settings › Interface: brightness and accent color. ("Brightness", "Helligkeit"), ("Dark", "Dunkel"), @@ -1037,8 +956,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), ("Brushes", "Pinsel"), - ("My brushes", "Meine Pinsel"), - ("Use this brush (keeps its size)", "Diesen Pinsel verwenden (Größe bleibt)"), ("Brush name", "Pinselname"), ("Save current brush", "Aktuellen Pinsel speichern"), ("Start window", "Startfenster"), @@ -1059,12 +976,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Ungespeicherte Änderungen"), ("Don't save", "Nicht speichern"), ("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"), - ("Skew correction", "Skew-Korrektur"), - ("Paint skew in the 2D view", "Skew in der 2D-Ansicht malen"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "In der 2D-Ansicht ziehen, um zu malen, wo sich die Bake-Strahlen zur Basisnormalen drehen; mit dem Wert 0 wird gelöscht", - ), ("Radius", "Radius"), ("Remove skew correction", "Skew-Korrektur entfernen"), ("Twill weave", "Köperbindung"), @@ -1084,4 +995,200 @@ pub const TABLE: &[(&str, &str)] = &[ "In MaterialCraft geöffnet: Dort mit Datei > An TextureCraft senden die Änderungen zurückholen", ), ("Parameters change in the desktop app, with MaterialCraft installed", "Parameter lassen sich in der Desktop-App mit installiertem MaterialCraft ändern"), + ("Add High-Poly Meshes", "High-Poly-Meshes hinzufügen"), + ("All", "Alle"), + ("Apply Diffusion", "Diffusion anwenden"), + ("Attenuation", "Abschwächung"), + ("Auto Tonemapping", "Automatisches Tonemapping"), + ("Average Normals", "Normalen mitteln"), + ("BBox", "Begrenzungsrahmen"), + ("BSphere", "Begrenzungskugel"), + ("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"), + ("Cage Scene", "Käfigszene"), + ("Cage Type", "Käfigtyp"), + ("Color Generator", "Farbgenerator"), + ("Color Source", "Farbquelle"), + ("Common Parameters", "Gemeinsame Parameter"), + ("Custom File", "Benutzerdefinierte Datei"), + ("Details", "Details"), + ("Dilation Width", "Dilatationsbreite"), + ("Distance-Based", "Distanzbasiert"), + ("Edge Contrast", "Kantenkontrast"), + ("Edge Distance", "Kantenabstand"), + ("Edge Protection", "Kantenschutz"), + ("Enable Seams", "Nähte aktivieren"), + ("File ID", "Datei-ID"), + ("Full Scene", "Gesamte Szene"), + ("Generate from Mesh", "Aus Mesh erzeugen"), + ("Generate from Normal Map", "Aus Normal-Map erzeugen"), + ("Ground Plane", "Bodenebene"), + ("Ground Plane Offset", "Bodenversatz"), + ("High Poly Mesh Suffix", "Suffix für High-Poly-Mesh"), + ("High Poly Scene", "High-Poly-Szene"), + ("High-Poly Parameters", "High-Poly-Parameter"), + ("Hue Shift", "Farbtonverschiebung"), + ("Ignore Backface", "Rückseiten ignorieren"), + ("Ignore Backface Suffix", "Suffix für ignorierte Rückseiten"), + ("Include in Bake", "Beim Backen einschließen"), + ("Load Cage", "Käfig laden"), + ("Lock Output Size", "Ausgabegröße sperren"), + ("Low Poly Mesh Suffix", "Suffix für Low-Poly-Mesh"), + ("Manual", "Manuell"), + ("Material Color", "Materialfarbe"), + ("Max Frontal Distance", "Max. vordere Distanz"), + ("Max Occluder Distance", "Max. Verdeckerdistanz"), + ("Max Rear Distance", "Max. hintere Distanz"), + ("Mesh ID", "Mesh-ID"), + ("Method", "Methode"), + ("Min Occluder Distance", "Minimaler Verdeckungsabstand"), + ("Never", "Nie"), + ("No High-Poly Meshes", "Keine High-Poly-Meshes"), + ("Normalization Scale", "Normalisierungsskala"), + ("Normalization Type", "Normalisierungstyp"), + ("Only Same Mesh Name", "Nur gleicher Mesh-Name"), + ("Output Size", "Ausgabegröße"), + ("Match", "Zuordnung"), + ("Skew Correction Method", "Methode der Verzerrungskorrektur"), + ("Mesh Normals Based", "Basierend auf Mesh-Normalen"), + ("Face Normals Based", "Basierend auf Flächennormalen"), + ("Reset Painted Cage", "Gemalten Käfig Zurücksetzen"), + ("Paint Cage", "Käfig malen"), + ("Paint Skew Correction", "Verzerrungskorrektur malen"), + ("Per Material", "Pro Material"), + ("Random", "Zufällig"), + ("Relative to Bounding Box", "Relativ zum Begrenzungsrahmen"), + ("Relative to Low Mesh", "Relativ zum Low-Poly-Mesh"), + ("Relative to Min/Max", "Relativ zu Min/Max"), + ("Relative to Ray Distances", "Relativ zu Strahlabständen"), + ("Remove Cage", "Käfig entfernen"), + ("Remove Skew Correction", "Skew-Korrektur entfernen"), + ("Restore Defaults", "Standardwerte wiederherstellen"), + ("Return to Painting Mode", "Zurück zum Malmodus"), + ("Sampling Radius", "Abtastradius"), + ("Scaling Divisor", "Skalierungsdivisor"), + ("Seams Intensity", "Nahtintensität"), + ("Secondary Rays", "Sekundärstrahlen"), + ("Self Intersection", "Selbstüberschneidung"), + ("Self Occlusion", "Eigenverdeckung"), + ("Skew Correction", "Skew-Korrektur"), + ("Smooth", "Glatt"), + ("Spread Angle", "Streuwinkel"), + ("Submesh", "Teilmesh"), + ("Use Low Poly Mesh as High Poly Mesh", "Low-Poly-Mesh als High-Poly-Mesh verwenden"), + ("Value Bounds Max", "Maximaler Grenzwert"), + ("Value Bounds Min", "Minimaler Grenzwert"), + ("Vertex Color", "Scheitelpunktfarbe"), + ("Select the layer content", "Ebeneninhalt auswählen"), + ("Paint layer", "Malebene"), + ("Fill layer", "Füllebene"), + ("1 effect", "1 Effekt"), + ("{count} effects", "{count} Effekte"), + ("Mask effects", "Maskeneffekte"), + ("Content effects", "Inhaltseffekte"), + ("Fold or unfold these effects", "Diese Effekte ein- oder ausklappen"), + ("Remove resolution override", "Auflösungsüberschreibung entfernen"), + ("Texture set resolution", "Auflösung des Textursets"), + ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Angle span", "Winkelbereich"), + ("Axis position", "Achsenposition"), + ("Count", "Anzahl"), + ("Display", "Anzeige"), + ("Hide while painting", "Beim Malen ausblenden"), + ("Manipulator size", "Manipulatorgröße"), + ("Mirror symmetry", "Spiegelsymmetrie"), + ("Radial settings", "Radial-Einstellungen"), + ("Radial symmetry", "Radialsymmetrie"), + ("Show axis", "Achse anzeigen"), + ("Show axis position manipulator", "Manipulator für die Achsenposition anzeigen"), + ("Show cursor", "Cursor anzeigen"), + ("Show intersection", "Schnittlinie anzeigen"), + ("Show plane", "Ebene anzeigen"), + ("Symmetry", "Symmetrie"), + ("Symmetry color display", "Anzeigefarbe der Symmetrie"), + ("Symmetry settings", "Symmetrie-Einstellungen"), + ("Type", "Typ"), + ("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"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Das Speichern nutzt die übrigen Kerne und höchstens diesen Anteil des freien RAMs. Mindestens ein Kern arbeitet immer.", + ), + ("Max project size on open", "Max. Projektgröße beim Öffnen"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", + ), + ("Filter by type", "Nach Typ filtern"), + ("All libraries", "Alle Bibliotheken"), + ("Browse folders", "Ordner durchsuchen"), + ("Starter assets", "Mitgelieferte Assets"), + ("Your assets", "Eigene Assets"), + ("Reset query", "Abfrage zurücksetzen"), + ("Refresh", "Aktualisieren"), + ("Saved searches", "Gespeicherte Suchen"), + ("Save the current search", "Aktuelle Suche speichern"), + ("Delete", "Löschen"), + ("Filter by path", "Nach Pfad filtern"), + ("Hide non-applicable folders", "Nicht zutreffende Ordner ausblenden"), + ("Thumbnail size", "Vorschaugröße"), + ("Small", "Klein"), + ("Medium", "Mittel"), + ("Large", "Groß"), + ("List", "Liste"), + ("Procedurals", "Prozedurale"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 00964af6..ed759054 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1,6 +1,17 @@ //! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Horneando {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Horneando {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir el mapa más reciente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pintura está en pausa mientras se muestra un horneado. Cancela el horneado o espera a que termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Lo que muestra la vista 3D mientras se hornea: el último mapa terminado, un mapa terminado a elección o el material. Los mapas aún sin hornear muestran un valor neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), ("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"), ("2D view only", "Solo vista 2D"), @@ -22,15 +33,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)"), @@ -44,7 +46,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Añadir filtro"), ("Add folder", "Añadir carpeta"), ("Add generator", "Añadir generador"), - ("Add high definition meshes", "Añadir mallas de alta definición"), ("Add levels", "Añadir niveles"), ("Add mask", "Añadir máscara"), ("Add mask with color selection", "Añadir máscara con selección de color"), @@ -52,20 +53,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"), ( @@ -80,8 +69,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "También asignado a {item} ({menu})"), ("Alt + LMB drag", "Alt + arrastrar con botón izq."), ("Always", "Siempre"), + ("Ambient Occlusion", "Oclusión ambiental"), ("Ambient occlusion", "Oclusión ambiental"), - ("Ambient occlusion intensity", "Intensidad de la oclusión ambiental"), ("Amount", "Cantidad"), ("Anchor point", "Punto de anclaje"), ("Anchor: {name}", "Anclaje: {name}"), @@ -96,27 +85,25 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), ("Apply", "Aplicar"), - ("Apply to all texture sets", "Aplicar a todos los conjuntos de texturas"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"), ("Autosave every", "Autoguardar cada"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Las copias automáticas, los materiales inteligentes, los ajustes preestablecidos, las plantillas y los diseños de la interfaz se guardan en la carpeta de datos. Una carpeta nueva se aplica al reiniciar; los archivos ya guardados se quedan donde están.", ), - ("Average normals", "Promediar normales"), ("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"), ( "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Hornea los mapas de malla (F8) para los generadores basados en curvatura, AO y grosor.", ), - ("Bake selected textures ({n})", "Hornear texturas seleccionadas ({n})"), - ("Bake with \"Bake selected textures\"", "Hornear con \"Hornear texturas seleccionadas\""), ("Baked Lighting", "Iluminación horneada"), ("Baking", "Horneado"), ("Base color", "Color base"), @@ -127,10 +114,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Color base, Metálico, Rugosidad y Nivel especular."), ("Based on each texture set's size", "Según el tamaño de cada conjunto de texturas"), ("Basic settings", "Ajustes básicos"), - ("Bent normals", "Normales curvadas"), + ("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"), @@ -145,9 +131,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Integrada (solo lectura): duplícala para editarla"), ("Built-in templates are read-only: duplicate one to edit it", "Las plantillas integradas son de solo lectura: duplica una para editarla"), ("Built-in: {mesh}", "Integrada: {mesh}"), - ("By mesh name", "Por nombre de malla"), ("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"), @@ -156,6 +151,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"), @@ -177,7 +173,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Equilibrio de color"), ("Color burn", "Subexponer color"), ("Color dodge", "Sobreexponer color"), - ("Color map", "Mapa de color"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Color de la luz que viaja bajo la superficie (cada canal llega tan lejos como su valor)", @@ -194,7 +189,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Los colores se leen como gris. Añade encima un efecto de niveles o desenfoque para ajustar el resultado.", ), ("Combine with the layer's height", "Combinar con la altura de la capa"), - ("Common parameters", "Parámetros comunes"), ("Compare mask", "Máscara de comparación"), ("Compositing", "Composición"), ("Constant", "Constante"), @@ -207,7 +201,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar capa(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"), - ("Copy these bake settings to every texture set", "Copiar estos ajustes de horneado a todos los conjuntos de texturas"), ("Copy to all texture sets", "Copiar a todos los conjuntos de texturas"), ("Copy what the texture set shows", "Copiar lo que muestra el conjunto de texturas"), ("Couldn't encode the render", "No se pudo codificar el render"), @@ -258,8 +251,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatación + color de fondo predeterminado"), ("Dilation + transparent", "Dilatación + transparente"), ("Dilation infinite", "Dilatación infinita"), - ("Dilation width", "Ancho de dilatación"), - ("Direction {axis}", "Dirección {axis}"), ("DirectX normal map", "Mapa de normales DirectX"), ("Dirt", "Suciedad"), ("Disable", "Desactivado"), @@ -342,10 +333,14 @@ 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"), ("Fingerprints", "Huellas dactilares"), + ("Enter a finite number", "Introduce un número finito"), + ("Double-click or press Enter to edit", "Haz doble clic o pulsa Intro para editar"), + ("Fit the input range to the histogram", "Ajustar el rango de entrada al histograma"), ("Flatten layer", "Acoplar capa"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -363,11 +358,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Para todo el proyecto: cómo se leen las imágenes de mapas de normales usadas como mapas de malla (vuelve a asignarlas tras un cambio) y el valor predeterminado al exportar", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libre y de código abierto (MIT OR Apache-2.0), escrito en Rust."), - ("From normal map", "Desde el mapa de normales"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Desde el mapa de normales: curvatura del detalle del mapa de normales horneado en lugar de la malla.", - ), ("From template", "Desde la plantilla"), ("From template / project", "Desde la plantilla / el proyecto"), ("Full", "Completa"), @@ -407,12 +397,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Ayuda"), ("Hide UI", "Ocultar interfaz"), ("High", "Alto"), - ("High definition meshes", "Mallas de alta definición"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Altura de la malla high poly entre las distancias máximas trasera (negro) y frontal (blanco).", - ), - ("High poly mesh suffix", "Sufijo de malla high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Iluminaciones"), ("Histogram Range", "Rango de histograma"), @@ -446,7 +430,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Importa una imagen (Archivo > Importar recursos) para proyectarla sobre la malla.", ), - ("Import images to use them in fills and masks", "Importar imágenes para usarlas en rellenos y máscaras"), ("Import resources...", "Importar recursos..."), ("Import MaterialX material...", "Importar material MaterialX..."), ("MaterialX materials", "Materiales MaterialX"), @@ -468,6 +451,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Invertir"), ("Invert mask", "Invertir máscara"), ("Invert mask background", "Invertir fondo de la máscara"), + ("Invert mask value", "Invertir valor de máscara"), ("Invert quick mask", "Invertir máscara rápida"), ("Jitters", "Variaciones"), ("Join the ArtCraft community on Discord", "Únete a la comunidad de ArtCraft en Discord"), @@ -484,7 +468,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memoria de capas: {mb} MB"), ("Layers", "Capas"), ("Lazy mouse", "Ratón perezoso"), - ("Lazy mouse and symmetry", "Ratón perezoso y simetría"), ("Lazy mouse distance", "Distancia del ratón perezoso"), ("Leather grain", "Grano de cuero"), ("Lens size: how quickly things blur away from the focus distance", "Tamaño de la lente: lo rápido que se desenfoca todo fuera de la distancia de enfoque"), @@ -500,17 +483,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Luz lineal"), ("List of exports", "Lista de exportaciones"), ("Load UI Layout", "Cargar diseño de interfaz"), - ("Load a cage (the low poly, inflated)", "Cargar una jaula (la low poly, inflada)"), ("Loaded UI layout {path}", "Diseño de interfaz cargado: {path}"), ("Log", "Registro"), ("Low", "Bajo"), - ("Low poly mesh suffix", "Sufijo de malla low poly"), ("Luminosity", "Luminosidad"), ("MMB drag / Alt + MMB", "Arrastrar con botón central / Alt + botón central"), ("Made by the ArtCraft team and community.", "Creado por el equipo y la comunidad de ArtCraft."), ("Magenta / green", "Magenta / verde"), ("Main shader", "Sombreador principal"), ("Marble veins", "Vetas de mármol"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscaras: desgaste de bordes"), ("Mask value (gray)", "Valor de máscara (gris)"), ("Mask with height", "Enmascarar con la altura"), @@ -518,17 +500,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "Acabado martillado"), ("MatFinish Raw", "Acabado en bruto"), ("MatFinish Sanded", "Acabado lijado"), - ("Match", "Correspondencia"), ("Material", "Material"), ("Material ball", "Bola de material"), ("Material finish", "Acabado de material"), ("Materials", "Materiales"), - ("Max frontal distance", "Distancia frontal máx."), - ("Max occluder distance", "Distancia máx. de oclusor"), - ("Max rear distance", "Distancia trasera máx."), ("Maximum", "Máximo"), ("Mesh fill", "Relleno de malla"), - ("Mesh map bakers", "Horneadores de mapas de malla"), ("Mesh map: {map}", "Mapa de malla: {map}"), ("Mesh maps", "Mapas de malla"), ("Mesh maps baked", "Mapas de malla horneados"), @@ -537,9 +514,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Medios tonos"), ("Minimum", "Mínimo"), ("Minimum size (%)", "Tamaño mínimo (%)"), - ("Mirror X", "Reflejar X"), - ("Mirror Y", "Reflejar Y"), - ("Mirror Z", "Reflejar Z"), ("Missing (bake to create)", "Falta (hornear para crear)"), ("Mixed AO", "AO mixta"), ("Mode", "Modo"), @@ -567,7 +541,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Cantidad de ruido"), ("Noise scale", "Escala del ruido"), ("None", "Ninguno"), - ("None: the low poly is its own high poly.", "Ninguna: la low poly es su propia high poly."), ("Normal", "Normal"), ("Normal DirectX", "Normal DirectX"), ("Normal Invert", "Invertir normal"), @@ -599,7 +572,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Desplaza las texturas según el canal de altura, con la intensidad de altura a normal", ), ("On", "Activado"), - ("One color per mesh part.", "Un color por cada parte de la malla."), ("Opacity", "Opacidad"), ("Open sample project...", "Abrir proyecto de ejemplo..."), ("Open...", "Abrir..."), @@ -610,15 +582,16 @@ 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"), - ("Output size", "Tamaño de salida"), ("Output template", "Plantilla de salida"), ("Output templates", "Plantillas de salida"), ("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"), @@ -628,7 +601,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinta sobre la malla para editar esta máscara. Usa el valor de máscara de la pestaña Material para el gris.", ), - ("Paint the path with the brush (Enter)", "Pintar el trazado con el pincel (Intro)"), ("Paint with the current tool", "Pintar con la herramienta actual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -650,7 +622,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Pegar capa(s)"), ("Path", "Trazado"), ("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Trazado: clic añade un punto, arrastrar lo mueve, Intro aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Trazado: clic añade un punto, clic en la curva inserta uno, arrastrar lo mueve, Intro aplica, Esc cancela", + ), ("Pattern scale", "Escala del patrón"), ("Perlin noise", "Ruido Perlin"), ("Pick focus in the viewport", "Elegir el enfoque en la ventana gráfica"), @@ -666,7 +641,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variación de posición"), ("Posterize", "Posterizar"), ("Press a key...", "Pulsa una tecla..."), - ("Procedurals", "Procedurales"), ("Project", "Proyecto"), ("Project Configuration...", "Configuración del proyecto..."), ("Project opened", "Proyecto abierto"), @@ -677,8 +651,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Cuarto"), ("Quick mask", "Máscara rápida"), ("Quit", "Salir"), - ("Radial axis", "Eje radial"), - ("Radial copies", "Copias radiales"), ("Radius (texels at 2K)", "Radio (téxeles a 2K)"), ("RENDERING", "RENDERIZADO"), ("Range", "Rango"), @@ -690,7 +662,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Rehacer"), ("Reimport mesh", "Reimportar malla"), - ("Relative to the bounding box diagonal.", "Relativo a la diagonal del cuadro delimitador."), ("Remove", "Quitar"), ("Remove channel", "Quitar canal"), ("Remove effect", "Quitar efecto"), @@ -698,9 +669,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Eliminar capa"), ("Remove layer(s)", "Eliminar capa(s)"), ("Remove mask", "Quitar máscara"), + ("Remove point", "Quitar punto"), ("Remove resource", "Quitar recurso"), - ("Remove the cage", "Quitar la jaula"), - ("Remove the path (Esc)", "Quitar el trazado (Esc)"), ("Remove the shortcut", "Quitar el atajo"), ("Remove this output", "Quitar esta salida"), ("Remove unused resources...", "Quitar recursos no usados..."), @@ -713,25 +683,17 @@ 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"), + ("Reset", "Restablecer"), ("Reset UI", "Restablecer interfaz"), ("Reset all", "Restablecer todo"), + ("Reset to defaults", "Restablecer valores predeterminados"), ("Reset to {shortcut}", "Restablecer a {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), - ("Return to painting mode", "Volver al modo de pintura"), ("Return to this step", "Volver a este paso"), - ("Auto-rebake", "Rehornear automáticamente"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Vuelve a hornear este mapa automáticamente cuando cambian sus ajustes de horneado, la malla low poly o las high poly", - ), ("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"), ("Rotation", "Rotación"), ("Rotation (degrees)", "Rotación (grados)"), @@ -759,9 +721,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arañazos"), ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), - ("Search all assets", "Buscar en todos los recursos"), + ("Search", "Buscar"), ("Search commands or keys", "Buscar comandos o teclas"), - ("Secondary rays", "Rayos secundarios"), ("Seed", "Semilla"), ("Select a layer", "Selecciona una capa"), ("Select an output template", "Selecciona una plantilla de salida"), @@ -826,16 +787,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Submuestreo 8x8"), ("Subsurface scattering", "Dispersión subsuperficial"), ("Subtract", "Restar"), - ("Symmetry (X)", "Simetría (X)"), - ("Symmetry (Y)", "Simetría (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), - ("Tangent-space normals of the high definition meshes.", "Normales en espacio tangente de las mallas de alta definición."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antialiasing temporal (refina la vista 3D mientras está quieta)"), - ("Texture Set List", "Lista de conjuntos de texturas"), + ("Texture Sets", "Conjuntos de texturas"), ("Texture Set Settings", "Ajustes del conjunto de texturas"), ("Texture resolution", "Resolución de texturas"), ("Texture set channels", "Canales del conjunto de texturas"), - ("Texture set list", "Lista de conjuntos de texturas"), ("Texture sets", "Conjuntos de texturas"), ("TextureCraft had to close:", "TextureCraft tuvo que cerrarse:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metálico Rugosidad"), @@ -880,17 +837,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 low poly mesh as high poly mesh", "Usar la malla low poly como malla high poly"), ("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}"), @@ -911,18 +864,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Rueda / Alt + arrastrar con botón der."), ("White", "Blanco"), - ( - "White where the surface faces the direction, black where it faces away.", - "Blanco donde la superficie mira hacia la dirección, negro donde mira en sentido contrario.", - ), ("Width", "Ancho"), ("Width (texels at 2K)", "Anchura (téxeles a 2K)"), ("Window", "Ventana"), ("Wood grain", "Veta de madera"), ("Works in texture space, like the blur: it does not cross UV seams.", "Funciona en espacio de textura, como el desenfoque: no cruza las costuras UV."), - ("World space direction", "Dirección en espacio de mundo"), - ("World space normal", "Normal en espacio de mundo"), - ("World-space normals of the high poly (or the low poly).", "Normales en espacio de mundo de la high poly (o de la low poly)."), + ("World Space Normal", "Normal en espacio de mundo"), ("Yellow / blue", "Amarillo / azul"), ("Zoom", "Zoom"), ("a missing layer", "una capa inexistente"), @@ -959,7 +906,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: añadir sobre la capa seleccionada (o arrastrarlo a la pila de capas o a la ventana gráfica)", ), - ("{name} ({n} triangles)", "{name} ({n} triángulos)"), ("{name} copy", "Copia de {name}"), ("{n} bits", "{n} bits"), ( @@ -970,31 +916,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (escala {scale}, semilla {seed})"), ("Template name", "Nombre de la plantilla"), ("Save current project as template", "Guardar el proyecto actual como plantilla"), - ("Spread angle", "Ángulo de dispersión"), ("Distribution", "Distribución"), ("Cosine", "Coseno"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignorar caras traseras"), - ("Self occlusion", "Autooclusión"), - ("Only same mesh name", "Solo el mismo nombre de malla"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Los rayos de las normales curvadas siguen los ajustes de oclusores de la oclusión ambiental.", - ), - ("Sampling radius", "Radio de muestreo"), - ("0 picks a radius from the output size.", "0 elige un radio según el tamaño de salida."), - ("Encoding", "Codificación"), - ("Signed (-1..1)", "Con signo (-1..1)"), - ("Positive (0..1)", "Positivo (0..1)"), ("Normalization", "Normalización"), - ("Bounding box", "Cuadro delimitador"), - ("Bounding sphere", "Esfera delimitadora"), - ("Position normalized to the low poly's bounding box or sphere.", "Posición normalizada al cuadro o la esfera delimitadora de la low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Colores base (texturas, factores) y colores de vértice de las mallas de alta definición.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Blanco donde la high poly cubre la low poly, multiplicado por su alfa."), // Settings › Interface: brightness and accent color. ("Brightness", "Brillo"), ("Dark", "Oscuro"), @@ -1019,8 +944,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), ("Brushes", "Pinceles"), - ("My brushes", "Mis pinceles"), - ("Use this brush (keeps its size)", "Usar este pincel (conserva su tamaño)"), ("Brush name", "Nombre del pincel"), ("Save current brush", "Guardar el pincel actual"), ("Start window", "Ventana de inicio"), @@ -1041,12 +964,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Cambios sin guardar"), ("Don't save", "No guardar"), ("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"), - ("Skew correction", "Corrección de sesgo"), - ("Paint skew in the 2D view", "Pintar el sesgo en la vista 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Arrastra en la vista 2D para pintar dónde los rayos del bake se giran hacia la normal base; pinta con valor 0 para borrar", - ), ("Radius", "Radio"), ("Remove skew correction", "Quitar la corrección de sesgo"), ("Twill weave", "Tejido de sarga"), @@ -1066,4 +983,203 @@ pub const TABLE: &[(&str, &str)] = &[ "Abierto en MaterialCraft: usa allí Archivo > Enviar a TextureCraft para traer tus cambios", ), ("Parameters change in the desktop app, with MaterialCraft installed", "Los parámetros se cambian en la app de escritorio, con MaterialCraft instalado"), + ("Add High-Poly Meshes", "Añadir mallas de alta resolución"), + ("All", "Todos"), + ("Apply Diffusion", "Aplicar difusión"), + ("Attenuation", "Atenuación"), + ("Auto Tonemapping", "Mapeo tonal automático"), + ("Average Normals", "Promediar normales"), + ("BBox", "Caja delimitadora"), + ("BSphere", "Esfera delimitadora"), + ("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"), + ("Cage Scene", "Escena de jaula"), + ("Cage Type", "Tipo de jaula"), + ("Color Generator", "Generador de color"), + ("Color Source", "Origen del color"), + ("Common Parameters", "Parámetros comunes"), + ("Custom File", "Archivo personalizado"), + ("Details", "Detalles"), + ("Dilation Width", "Ancho de dilatación"), + ("Distance-Based", "Basada en distancia"), + ("Edge Contrast", "Contraste de bordes"), + ("Edge Distance", "Distancia de bordes"), + ("Edge Protection", "Protección de bordes"), + ("Enable Seams", "Activar costuras"), + ("File ID", "ID de archivo"), + ("Full Scene", "Escena completa"), + ("Generate from Mesh", "Generar desde la malla"), + ("Generate from Normal Map", "Generar desde el mapa de normales"), + ("Ground Plane", "Plano del suelo"), + ("Ground Plane Offset", "Desplazamiento del suelo"), + ("High Poly Mesh Suffix", "Sufijo de malla high poly"), + ("High Poly Scene", "Escena de alta resolución"), + ("High-Poly Parameters", "Parámetros de alta resolución"), + ("Hue Shift", "Cambio de tono"), + ("Ignore Backface", "Ignorar caras traseras"), + ("Ignore Backface Suffix", "Sufijo para ignorar caras traseras"), + ("Include in Bake", "Incluir en el horneado"), + ("Load Cage", "Cargar jaula"), + ("Lock Output Size", "Bloquear tamaño de salida"), + ("Low Poly Mesh Suffix", "Sufijo de malla low poly"), + ("Manual", "Manual"), + ("Material Color", "Color del material"), + ("Max Frontal Distance", "Distancia frontal máx."), + ("Max Occluder Distance", "Distancia máx. de oclusor"), + ("Max Rear Distance", "Distancia trasera máx."), + ("Mesh ID", "ID de malla"), + ("Method", "Método"), + ("Min Occluder Distance", "Distancia mínima del oclusor"), + ("Never", "Nunca"), + ("No High-Poly Meshes", "Sin mallas de alta resolución"), + ("Normalization Scale", "Escala de normalización"), + ("Normalization Type", "Tipo de normalización"), + ("Only Same Mesh Name", "Solo el mismo nombre de malla"), + ("Output Size", "Tamaño de salida"), + ("Match", "Coincidencia"), + ("Skew Correction Method", "Método de Corrección de Sesgo"), + ("Mesh Normals Based", "Basado en Normales de Malla"), + ("Face Normals Based", "Basado en Normales de Cara"), + ("Reset Painted Cage", "Restablecer Jaula Pintada"), + ("Paint Cage", "Pintar jaula"), + ("Paint Skew Correction", "Pintar corrección de inclinación"), + ("Per Material", "Por material"), + ("Random", "Aleatorio"), + ("Relative to Bounding Box", "Relativo a la caja delimitadora"), + ("Relative to Low Mesh", "Relativo a la malla de baja resolución"), + ("Relative to Min/Max", "Relativo al mínimo/máximo"), + ("Relative to Ray Distances", "Relativo a distancias de rayos"), + ("Remove Cage", "Eliminar jaula"), + ("Remove Skew Correction", "Quitar la corrección de sesgo"), + ("Restore Defaults", "Restaurar valores predeterminados"), + ("Return to Painting Mode", "Volver al modo de pintura"), + ("Sampling Radius", "Radio de muestreo"), + ("Scaling Divisor", "Divisor de escala"), + ("Seams Intensity", "Intensidad de costuras"), + ("Secondary Rays", "Rayos secundarios"), + ("Self Intersection", "Autointersección"), + ("Self Occlusion", "Autooclusión"), + ("Skew Correction", "Corrección de sesgo"), + ("Smooth", "Suave"), + ("Spread Angle", "Ángulo de dispersión"), + ("Submesh", "Submalla"), + ("Use Low Poly Mesh as High Poly Mesh", "Usar la malla low poly como malla high poly"), + ("Value Bounds Max", "Límite máximo"), + ("Value Bounds Min", "Límite mínimo"), + ("Vertex Color", "Color de vértice"), + ("Select the layer content", "Seleccionar el contenido de la capa"), + ("Paint layer", "Capa de pintura"), + ("Fill layer", "Capa de relleno"), + ("1 effect", "1 efecto"), + ("{count} effects", "{count} efectos"), + ("Mask effects", "Efectos de la máscara"), + ("Content effects", "Efectos del contenido"), + ("Fold or unfold these effects", "Plegar o desplegar estos efectos"), + ("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}"), + ("Angle span", "Amplitud del ángulo"), + ("Axis position", "Posición del eje"), + ("Count", "Cantidad"), + ("Display", "Visualización"), + ("Hide while painting", "Ocultar al pintar"), + ("Manipulator size", "Tamaño del manipulador"), + ("Mirror symmetry", "Simetría de espejo"), + ("Radial settings", "Ajustes radiales"), + ("Radial symmetry", "Simetría radial"), + ("Show axis", "Mostrar eje"), + ("Show axis position manipulator", "Mostrar manipulador de posición del eje"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar intersección"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetría"), + ("Symmetry color display", "Color de visualización de simetría"), + ("Symmetry settings", "Ajustes de simetría"), + ("Type", "Tipo"), + ("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"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Guardar usa los demás núcleos y como máximo esta parte de la RAM libre. Siempre trabaja al menos un núcleo.", + ), + ("Max project size on open", "Tamaño máximo al abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", + ), + ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas las bibliotecas"), + ("Browse folders", "Explorar carpetas"), + ("Starter assets", "Recursos incluidos"), + ("Your assets", "Tus recursos"), + ("Reset query", "Restablecer consulta"), + ("Refresh", "Actualizar"), + ("Saved searches", "Búsquedas guardadas"), + ("Save the current search", "Guardar la búsqueda actual"), + ("Delete", "Eliminar"), + ("Filter by path", "Filtrar por ruta"), + ("Hide non-applicable folders", "Ocultar carpetas no aplicables"), + ("Thumbnail size", "Tamaño de miniatura"), + ("Small", "Pequeño"), + ("Medium", "Mediano"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurales"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f9fa0d3b..ebcb248a 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1,6 +1,17 @@ //! French UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Cuisson de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Cuisson de {map} ({n}/{total}), jeu de textures {set} sur {sets}"), + ("Follow Newest Map", "Suivre la dernière carte"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La peinture est suspendue tant qu'une cuisson est affichée. Annulez la cuisson ou attendez qu'elle se termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Ce que la vue 3D affiche pendant la cuisson : la dernière carte terminée, une carte terminée au choix ou le matériau. Les cartes pas encore cuites affichent une valeur neutre.", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", @@ -25,15 +36,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.", @@ -50,7 +52,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Ajouter un filtre"), ("Add folder", "Ajouter un dossier"), ("Add generator", "Ajouter un générateur"), - ("Add high definition meshes", "Ajouter des maillages haute définition"), ("Add levels", "Ajouter des niveaux"), ("Add mask", "Ajouter un masque"), ("Add mask with color selection", "Ajouter un masque par sélection de couleur"), @@ -58,20 +59,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"), ( @@ -86,8 +75,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Également attribué à {item} ({menu})"), ("Alt + LMB drag", "Alt + glisser (clic gauche)"), ("Always", "Toujours"), + ("Ambient Occlusion", "Occlusion ambiante"), ("Ambient occlusion", "Occlusion ambiante"), - ("Ambient occlusion intensity", "Intensité de l'occlusion ambiante"), ("Amount", "Quantité"), ("Anchor point", "Point d'ancrage"), ("Anchor: {name}", "Ancrage : {name}"), @@ -102,27 +91,25 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Anticrénelage"), ("Aperture", "Ouverture"), ("Apply", "Appliquer"), - ("Apply to all texture sets", "Appliquer à tous les ensembles de textures"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"), ("Autosave every", "Sauvegarde automatique toutes les"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Les sauvegardes automatiques, matériaux intelligents, préréglages, modèles et dispositions de l'interface vont dans le dossier de données. Un nouveau dossier s'applique au redémarrage ; les fichiers déjà enregistrés restent où ils sont.", ), - ("Average normals", "Moyenne des normales"), ("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"), ( "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Précalculez les cartes de maillage (F8) pour les générateurs basés sur la courbure, l'AO et l'épaisseur.", ), - ("Bake selected textures ({n})", "Précalculer les textures sélectionnées ({n})"), - ("Bake with \"Bake selected textures\"", "Précalculer avec « Précalculer les textures sélectionnées »"), ("Baked Lighting", "Éclairage précalculé"), ("Baking", "Précalcul"), ("Base color", "Couleur de base"), @@ -133,10 +120,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Couleur de base, Métallique, Rugosité et Niveau spéculaire."), ("Based on each texture set's size", "Selon la taille de chaque ensemble de textures"), ("Basic settings", "Paramètres de base"), - ("Bent normals", "Normales déviées"), + ("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"), @@ -151,9 +137,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Intégré (lecture seule) : dupliquez-le pour le modifier"), ("Built-in templates are read-only: duplicate one to edit it", "Les modèles intégrés sont en lecture seule : dupliquez-en un pour le modifier"), ("Built-in: {mesh}", "Intégré : {mesh}"), - ("By mesh name", "Par nom de maillage"), ("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"), @@ -162,6 +157,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"), @@ -183,7 +179,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Balance des couleurs"), ("Color burn", "Densité couleur +"), ("Color dodge", "Densité couleur -"), - ("Color map", "Carte de couleur"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Couleur de la lumière qui se propage sous la surface (chaque canal va aussi loin que sa valeur)", @@ -200,7 +195,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Les couleurs sont lues en niveaux de gris. Ajoutez un effet de niveaux ou de flou au-dessus pour ajuster le résultat.", ), ("Combine with the layer's height", "Combiner avec la hauteur du calque"), - ("Common parameters", "Paramètres communs"), ("Compare mask", "Masque de comparaison"), ("Compositing", "Composition"), ("Constant", "Constante"), @@ -213,7 +207,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copier depuis"), ("Copy layer(s)", "Copier le(s) calque(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"), - ("Copy these bake settings to every texture set", "Copier ces paramètres de précalcul dans chaque ensemble de textures"), ("Copy to all texture sets", "Copier dans tous les ensembles de textures"), ("Copy what the texture set shows", "Copier ce qu'affiche l'ensemble de textures"), ("Couldn't encode the render", "Impossible d'encoder le rendu"), @@ -264,8 +257,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatation + couleur de fond par défaut"), ("Dilation + transparent", "Dilatation + transparent"), ("Dilation infinite", "Dilatation infinie"), - ("Dilation width", "Largeur de dilatation"), - ("Direction {axis}", "Direction {axis}"), ("DirectX normal map", "Carte de normales DirectX"), ("Dirt", "Saleté"), ("Disable", "Désactivé"), @@ -354,10 +345,14 @@ 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"), ("Fingerprints", "Empreintes digitales"), + ("Enter a finite number", "Saisissez un nombre fini"), + ("Double-click or press Enter to edit", "Double-cliquez ou appuyez sur Entrée pour modifier"), + ("Fit the input range to the histogram", "Ajuster la plage d'entrée à l'histogramme"), ("Flatten layer", "Aplatir le calque"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -375,11 +370,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Pour tout le projet : comment les images de carte de normales utilisées comme cartes de maillage sont lues (réaffectez-les après un changement), et la valeur par défaut à l'export", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libre et open source (MIT OR Apache-2.0), écrit en Rust."), - ("From normal map", "Depuis la carte de normales"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Depuis la carte de normales : courbure des détails de la carte de normales précalculée au lieu du maillage.", - ), ("From template", "Selon le modèle"), ("From template / project", "Selon le modèle / projet"), ("Full", "Pleine"), @@ -419,12 +409,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Aide"), ("Hide UI", "Masquer l'interface"), ("High", "Haut"), - ("High definition meshes", "Maillages haute définition"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Hauteur du high poly entre les distances arrière max (noir) et frontale max (blanc).", - ), - ("High poly mesh suffix", "Suffixe du maillage high poly"), ("High poly: {name}", "High poly : {name}"), ("Highlights", "Tons clairs"), ("Histogram Range", "Plage d'histogramme"), @@ -458,7 +442,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Importez une image (Fichier > Importer des ressources) pour la projeter sur le maillage.", ), - ("Import images to use them in fills and masks", "Importez des images pour les utiliser dans les remplissages et les masques"), ("Import resources...", "Importer des ressources..."), ("Import MaterialX material...", "Importer un matériau MaterialX..."), ("MaterialX materials", "Matériaux MaterialX"), @@ -480,6 +463,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverser"), ("Invert mask", "Inverser le masque"), ("Invert mask background", "Inverser le fond du masque"), + ("Invert mask value", "Inverser la valeur du masque"), ("Invert quick mask", "Inverser le masque rapide"), ("Jitters", "Variations"), ("Join the ArtCraft community on Discord", "Rejoindre la communauté ArtCraft sur Discord"), @@ -496,7 +480,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Mémoire des calques : {mb} Mo"), ("Layers", "Calques"), ("Lazy mouse", "Stabilisateur"), - ("Lazy mouse and symmetry", "Stabilisateur et symétrie"), ("Lazy mouse distance", "Distance du stabilisateur"), ("Leather grain", "Grain de cuir"), ( @@ -515,17 +498,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Lumière linéaire"), ("List of exports", "Liste des exports"), ("Load UI Layout", "Charger une disposition"), - ("Load a cage (the low poly, inflated)", "Charger une cage (le low poly, gonflé)"), ("Loaded UI layout {path}", "Disposition de l'interface chargée : {path}"), ("Log", "Journal"), ("Low", "Bas"), - ("Low poly mesh suffix", "Suffixe du maillage low poly"), ("Luminosity", "Luminosité"), ("MMB drag / Alt + MMB", "Glisser (clic milieu) / Alt + clic milieu"), ("Made by the ArtCraft team and community.", "Créé par l'équipe et la communauté ArtCraft."), ("Magenta / green", "Magenta / vert"), ("Main shader", "Shader principal"), ("Marble veins", "Veines de marbre"), + ("Mask", "Masque"), ("Mask Editor: Edge wear", "Éditeur de masque : usure des arêtes"), ("Mask value (gray)", "Valeur du masque (gris)"), ("Mask with height", "Masquer avec la hauteur"), @@ -533,17 +515,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Martelé"), ("MatFinish Raw", "MatFinish Brut"), ("MatFinish Sanded", "MatFinish Poncé"), - ("Match", "Correspondance"), ("Material", "Matériau"), ("Material ball", "Boule de matériau"), ("Material finish", "Finition du matériau"), ("Materials", "Matériaux"), - ("Max frontal distance", "Distance frontale max"), - ("Max occluder distance", "Distance max des occulteurs"), - ("Max rear distance", "Distance arrière max"), ("Maximum", "Maximum"), ("Mesh fill", "Remplissage par maillage"), - ("Mesh map bakers", "Précalcul des cartes de maillage"), ("Mesh map: {map}", "Carte de maillage : {map}"), ("Mesh maps", "Cartes de maillage"), ("Mesh maps baked", "Cartes de maillage précalculées"), @@ -552,9 +529,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Tons moyens"), ("Minimum", "Minimum"), ("Minimum size (%)", "Taille minimale (%)"), - ("Mirror X", "Miroir X"), - ("Mirror Y", "Miroir Y"), - ("Mirror Z", "Miroir Z"), ("Missing (bake to create)", "Manquante (précalculer pour la créer)"), ("Mixed AO", "AO mixte"), ("Mode", "Mode"), @@ -582,7 +556,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Quantité de bruit"), ("Noise scale", "Échelle du bruit"), ("None", "Aucun"), - ("None: the low poly is its own high poly.", "Aucun : le low poly est son propre high poly."), ("Normal", "Normal"), ("Normal DirectX", "Normale DirectX"), ("Normal Invert", "Inversion de normale"), @@ -614,7 +587,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Décale les textures selon le canal de hauteur, avec l'intensité hauteur vers normale", ), ("On", "Activé"), - ("One color per mesh part.", "Une couleur par partie du maillage."), ("Opacity", "Opacité"), ("Open sample project...", "Ouvrir un projet d'exemple..."), ("Open...", "Ouvrir..."), @@ -625,15 +597,16 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbite"), ("Orthographic", "Orthographique"), + ("Perspective", "Perspective"), ("Output directory", "Dossier de sortie"), ("Output high", "Sortie haute"), ("Output low", "Sortie basse"), - ("Output size", "Taille de sortie"), ("Output template", "Modèle de sortie"), ("Output templates", "Modèles de sortie"), ("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"), @@ -643,7 +616,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Peignez sur le maillage pour modifier ce masque. Utilisez la valeur de masque de l'onglet Matériau pour le gris.", ), - ("Paint the path with the brush (Enter)", "Peindre le tracé avec le pinceau (Enter)"), ("Paint with the current tool", "Peindre avec l'outil actuel"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -665,7 +637,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Coller le(s) calque(s)"), ("Path", "Tracé"), ("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Tracé : cliquer ajoute un point, glisser le déplace, Enter applique, Esc annule"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracé : cliquer ajoute un point, cliquer sur la courbe en insère un, glisser le déplace, Enter applique, Esc annule", + ), ("Pattern scale", "Échelle du motif"), ("Perlin noise", "Bruit de Perlin"), ("Pick focus in the viewport", "Choisir la mise au point dans la fenêtre d'affichage"), @@ -681,7 +656,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variation de position"), ("Posterize", "Postérisation"), ("Press a key...", "Appuyez sur une touche..."), - ("Procedurals", "Procéduraux"), ("Project", "Projet"), ("Project Configuration...", "Configuration du projet..."), ("Project opened", "Projet ouvert"), @@ -692,8 +666,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Quart"), ("Quick mask", "Masque rapide"), ("Quit", "Quitter"), - ("Radial axis", "Axe radial"), - ("Radial copies", "Copies radiales"), ("Radius (texels at 2K)", "Rayon (texels en 2K)"), ("RENDERING", "RENDU"), ("Range", "Plage"), @@ -705,7 +677,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Rétablir"), ("Reimport mesh", "Réimporter le maillage"), - ("Relative to the bounding box diagonal.", "Relatif à la diagonale de la boîte englobante."), ("Remove", "Supprimer"), ("Remove channel", "Supprimer le canal"), ("Remove effect", "Supprimer l'effet"), @@ -713,9 +684,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Supprimer le calque"), ("Remove layer(s)", "Supprimer le(s) calque(s)"), ("Remove mask", "Supprimer le masque"), + ("Remove point", "Retirer le point"), ("Remove resource", "Supprimer la ressource"), - ("Remove the cage", "Supprimer la cage"), - ("Remove the path (Esc)", "Supprimer le tracé (Esc)"), ("Remove the shortcut", "Supprimer le raccourci"), ("Remove this output", "Supprimer cette sortie"), ("Remove unused resources...", "Supprimer les ressources inutilisées..."), @@ -728,25 +698,17 @@ 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"), + ("Reset", "Réinitialiser"), ("Reset UI", "Réinitialiser l'interface"), ("Reset all", "Tout réinitialiser"), + ("Reset to defaults", "Rétablir les valeurs par défaut"), ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), - ("Return to painting mode", "Revenir au mode peinture"), ("Return to this step", "Revenir à cette étape"), - ("Auto-rebake", "Précalcul automatique"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Précalcule à nouveau cette carte automatiquement quand ses réglages de précalcul, le maillage low poly ou les maillages high poly changent", - ), ("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"), ("Rotation", "Rotation"), ("Rotation (degrees)", "Rotation (degrés)"), @@ -777,9 +739,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Rayures"), ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), - ("Search all assets", "Rechercher dans toutes les ressources"), + ("Search", "Rechercher"), ("Search commands or keys", "Rechercher des commandes ou des touches"), - ("Secondary rays", "Rayons secondaires"), ("Seed", "Graine"), ("Select a layer", "Sélectionnez un calque"), ("Select an output template", "Sélectionnez un modèle de sortie"), @@ -844,16 +805,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Sous-échantillonnage 8x8"), ("Subsurface scattering", "Diffusion sous-surfacique"), ("Subtract", "Soustraction"), - ("Symmetry (X)", "Symétrie (X)"), - ("Symmetry (Y)", "Symétrie (Y)"), ("Tangent | Wrap", "Tangente | Enveloppe"), - ("Tangent-space normals of the high definition meshes.", "Normales en espace tangent des maillages haute définition."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anticrénelage temporel (affine la vue 3D tant qu'elle est immobile)"), - ("Texture Set List", "Liste des ensembles de textures"), + ("Texture Sets", "Ensembles de textures"), ("Texture Set Settings", "Paramètres de l'ensemble de textures"), ("Texture resolution", "Résolution des textures"), ("Texture set channels", "Canaux de l'ensemble de textures"), - ("Texture set list", "Liste des ensembles de textures"), ("Texture sets", "Ensembles de textures"), ("TextureCraft had to close:", "TextureCraft a dû se fermer :"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Métallique Rugosité"), @@ -898,17 +855,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 low poly mesh as high poly mesh", "Utiliser le maillage low poly comme maillage high poly"), ( "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", @@ -932,18 +885,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Molette / Alt + glisser (clic droit)"), ("White", "Blanc"), - ( - "White where the surface faces the direction, black where it faces away.", - "Blanc là où la surface fait face à la direction, noir là où elle s'en détourne.", - ), ("Width", "Largeur"), ("Width (texels at 2K)", "Largeur (texels en 2K)"), ("Window", "Fenêtre"), ("Wood grain", "Veinage du bois"), ("Works in texture space, like the blur: it does not cross UV seams.", "Fonctionne en espace texture, comme le flou : ne traverse pas les coutures UV."), - ("World space direction", "Direction en espace monde"), - ("World space normal", "Normale en espace monde"), - ("World-space normals of the high poly (or the low poly).", "Normales en espace monde du high poly (ou du low poly)."), + ("World Space Normal", "Normale en espace monde"), ("Yellow / blue", "Jaune / bleu"), ("Zoom", "Zoom"), ("a missing layer", "un calque manquant"), @@ -980,7 +927,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file} : ajouter au-dessus du calque sélectionné (ou le glisser dans la pile de calques ou sur la fenêtre d'affichage)", ), - ("{name} ({n} triangles)", "{name} ({n} triangles)"), ("{name} copy", "Copie de {name}"), ("{n} bits", "{n} bits"), ( @@ -991,31 +937,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (échelle {scale}, graine {seed})"), ("Template name", "Nom du modèle"), ("Save current project as template", "Enregistrer le projet actuel comme modèle"), - ("Spread angle", "Angle de dispersion"), ("Distribution", "Distribution"), ("Cosine", "Cosinus"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignorer les faces arrière"), - ("Self occlusion", "Auto-occlusion"), - ("Only same mesh name", "Seulement le même nom de maillage"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Les rayons des normales déviées suivent les réglages d'occulteurs de l'occlusion ambiante.", - ), - ("Sampling radius", "Rayon d'échantillonnage"), - ("0 picks a radius from the output size.", "0 choisit un rayon selon la taille de sortie."), - ("Encoding", "Encodage"), - ("Signed (-1..1)", "Signé (-1..1)"), - ("Positive (0..1)", "Positif (0..1)"), ("Normalization", "Normalisation"), - ("Bounding box", "Boîte englobante"), - ("Bounding sphere", "Sphère englobante"), - ("Position normalized to the low poly's bounding box or sphere.", "Position normalisée sur la boîte ou la sphère englobante du low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Couleurs de base (textures, facteurs) et couleurs de sommets des maillages haute définition.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Blanc là où le high poly couvre le low poly, multiplié par son alpha."), // Settings › Interface: brightness and accent color. ("Brightness", "Luminosité"), ("Dark", "Sombre"), @@ -1040,8 +965,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), ("Brushes", "Pinceaux"), - ("My brushes", "Mes pinceaux"), - ("Use this brush (keeps its size)", "Utiliser ce pinceau (garde sa taille)"), ("Brush name", "Nom du pinceau"), ("Save current brush", "Enregistrer le pinceau actuel"), ("Start window", "Fenêtre de démarrage"), @@ -1062,12 +985,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Modifications non enregistrées"), ("Don't save", "Ne pas enregistrer"), ("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"), - ("Skew correction", "Correction d'inclinaison"), - ("Paint skew in the 2D view", "Peindre l'inclinaison dans la vue 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Faites glisser dans la vue 2D pour peindre où les rayons du bake se tournent vers la normale de base ; peignez avec la valeur 0 pour effacer", - ), ("Radius", "Rayon"), ("Remove skew correction", "Supprimer la correction d'inclinaison"), ("Twill weave", "Armure sergé"), @@ -1090,4 +1007,203 @@ pub const TABLE: &[(&str, &str)] = &[ "Parameters change in the desktop app, with MaterialCraft installed", "Les paramètres se modifient dans l'application de bureau, avec MaterialCraft installé", ), + ("Add High-Poly Meshes", "Ajouter des maillages haute définition"), + ("All", "Tous"), + ("Apply Diffusion", "Appliquer la diffusion"), + ("Attenuation", "Atténuation"), + ("Auto Tonemapping", "Mappage tonal automatique"), + ("Average Normals", "Moyenne des normales"), + ("BBox", "Boîte englobante"), + ("BSphere", "Sphère englobante"), + ("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"), + ("Cage Scene", "Scène de cage"), + ("Cage Type", "Type de cage"), + ("Color Generator", "Générateur de couleurs"), + ("Color Source", "Source de couleur"), + ("Common Parameters", "Paramètres communs"), + ("Custom File", "Fichier personnalisé"), + ("Details", "Détails"), + ("Dilation Width", "Largeur de dilatation"), + ("Distance-Based", "Selon la distance"), + ("Edge Contrast", "Contraste des arêtes"), + ("Edge Distance", "Distance des arêtes"), + ("Edge Protection", "Protection des arêtes"), + ("Enable Seams", "Activer les coutures"), + ("File ID", "ID du fichier"), + ("Full Scene", "Scène entière"), + ("Generate from Mesh", "Générer depuis le maillage"), + ("Generate from Normal Map", "Générer depuis la carte de normales"), + ("Ground Plane", "Plan du sol"), + ("Ground Plane Offset", "Décalage du sol"), + ("High Poly Mesh Suffix", "Suffixe du maillage high poly"), + ("High Poly Scene", "Scène haute définition"), + ("High-Poly Parameters", "Paramètres haute définition"), + ("Hue Shift", "Décalage de teinte"), + ("Ignore Backface", "Ignorer les faces arrière"), + ("Ignore Backface Suffix", "Suffixe des faces arrière ignorées"), + ("Include in Bake", "Inclure dans le précalcul"), + ("Load Cage", "Charger une cage"), + ("Lock Output Size", "Verrouiller les dimensions de sortie"), + ("Low Poly Mesh Suffix", "Suffixe du maillage low poly"), + ("Manual", "Manuel"), + ("Material Color", "Couleur du matériau"), + ("Max Frontal Distance", "Distance frontale max"), + ("Max Occluder Distance", "Distance max des occulteurs"), + ("Max Rear Distance", "Distance arrière max"), + ("Mesh ID", "ID du maillage"), + ("Method", "Méthode"), + ("Min Occluder Distance", "Distance minimale des occluseurs"), + ("Never", "Jamais"), + ("No High-Poly Meshes", "Aucun maillage haute définition"), + ("Normalization Scale", "Échelle de normalisation"), + ("Normalization Type", "Type de normalisation"), + ("Only Same Mesh Name", "Seulement le même nom de maillage"), + ("Output Size", "Taille de sortie"), + ("Match", "Correspondance"), + ("Skew Correction Method", "Méthode de Correction de Déformation"), + ("Mesh Normals Based", "Basée sur les Normales du Maillage"), + ("Face Normals Based", "Basée sur les Normales des Faces"), + ("Reset Painted Cage", "Réinitialiser la Cage Peinte"), + ("Paint Cage", "Peindre la cage"), + ("Paint Skew Correction", "Peindre la correction d'inclinaison"), + ("Per Material", "Par matériau"), + ("Random", "Aléatoire"), + ("Relative to Bounding Box", "Relatif à la boîte englobante"), + ("Relative to Low Mesh", "Relatif au maillage basse définition"), + ("Relative to Min/Max", "Relatif au minimum/maximum"), + ("Relative to Ray Distances", "Relatif aux distances des rayons"), + ("Remove Cage", "Supprimer la cage"), + ("Remove Skew Correction", "Supprimer la correction d'inclinaison"), + ("Restore Defaults", "Rétablir les valeurs par défaut"), + ("Return to Painting Mode", "Revenir au mode peinture"), + ("Sampling Radius", "Rayon d'échantillonnage"), + ("Scaling Divisor", "Diviseur d'échelle"), + ("Seams Intensity", "Intensité des coutures"), + ("Secondary Rays", "Rayons secondaires"), + ("Self Intersection", "Auto-intersection"), + ("Self Occlusion", "Auto-occlusion"), + ("Skew Correction", "Correction d'inclinaison"), + ("Smooth", "Lisse"), + ("Spread Angle", "Angle de dispersion"), + ("Submesh", "Sous-maillage"), + ("Use Low Poly Mesh as High Poly Mesh", "Utiliser le maillage low poly comme maillage high poly"), + ("Value Bounds Max", "Borne maximale"), + ("Value Bounds Min", "Borne minimale"), + ("Vertex Color", "Couleur des sommets"), + ("Select the layer content", "Sélectionner le contenu du calque"), + ("Paint layer", "Calque de peinture"), + ("Fill layer", "Calque de remplissage"), + ("1 effect", "1 effet"), + ("{count} effects", "{count} effets"), + ("Mask effects", "Effets du masque"), + ("Content effects", "Effets du contenu"), + ("Fold or unfold these effects", "Replier ou déplier ces effets"), + ("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}"), + ("Angle span", "Amplitude d'angle"), + ("Axis position", "Position de l'axe"), + ("Count", "Nombre"), + ("Display", "Affichage"), + ("Hide while painting", "Masquer pendant la peinture"), + ("Manipulator size", "Taille du manipulateur"), + ("Mirror symmetry", "Symétrie miroir"), + ("Radial settings", "Paramètres radiaux"), + ("Radial symmetry", "Symétrie radiale"), + ("Show axis", "Afficher l'axe"), + ("Show axis position manipulator", "Afficher le manipulateur de position de l'axe"), + ("Show cursor", "Afficher le curseur"), + ("Show intersection", "Afficher l'intersection"), + ("Show plane", "Afficher le plan"), + ("Symmetry", "Symétrie"), + ("Symmetry color display", "Couleur d'affichage de la symétrie"), + ("Symmetry settings", "Paramètres de symétrie"), + ("Type", "Type"), + ("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"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "L'enregistrement utilise les autres cœurs et au plus cette part de la RAM libre. Au moins un cœur travaille toujours.", + ), + ("Max project size on open", "Taille max. à l’ouverture"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", + ), + ("Filter by type", "Filtrer par type"), + ("All libraries", "Toutes les bibliothèques"), + ("Browse folders", "Parcourir les dossiers"), + ("Starter assets", "Ressources fournies"), + ("Your assets", "Vos ressources"), + ("Reset query", "Réinitialiser la requête"), + ("Refresh", "Actualiser"), + ("Saved searches", "Recherches enregistrées"), + ("Save the current search", "Enregistrer la recherche actuelle"), + ("Delete", "Supprimer"), + ("Filter by path", "Filtrer par chemin"), + ("Hide non-applicable folders", "Masquer les dossiers non applicables"), + ("Thumbnail size", "Taille des miniatures"), + ("Small", "Petit"), + ("Medium", "Moyen"), + ("Large", "Grand"), + ("List", "Liste"), + ("Procedurals", "Procéduraux"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 765f5e8c..55fe9abd 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1,6 +1,17 @@ //! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Bake di {map} in corso ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Bake di {map} in corso ({n}/{total}), set di texture {set} di {sets}"), + ("Follow Newest Map", "Segui la mappa più recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pittura è in pausa finché viene mostrato un bake. Annulla il bake o attendi che finisca.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Cosa mostra la vista 3D durante il bake: l'ultima mappa completata, una mappa completata a scelta o il materiale. Le mappe non ancora create mostrano un valore neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), ("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"), ("2D view only", "Solo vista 2D"), @@ -22,15 +33,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.", @@ -47,7 +49,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Aggiungi filtro"), ("Add folder", "Aggiungi cartella"), ("Add generator", "Aggiungi generatore"), - ("Add high definition meshes", "Aggiungi mesh ad alta definizione"), ("Add levels", "Aggiungi Livelli"), ("Add mask", "Aggiungi maschera"), ("Add mask with color selection", "Aggiungi maschera con selezione colore"), @@ -55,20 +56,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"), ( @@ -83,8 +72,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Assegnata anche a {item} ({menu})"), ("Alt + LMB drag", "Alt + trascina (tasto sinistro)"), ("Always", "Sempre"), + ("Ambient Occlusion", "Occlusione ambientale"), ("Ambient occlusion", "Occlusione ambientale"), - ("Ambient occlusion intensity", "Intensità occlusione ambientale"), ("Amount", "Quantità"), ("Anchor point", "Punto di ancoraggio"), ("Anchor: {name}", "Ancoraggio: {name}"), @@ -99,27 +88,25 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), ("Apply", "Applica"), - ("Apply to all texture sets", "Applica a tutti i set di texture"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"), ("Autosave every", "Salvataggio automatico ogni"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Salvataggi automatici, materiali smart, preset, modelli e layout dell'interfaccia vanno nella cartella dei dati. Una nuova cartella si applica al riavvio; i file già salvati restano dove sono.", ), - ("Average normals", "Normali medie"), ("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"), ( "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Esegui il bake delle mappe mesh (F8) per i generatori basati su curvatura, AO e spessore.", ), - ("Bake selected textures ({n})", "Bake texture selezionate ({n})"), - ("Bake with \"Bake selected textures\"", "Esegui il bake con \"Bake texture selezionate\""), ("Baked Lighting", "Illuminazione precalcolata"), ("Baking", "Baking"), ("Base color", "Colore base"), @@ -130,10 +117,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Colore base, Metallico, Rugosità e Livello speculare."), ("Based on each texture set's size", "In base alla dimensione di ciascun set di texture"), ("Basic settings", "Impostazioni di base"), - ("Bent normals", "Bent normal"), + ("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"), @@ -148,9 +134,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Integrato (sola lettura): duplicalo per modificarlo"), ("Built-in templates are read-only: duplicate one to edit it", "I modelli integrati sono di sola lettura: duplicane uno per modificarlo"), ("Built-in: {mesh}", "Integrata: {mesh}"), - ("By mesh name", "Per nome della 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"), @@ -159,6 +154,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"), @@ -183,7 +179,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Bilanciamento colore"), ("Color burn", "Brucia colore"), ("Color dodge", "Scherma colore"), - ("Color map", "Mappa colore"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Colore della luce che viaggia sotto la superficie (ogni canale arriva fino al proprio valore)", @@ -200,7 +195,6 @@ pub const TABLE: &[(&str, &str)] = &[ "I colori vengono letti come grigio. Aggiungi sopra un effetto Livelli o Sfocatura per modellare il risultato.", ), ("Combine with the layer's height", "Combina con l'altezza del livello"), - ("Common parameters", "Parametri comuni"), ("Compare mask", "Maschera di confronto"), ("Compositing", "Compositing"), ("Constant", "Costante"), @@ -213,7 +207,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copia da"), ("Copy layer(s)", "Copia livello/i"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"), - ("Copy these bake settings to every texture set", "Copia queste impostazioni di bake in tutti i set di texture"), ("Copy to all texture sets", "Copia in tutti i set di texture"), ("Copy what the texture set shows", "Copia ciò che mostra il set di texture"), ("Couldn't encode the render", "Impossibile codificare il render"), @@ -264,8 +257,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatazione + colore di sfondo predefinito"), ("Dilation + transparent", "Dilatazione + trasparente"), ("Dilation infinite", "Dilatazione infinita"), - ("Dilation width", "Ampiezza dilatazione"), - ("Direction {axis}", "Direzione {axis}"), ("DirectX normal map", "Mappa normali DirectX"), ("Dirt", "Sporco"), ("Disable", "Disattiva"), @@ -348,10 +339,14 @@ 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"), ("Fingerprints", "Impronte digitali"), + ("Enter a finite number", "Inserisci un numero finito"), + ("Double-click or press Enter to edit", "Fai doppio clic o premi Invio per modificare"), + ("Fit the input range to the histogram", "Adatta l'intervallo di input all'istogramma"), ("Flatten layer", "Appiattisci livello"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -369,11 +364,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Per l'intero progetto: come vengono lette le immagini di mappe normali usate come mappe mesh (riassegnale dopo una modifica) e il valore predefinito per l'esportazione", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libero e open source (MIT OR Apache-2.0), scritto in Rust."), - ("From normal map", "Da mappa normali"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Da mappa normali: curvatura dei dettagli della mappa normali sottoposta a bake anziché della mesh.", - ), ("From template", "Da modello"), ("From template / project", "Da modello / progetto"), ("Full", "Piena"), @@ -413,12 +403,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Aiuto"), ("Hide UI", "Nascondi interfaccia"), ("High", "Alto"), - ("High definition meshes", "Mesh ad alta definizione"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Altezza dell'high poly tra la distanza posteriore massima (nero) e la distanza frontale massima (bianco).", - ), - ("High poly mesh suffix", "Suffisso mesh high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Luci"), ("Histogram Range", "Intervallo istogramma"), @@ -449,7 +433,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "Importa HDR..."), ("Import a template (.json)", "Importa un modello (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "Importa un'immagine (File > Importa risorse) per proiettarla sulla mesh."), - ("Import images to use them in fills and masks", "Importa immagini per usarle in riempimenti e maschere"), ("Import resources...", "Importa risorse..."), ("Import MaterialX material...", "Importa materiale MaterialX..."), ("MaterialX materials", "Materiali MaterialX"), @@ -471,6 +454,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverti"), ("Invert mask", "Inverti maschera"), ("Invert mask background", "Inverti sfondo maschera"), + ("Invert mask value", "Inverti valore maschera"), ("Invert quick mask", "Inverti maschera rapida"), ("Jitters", "Variazioni"), ("Join the ArtCraft community on Discord", "Unisciti alla community di ArtCraft su Discord"), @@ -487,7 +471,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memoria livelli: {mb} MB"), ("Layers", "Livelli"), ("Lazy mouse", "Lazy mouse"), - ("Lazy mouse and symmetry", "Lazy mouse e simmetria"), ("Lazy mouse distance", "Distanza lazy mouse"), ("Leather grain", "Grana pelle"), ( @@ -506,17 +489,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Luce lineare"), ("List of exports", "Elenco esportazioni"), ("Load UI Layout", "Carica layout interfaccia"), - ("Load a cage (the low poly, inflated)", "Carica una gabbia (la low poly, gonfiata)"), ("Loaded UI layout {path}", "Layout interfaccia caricato: {path}"), ("Log", "Log"), ("Low", "Basso"), - ("Low poly mesh suffix", "Suffisso mesh low poly"), ("Luminosity", "Luminosità"), ("MMB drag / Alt + MMB", "Trascina (tasto centrale) / Alt + tasto centrale"), ("Made by the ArtCraft team and community.", "Realizzato dal team e dalla community di ArtCraft."), ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principale"), ("Marble veins", "Venature marmo"), + ("Mask", "Maschera"), ("Mask Editor: Edge wear", "Editor maschera: Usura bordi"), ("Mask value (gray)", "Valore maschera (grigio)"), ("Mask with height", "Maschera con altezza"), @@ -524,17 +506,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Martellato"), ("MatFinish Raw", "MatFinish Grezzo"), ("MatFinish Sanded", "MatFinish Carteggiato"), - ("Match", "Corrispondenza"), ("Material", "Materiale"), ("Material ball", "Sfera materiale"), ("Material finish", "Finitura materiale"), ("Materials", "Materiali"), - ("Max frontal distance", "Distanza frontale max"), - ("Max occluder distance", "Distanza max occlusori"), - ("Max rear distance", "Distanza posteriore max"), ("Maximum", "Massimo"), ("Mesh fill", "Riempimento mesh"), - ("Mesh map bakers", "Baker mappe mesh"), ("Mesh map: {map}", "Mappa mesh: {map}"), ("Mesh maps", "Mappe mesh"), ("Mesh maps baked", "Bake delle mappe mesh completato"), @@ -543,9 +520,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Mezzitoni"), ("Minimum", "Minimo"), ("Minimum size (%)", "Dimensione minima (%)"), - ("Mirror X", "Specchia X"), - ("Mirror Y", "Specchia Y"), - ("Mirror Z", "Specchia Z"), ("Missing (bake to create)", "Mancante (esegui il bake per crearla)"), ("Mixed AO", "AO miscelata"), ("Mode", "Modalità"), @@ -573,7 +547,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Quantità rumore"), ("Noise scale", "Scala rumore"), ("None", "Nessuno"), - ("None: the low poly is its own high poly.", "Nessuna: la low poly è la propria high poly."), ("Normal", "Normale"), ("Normal DirectX", "Normale DirectX"), ("Normal Invert", "Inverti normale"), @@ -605,7 +578,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Sposta le texture in base al canale altezza, con l'intensità altezza in normale", ), ("On", "Attivato"), - ("One color per mesh part.", "Un colore per ogni parte della mesh."), ("Opacity", "Opacità"), ("Open sample project...", "Apri progetto di esempio..."), ("Open...", "Apri..."), @@ -616,15 +588,16 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbita"), ("Orthographic", "Ortografica"), + ("Perspective", "Prospettica"), ("Output directory", "Cartella di output"), ("Output high", "Output alto"), ("Output low", "Output basso"), - ("Output size", "Dimensione output"), ("Output template", "Modello di output"), ("Output templates", "Modelli di output"), ("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"), @@ -634,7 +607,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Dipingi sulla mesh per modificare questa maschera. Usa il valore maschera della scheda Materiale per il grigio.", ), - ("Paint the path with the brush (Enter)", "Dipingi il tracciato con il pennello (Invio)"), ("Paint with the current tool", "Dipingi con lo strumento corrente"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -657,8 +629,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Tracciato"), ("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Tracciato: clic aggiunge un punto, trascina lo sposta, Invio applica, Esc annulla", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracciato: clic aggiunge un punto, clic sulla curva ne inserisce uno, trascina lo sposta, Invio applica, Esc annulla", ), ("Pattern scale", "Scala motivo"), ("Perlin noise", "Rumore Perlin"), @@ -675,7 +647,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variazione posizione"), ("Posterize", "Posterizza"), ("Press a key...", "Premi un tasto..."), - ("Procedurals", "Procedurali"), ("Project", "Progetto"), ("Project Configuration...", "Configurazione progetto..."), ("Project opened", "Progetto aperto"), @@ -686,8 +657,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Un quarto"), ("Quick mask", "Maschera rapida"), ("Quit", "Esci"), - ("Radial axis", "Asse radiale"), - ("Radial copies", "Copie radiali"), ("Radius (texels at 2K)", "Raggio (texel a 2K)"), ("RENDERING", "RENDERING"), ("Range", "Intervallo"), @@ -699,7 +668,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Ripeti"), ("Reimport mesh", "Reimporta mesh"), - ("Relative to the bounding box diagonal.", "Relativa alla diagonale del bounding box."), ("Remove", "Rimuovi"), ("Remove channel", "Rimuovi canale"), ("Remove effect", "Rimuovi effetto"), @@ -707,9 +675,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Rimuovi livello"), ("Remove layer(s)", "Rimuovi livello/i"), ("Remove mask", "Rimuovi maschera"), + ("Remove point", "Rimuovi punto"), ("Remove resource", "Rimuovi risorsa"), - ("Remove the cage", "Rimuovi la gabbia"), - ("Remove the path (Esc)", "Rimuovi il tracciato (Esc)"), ("Remove the shortcut", "Rimuovi la scorciatoia"), ("Remove this output", "Rimuovi questo output"), ("Remove unused resources...", "Rimuovi risorse inutilizzate..."), @@ -722,25 +689,17 @@ 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"), + ("Reset", "Reimposta"), ("Reset UI", "Ripristina interfaccia"), ("Reset all", "Ripristina tutto"), + ("Reset to defaults", "Ripristina i valori predefiniti"), ("Reset to {shortcut}", "Ripristina {shortcut}"), ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), - ("Return to painting mode", "Torna alla modalità pittura"), ("Return to this step", "Torna a questo passaggio"), - ("Auto-rebake", "Bake automatico"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Esegue di nuovo il bake di questa mappa quando cambiano le sue impostazioni di bake, la mesh low poly o le mesh high poly", - ), ("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"), ("Rotation", "Rotazione"), ("Rotation (degrees)", "Rotazione (gradi)"), @@ -768,9 +727,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Graffi"), ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), - ("Search all assets", "Cerca in tutte le risorse"), + ("Search", "Cerca"), ("Search commands or keys", "Cerca comandi o tasti"), - ("Secondary rays", "Raggi secondari"), ("Seed", "Seme"), ("Select a layer", "Seleziona un livello"), ("Select an output template", "Seleziona un modello di output"), @@ -835,16 +793,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Sottocampionamento 8x8"), ("Subsurface scattering", "Subsurface scattering"), ("Subtract", "Sottrai"), - ("Symmetry (X)", "Simmetria (X)"), - ("Symmetry (Y)", "Simmetria (Y)"), ("Tangent | Wrap", "Tangente | Avvolgi"), - ("Tangent-space normals of the high definition meshes.", "Normali in spazio tangente delle mesh ad alta definizione."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anti-aliasing temporale (affina la vista 3D quando è ferma)"), - ("Texture Set List", "Elenco set di texture"), + ("Texture Sets", "Set di texture"), ("Texture Set Settings", "Impostazioni set di texture"), ("Texture resolution", "Risoluzione texture"), ("Texture set channels", "Canali del set di texture"), - ("Texture set list", "Elenco set di texture"), ("Texture sets", "Set di texture"), ("TextureCraft had to close:", "TextureCraft ha dovuto chiudersi:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metallico Rugosità"), @@ -889,17 +843,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 low poly mesh as high poly mesh", "Usa la mesh low poly come mesh high poly"), ("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}"), @@ -920,18 +870,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Rotella / Alt + trascina (tasto destro)"), ("White", "Bianco"), - ( - "White where the surface faces the direction, black where it faces away.", - "Bianco dove la superficie è rivolta verso la direzione, nero dove è rivolta nel verso opposto.", - ), ("Width", "Larghezza"), ("Width (texels at 2K)", "Larghezza (texel a 2K)"), ("Window", "Finestra"), ("Wood grain", "Venatura legno"), ("Works in texture space, like the blur: it does not cross UV seams.", "Opera nello spazio texture, come la sfocatura: non attraversa le cuciture UV."), - ("World space direction", "Direzione spazio mondo"), - ("World space normal", "Normale spazio mondo"), - ("World-space normals of the high poly (or the low poly).", "Normali in spazio mondo dell'high poly (o della low poly)."), + ("World Space Normal", "Normale spazio mondo"), ("Yellow / blue", "Giallo / blu"), ("Zoom", "Zoom"), ("a missing layer", "un livello mancante"), @@ -968,7 +912,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: aggiungi sopra il livello selezionato (o trascinalo nella pila dei livelli o nella viewport)", ), - ("{name} ({n} triangles)", "{name} ({n} triangoli)"), ("{name} copy", "{name} copia"), ("{n} bits", "{n} bit"), ( @@ -979,31 +922,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (scala {scale}, seme {seed})"), ("Template name", "Nome del modello"), ("Save current project as template", "Salva il progetto corrente come modello"), - ("Spread angle", "Angolo di diffusione"), ("Distribution", "Distribuzione"), ("Cosine", "Coseno"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignora facce posteriori"), - ("Self occlusion", "Auto-occlusione"), - ("Only same mesh name", "Solo stesso nome mesh"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "I raggi delle bent normal seguono le impostazioni degli occlusori dell'occlusione ambientale.", - ), - ("Sampling radius", "Raggio di campionamento"), - ("0 picks a radius from the output size.", "0 sceglie un raggio in base alla dimensione di output."), - ("Encoding", "Codifica"), - ("Signed (-1..1)", "Con segno (-1..1)"), - ("Positive (0..1)", "Positivo (0..1)"), ("Normalization", "Normalizzazione"), - ("Bounding box", "Bounding box"), - ("Bounding sphere", "Sfera di contenimento"), - ("Position normalized to the low poly's bounding box or sphere.", "Posizione normalizzata sul bounding box o sulla sfera di contenimento della low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Colori base (texture, fattori) e colori dei vertici delle mesh ad alta definizione.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Bianco dove la high poly copre la low poly, moltiplicato per il suo alfa."), // Settings › Interface: brightness and accent color. ("Brightness", "Luminosità"), ("Dark", "Scuro"), @@ -1028,8 +950,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), ("Brushes", "Pennelli"), - ("My brushes", "I miei pennelli"), - ("Use this brush (keeps its size)", "Usa questo pennello (mantiene la dimensione)"), ("Brush name", "Nome del pennello"), ("Save current brush", "Salva il pennello attuale"), ("Start window", "Finestra iniziale"), @@ -1050,12 +970,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Modifiche non salvate"), ("Don't save", "Non salvare"), ("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"), - ("Skew correction", "Correzione dell'inclinazione"), - ("Paint skew in the 2D view", "Dipingi l'inclinazione nella vista 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Trascina nella vista 2D per dipingere dove i raggi del bake si orientano verso la normale di base; dipingi con valore 0 per cancellare", - ), ("Radius", "Raggio"), ("Remove skew correction", "Rimuovi la correzione dell'inclinazione"), ("Twill weave", "Tessuto a saia"), @@ -1075,4 +989,203 @@ pub const TABLE: &[(&str, &str)] = &[ "Aperto in MaterialCraft: usa lì File > Invia a TextureCraft per riportare le modifiche", ), ("Parameters change in the desktop app, with MaterialCraft installed", "I parametri si modificano nell'app desktop, con MaterialCraft installato"), + ("Add High-Poly Meshes", "Aggiungi mesh ad alta risoluzione"), + ("All", "Tutti"), + ("Apply Diffusion", "Applica diffusione"), + ("Attenuation", "Attenuazione"), + ("Auto Tonemapping", "Mappatura tonale automatica"), + ("Average Normals", "Normali medie"), + ("BBox", "Riquadro di delimitazione"), + ("BSphere", "Sfera di delimitazione"), + ("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"), + ("Cage Scene", "Scena della gabbia"), + ("Cage Type", "Tipo di gabbia"), + ("Color Generator", "Generatore di colori"), + ("Color Source", "Origine del colore"), + ("Common Parameters", "Parametri comuni"), + ("Custom File", "File personalizzato"), + ("Details", "Dettagli"), + ("Dilation Width", "Ampiezza dilatazione"), + ("Distance-Based", "Basata sulla distanza"), + ("Edge Contrast", "Contrasto dei bordi"), + ("Edge Distance", "Distanza dei bordi"), + ("Edge Protection", "Protezione dei bordi"), + ("Enable Seams", "Abilita cuciture"), + ("File ID", "ID del file"), + ("Full Scene", "Intera scena"), + ("Generate from Mesh", "Genera dalla mesh"), + ("Generate from Normal Map", "Genera dalla mappa delle normali"), + ("Ground Plane", "Piano del terreno"), + ("Ground Plane Offset", "Scostamento del terreno"), + ("High Poly Mesh Suffix", "Suffisso mesh high poly"), + ("High Poly Scene", "Scena ad alta risoluzione"), + ("High-Poly Parameters", "Parametri ad alta risoluzione"), + ("Hue Shift", "Variazione di tonalità"), + ("Ignore Backface", "Ignora facce posteriori"), + ("Ignore Backface Suffix", "Suffisso per ignorare le facce posteriori"), + ("Include in Bake", "Includi nel bake"), + ("Load Cage", "Carica gabbia"), + ("Lock Output Size", "Blocca dimensioni di output"), + ("Low Poly Mesh Suffix", "Suffisso mesh low poly"), + ("Manual", "Manuale"), + ("Material Color", "Colore del materiale"), + ("Max Frontal Distance", "Distanza frontale max"), + ("Max Occluder Distance", "Distanza max occlusori"), + ("Max Rear Distance", "Distanza posteriore max"), + ("Mesh ID", "ID della mesh"), + ("Method", "Metodo"), + ("Min Occluder Distance", "Distanza minima dell'occlusore"), + ("Never", "Mai"), + ("No High-Poly Meshes", "Nessuna mesh ad alta risoluzione"), + ("Normalization Scale", "Scala di normalizzazione"), + ("Normalization Type", "Tipo di normalizzazione"), + ("Only Same Mesh Name", "Solo stesso nome mesh"), + ("Output Size", "Dimensione output"), + ("Match", "Corrispondenza"), + ("Skew Correction Method", "Metodo di Correzione della Distorsione"), + ("Mesh Normals Based", "Basato sulle Normali della Mesh"), + ("Face Normals Based", "Basato sulle Normali delle Facce"), + ("Reset Painted Cage", "Ripristina Gabbia Dipinta"), + ("Paint Cage", "Dipingi gabbia"), + ("Paint Skew Correction", "Dipingi correzione dell'inclinazione"), + ("Per Material", "Per materiale"), + ("Random", "Casuale"), + ("Relative to Bounding Box", "Relativo al riquadro di delimitazione"), + ("Relative to Low Mesh", "Relativo alla mesh a bassa risoluzione"), + ("Relative to Min/Max", "Relativo a minimo/massimo"), + ("Relative to Ray Distances", "Relativo alle distanze dei raggi"), + ("Remove Cage", "Rimuovi gabbia"), + ("Remove Skew Correction", "Rimuovi la correzione dell'inclinazione"), + ("Restore Defaults", "Ripristina valori predefiniti"), + ("Return to Painting Mode", "Torna alla modalità pittura"), + ("Sampling Radius", "Raggio di campionamento"), + ("Scaling Divisor", "Divisore di scala"), + ("Seams Intensity", "Intensità delle cuciture"), + ("Secondary Rays", "Raggi secondari"), + ("Self Intersection", "Autointersezione"), + ("Self Occlusion", "Auto-occlusione"), + ("Skew Correction", "Correzione dell'inclinazione"), + ("Smooth", "Uniforme"), + ("Spread Angle", "Angolo di diffusione"), + ("Submesh", "Sottomesh"), + ("Use Low Poly Mesh as High Poly Mesh", "Usa la mesh low poly come mesh high poly"), + ("Value Bounds Max", "Limite massimo"), + ("Value Bounds Min", "Limite minimo"), + ("Vertex Color", "Colore dei vertici"), + ("Select the layer content", "Seleziona il contenuto del livello"), + ("Paint layer", "Livello di pittura"), + ("Fill layer", "Livello di riempimento"), + ("1 effect", "1 effetto"), + ("{count} effects", "{count} effetti"), + ("Mask effects", "Effetti della maschera"), + ("Content effects", "Effetti del contenuto"), + ("Fold or unfold these effects", "Comprimi o espandi questi effetti"), + ("Remove resolution override", "Rimuovi risoluzione personalizzata"), + ("Texture set resolution", "Risoluzione del set di texture"), + ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Angle span", "Ampiezza angolo"), + ("Axis position", "Posizione asse"), + ("Count", "Numero"), + ("Display", "Visualizzazione"), + ("Hide while painting", "Nascondi durante la pittura"), + ("Manipulator size", "Dimensione manipolatore"), + ("Mirror symmetry", "Simmetria speculare"), + ("Radial settings", "Impostazioni radiali"), + ("Radial symmetry", "Simmetria radiale"), + ("Show axis", "Mostra asse"), + ("Show axis position manipulator", "Mostra manipolatore posizione asse"), + ("Show cursor", "Mostra cursore"), + ("Show intersection", "Mostra intersezione"), + ("Show plane", "Mostra piano"), + ("Symmetry", "Simmetria"), + ("Symmetry color display", "Colore di visualizzazione simmetria"), + ("Symmetry settings", "Impostazioni simmetria"), + ("Type", "Tipo"), + ("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"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Il salvataggio usa gli altri core e al massimo questa quota della RAM libera. Almeno un core lavora sempre.", + ), + ("Max project size on open", "Dimensione massima all’apertura"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", + ), + ("Filter by type", "Filtra per tipo"), + ("All libraries", "Tutte le librerie"), + ("Browse folders", "Sfoglia cartelle"), + ("Starter assets", "Risorse incluse"), + ("Your assets", "Le tue risorse"), + ("Reset query", "Reimposta query"), + ("Refresh", "Aggiorna"), + ("Saved searches", "Ricerche salvate"), + ("Save the current search", "Salva la ricerca attuale"), + ("Delete", "Elimina"), + ("Filter by path", "Filtra per percorso"), + ("Hide non-applicable folders", "Nascondi le cartelle non pertinenti"), + ("Thumbnail size", "Dimensione miniature"), + ("Small", "Piccolo"), + ("Medium", "Medio"), + ("Large", "Grande"), + ("List", "Elenco"), + ("Procedurals", "Procedurali"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 41f6a048..bb4f5152 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1,6 +1,17 @@ //! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} をベイク中 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} をベイク中 ({n}/{total})、テクスチャセット {set}/{sets}"), + ("Follow Newest Map", "最新のマップを追う"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "ベイクの表示中はペイントを一時停止しています。ベイクをキャンセルするか、終わるまでお待ちください。", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ベイク中に3Dビューが表示するもの:最後に完成したマップ、完成済みの好きなマップ、またはマテリアル。まだベイクされていないマップは中立値で表示されます。", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", @@ -25,15 +36,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.", "下のレイヤーにアンカーポイントを追加すると、そのスタックをマスクとして使用できます。", @@ -50,7 +52,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "フィルターを追加"), ("Add folder", "フォルダーを追加"), ("Add generator", "ジェネレーターを追加"), - ("Add high definition meshes", "高精細メッシュを追加"), ("Add levels", "レベル補正を追加"), ("Add mask", "マスクを追加"), ("Add mask with color selection", "カラー選択でマスクを追加"), @@ -58,20 +59,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", "色調補正"), ( @@ -86,8 +75,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "{item} ({menu}) にも割り当て済み"), ("Alt + LMB drag", "Alt + 左ドラッグ"), ("Always", "常に"), + ("Ambient Occlusion", "アンビエントオクルージョン"), ("Ambient occlusion", "アンビエントオクルージョン"), - ("Ambient occlusion intensity", "アンビエントオクルージョンの強度"), ("Amount", "量"), ("Anchor point", "アンカーポイント"), ("Anchor: {name}", "アンカー: {name}"), @@ -102,27 +91,25 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "アンチエイリアス"), ("Aperture", "絞り"), ("Apply", "適用"), - ("Apply to all texture sets", "すべてのテクスチャセットに適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), + ("Auto", "自動"), ("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"), ("Autosave every", "自動保存の間隔"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "自動保存、スマートマテリアル、プリセット、テンプレート、UI レイアウトはデータフォルダーに保存されます。新しいフォルダーは再起動後に適用され、保存済みのファイルはそのまま残ります。", ), - ("Average normals", "法線を平均化"), ("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) が必要です。", ), - ("Bake selected textures ({n})", "選択したテクスチャをベイク ({n})"), - ("Bake with \"Bake selected textures\"", "「選択したテクスチャをベイク」でベイク"), ("Baked Lighting", "ライティングのベイク"), ("Baking", "ベイク"), ("Base color", "ベースカラー"), @@ -133,10 +120,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "ベースカラー、メタリック、ラフネス、スペキュラーレベル。"), ("Based on each texture set's size", "各テクスチャセットのサイズに基づく"), ("Basic settings", "基本設定"), - ("Bent normals", "ベントノーマル"), + ("Bent Normals", "ベントノーマル"), ("Bevel", "ベベル"), ("Black", "黒"), - ("Blend sharpness", "ブレンドのシャープさ"), ("Blending", "ブレンド"), ("Blending mode of the displayed channel", "表示中のチャンネルのブレンドモード"), ("Blur", "ぼかし"), @@ -151,9 +137,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "組み込み (読み取り専用): 複製して編集"), ("Built-in templates are read-only: duplicate one to edit it", "組み込みテンプレートは読み取り専用です: 複製して編集"), ("Built-in: {mesh}", "組み込み: {mesh}"), - ("By mesh name", "メッシュ名で"), ("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", "ストロークをキャンセル"), @@ -162,6 +157,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "チャンネル"), ("Channel source: uniform value, procedural, image or anchor", "チャンネルのソース: 均一値、プロシージャル、画像、アンカー"), ("Channels", "チャンネル"), + ("Check for Updates...", "アップデートを確認..."), ("Checker", "チェッカー"), ("Clamp", "クランプ"), ("Clear", "クリア"), @@ -186,7 +182,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "カラーバランス"), ("Color burn", "焼き込みカラー"), ("Color dodge", "覆い焼きカラー"), - ("Color map", "カラーマップ"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "表面下を伝わる光の色 (各チャンネルは値に応じた距離まで届く)", @@ -200,7 +195,6 @@ pub const TABLE: &[(&str, &str)] = &[ "カラーはグレーとして読み取られます。結果を調整するには、上にレベル補正またはぼかしエフェクトを追加します。", ), ("Combine with the layer's height", "レイヤーのハイトと合成"), - ("Common parameters", "共通パラメーター"), ("Compare mask", "比較マスク"), ("Compositing", "合成中"), ("Constant", "定数"), @@ -213,7 +207,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "コピー元"), ("Copy layer(s)", "レイヤーをコピー"), ("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"), - ("Copy these bake settings to every texture set", "このベイク設定をすべてのテクスチャセットにコピー"), ("Copy to all texture sets", "すべてのテクスチャセットにコピー"), ("Copy what the texture set shows", "テクスチャセットの表示内容をコピー"), ("Couldn't encode the render", "レンダリング結果をエンコードできませんでした"), @@ -261,8 +254,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "ダイレーション + デフォルト背景色"), ("Dilation + transparent", "ダイレーション + 透明"), ("Dilation infinite", "ダイレーション (無限)"), - ("Dilation width", "ダイレーション幅"), - ("Direction {axis}", "方向 {axis}"), ("DirectX normal map", "DirectX ノーマルマップ"), ("Dirt", "汚れ"), ("Disable", "無効"), @@ -339,10 +330,14 @@ 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", "細かいノイズ"), ("Fingerprints", "指紋"), + ("Enter a finite number", "有限の数値を入力してください"), + ("Double-click or press Enter to edit", "ダブルクリックまたは Enter キーで編集"), + ("Fit the input range to the histogram", "入力範囲をヒストグラムに合わせる"), ("Flatten layer", "レイヤーを統合"), ("Flips the image's green channel, for normal maps made with Y pointing down", "画像の緑チャンネルを反転します (Y が下向きで作られたノーマルマップ用)"), ("Flow", "フロー"), @@ -357,11 +352,6 @@ pub const TABLE: &[(&str, &str)] = &[ "プロジェクト全体: メッシュマップとして設定したノーマルマップ画像の読み取り方 (変更後は設定し直してください) と、書き出しの既定値", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "無料のオープンソース (MIT OR Apache-2.0)、Rustで開発。"), - ("From normal map", "ノーマルマップから"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "ノーマルマップから: メッシュではなく、ベイクしたノーマルマップのディテールの曲率。", - ), ("From template", "テンプレートから"), ("From template / project", "テンプレート / プロジェクトから"), ("Full", "フル"), @@ -401,9 +391,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "ヘルプ"), ("Hide UI", "UIを非表示"), ("High", "高"), - ("High definition meshes", "高精細メッシュ"), - ("High poly height between the max rear (black) and max frontal (white) distances.", "後方最大距離 (黒) から前方最大距離 (白) までのハイポリの高さ。"), - ("High poly mesh suffix", "ハイポリメッシュの接尾辞"), ("High poly: {name}", "ハイポリ: {name}"), ("Highlights", "ハイライト"), ("Histogram Range", "ヒストグラム範囲"), @@ -437,7 +424,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "画像をインポートすると (ファイル > リソースをインポート)、メッシュに投影できます。", ), - ("Import images to use them in fills and masks", "画像をインポートして塗りつぶしやマスクで使用"), ("Import resources...", "リソースをインポート..."), ("Import MaterialX material...", "MaterialX マテリアルをインポート..."), ("MaterialX materials", "MaterialX マテリアル"), @@ -459,6 +445,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "反転"), ("Invert mask", "マスクを反転"), ("Invert mask background", "マスクの背景を反転"), + ("Invert mask value", "マスク値を反転"), ("Invert quick mask", "クイックマスクを反転"), ("Jitters", "ジッター"), ("Join the ArtCraft community on Discord", "DiscordでArtCraftコミュニティに参加"), @@ -475,7 +462,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "レイヤーメモリ: {mb} MB"), ("Layers", "レイヤー"), ("Lazy mouse", "レイジーマウス"), - ("Lazy mouse and symmetry", "レイジーマウスと対称"), ("Lazy mouse distance", "レイジーマウスの距離"), ("Leather grain", "革のシボ"), ("Lens size: how quickly things blur away from the focus distance", "レンズサイズ: フォーカス距離から離れるにつれてぼける速さ"), @@ -491,17 +477,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "リニアライト"), ("List of exports", "エクスポート一覧"), ("Load UI Layout", "UIレイアウトを読み込み"), - ("Load a cage (the low poly, inflated)", "ケージを読み込み (膨張させたローポリ)"), ("Loaded UI layout {path}", "UIレイアウト {path} を読み込みました"), ("Log", "ログ"), ("Low", "低"), - ("Low poly mesh suffix", "ローポリメッシュの接尾辞"), ("Luminosity", "輝度"), ("MMB drag / Alt + MMB", "中ドラッグ / Alt + 中ドラッグ"), ("Made by the ArtCraft team and community.", "ArtCraftチームとコミュニティによって制作。"), ("Magenta / green", "マゼンタ / グリーン"), ("Main shader", "メインシェーダー"), ("Marble veins", "大理石の筋"), + ("Mask", "マスク"), ("Mask Editor: Edge wear", "マスクエディター: エッジの摩耗"), ("Mask value (gray)", "マスク値 (グレー)"), ("Mask with height", "ハイトでマスク"), @@ -509,17 +494,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish 槌目"), ("MatFinish Raw", "MatFinish 未加工"), ("MatFinish Sanded", "MatFinish サンディング"), - ("Match", "マッチング"), ("Material", "マテリアル"), ("Material ball", "マテリアルボール"), ("Material finish", "マテリアル仕上げ"), ("Materials", "マテリアル"), - ("Max frontal distance", "前方最大距離"), - ("Max occluder distance", "遮蔽物の最大距離"), - ("Max rear distance", "後方最大距離"), ("Maximum", "最大"), ("Mesh fill", "メッシュ塗りつぶし"), - ("Mesh map bakers", "メッシュマップベイカー"), ("Mesh map: {map}", "メッシュマップ: {map}"), ("Mesh maps", "メッシュマップ"), ("Mesh maps baked", "メッシュマップをベイクしました"), @@ -528,9 +508,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "中間調"), ("Minimum", "最小"), ("Minimum size (%)", "最小サイズ (%)"), - ("Mirror X", "ミラー X"), - ("Mirror Y", "ミラー Y"), - ("Mirror Z", "ミラー Z"), ("Missing (bake to create)", "なし (ベイクで作成)"), ("Mixed AO", "ミックスAO"), ("Mode", "モード"), @@ -558,7 +535,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "ノイズ量"), ("Noise scale", "ノイズスケール"), ("None", "なし"), - ("None: the low poly is its own high poly.", "なし: ローポリ自体をハイポリとして使用します。"), ("Normal", "ノーマル"), ("Normal DirectX", "ノーマル DirectX"), ("Normal Invert", "ノーマル反転"), @@ -590,7 +566,6 @@ pub const TABLE: &[(&str, &str)] = &[ "ハイトチャンネルに応じてテクスチャをオフセットします (強度はハイト→ノーマル強度)", ), ("On", "オン"), - ("One color per mesh part.", "メッシュパーツごとに1色。"), ("Opacity", "不透明度"), ("Open sample project...", "サンプルプロジェクトを開く..."), ("Open...", "開く..."), @@ -601,15 +576,16 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "オービット"), ("Orthographic", "平行投影"), + ("Perspective", "透視投影"), ("Output directory", "出力先フォルダー"), ("Output high", "出力の上限"), ("Output low", "出力の下限"), - ("Output size", "出力サイズ"), ("Output template", "出力テンプレート"), ("Output templates", "出力テンプレート"), ("Overlay", "オーバーレイ"), ("Overlay opacity", "オーバーレイの不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - メタリック/ラフネス (TextureCraft)"), + ("Pick color", "色を拾う"), ("PNG image", "PNG画像"), ("Padding", "パディング"), ("Paint", "ペイント"), @@ -619,7 +595,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "メッシュにペイントしてこのマスクを編集します。グレーには「マテリアル」タブのマスク値を使用します。", ), - ("Paint the path with the brush (Enter)", "ブラシでパスをペイント (Enter)"), ("Paint with the current tool", "現在のツールでペイント"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -638,7 +613,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "レイヤーを貼り付け"), ("Path", "パス"), ("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "パス: クリックでポイントを追加、ドラッグで移動、Enterで適用、Escでキャンセル"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "パス: クリックでポイントを追加、カーブをクリックで挿入、ドラッグで移動、Enterで適用、Escでキャンセル", + ), ("Pattern scale", "パターンのスケール"), ("Perlin noise", "パーリンノイズ"), ("Pick focus in the viewport", "ビューポートでフォーカスを指定"), @@ -654,7 +632,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "位置ジッター"), ("Posterize", "ポスタリゼーション"), ("Press a key...", "キーを押してください..."), - ("Procedurals", "プロシージャル"), ("Project", "プロジェクト"), ("Project Configuration...", "プロジェクト構成..."), ("Project opened", "プロジェクトを開きました"), @@ -665,8 +642,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "クイックマスク"), ("Quit", "終了"), - ("Radial axis", "放射軸"), - ("Radial copies", "放射状コピー"), ("Radius (texels at 2K)", "半径 (2K時のテクセル)"), ("RENDERING", "レンダリング"), ("Range", "範囲"), @@ -678,7 +653,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "やり直し"), ("Reimport mesh", "メッシュを再インポート"), - ("Relative to the bounding box diagonal.", "バウンディングボックスの対角線に対する相対値。"), ("Remove", "削除"), ("Remove channel", "チャンネルを削除"), ("Remove effect", "エフェクトを削除"), @@ -686,9 +660,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "レイヤーを削除"), ("Remove layer(s)", "レイヤーを削除"), ("Remove mask", "マスクを削除"), + ("Remove point", "ポイントを削除"), ("Remove resource", "リソースを削除"), - ("Remove the cage", "ケージを削除"), - ("Remove the path (Esc)", "パスを削除 (Esc)"), ("Remove the shortcut", "ショートカットを削除"), ("Remove this output", "この出力を削除"), ("Remove unused resources...", "未使用のリソースを削除..."), @@ -701,25 +674,17 @@ 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", "ライブラリフォルダーを再スキャン"), + ("Reset", "リセット"), ("Reset UI", "UIをリセット"), ("Reset all", "すべてリセット"), + ("Reset to defaults", "デフォルトに戻す"), ("Reset to {shortcut}", "{shortcut} にリセット"), ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), - ("Return to painting mode", "ペイントモードに戻る"), ("Return to this step", "このステップに戻る"), - ("Auto-rebake", "自動再ベイク"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "ベイク設定、ローポリ、またはハイポリが変わると、このマップを自動的にベイクし直します", - ), ("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"), ("Rotation", "回転"), ("Rotation (degrees)", "回転 (度)"), @@ -747,9 +712,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "引っかき傷"), ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), - ("Search all assets", "すべてのアセットを検索"), + ("Search", "検索"), ("Search commands or keys", "コマンドまたはキーを検索"), - ("Secondary rays", "二次レイ"), ("Seed", "シード"), ("Select a layer", "レイヤーを選択"), ("Select an output template", "出力テンプレートを選択"), @@ -814,16 +778,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "サブサンプリング 8x8"), ("Subsurface scattering", "サブサーフェススキャタリング"), ("Subtract", "減算"), - ("Symmetry (X)", "対称 (X)"), - ("Symmetry (Y)", "対称 (Y)"), ("Tangent | Wrap", "タンジェント | ラップ"), - ("Tangent-space normals of the high definition meshes.", "高精細メッシュのタンジェント空間法線。"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "テンポラルアンチエイリアス (静止中に3Dビューを精細化)"), - ("Texture Set List", "テクスチャセット一覧"), + ("Texture Sets", "テクスチャセット"), ("Texture Set Settings", "テクスチャセット設定"), ("Texture resolution", "テクスチャ解像度"), ("Texture set channels", "テクスチャセットのチャンネル"), - ("Texture set list", "テクスチャセット一覧"), ("Texture sets", "テクスチャセット"), ("TextureCraft had to close:", "TextureCraft を終了する必要がありました:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - メタリック/ラフネス"), @@ -868,17 +828,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 low poly mesh as high poly mesh", "ローポリメッシュをハイポリメッシュとして使用"), ( "Use the control channel or `texturecraft-cli render` for screenshots", "スクリーンショットにはコントロールチャンネルまたは `texturecraft-cli render` を使用", @@ -902,15 +858,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "ホイール / Alt + 右ドラッグ"), ("White", "白"), - ("White where the surface faces the direction, black where it faces away.", "表面がその方向を向く部分は白、反対を向く部分は黒。"), ("Width", "幅"), ("Width (texels at 2K)", "幅 (2K時のテクセル)"), ("Window", "ウィンドウ"), ("Wood grain", "木目"), ("Works in texture space, like the blur: it does not cross UV seams.", "ぼかしと同様にテクスチャ空間で処理するため、UVシームをまたぎません。"), - ("World space direction", "ワールド空間方向"), - ("World space normal", "ワールド空間ノーマル"), - ("World-space normals of the high poly (or the low poly).", "ハイポリ (またはローポリ) のワールド空間法線。"), + ("World Space Normal", "ワールド空間ノーマル"), ("Yellow / blue", "イエロー / ブルー"), ("Zoom", "ズーム"), ("a missing layer", "見つからないレイヤー"), @@ -947,7 +900,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: 選択中のレイヤーの上に追加 (レイヤースタックやビューポートへのドラッグも可)", ), - ("{name} ({n} triangles)", "{name} (三角形 {n} 個)"), ("{name} copy", "{name} のコピー"), ("{n} bits", "{n} ビット"), ( @@ -958,25 +910,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (スケール {scale}、シード {seed})"), ("Template name", "テンプレート名"), ("Save current project as template", "現在のプロジェクトをテンプレートとして保存"), - ("Spread angle", "拡散角度"), ("Distribution", "分布"), ("Cosine", "コサイン"), ("Uniform", "均一"), - ("Ignore backface", "裏面を無視"), - ("Self occlusion", "自己遮蔽"), - ("Only same mesh name", "同じメッシュ名のみ"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "ベントノーマルのレイはアンビエントオクルージョンの遮蔽物設定に従います。"), - ("Sampling radius", "サンプリング半径"), - ("0 picks a radius from the output size.", "0 の場合は出力サイズから半径を決めます。"), - ("Encoding", "エンコード"), - ("Signed (-1..1)", "符号付き (-1..1)"), - ("Positive (0..1)", "正の値 (0..1)"), ("Normalization", "正規化"), - ("Bounding box", "バウンディングボックス"), - ("Bounding sphere", "バウンディングスフィア"), - ("Position normalized to the low poly's bounding box or sphere.", "ローポリのバウンディングボックスまたはスフィアで正規化した位置。"), - ("Base colors (textures, factors) and vertex colors of the high definition meshes.", "高精細メッシュのベースカラー (テクスチャ、係数) と頂点カラー。"), - ("White where the high poly covers the low poly, times its alpha.", "ハイポリがローポリを覆う部分が白 (アルファを乗算)。"), // Settings › Interface: brightness and accent color. ("Brightness", "明るさ"), ("Dark", "ダーク"), @@ -1001,8 +938,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), ("Brushes", "ブラシ一覧"), - ("My brushes", "マイブラシ"), - ("Use this brush (keeps its size)", "このブラシを使用(サイズはそのまま)"), ("Brush name", "ブラシ名"), ("Save current brush", "現在のブラシを保存"), ("Start window", "スタートウィンドウ"), @@ -1023,12 +958,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "未保存の変更"), ("Don't save", "保存しない"), ("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"), - ("Skew correction", "スキュー補正"), - ("Paint skew in the 2D view", "2Dビューでスキューをペイント"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "2Dビューでドラッグして、ベイクのレイがベース法線へ向かう箇所をペイントします。値0でペイントすると消去されます", - ), ("Radius", "半径"), ("Remove skew correction", "スキュー補正を削除"), ("Twill weave", "綾織り"), @@ -1048,4 +977,200 @@ pub const TABLE: &[(&str, &str)] = &[ "MaterialCraft で開きました。変更を戻すには、そちらで「ファイル > TextureCraft に送る」を使います", ), ("Parameters change in the desktop app, with MaterialCraft installed", "パラメーターは MaterialCraft をインストールしたデスクトップ版で変更できます"), + ("Add High-Poly Meshes", "ハイポリメッシュを追加"), + ("All", "すべて"), + ("Apply Diffusion", "拡散を適用"), + ("Attenuation", "減衰"), + ("Auto Tonemapping", "自動トーンマッピング"), + ("Average Normals", "法線を平均化"), + ("BBox", "バウンディングボックス"), + ("BSphere", "バウンディングスフィア"), + ("Mesh Map Bakers", "メッシュマップベイカー"), + ("Common Settings", "共通設定"), + ("Mesh Map Settings", "メッシュマップ設定"), + ("Check All", "すべてチェック"), + ("No Parameters", "パラメーターなし"), + ("Bake Selected Textures ({n})", "選択したテクスチャをベイク ({n})"), + ("By Mesh Name", "メッシュ名で"), + ("Cage", "ケージ"), + ("Cage Scene", "ケージシーン"), + ("Cage Type", "ケージの種類"), + ("Color Generator", "カラー生成"), + ("Color Source", "カラーソース"), + ("Common Parameters", "共通パラメーター"), + ("Custom File", "カスタムファイル"), + ("Details", "ディテール"), + ("Dilation Width", "ダイレーション幅"), + ("Distance-Based", "距離ベース"), + ("Edge Contrast", "エッジコントラスト"), + ("Edge Distance", "エッジ距離"), + ("Edge Protection", "エッジ保護"), + ("Enable Seams", "シームを有効化"), + ("File ID", "ファイルID"), + ("Full Scene", "シーン全体"), + ("Generate from Mesh", "メッシュから生成"), + ("Generate from Normal Map", "法線マップから生成"), + ("Ground Plane", "グラウンドプレーン"), + ("Ground Plane Offset", "グラウンドプレーンのオフセット"), + ("High Poly Mesh Suffix", "ハイポリメッシュの接尾辞"), + ("High Poly Scene", "ハイポリシーン"), + ("High-Poly Parameters", "ハイポリパラメーター"), + ("Hue Shift", "色相シフト"), + ("Ignore Backface", "裏面を無視"), + ("Ignore Backface Suffix", "裏面を無視するサフィックス"), + ("Include in Bake", "ベイク対象に含める"), + ("Load Cage", "ケージを読み込む"), + ("Lock Output Size", "出力サイズをロック"), + ("Low Poly Mesh Suffix", "ローポリメッシュの接尾辞"), + ("Manual", "手動"), + ("Material Color", "マテリアルカラー"), + ("Max Frontal Distance", "前方最大距離"), + ("Max Occluder Distance", "遮蔽物の最大距離"), + ("Max Rear Distance", "後方最大距離"), + ("Mesh ID", "メッシュID"), + ("Method", "方式"), + ("Min Occluder Distance", "最小遮蔽距離"), + ("Never", "しない"), + ("No High-Poly Meshes", "ハイポリメッシュなし"), + ("Normalization Scale", "正規化スケール"), + ("Normalization Type", "正規化の種類"), + ("Only Same Mesh Name", "同じメッシュ名のみ"), + ("Output Size", "出力サイズ"), + ("Match", "マッチング"), + ("Skew Correction Method", "スキュー補正方法"), + ("Mesh Normals Based", "メッシュ法線ベース"), + ("Face Normals Based", "面法線ベース"), + ("Reset Painted Cage", "ペイントしたケージをリセット"), + ("Paint Cage", "ケージをペイント"), + ("Paint Skew Correction", "スキュー補正をペイント"), + ("Per Material", "マテリアルごと"), + ("Random", "ランダム"), + ("Relative to Bounding Box", "バウンディングボックスに相対"), + ("Relative to Low Mesh", "ローポリメッシュに相対"), + ("Relative to Min/Max", "最小値・最大値に相対"), + ("Relative to Ray Distances", "レイ距離に相対"), + ("Remove Cage", "ケージを削除"), + ("Remove Skew Correction", "スキュー補正を削除"), + ("Restore Defaults", "既定値に戻す"), + ("Return to Painting Mode", "ペイントモードに戻る"), + ("Sampling Radius", "サンプリング半径"), + ("Scaling Divisor", "スケーリング除数"), + ("Seams Intensity", "シームの強度"), + ("Secondary Rays", "二次レイ"), + ("Self Intersection", "自己交差"), + ("Self Occlusion", "自己遮蔽"), + ("Skew Correction", "スキュー補正"), + ("Smooth", "スムーズ"), + ("Spread Angle", "拡散角度"), + ("Submesh", "サブメッシュ"), + ("Use Low Poly Mesh as High Poly Mesh", "ローポリメッシュをハイポリメッシュとして使用"), + ("Value Bounds Max", "値の上限"), + ("Value Bounds Min", "値の下限"), + ("Vertex Color", "頂点カラー"), + ("Select the layer content", "レイヤーの内容を選択"), + ("Paint layer", "ペイントレイヤー"), + ("Fill layer", "塗りつぶしレイヤー"), + ("1 effect", "エフェクト 1 件"), + ("{count} effects", "エフェクト {count} 件"), + ("Mask effects", "マスクのエフェクト"), + ("Content effects", "コンテンツのエフェクト"), + ("Fold or unfold these effects", "これらのエフェクトを折りたたむ/展開する"), + ("Remove resolution override", "解像度の上書きを解除"), + ("Texture set resolution", "テクスチャセットの解像度"), + ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Angle span", "角度範囲"), + ("Axis position", "軸の位置"), + ("Count", "数"), + ("Display", "表示"), + ("Hide while painting", "ペイント中は隠す"), + ("Manipulator size", "マニピュレーターのサイズ"), + ("Mirror symmetry", "ミラー対称"), + ("Radial settings", "放射の設定"), + ("Radial symmetry", "放射対称"), + ("Show axis", "軸を表示"), + ("Show axis position manipulator", "軸位置マニピュレーターを表示"), + ("Show cursor", "カーソルを表示"), + ("Show intersection", "交差部を表示"), + ("Show plane", "平面を表示"), + ("Symmetry", "対称"), + ("Symmetry color display", "対称の表示色"), + ("Symmetry settings", "対称の設定"), + ("Type", "種類"), + ("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上限"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存は残りのコアと、空きRAMのこの割合までを使います。少なくとも1コアは常に動作します。", + ), + ("Max project size on open", "開くプロジェクトの最大サイズ"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", + ), + ("Filter by type", "種類で絞り込む"), + ("All libraries", "すべてのライブラリ"), + ("Browse folders", "フォルダーを参照"), + ("Starter assets", "付属アセット"), + ("Your assets", "マイアセット"), + ("Reset query", "クエリをリセット"), + ("Refresh", "更新"), + ("Saved searches", "保存した検索"), + ("Save the current search", "現在の検索を保存"), + ("Delete", "削除"), + ("Filter by path", "パスで絞り込む"), + ("Hide non-applicable folders", "該当しないフォルダーを隠す"), + ("Thumbnail size", "サムネイルのサイズ"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "リスト"), + ("Procedurals", "プロシージャル"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 9f6aabbe..4273f92c 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1,6 +1,17 @@ //! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} 베이크 중 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} 베이크 중 ({n}/{total}), 텍스처 세트 {set}/{sets}"), + ("Follow Newest Map", "최신 맵 따라가기"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "베이크를 표시하는 동안에는 페인팅이 일시 중지됩니다. 베이크를 취소하거나 끝날 때까지 기다리세요.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "베이크하는 동안 3D 뷰가 보여 주는 것: 가장 최근에 완료된 맵, 완료된 맵 중 선택한 하나, 또는 머티리얼. 아직 베이크되지 않은 맵은 중립 값으로 표시됩니다.", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", @@ -25,15 +36,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)", "데칼로 추가 (뷰 중앙)"), @@ -47,7 +49,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "필터 추가"), ("Add folder", "폴더 추가"), ("Add generator", "제너레이터 추가"), - ("Add high definition meshes", "고해상도 메시 추가"), ("Add levels", "레벨 추가"), ("Add mask", "마스크 추가"), ("Add mask with color selection", "색상 선택으로 마스크 추가"), @@ -55,20 +56,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", "조정"), ( @@ -83,8 +72,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "{item}({menu})에도 지정됨"), ("Alt + LMB drag", "Alt + 왼쪽 드래그"), ("Always", "항상"), + ("Ambient Occlusion", "앰비언트 오클루전"), ("Ambient occlusion", "앰비언트 오클루전"), - ("Ambient occlusion intensity", "앰비언트 오클루전 강도"), ("Amount", "양"), ("Anchor point", "앵커 포인트"), ("Anchor: {name}", "앵커: {name}"), @@ -99,24 +88,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "안티앨리어싱"), ("Aperture", "조리개"), ("Apply", "적용"), - ("Apply to all texture sets", "모든 텍스처 세트에 적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), + ("Auto", "자동"), ("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"), ("Autosave every", "자동 저장 간격"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "자동 저장, 스마트 머티리얼, 프리셋, 템플릿과 UI 레이아웃은 데이터 폴더에 저장됩니다. 새 폴더는 다시 시작하면 적용되며, 이미 저장된 파일은 그대로 남습니다.", ), - ("Average normals", "노멀 평균화"), ("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)."), - ("Bake selected textures ({n})", "선택한 텍스처 베이크 ({n})"), - ("Bake with \"Bake selected textures\"", "\"선택한 텍스처 베이크\"로 베이크합니다"), ("Baked Lighting", "베이크된 조명"), ("Baking", "베이킹"), ("Base color", "베이스 컬러"), @@ -127,10 +114,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "베이스 컬러, 메탈릭, 러프니스, 스페큘러 레벨."), ("Based on each texture set's size", "각 텍스처 세트 크기 기준"), ("Basic settings", "기본 설정"), - ("Bent normals", "벤트 노멀"), + ("Bent Normals", "벤트 노멀"), ("Bevel", "베벨"), ("Black", "검은색"), - ("Blend sharpness", "블렌드 선명도"), ("Blending", "블렌딩"), ("Blending mode of the displayed channel", "표시된 채널의 블렌딩 모드"), ("Blur", "블러"), @@ -145,9 +131,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "기본 제공 (읽기 전용): 편집하려면 복제하세요"), ("Built-in templates are read-only: duplicate one to edit it", "기본 제공 템플릿은 읽기 전용입니다. 편집하려면 복제하세요"), ("Built-in: {mesh}", "기본 제공: {mesh}"), - ("By mesh name", "메시 이름으로"), ("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", "스트로크 취소"), @@ -156,6 +151,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "채널"), ("Channel source: uniform value, procedural, image or anchor", "채널 소스: 균일 값, 프로시저럴, 이미지 또는 앵커"), ("Channels", "채널"), + ("Check for Updates...", "업데이트 확인..."), ("Checker", "체커"), ("Clamp", "클램프"), ("Clear", "지우기"), @@ -177,7 +173,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "색상 균형"), ("Color burn", "색상 번"), ("Color dodge", "색상 닷지"), - ("Color map", "컬러 맵"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "표면 아래로 이동하는 빛의 색상입니다 (각 채널은 값만큼 멀리 이동)", @@ -191,7 +186,6 @@ pub const TABLE: &[(&str, &str)] = &[ "색상은 회색으로 읽힙니다. 결과를 조정하려면 위에 레벨 또는 블러 이펙트를 추가하세요.", ), ("Combine with the layer's height", "레이어 높이와 결합"), - ("Common parameters", "공통 매개변수"), ("Compare mask", "비교 마스크"), ("Compositing", "합성 중"), ("Constant", "상수"), @@ -204,7 +198,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "복사 원본"), ("Copy layer(s)", "레이어 복사"), ("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"), - ("Copy these bake settings to every texture set", "이 베이크 설정을 모든 텍스처 세트에 복사합니다"), ("Copy to all texture sets", "모든 텍스처 세트에 복사"), ("Copy what the texture set shows", "텍스처 세트에 표시되는 내용을 복사합니다"), ("Couldn't encode the render", "렌더를 인코딩할 수 없습니다"), @@ -255,8 +248,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "확장 + 기본 배경색"), ("Dilation + transparent", "확장 + 투명"), ("Dilation infinite", "무한 확장"), - ("Dilation width", "확장 폭"), - ("Direction {axis}", "방향 {axis}"), ("DirectX normal map", "DirectX 노멀 맵"), ("Dirt", "먼지"), ("Disable", "비활성화"), @@ -336,10 +327,14 @@ 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", "미세 노이즈"), ("Fingerprints", "지문"), + ("Enter a finite number", "유한한 숫자를 입력하세요"), + ("Double-click or press Enter to edit", "두 번 클릭하거나 Enter 키를 눌러 편집"), + ("Fit the input range to the histogram", "입력 범위를 히스토그램에 맞추기"), ("Flatten layer", "레이어 병합"), ("Flips the image's green channel, for normal maps made with Y pointing down", "이미지의 녹색 채널을 뒤집습니다 (Y가 아래를 향하도록 만든 노멀 맵용)"), ("Flow", "흐름"), @@ -354,8 +349,6 @@ pub const TABLE: &[(&str, &str)] = &[ "프로젝트 전체: 메시 맵으로 지정한 노멀 맵 이미지를 읽는 방식(변경 후 다시 지정하세요)과 내보내기 기본값", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Rust로 작성된 무료 오픈 소스 소프트웨어입니다 (MIT OR Apache-2.0)."), - ("From normal map", "노멀 맵에서"), - ("From normal map: curvature of the baked normal map's detail instead of the mesh.", "노멀 맵에서: 메시 대신 베이크된 노멀 맵 디테일의 곡률을 사용합니다."), ("From template", "템플릿 기준"), ("From template / project", "템플릿 / 프로젝트 기준"), ("Full", "전체"), @@ -395,12 +388,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "도움말"), ("Hide UI", "UI 숨기기"), ("High", "높음"), - ("High definition meshes", "고해상도 메시"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "최대 후방 거리(검은색)와 최대 전방 거리(흰색) 사이의 하이 폴리 높이입니다.", - ), - ("High poly mesh suffix", "하이 폴리 메시 접미사"), ("High poly: {name}", "하이 폴리: {name}"), ("Highlights", "밝은 영역"), ("Histogram Range", "히스토그램 범위"), @@ -431,7 +418,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "HDR 가져오기..."), ("Import a template (.json)", "템플릿을 가져옵니다 (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "메시에 투영할 이미지를 가져오세요 (파일 > 리소스 가져오기)."), - ("Import images to use them in fills and masks", "채우기와 마스크에 사용할 이미지를 가져옵니다"), ("Import resources...", "리소스 가져오기..."), ("Import MaterialX material...", "MaterialX 머티리얼 가져오기..."), ("MaterialX materials", "MaterialX 머티리얼"), @@ -453,6 +439,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "반전"), ("Invert mask", "마스크 반전"), ("Invert mask background", "마스크 배경 반전"), + ("Invert mask value", "마스크 값 반전"), ("Invert quick mask", "퀵 마스크 반전"), ("Jitters", "지터"), ("Join the ArtCraft community on Discord", "Discord에서 ArtCraft 커뮤니티에 참여하세요"), @@ -469,7 +456,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "레이어 메모리: {mb} MB"), ("Layers", "레이어"), ("Lazy mouse", "레이지 마우스"), - ("Lazy mouse and symmetry", "레이지 마우스 및 대칭"), ("Lazy mouse distance", "레이지 마우스 거리"), ("Leather grain", "가죽 결"), ("Lens size: how quickly things blur away from the focus distance", "렌즈 크기: 초점 거리에서 멀어질수록 얼마나 빠르게 흐려지는지 결정합니다"), @@ -485,17 +471,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "선형 라이트"), ("List of exports", "내보내기 목록"), ("Load UI Layout", "UI 레이아웃 불러오기"), - ("Load a cage (the low poly, inflated)", "케이지를 불러옵니다 (부풀린 로우 폴리)"), ("Loaded UI layout {path}", "UI 레이아웃 불러옴: {path}"), ("Log", "로그"), ("Low", "낮음"), - ("Low poly mesh suffix", "로우 폴리 메시 접미사"), ("Luminosity", "광도"), ("MMB drag / Alt + MMB", "가운데 드래그 / Alt + 가운데 버튼"), ("Made by the ArtCraft team and community.", "ArtCraft 팀과 커뮤니티가 만들었습니다."), ("Magenta / green", "마젠타 / 녹색"), ("Main shader", "메인 셰이더"), ("Marble veins", "대리석 무늬"), + ("Mask", "마스크"), ("Mask Editor: Edge wear", "마스크 에디터: 모서리 마모"), ("Mask value (gray)", "마스크 값 (회색)"), ("Mask with height", "높이로 마스크"), @@ -503,17 +488,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "마감 - 망치 자국"), ("MatFinish Raw", "마감 - 원재료"), ("MatFinish Sanded", "마감 - 샌딩"), - ("Match", "매칭"), ("Material", "머티리얼"), ("Material ball", "머티리얼 볼"), ("Material finish", "머티리얼 마감"), ("Materials", "머티리얼"), - ("Max frontal distance", "최대 전방 거리"), - ("Max occluder distance", "최대 차폐물 거리"), - ("Max rear distance", "최대 후방 거리"), ("Maximum", "최대"), ("Mesh fill", "메시 채우기"), - ("Mesh map bakers", "메시 맵 베이커"), ("Mesh map: {map}", "메시 맵: {map}"), ("Mesh maps", "메시 맵"), ("Mesh maps baked", "메시 맵 베이크 완료"), @@ -522,9 +502,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "중간 영역"), ("Minimum", "최소"), ("Minimum size (%)", "최소 크기 (%)"), - ("Mirror X", "미러 X"), - ("Mirror Y", "미러 Y"), - ("Mirror Z", "미러 Z"), ("Missing (bake to create)", "없음 (베이크하여 생성)"), ("Mixed AO", "혼합 AO"), ("Mode", "모드"), @@ -552,7 +529,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "노이즈 양"), ("Noise scale", "노이즈 스케일"), ("None", "없음"), - ("None: the low poly is its own high poly.", "없음: 로우 폴리를 하이 폴리로 사용합니다."), ("Normal", "노멀"), ("Normal DirectX", "노멀 DirectX"), ("Normal Invert", "노멀 반전"), @@ -581,7 +557,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Offset {axis}", "오프셋 {axis}"), ("Offsets the textures by the height channel, at the height to normal strength", "높이-노멀 변환 강도로 높이 채널에 따라 텍스처를 오프셋합니다"), ("On", "켜기"), - ("One color per mesh part.", "메시 파트마다 하나의 색상을 사용합니다."), ("Opacity", "불투명도"), ("Open sample project...", "샘플 프로젝트 열기..."), ("Open...", "열기..."), @@ -592,15 +567,16 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "궤도 회전"), ("Orthographic", "직교"), + ("Perspective", "원근"), ("Output directory", "출력 디렉터리"), ("Output high", "출력 상한"), ("Output low", "출력 하한"), - ("Output size", "출력 크기"), ("Output template", "출력 템플릿"), ("Output templates", "출력 템플릿"), ("Overlay", "오버레이"), ("Overlay opacity", "오버레이 불투명도"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 메탈릭 러프니스 (TextureCraft)"), + ("Pick color", "색 고르기"), ("PNG image", "PNG 이미지"), ("Padding", "패딩"), ("Paint", "페인트"), @@ -610,7 +586,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "메시에 칠하여 이 마스크를 편집합니다. 회색은 머티리얼 탭의 마스크 값을 사용하세요.", ), - ("Paint the path with the brush (Enter)", "브러시로 패스를 칠합니다 (Enter)"), ("Paint with the current tool", "현재 도구로 페인팅"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -629,7 +604,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "레이어 붙여넣기"), ("Path", "패스"), ("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "패스: 클릭으로 점 추가, 드래그로 이동, Enter로 적용, Esc로 취소"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "패스: 클릭으로 점 추가, 곡선 클릭으로 점 삽입, 드래그로 이동, Enter로 적용, Esc로 취소", + ), ("Pattern scale", "패턴 스케일"), ("Perlin noise", "펄린 노이즈"), ("Pick focus in the viewport", "뷰포트에서 초점 선택"), @@ -645,7 +623,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "위치 지터"), ("Posterize", "포스터화"), ("Press a key...", "키를 누르세요..."), - ("Procedurals", "프로시저럴"), ("Project", "프로젝트"), ("Project Configuration...", "프로젝트 구성..."), ("Project opened", "프로젝트를 열었습니다"), @@ -656,8 +633,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "퀵 마스크"), ("Quit", "종료"), - ("Radial axis", "방사형 축"), - ("Radial copies", "방사형 복사본"), ("Radius (texels at 2K)", "반경 (2K 기준 텍셀)"), ("RENDERING", "렌더링"), ("Range", "범위"), @@ -669,7 +644,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "다시 실행"), ("Reimport mesh", "메시 다시 가져오기"), - ("Relative to the bounding box diagonal.", "바운딩 박스 대각선 기준입니다."), ("Remove", "제거"), ("Remove channel", "채널 제거"), ("Remove effect", "이펙트 제거"), @@ -677,9 +651,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "레이어 제거"), ("Remove layer(s)", "레이어 제거"), ("Remove mask", "마스크 제거"), + ("Remove point", "점 제거"), ("Remove resource", "리소스 제거"), - ("Remove the cage", "케이지를 제거합니다"), - ("Remove the path (Esc)", "패스를 제거합니다 (Esc)"), ("Remove the shortcut", "단축키를 제거합니다"), ("Remove this output", "이 출력을 제거합니다"), ("Remove unused resources...", "사용하지 않는 리소스 제거..."), @@ -692,25 +665,17 @@ 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", "라이브러리 폴더를 다시 검색합니다"), + ("Reset", "초기화"), ("Reset UI", "UI 초기화"), ("Reset all", "모두 초기화"), + ("Reset to defaults", "기본값으로 초기화"), ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), - ("Return to painting mode", "페인팅 모드로 돌아가기"), ("Return to this step", "이 단계로 돌아가기"), - ("Auto-rebake", "자동 다시 베이크"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "베이크 설정, 로우 폴리 또는 하이 폴리가 바뀌면 이 맵을 자동으로 다시 베이크합니다", - ), ("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"), ("Rotation", "회전"), ("Rotation (degrees)", "회전 (도)"), @@ -738,9 +703,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "스크래치"), ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), - ("Search all assets", "모든 에셋 검색"), + ("Search", "검색"), ("Search commands or keys", "명령 또는 키 검색"), - ("Secondary rays", "보조 광선"), ("Seed", "시드"), ("Select a layer", "레이어를 선택하세요"), ("Select an output template", "출력 템플릿을 선택하세요"), @@ -805,16 +769,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "서브샘플링 8x8"), ("Subsurface scattering", "서브서피스 스캐터링"), ("Subtract", "빼기"), - ("Symmetry (X)", "대칭 (X)"), - ("Symmetry (Y)", "대칭 (Y)"), ("Tangent | Wrap", "탄젠트 | 랩"), - ("Tangent-space normals of the high definition meshes.", "고해상도 메시의 탄젠트 공간 노멀입니다."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "시간적 안티앨리어싱 (3D 뷰가 정지해 있을 때 품질을 높임)"), - ("Texture Set List", "텍스처 세트 목록"), + ("Texture Sets", "텍스처 세트"), ("Texture Set Settings", "텍스처 세트 설정"), ("Texture resolution", "텍스처 해상도"), ("Texture set channels", "텍스처 세트 채널"), - ("Texture set list", "텍스처 세트 목록"), ("Texture sets", "텍스처 세트"), ("TextureCraft had to close:", "TextureCraft를 종료해야 했습니다:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - 메탈릭 러프니스"), @@ -859,14 +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 low poly mesh as high poly mesh", "로우 폴리 메시를 하이 폴리 메시로 사용"), ("Use the control channel or `texturecraft-cli render` for screenshots", "스크린샷은 제어 채널 또는 `texturecraft-cli render`를 사용하세요"), ("Value", "값"), ("Version {version}", "버전 {version}"), @@ -887,15 +846,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "휠 / Alt + 오른쪽 드래그"), ("White", "흰색"), - ("White where the surface faces the direction, black where it faces away.", "표면이 해당 방향을 향하면 흰색, 반대쪽을 향하면 검은색입니다."), ("Width", "너비"), ("Width (texels at 2K)", "폭 (2K 기준 텍셀)"), ("Window", "창"), ("Wood grain", "나뭇결"), ("Works in texture space, like the blur: it does not cross UV seams.", "블러와 마찬가지로 텍스처 공간에서 작동하므로 UV 경계를 넘지 않습니다."), - ("World space direction", "월드 공간 방향"), - ("World space normal", "월드 공간 노멀"), - ("World-space normals of the high poly (or the low poly).", "하이 폴리(또는 로우 폴리)의 월드 공간 노멀입니다."), + ("World Space Normal", "월드 공간 노멀"), ("Yellow / blue", "노랑 / 파랑"), ("Zoom", "확대/축소"), ("a missing layer", "누락된 레이어"), @@ -932,7 +888,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: 선택한 레이어 위에 추가합니다 (또는 레이어 스택이나 뷰포트로 드래그)", ), - ("{name} ({n} triangles)", "{name} (삼각형 {n}개)"), ("{name} copy", "{name} 사본"), ("{n} bits", "{n}비트"), ( @@ -943,25 +898,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (스케일 {scale}, 시드 {seed})"), ("Template name", "템플릿 이름"), ("Save current project as template", "현재 프로젝트를 템플릿으로 저장"), - ("Spread angle", "확산 각도"), ("Distribution", "분포"), ("Cosine", "코사인"), ("Uniform", "균일"), - ("Ignore backface", "뒷면 무시"), - ("Self occlusion", "자기 차폐"), - ("Only same mesh name", "같은 메시 이름만"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "벤트 노멀 광선은 앰비언트 오클루전의 차폐물 설정을 따릅니다."), - ("Sampling radius", "샘플링 반경"), - ("0 picks a radius from the output size.", "0이면 출력 크기에 따라 반경을 정합니다."), - ("Encoding", "인코딩"), - ("Signed (-1..1)", "부호 있음 (-1..1)"), - ("Positive (0..1)", "양수 (0..1)"), ("Normalization", "정규화"), - ("Bounding box", "바운딩 박스"), - ("Bounding sphere", "바운딩 스피어"), - ("Position normalized to the low poly's bounding box or sphere.", "로우 폴리의 바운딩 박스 또는 스피어로 정규화한 위치입니다."), - ("Base colors (textures, factors) and vertex colors of the high definition meshes.", "고해상도 메시의 베이스 컬러(텍스처, 계수)와 버텍스 컬러입니다."), - ("White where the high poly covers the low poly, times its alpha.", "하이 폴리가 로우 폴리를 덮는 곳은 흰색이며, 알파가 곱해집니다."), // Settings › Interface: brightness and accent color. ("Brightness", "밝기"), ("Dark", "어둡게"), @@ -986,8 +926,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), ("Brushes", "브러시 목록"), - ("My brushes", "내 브러시"), - ("Use this brush (keeps its size)", "이 브러시 사용 (크기 유지)"), ("Brush name", "브러시 이름"), ("Save current brush", "현재 브러시 저장"), ("Start window", "시작 창"), @@ -1008,12 +946,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "저장되지 않은 변경 사항"), ("Don't save", "저장 안 함"), ("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"), - ("Skew correction", "스큐 보정"), - ("Paint skew in the 2D view", "2D 뷰에서 스큐 칠하기"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "2D 뷰에서 드래그하여 베이크 레이가 기본 노멀 쪽으로 향하는 위치를 칠합니다. 값 0으로 칠하면 지워집니다", - ), ("Radius", "반경"), ("Remove skew correction", "스큐 보정 제거"), ("Twill weave", "능직"), @@ -1033,4 +965,197 @@ pub const TABLE: &[(&str, &str)] = &[ "MaterialCraft에서 열었습니다. 변경 내용을 가져오려면 그곳에서 파일 > TextureCraft로 보내기를 사용하세요", ), ("Parameters change in the desktop app, with MaterialCraft installed", "매개변수는 MaterialCraft가 설치된 데스크톱 앱에서 바꿀 수 있습니다"), + ("Add High-Poly Meshes", "하이 폴리 메시 추가"), + ("All", "전체"), + ("Apply Diffusion", "확산 적용"), + ("Attenuation", "감쇠"), + ("Auto Tonemapping", "자동 톤 매핑"), + ("Average Normals", "노멀 평균화"), + ("BBox", "경계 상자"), + ("BSphere", "경계 구"), + ("Mesh Map Bakers", "메시 맵 베이커"), + ("Common Settings", "공통 설정"), + ("Mesh Map Settings", "메시 맵 설정"), + ("Check All", "모두 선택"), + ("No Parameters", "매개변수 없음"), + ("Bake Selected Textures ({n})", "선택한 텍스처 베이크 ({n})"), + ("By Mesh Name", "메시 이름으로"), + ("Cage", "케이지"), + ("Cage Scene", "케이지 장면"), + ("Cage Type", "케이지 유형"), + ("Color Generator", "색상 생성기"), + ("Color Source", "색상 소스"), + ("Common Parameters", "공통 매개변수"), + ("Custom File", "사용자 지정 파일"), + ("Details", "세부 사항"), + ("Dilation Width", "확장 폭"), + ("Distance-Based", "거리 기반"), + ("Edge Contrast", "가장자리 대비"), + ("Edge Distance", "가장자리 거리"), + ("Edge Protection", "가장자리 보호"), + ("Enable Seams", "이음새 활성화"), + ("File ID", "파일 ID"), + ("Full Scene", "전체 장면"), + ("Generate from Mesh", "메시에서 생성"), + ("Generate from Normal Map", "노멀 맵에서 생성"), + ("Ground Plane", "바닥 평면"), + ("Ground Plane Offset", "바닥 평면 오프셋"), + ("High Poly Mesh Suffix", "하이 폴리 메시 접미사"), + ("High Poly Scene", "하이 폴리 장면"), + ("High-Poly Parameters", "하이 폴리 매개변수"), + ("Hue Shift", "색조 이동"), + ("Ignore Backface", "뒷면 무시"), + ("Ignore Backface Suffix", "뒷면 무시 접미사"), + ("Include in Bake", "베이크에 포함"), + ("Load Cage", "케이지 불러오기"), + ("Lock Output Size", "출력 크기 잠금"), + ("Low Poly Mesh Suffix", "로우 폴리 메시 접미사"), + ("Manual", "수동"), + ("Material Color", "재질 색상"), + ("Max Frontal Distance", "최대 전방 거리"), + ("Max Occluder Distance", "최대 차폐물 거리"), + ("Max Rear Distance", "최대 후방 거리"), + ("Mesh ID", "메시 ID"), + ("Method", "방식"), + ("Min Occluder Distance", "최소 차폐 거리"), + ("Never", "안 함"), + ("No High-Poly Meshes", "하이 폴리 메시 없음"), + ("Normalization Scale", "정규화 범위"), + ("Normalization Type", "정규화 유형"), + ("Only Same Mesh Name", "같은 메시 이름만"), + ("Output Size", "출력 크기"), + ("Match", "일치"), + ("Skew Correction Method", "왜곡 보정 방법"), + ("Mesh Normals Based", "메시 법선 기반"), + ("Face Normals Based", "면 법선 기반"), + ("Reset Painted Cage", "페인트한 케이지 초기화"), + ("Paint Cage", "케이지 페인트"), + ("Paint Skew Correction", "기울기 보정 페인트"), + ("Per Material", "재질별"), + ("Random", "무작위"), + ("Relative to Bounding Box", "경계 상자 기준"), + ("Relative to Low Mesh", "로우 폴리 메시 기준"), + ("Relative to Min/Max", "최소/최대 기준"), + ("Relative to Ray Distances", "광선 거리 기준"), + ("Remove Cage", "케이지 제거"), + ("Remove Skew Correction", "스큐 보정 제거"), + ("Restore Defaults", "기본값 복원"), + ("Return to Painting Mode", "페인팅 모드로 돌아가기"), + ("Sampling Radius", "샘플링 반경"), + ("Scaling Divisor", "배율 나눗수"), + ("Seams Intensity", "이음새 강도"), + ("Secondary Rays", "보조 광선"), + ("Self Intersection", "자체 교차"), + ("Self Occlusion", "자기 차폐"), + ("Skew Correction", "스큐 보정"), + ("Smooth", "부드러움"), + ("Spread Angle", "확산 각도"), + ("Submesh", "하위 메시"), + ("Use Low Poly Mesh as High Poly Mesh", "로우 폴리 메시를 하이 폴리 메시로 사용"), + ("Value Bounds Max", "값 상한"), + ("Value Bounds Min", "값 하한"), + ("Vertex Color", "정점 색상"), + ("Select the layer content", "레이어 내용 선택"), + ("Paint layer", "페인트 레이어"), + ("Fill layer", "채우기 레이어"), + ("1 effect", "이펙트 1개"), + ("{count} effects", "이펙트 {count}개"), + ("Mask effects", "마스크 이펙트"), + ("Content effects", "콘텐츠 이펙트"), + ("Fold or unfold these effects", "이 이펙트 접기/펼치기"), + ("Remove resolution override", "해상도 재정의 제거"), + ("Texture set resolution", "텍스처 세트 해상도"), + ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Angle span", "각도 범위"), + ("Axis position", "축 위치"), + ("Count", "개수"), + ("Display", "표시"), + ("Hide while painting", "페인팅 중 숨기기"), + ("Manipulator size", "조작기 크기"), + ("Mirror symmetry", "미러 대칭"), + ("Radial settings", "방사형 설정"), + ("Radial symmetry", "방사형 대칭"), + ("Show axis", "축 표시"), + ("Show axis position manipulator", "축 위치 조작기 표시"), + ("Show cursor", "커서 표시"), + ("Show intersection", "교차선 표시"), + ("Show plane", "평면 표시"), + ("Symmetry", "대칭"), + ("Symmetry color display", "대칭 표시 색상"), + ("Symmetry settings", "대칭 설정"), + ("Type", "유형"), + ("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"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "저장은 나머지 코어와 여유 RAM의 이 비율까지만 사용합니다. 최소 한 개의 코어는 항상 작동합니다.", + ), + ("Max project size on open", "열기 시 최대 프로젝트 크기"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", + ), + ("Filter by type", "유형별 필터"), + ("All libraries", "모든 라이브러리"), + ("Browse folders", "폴더 찾아보기"), + ("Starter assets", "기본 에셋"), + ("Your assets", "내 에셋"), + ("Reset query", "쿼리 초기화"), + ("Refresh", "새로 고침"), + ("Saved searches", "저장된 검색"), + ("Save the current search", "현재 검색 저장"), + ("Delete", "삭제"), + ("Filter by path", "경로별 필터"), + ("Hide non-applicable folders", "해당 없는 폴더 숨기기"), + ("Thumbnail size", "썸네일 크기"), + ("Small", "작게"), + ("Medium", "보통"), + ("Large", "크게"), + ("List", "목록"), + ("Procedurals", "프로시저럴"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 67b4697b..70d68d21 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1,6 +1,17 @@ //! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Fazendo o bake de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Fazendo o bake de {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir o mapa mais recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "A pintura fica em pausa enquanto um bake é exibido. Cancele o bake ou espere ele terminar.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "O que a vista 3D mostra durante o bake: o último mapa concluído, um mapa concluído à escolha ou o material. Mapas ainda não gerados mostram um valor neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), ("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"), ("2D view only", "Apenas vista 2D"), @@ -22,15 +33,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.", @@ -47,7 +49,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Adicionar filtro"), ("Add folder", "Adicionar pasta"), ("Add generator", "Adicionar gerador"), - ("Add high definition meshes", "Adicionar malhas de alta definição"), ("Add levels", "Adicionar níveis"), ("Add mask", "Adicionar máscara"), ("Add mask with color selection", "Adicionar máscara com seleção de cor"), @@ -55,20 +56,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"), ( @@ -83,8 +72,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Também atribuído a {item} ({menu})"), ("Alt + LMB drag", "Alt + arrastar com botão esquerdo"), ("Always", "Sempre"), + ("Ambient Occlusion", "Oclusão de ambiente"), ("Ambient occlusion", "Oclusão de ambiente"), - ("Ambient occlusion intensity", "Intensidade da oclusão de ambiente"), ("Amount", "Quantidade"), ("Anchor point", "Ponto de ancoragem"), ("Anchor: {name}", "Âncora: {name}"), @@ -99,27 +88,25 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Antisserrilhamento"), ("Aperture", "Abertura"), ("Apply", "Aplicar"), - ("Apply to all texture sets", "Aplicar a todos os conjuntos de texturas"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"), ("Autosave every", "Salvar automaticamente a cada"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Salvamentos automáticos, materiais inteligentes, predefinições, modelos e layouts da interface vão para a pasta de dados. Uma nova pasta vale após reiniciar; os arquivos já salvos ficam onde estão.", ), - ("Average normals", "Normais médias"), ("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"), ( "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Faça o bake dos mapas de malha (F8) para geradores baseados em curvatura, AO e espessura.", ), - ("Bake selected textures ({n})", "Fazer bake das texturas selecionadas ({n})"), - ("Bake with \"Bake selected textures\"", "Faça o bake com \"Fazer bake das texturas selecionadas\""), ("Baked Lighting", "Iluminação pré-calculada"), ("Baking", "Bake"), ("Base color", "Cor base"), @@ -130,10 +117,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Cor base, Metálico, Rugosidade e Nível especular."), ("Based on each texture set's size", "Com base no tamanho de cada conjunto de texturas"), ("Basic settings", "Configurações básicas"), - ("Bent normals", "Normais curvadas"), + ("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"), @@ -148,9 +134,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Embutido (somente leitura): duplique-o para editar"), ("Built-in templates are read-only: duplicate one to edit it", "Os modelos embutidos são somente leitura: duplique um para editá-lo"), ("Built-in: {mesh}", "Embutida: {mesh}"), - ("By mesh name", "Por nome da malha"), ("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"), @@ -159,6 +154,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"), @@ -180,7 +176,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Equilíbrio de cores"), ("Color burn", "Superexposição de cor"), ("Color dodge", "Subexposição de cor"), - ("Color map", "Mapa de cor"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Cor da luz que viaja sob a superfície (cada canal vai tão longe quanto seu valor)", @@ -194,7 +189,6 @@ pub const TABLE: &[(&str, &str)] = &[ "As cores são lidas como cinza. Adicione um efeito de níveis ou desfoque acima para ajustar o resultado.", ), ("Combine with the layer's height", "Combinar com a altura da camada"), - ("Common parameters", "Parâmetros comuns"), ("Compare mask", "Máscara de comparação"), ("Compositing", "Composição"), ("Constant", "Constante"), @@ -207,7 +201,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar camada(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"), - ("Copy these bake settings to every texture set", "Copiar estas configurações de bake para todos os conjuntos de texturas"), ("Copy to all texture sets", "Copiar para todos os conjuntos de texturas"), ("Copy what the texture set shows", "Copiar o que o conjunto de texturas exibe"), ("Couldn't encode the render", "Não foi possível codificar a renderização"), @@ -258,8 +251,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatação + cor de fundo padrão"), ("Dilation + transparent", "Dilatação + transparente"), ("Dilation infinite", "Dilatação infinita"), - ("Dilation width", "Largura da dilatação"), - ("Direction {axis}", "Direção {axis}"), ("DirectX normal map", "Mapa normal DirectX"), ("Dirt", "Sujeira"), ("Disable", "Desativado"), @@ -342,10 +333,14 @@ 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"), ("Fingerprints", "Impressões digitais"), + ("Enter a finite number", "Insira um número finito"), + ("Double-click or press Enter to edit", "Clique duas vezes ou pressione Enter para editar"), + ("Fit the input range to the histogram", "Ajustar o intervalo de entrada ao histograma"), ("Flatten layer", "Achatar camada"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -363,11 +358,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Para todo o projeto: como as imagens de mapa normal usadas como mapas de malha são lidas (atribua-as de novo após uma mudança), e o padrão para exportação", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Livre e de código aberto (MIT OR Apache-2.0), escrito em Rust."), - ("From normal map", "Do mapa normal"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Do mapa normal: curvatura dos detalhes do mapa normal com bake em vez da malha.", - ), ("From template", "Do modelo"), ("From template / project", "Do modelo / projeto"), ("Full", "Completa"), @@ -407,12 +397,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Ajuda"), ("Hide UI", "Ocultar interface"), ("High", "Alto"), - ("High definition meshes", "Malhas de alta definição"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Altura do high poly entre as distâncias máxima traseira (preto) e máxima frontal (branco).", - ), - ("High poly mesh suffix", "Sufixo da malha high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Realces"), ("Histogram Range", "Intervalo do histograma"), @@ -443,7 +427,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "Importar HDR..."), ("Import a template (.json)", "Importar um modelo (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "Importe uma imagem (Arquivo > Importar recursos) para projetá-la na malha."), - ("Import images to use them in fills and masks", "Importe imagens para usá-las em preenchimentos e máscaras"), ("Import resources...", "Importar recursos..."), ("Import MaterialX material...", "Importar material MaterialX..."), ("MaterialX materials", "Materiais MaterialX"), @@ -465,6 +448,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverter"), ("Invert mask", "Inverter máscara"), ("Invert mask background", "Inverter fundo da máscara"), + ("Invert mask value", "Inverter valor da máscara"), ("Invert quick mask", "Inverter máscara rápida"), ("Jitters", "Variações"), ("Join the ArtCraft community on Discord", "Participe da comunidade ArtCraft no Discord"), @@ -481,7 +465,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memória das camadas: {mb} MB"), ("Layers", "Camadas"), ("Lazy mouse", "Lazy mouse"), - ("Lazy mouse and symmetry", "Lazy mouse e simetria"), ("Lazy mouse distance", "Distância do lazy mouse"), ("Leather grain", "Grão de couro"), ("Lens size: how quickly things blur away from the focus distance", "Tamanho da lente: quão rápido os objetos desfocam fora da distância de foco"), @@ -497,17 +480,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Luz linear"), ("List of exports", "Lista de exportações"), ("Load UI Layout", "Carregar layout da interface"), - ("Load a cage (the low poly, inflated)", "Carregar uma cage (o low poly, inflado)"), ("Loaded UI layout {path}", "Layout da interface carregado de {path}"), ("Log", "Log"), ("Low", "Baixo"), - ("Low poly mesh suffix", "Sufixo da malha low poly"), ("Luminosity", "Luminosidade"), ("MMB drag / Alt + MMB", "Arrastar com botão do meio / Alt + botão do meio"), ("Made by the ArtCraft team and community.", "Feito pela equipe e pela comunidade ArtCraft."), ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principal"), ("Marble veins", "Veios de mármore"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscara: Desgaste de bordas"), ("Mask value (gray)", "Valor da máscara (cinza)"), ("Mask with height", "Mascarar com altura"), @@ -515,17 +497,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Martelado"), ("MatFinish Raw", "MatFinish Bruto"), ("MatFinish Sanded", "MatFinish Lixado"), - ("Match", "Correspondência"), ("Material", "Material"), ("Material ball", "Esfera de material"), ("Material finish", "Acabamento de material"), ("Materials", "Materiais"), - ("Max frontal distance", "Distância frontal máxima"), - ("Max occluder distance", "Distância máxima do oclusor"), - ("Max rear distance", "Distância traseira máxima"), ("Maximum", "Máximo"), ("Mesh fill", "Preenchimento de malha"), - ("Mesh map bakers", "Bakers de mapas de malha"), ("Mesh map: {map}", "Mapa de malha: {map}"), ("Mesh maps", "Mapas de malha"), ("Mesh maps baked", "Bake dos mapas de malha concluído"), @@ -534,9 +511,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Tons médios"), ("Minimum", "Mínimo"), ("Minimum size (%)", "Tamanho mínimo (%)"), - ("Mirror X", "Espelhar X"), - ("Mirror Y", "Espelhar Y"), - ("Mirror Z", "Espelhar Z"), ("Missing (bake to create)", "Ausente (faça o bake para criar)"), ("Mixed AO", "AO combinada"), ("Mode", "Modo"), @@ -564,7 +538,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Quantidade de ruído"), ("Noise scale", "Escala do ruído"), ("None", "Nenhum"), - ("None: the low poly is its own high poly.", "Nenhuma: o low poly é o seu próprio high poly."), ("Normal", "Normal"), ("Normal DirectX", "Normal DirectX"), ("Normal Invert", "Inverter normal"), @@ -596,7 +569,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Desloca as texturas pelo canal de altura, com a intensidade de altura para normal", ), ("On", "Ligado"), - ("One color per mesh part.", "Uma cor por parte da malha."), ("Opacity", "Opacidade"), ("Open sample project...", "Abrir projeto de exemplo..."), ("Open...", "Abrir..."), @@ -607,15 +579,16 @@ 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"), - ("Output size", "Tamanho de saída"), ("Output template", "Modelo de saída"), ("Output templates", "Modelos de saída"), ("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"), @@ -625,7 +598,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinte na malha para editar esta máscara. Use o valor de máscara da aba Material para cinza.", ), - ("Paint the path with the brush (Enter)", "Pintar o caminho com o pincel (Enter)"), ("Paint with the current tool", "Pintar com a ferramenta atual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -647,7 +619,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Colar camada(s)"), ("Path", "Caminho"), ("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Caminho: clicar adiciona um ponto, arrastar o move, Enter aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Caminho: clicar adiciona um ponto, clicar na curva insere um, arrastar o move, Enter aplica, Esc cancela", + ), ("Pattern scale", "Escala do padrão"), ("Perlin noise", "Ruído Perlin"), ("Pick focus in the viewport", "Escolher o foco na viewport"), @@ -663,7 +638,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variação de posição"), ("Posterize", "Posterizar"), ("Press a key...", "Pressione uma tecla..."), - ("Procedurals", "Procedurais"), ("Project", "Projeto"), ("Project Configuration...", "Configuração do projeto..."), ("Project opened", "Projeto aberto"), @@ -674,8 +648,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Um quarto"), ("Quick mask", "Máscara rápida"), ("Quit", "Sair"), - ("Radial axis", "Eixo radial"), - ("Radial copies", "Cópias radiais"), ("Radius (texels at 2K)", "Raio (texels em 2K)"), ("RENDERING", "RENDERIZAÇÃO"), ("Range", "Intervalo"), @@ -687,7 +659,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Refazer"), ("Reimport mesh", "Reimportar malha"), - ("Relative to the bounding box diagonal.", "Relativo à diagonal da caixa delimitadora."), ("Remove", "Remover"), ("Remove channel", "Remover canal"), ("Remove effect", "Remover efeito"), @@ -695,9 +666,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Remover camada"), ("Remove layer(s)", "Remover camada(s)"), ("Remove mask", "Remover máscara"), + ("Remove point", "Remover ponto"), ("Remove resource", "Remover recurso"), - ("Remove the cage", "Remover a cage"), - ("Remove the path (Esc)", "Remover o caminho (Esc)"), ("Remove the shortcut", "Remover o atalho"), ("Remove this output", "Remover esta saída"), ("Remove unused resources...", "Remover recursos não usados..."), @@ -710,25 +680,17 @@ 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"), + ("Reset", "Redefinir"), ("Reset UI", "Redefinir interface"), ("Reset all", "Redefinir tudo"), + ("Reset to defaults", "Redefinir para o padrão"), ("Reset to {shortcut}", "Redefinir para {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), - ("Return to painting mode", "Voltar ao modo de pintura"), ("Return to this step", "Voltar a esta etapa"), - ("Auto-rebake", "Refazer bake automaticamente"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Refaz o bake deste mapa automaticamente quando as configurações de bake, a malha low poly ou as high poly mudam", - ), ("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"), ("Rotation", "Rotação"), ("Rotation (degrees)", "Rotação (graus)"), @@ -756,9 +718,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arranhões"), ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), - ("Search all assets", "Pesquisar em todos os recursos"), + ("Search", "Pesquisar"), ("Search commands or keys", "Pesquisar comandos ou teclas"), - ("Secondary rays", "Raios secundários"), ("Seed", "Semente"), ("Select a layer", "Selecione uma camada"), ("Select an output template", "Selecione um modelo de saída"), @@ -823,16 +784,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Subamostragem 8x8"), ("Subsurface scattering", "Dispersão subsuperficial"), ("Subtract", "Subtração"), - ("Symmetry (X)", "Simetria (X)"), - ("Symmetry (Y)", "Simetria (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), - ("Tangent-space normals of the high definition meshes.", "Normais em espaço tangente das malhas de alta definição."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antisserrilhamento temporal (refina a vista 3D enquanto está parada)"), - ("Texture Set List", "Lista de conjuntos de texturas"), + ("Texture Sets", "Conjuntos de texturas"), ("Texture Set Settings", "Configurações do conjunto de texturas"), ("Texture resolution", "Resolução das texturas"), ("Texture set channels", "Canais do conjunto de texturas"), - ("Texture set list", "Lista de conjuntos de texturas"), ("Texture sets", "Conjuntos de texturas"), ("TextureCraft had to close:", "O TextureCraft precisou ser fechado:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metálico Rugosidade"), @@ -877,17 +834,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 low poly mesh as high poly mesh", "Usar a malha low poly como malha high poly"), ("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}"), @@ -908,18 +861,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Roda do mouse / Alt + arrastar com botão direito"), ("White", "Branco"), - ( - "White where the surface faces the direction, black where it faces away.", - "Branco onde a superfície está voltada para a direção, preto onde está voltada para o lado oposto.", - ), ("Width", "Largura"), ("Width (texels at 2K)", "Largura (texels em 2K)"), ("Window", "Janela"), ("Wood grain", "Veio de madeira"), ("Works in texture space, like the blur: it does not cross UV seams.", "Funciona no espaço de textura, como o desfoque: não atravessa costuras de UV."), - ("World space direction", "Direção no espaço do mundo"), - ("World space normal", "Normal no espaço do mundo"), - ("World-space normals of the high poly (or the low poly).", "Normais no espaço do mundo do high poly (ou do low poly)."), + ("World Space Normal", "Normal no espaço do mundo"), ("Yellow / blue", "Amarelo / azul"), ("Zoom", "Zoom"), ("a missing layer", "uma camada ausente"), @@ -956,7 +903,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: adicionar acima da camada selecionada (ou arraste-o para a pilha de camadas ou para a viewport)", ), - ("{name} ({n} triangles)", "{name} ({n} triângulos)"), ("{name} copy", "Cópia de {name}"), ("{n} bits", "{n} bits"), ( @@ -967,31 +913,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (escala {scale}, semente {seed})"), ("Template name", "Nome do modelo"), ("Save current project as template", "Salvar o projeto atual como modelo"), - ("Spread angle", "Ângulo de dispersão"), ("Distribution", "Distribuição"), ("Cosine", "Cosseno"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignorar faces traseiras"), - ("Self occlusion", "Autooclusão"), - ("Only same mesh name", "Somente o mesmo nome de malha"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Os raios das normais curvadas seguem os ajustes de oclusores da oclusão de ambiente.", - ), - ("Sampling radius", "Raio de amostragem"), - ("0 picks a radius from the output size.", "0 escolhe um raio pelo tamanho de saída."), - ("Encoding", "Codificação"), - ("Signed (-1..1)", "Com sinal (-1..1)"), - ("Positive (0..1)", "Positivo (0..1)"), ("Normalization", "Normalização"), - ("Bounding box", "Caixa delimitadora"), - ("Bounding sphere", "Esfera delimitadora"), - ("Position normalized to the low poly's bounding box or sphere.", "Posição normalizada pela caixa ou esfera delimitadora do low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Cores base (texturas, fatores) e cores de vértice das malhas de alta definição.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Branco onde o high poly cobre o low poly, multiplicado pelo seu alfa."), // Settings › Interface: brightness and accent color. ("Brightness", "Brilho"), ("Dark", "Escuro"), @@ -1016,8 +941,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), ("Brushes", "Pincéis"), - ("My brushes", "Meus pincéis"), - ("Use this brush (keeps its size)", "Usar este pincel (mantém o tamanho)"), ("Brush name", "Nome do pincel"), ("Save current brush", "Salvar o pincel atual"), ("Start window", "Janela inicial"), @@ -1038,12 +961,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Alterações não salvas"), ("Don't save", "Não salvar"), ("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"), - ("Skew correction", "Correção de inclinação"), - ("Paint skew in the 2D view", "Pintar a inclinação na vista 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Arraste na vista 2D para pintar onde os raios do bake se voltam para a normal base; pinte com valor 0 para apagar", - ), ("Radius", "Raio"), ("Remove skew correction", "Remover a correção de inclinação"), ("Twill weave", "Tecido sarja"), @@ -1063,4 +980,200 @@ pub const TABLE: &[(&str, &str)] = &[ "Aberto no MaterialCraft: use lá Arquivo > Enviar para o TextureCraft para trazer suas alterações", ), ("Parameters change in the desktop app, with MaterialCraft installed", "Os parâmetros mudam no app para desktop, com o MaterialCraft instalado"), + ("Add High-Poly Meshes", "Adicionar malhas de alta resolução"), + ("All", "Todos"), + ("Apply Diffusion", "Aplicar difusão"), + ("Attenuation", "Atenuação"), + ("Auto Tonemapping", "Mapeamento tonal automático"), + ("Average Normals", "Normais médias"), + ("BBox", "Caixa delimitadora"), + ("BSphere", "Esfera delimitadora"), + ("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"), + ("Cage Scene", "Cena da gaiola"), + ("Cage Type", "Tipo de gaiola"), + ("Color Generator", "Gerador de cores"), + ("Color Source", "Origem da cor"), + ("Common Parameters", "Parâmetros comuns"), + ("Custom File", "Arquivo personalizado"), + ("Details", "Detalhes"), + ("Dilation Width", "Largura da dilatação"), + ("Distance-Based", "Baseada em distância"), + ("Edge Contrast", "Contraste das arestas"), + ("Edge Distance", "Distância das arestas"), + ("Edge Protection", "Proteção das arestas"), + ("Enable Seams", "Ativar costuras"), + ("File ID", "ID do arquivo"), + ("Full Scene", "Cena inteira"), + ("Generate from Mesh", "Gerar a partir da malha"), + ("Generate from Normal Map", "Gerar a partir do mapa de normais"), + ("Ground Plane", "Plano do solo"), + ("Ground Plane Offset", "Deslocamento do solo"), + ("High Poly Mesh Suffix", "Sufixo da malha high poly"), + ("High Poly Scene", "Cena de alta resolução"), + ("High-Poly Parameters", "Parâmetros de alta resolução"), + ("Hue Shift", "Deslocamento de matiz"), + ("Ignore Backface", "Ignorar faces traseiras"), + ("Ignore Backface Suffix", "Sufixo para ignorar faces traseiras"), + ("Include in Bake", "Incluir no bake"), + ("Load Cage", "Carregar gaiola"), + ("Lock Output Size", "Bloquear tamanho de saída"), + ("Low Poly Mesh Suffix", "Sufixo da malha low poly"), + ("Manual", "Manual"), + ("Material Color", "Cor do material"), + ("Max Frontal Distance", "Distância frontal máxima"), + ("Max Occluder Distance", "Distância máxima do oclusor"), + ("Max Rear Distance", "Distância traseira máxima"), + ("Mesh ID", "ID da malha"), + ("Method", "Método"), + ("Min Occluder Distance", "Distância mínima do oclusor"), + ("Never", "Nunca"), + ("No High-Poly Meshes", "Nenhuma malha de alta resolução"), + ("Normalization Scale", "Escala de normalização"), + ("Normalization Type", "Tipo de normalização"), + ("Only Same Mesh Name", "Somente o mesmo nome de malha"), + ("Output Size", "Tamanho de saída"), + ("Match", "Correspondência"), + ("Skew Correction Method", "Método de Correção de Distorção"), + ("Mesh Normals Based", "Baseado nas Normais da Malha"), + ("Face Normals Based", "Baseado nas Normais das Faces"), + ("Reset Painted Cage", "Redefinir Gaiola Pintada"), + ("Paint Cage", "Pintar gaiola"), + ("Paint Skew Correction", "Pintar correção de inclinação"), + ("Per Material", "Por material"), + ("Random", "Aleatório"), + ("Relative to Bounding Box", "Relativo à caixa delimitadora"), + ("Relative to Low Mesh", "Relativo à malha de baixa resolução"), + ("Relative to Min/Max", "Relativo ao mínimo/máximo"), + ("Relative to Ray Distances", "Relativo às distâncias dos raios"), + ("Remove Cage", "Remover gaiola"), + ("Remove Skew Correction", "Remover a correção de inclinação"), + ("Restore Defaults", "Restaurar padrões"), + ("Return to Painting Mode", "Voltar ao modo de pintura"), + ("Sampling Radius", "Raio de amostragem"), + ("Scaling Divisor", "Divisor de escala"), + ("Seams Intensity", "Intensidade das costuras"), + ("Secondary Rays", "Raios secundários"), + ("Self Intersection", "Autointerseção"), + ("Self Occlusion", "Autooclusão"), + ("Skew Correction", "Correção de inclinação"), + ("Smooth", "Suave"), + ("Spread Angle", "Ângulo de dispersão"), + ("Submesh", "Submalha"), + ("Use Low Poly Mesh as High Poly Mesh", "Usar a malha low poly como malha high poly"), + ("Value Bounds Max", "Limite máximo"), + ("Value Bounds Min", "Limite mínimo"), + ("Vertex Color", "Cor do vértice"), + ("Select the layer content", "Selecionar o conteúdo da camada"), + ("Paint layer", "Camada de pintura"), + ("Fill layer", "Camada de preenchimento"), + ("1 effect", "1 efeito"), + ("{count} effects", "{count} efeitos"), + ("Mask effects", "Efeitos da máscara"), + ("Content effects", "Efeitos do conteúdo"), + ("Fold or unfold these effects", "Recolher ou expandir estes efeitos"), + ("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}"), + ("Angle span", "Amplitude do ângulo"), + ("Axis position", "Posição do eixo"), + ("Count", "Quantidade"), + ("Display", "Exibição"), + ("Hide while painting", "Ocultar ao pintar"), + ("Manipulator size", "Tamanho do manipulador"), + ("Mirror symmetry", "Simetria espelhada"), + ("Radial settings", "Configurações radiais"), + ("Radial symmetry", "Simetria radial"), + ("Show axis", "Mostrar eixo"), + ("Show axis position manipulator", "Mostrar manipulador da posição do eixo"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar interseção"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetria"), + ("Symmetry color display", "Cor de exibição da simetria"), + ("Symmetry settings", "Configurações de simetria"), + ("Type", "Tipo"), + ("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"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Salvar usa os outros núcleos e no máximo esta parte da RAM livre. Pelo menos um núcleo sempre trabalha.", + ), + ("Max project size on open", "Tamanho máximo ao abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", + ), + ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas as bibliotecas"), + ("Browse folders", "Navegar pelas pastas"), + ("Starter assets", "Recursos incluídos"), + ("Your assets", "Seus recursos"), + ("Reset query", "Redefinir consulta"), + ("Refresh", "Atualizar"), + ("Saved searches", "Pesquisas salvas"), + ("Save the current search", "Salvar a pesquisa atual"), + ("Delete", "Excluir"), + ("Filter by path", "Filtrar por caminho"), + ("Hide non-applicable folders", "Ocultar pastas não aplicáveis"), + ("Thumbnail size", "Tamanho da miniatura"), + ("Small", "Pequeno"), + ("Medium", "Médio"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurais"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 73e05b93..0b582484 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1,6 +1,14 @@ //! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "正在烘焙{map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "正在烘焙{map} ({n}/{total}),纹理集 {set}/{sets}"), + ("Follow Newest Map", "跟随最新贴图"), + ("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", "显示烘焙时已暂停绘制。请取消烘焙,或等待其完成。"), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "烘焙过程中 3D 视图显示的内容:最新完成的贴图、任意已完成的贴图,或材质。尚未烘焙的贴图显示中性值。", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), ("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"), ("2D view only", "仅 2D 视图"), @@ -19,12 +27,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)", "添加为贴花(视图中心)"), @@ -38,7 +40,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "添加滤镜"), ("Add folder", "添加文件夹"), ("Add generator", "添加生成器"), - ("Add high definition meshes", "添加高精度网格"), ("Add levels", "添加色阶"), ("Add mask", "添加遮罩"), ("Add mask with color selection", "添加颜色选择遮罩"), @@ -46,14 +47,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 并单击可设置新的源。"), @@ -65,8 +60,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "同时绑定到 {item}({menu})"), ("Alt + LMB drag", "Alt + 左键拖动"), ("Always", "始终"), + ("Ambient Occlusion", "环境光遮蔽"), ("Ambient occlusion", "环境光遮蔽"), - ("Ambient occlusion intensity", "环境光遮蔽强度"), ("Amount", "数量"), ("Anchor point", "锚点"), ("Anchor: {name}", "锚点:{name}"), @@ -81,24 +76,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "抗锯齿"), ("Aperture", "光圈"), ("Apply", "应用"), - ("Apply to all texture sets", "应用到所有纹理集"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), + ("Auto", "自动"), ("Automatic (from the mesh UVs)", "自动(基于网格 UV)"), ("Autosave every", "自动保存间隔"), ( "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "自动保存、智能材质、预设、模板和界面布局都保存在数据文件夹中。新文件夹在重启后生效;已保存的文件保留在原处。", ), - ("Average normals", "平均法线"), ("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 和厚度的生成器。"), - ("Bake selected textures ({n})", "烘焙所选纹理({n})"), - ("Bake with \"Bake selected textures\"", "使用“烘焙所选纹理”进行烘焙"), ("Baked Lighting", "烘焙光照"), ("Baking", "烘焙"), ("Base color", "基础色"), @@ -109,10 +102,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "基础色、金属度、粗糙度和高光强度。"), ("Based on each texture set's size", "基于各纹理集的尺寸"), ("Basic settings", "基本设置"), - ("Bent normals", "弯曲法线"), + ("Bent Normals", "弯曲法线"), ("Bevel", "斜角"), ("Black", "黑色"), - ("Blend sharpness", "混合锐度"), ("Blending", "混合"), ("Blending mode of the displayed channel", "所显示通道的混合模式"), ("Blur", "模糊"), @@ -127,9 +119,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "内置(只读):创建副本后即可编辑"), ("Built-in templates are read-only: duplicate one to edit it", "内置模板为只读:创建副本后即可编辑"), ("Built-in: {mesh}", "内置:{mesh}"), - ("By mesh name", "按网格名称"), ("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", "取消笔画"), @@ -138,6 +139,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "通道"), ("Channel source: uniform value, procedural, image or anchor", "通道来源:统一值、程序纹理、图像或锚点"), ("Channels", "通道"), + ("Check for Updates...", "检查更新..."), ("Checker", "棋盘格"), ("Clamp", "钳制"), ("Clear", "清除"), @@ -159,7 +161,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "色彩平衡"), ("Color burn", "颜色加深"), ("Color dodge", "颜色减淡"), - ("Color map", "颜色贴图"), ("Color of the light that travels under the surface (each channel goes as far as its value)", "在表面下传播的光的颜色(各通道的传播距离取决于其值)"), ("Color picker", "拾色器"), ("Color selection", "颜色选择"), @@ -167,7 +168,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Colors near the first shift towards the second, keeping their shading.", "接近第一种颜色的颜色会在保留明暗的同时转向第二种颜色。"), ("Colors read as gray. Add a levels or blur effect above to shape the result.", "颜色按灰度读取。可在上方添加色阶或模糊效果来调整结果。"), ("Combine with the layer's height", "与图层高度合并"), - ("Common parameters", "通用参数"), ("Compare mask", "比较遮罩"), ("Compositing", "合成"), ("Constant", "常量"), @@ -180,7 +180,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "复制自"), ("Copy layer(s)", "复制图层"), ("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"), - ("Copy these bake settings to every texture set", "将这些烘焙设置复制到所有纹理集"), ("Copy to all texture sets", "复制到所有纹理集"), ("Copy what the texture set shows", "复制纹理集显示的内容"), ("Couldn't encode the render", "无法编码渲染结果"), @@ -228,8 +227,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "扩张 + 默认背景色"), ("Dilation + transparent", "扩张 + 透明"), ("Dilation infinite", "无限扩张"), - ("Dilation width", "扩张宽度"), - ("Direction {axis}", "方向 {axis}"), ("DirectX normal map", "DirectX 法线贴图"), ("Dirt", "污垢"), ("Disable", "禁用"), @@ -300,10 +297,14 @@ 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", "细噪波"), ("Fingerprints", "指纹"), + ("Enter a finite number", "请输入有限数值"), + ("Double-click or press Enter to edit", "双击或按 Enter 键编辑"), + ("Fit the input range to the histogram", "使输入范围适合直方图"), ("Flatten layer", "合并图层"), ("Flips the image's green channel, for normal maps made with Y pointing down", "翻转图像的绿色通道,用于 Y 轴朝下制作的法线贴图"), ("Flow", "流量"), @@ -318,8 +319,6 @@ pub const TABLE: &[(&str, &str)] = &[ "整个项目:设为网格贴图的法线贴图图像的读取方式(更改后请重新设置),以及导出的默认值", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "免费开源(MIT OR Apache-2.0),使用 Rust 编写。"), - ("From normal map", "基于法线贴图"), - ("From normal map: curvature of the baked normal map's detail instead of the mesh.", "基于法线贴图:使用烘焙法线贴图细节的曲率,而非网格的曲率。"), ("From template", "基于模板"), ("From template / project", "基于模板 / 项目"), ("Full", "完整"), @@ -359,9 +358,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "帮助"), ("Hide UI", "隐藏界面"), ("High", "高"), - ("High definition meshes", "高精度网格"), - ("High poly height between the max rear (black) and max frontal (white) distances.", "高模高度,介于最大后向(黑)与最大前向(白)距离之间。"), - ("High poly mesh suffix", "高模网格后缀"), ("High poly: {name}", "高模:{name}"), ("Highlights", "高光"), ("Histogram Range", "直方图范围"), @@ -386,7 +382,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "导入 HDR..."), ("Import a template (.json)", "导入模板(.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "导入图像(文件 > 导入资源)以将其投影到网格上。"), - ("Import images to use them in fills and masks", "导入图像以在填充和遮罩中使用"), ("Import resources...", "导入资源..."), ("Import MaterialX material...", "导入 MaterialX 材质..."), ("MaterialX materials", "MaterialX 材质"), @@ -408,6 +403,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "反相"), ("Invert mask", "反相遮罩"), ("Invert mask background", "反相遮罩背景"), + ("Invert mask value", "反相遮罩值"), ("Invert quick mask", "反相快速遮罩"), ("Jitters", "抖动"), ("Join the ArtCraft community on Discord", "加入 Discord 上的 ArtCraft 社区"), @@ -424,7 +420,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "图层内存:{mb} MB"), ("Layers", "图层"), ("Lazy mouse", "平滑跟随"), - ("Lazy mouse and symmetry", "平滑跟随与对称"), ("Lazy mouse distance", "平滑跟随距离"), ("Leather grain", "皮革纹理"), ("Lens size: how quickly things blur away from the focus distance", "镜头大小:远离对焦距离时物体变模糊的速度"), @@ -440,17 +435,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "线性光"), ("List of exports", "导出列表"), ("Load UI Layout", "加载界面布局"), - ("Load a cage (the low poly, inflated)", "加载笼体(膨胀后的低模)"), ("Loaded UI layout {path}", "已加载界面布局 {path}"), ("Log", "日志"), ("Low", "低"), - ("Low poly mesh suffix", "低模网格后缀"), ("Luminosity", "亮度"), ("MMB drag / Alt + MMB", "中键拖动 / Alt + 中键"), ("Made by the ArtCraft team and community.", "由 ArtCraft 团队和社区打造。"), ("Magenta / green", "洋红 / 绿色"), ("Main shader", "主着色器"), ("Marble veins", "大理石纹"), + ("Mask", "遮罩"), ("Mask Editor: Edge wear", "遮罩编辑器:边缘磨损"), ("Mask value (gray)", "遮罩值(灰度)"), ("Mask with height", "用高度遮罩"), @@ -458,17 +452,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "表面处理:锤纹"), ("MatFinish Raw", "表面处理:原始"), ("MatFinish Sanded", "表面处理:砂磨"), - ("Match", "匹配"), ("Material", "材质"), ("Material ball", "材质球"), ("Material finish", "材质表面处理"), ("Materials", "材质"), - ("Max frontal distance", "最大前向距离"), - ("Max occluder distance", "最大遮挡物距离"), - ("Max rear distance", "最大后向距离"), ("Maximum", "最大值"), ("Mesh fill", "网格填充"), - ("Mesh map bakers", "网格贴图烘焙器"), ("Mesh map: {map}", "网格贴图:{map}"), ("Mesh maps", "网格贴图"), ("Mesh maps baked", "网格贴图已烘焙"), @@ -477,9 +466,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "中间调"), ("Minimum", "最小值"), ("Minimum size (%)", "最小尺寸(%)"), - ("Mirror X", "镜像 X"), - ("Mirror Y", "镜像 Y"), - ("Mirror Z", "镜像 Z"), ("Missing (bake to create)", "缺失(烘焙以创建)"), ("Mixed AO", "混合 AO"), ("Mode", "模式"), @@ -504,7 +490,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "噪波量"), ("Noise scale", "噪波缩放"), ("None", "无"), - ("None: the low poly is its own high poly.", "无:低模即为其自身的高模。"), ("Normal", "法线"), ("Normal DirectX", "法线 DirectX"), ("Normal Invert", "法线反转"), @@ -533,7 +518,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Offset {axis}", "偏移 {axis}"), ("Offsets the textures by the height channel, at the height to normal strength", "按高度通道偏移纹理,偏移量取决于高度转法线强度"), ("On", "开"), - ("One color per mesh part.", "每个网格部件一种颜色。"), ("Opacity", "不透明度"), ("Open sample project...", "打开示例项目..."), ("Open...", "打开..."), @@ -544,22 +528,22 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "环绕"), ("Orthographic", "正交"), + ("Perspective", "透视"), ("Output directory", "输出目录"), ("Output high", "输出高"), ("Output low", "输出低"), - ("Output size", "输出尺寸"), ("Output template", "输出模板"), ("Output templates", "输出模板"), ("Overlay", "叠加"), ("Overlay opacity", "叠加层不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 金属度/粗糙度(TextureCraft)"), + ("Pick color", "拾取颜色"), ("PNG image", "PNG 图像"), ("Padding", "扩边"), ("Paint", "绘画"), ("Paint chips", "掉漆"), ("Paint on the mesh to edit the layer content.", "在网格上绘画以编辑图层内容。"), ("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "在网格上绘画以编辑此遮罩。灰度请使用“材质”选项卡中的遮罩值。"), - ("Paint the path with the brush (Enter)", "用笔刷绘制路径(Enter)"), ("Paint with the current tool", "使用当前工具绘画"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -578,7 +562,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "粘贴图层"), ("Path", "路径"), ("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "路径:单击添加点,拖动移动点,Enter 应用,Esc 取消"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "路径:单击添加点,单击曲线插入点,拖动移动点,Enter 应用,Esc 取消", + ), ("Pattern scale", "图案缩放"), ("Perlin noise", "柏林噪波"), ("Pick focus in the viewport", "在视口中拾取焦点"), @@ -594,7 +581,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "位置抖动"), ("Posterize", "色调分离"), ("Press a key...", "请按下一个键..."), - ("Procedurals", "程序纹理"), ("Project", "项目"), ("Project Configuration...", "项目配置..."), ("Project opened", "项目已打开"), @@ -605,8 +591,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "快速遮罩"), ("Quit", "退出"), - ("Radial axis", "径向轴"), - ("Radial copies", "径向副本"), ("Radius (texels at 2K)", "半径(2K 下的纹素数)"), ("RENDERING", "渲染"), ("Range", "范围"), @@ -618,7 +602,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "重做"), ("Reimport mesh", "重新导入网格"), - ("Relative to the bounding box diagonal.", "相对于包围盒对角线。"), ("Remove", "移除"), ("Remove channel", "移除通道"), ("Remove effect", "移除效果"), @@ -626,9 +609,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "移除图层"), ("Remove layer(s)", "移除图层"), ("Remove mask", "移除遮罩"), + ("Remove point", "移除点"), ("Remove resource", "移除资源"), - ("Remove the cage", "移除笼体"), - ("Remove the path (Esc)", "移除路径(Esc)"), ("Remove the shortcut", "移除快捷键"), ("Remove this output", "移除此输出"), ("Remove unused resources...", "移除未使用的资源..."), @@ -641,19 +623,17 @@ 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", "重新扫描库文件夹"), + ("Reset", "重置"), ("Reset UI", "重置界面"), ("Reset all", "全部重置"), + ("Reset to defaults", "恢复默认值"), ("Reset to {shortcut}", "重置为 {shortcut}"), ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), - ("Return to painting mode", "返回绘画模式"), ("Return to this step", "返回到此步骤"), - ("Auto-rebake", "自动重新烘焙"), - ("Bake this map again by itself when its bake settings, the low poly or the high polys change", "当烘焙设置、低模或高模发生变化时,自动重新烘焙此贴图"), ("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"), ("Rotation", "旋转"), ("Rotation (degrees)", "旋转(度)"), @@ -681,9 +661,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "划痕"), ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), - ("Search all assets", "搜索所有资产"), + ("Search", "搜索"), ("Search commands or keys", "搜索命令或按键"), - ("Secondary rays", "二次光线"), ("Seed", "随机种子"), ("Select a layer", "选择图层"), ("Select an output template", "选择输出模板"), @@ -748,16 +727,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "8x8 子采样"), ("Subsurface scattering", "次表面散射"), ("Subtract", "减去"), - ("Symmetry (X)", "对称(X)"), - ("Symmetry (Y)", "对称(Y)"), ("Tangent | Wrap", "切线 | 包裹"), - ("Tangent-space normals of the high definition meshes.", "高精度网格的切线空间法线。"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "时间抗锯齿(在 3D 视图静止时逐步细化)"), - ("Texture Set List", "纹理集列表"), + ("Texture Sets", "纹理集"), ("Texture Set Settings", "纹理集设置"), ("Texture resolution", "纹理分辨率"), ("Texture set channels", "纹理集通道"), - ("Texture set list", "纹理集列表"), ("Texture sets", "纹理集"), ("TextureCraft had to close:", "TextureCraft 不得不关闭:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - 金属度/粗糙度"), @@ -802,14 +777,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 low poly mesh as high poly mesh", "将低模用作高模"), ("Use the control channel or `texturecraft-cli render` for screenshots", "截图请使用控制通道或 `texturecraft-cli render`"), ("Value", "值"), ("Version {version}", "版本 {version}"), @@ -830,15 +804,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "滚轮 / Alt + 右键拖动"), ("White", "白色"), - ("White where the surface faces the direction, black where it faces away.", "表面朝向该方向处为白色,背向处为黑色。"), ("Width", "宽度"), ("Width (texels at 2K)", "宽度(2K 下的纹素数)"), ("Window", "窗口"), ("Wood grain", "木纹"), ("Works in texture space, like the blur: it does not cross UV seams.", "在纹理空间中工作,与模糊相同:不会跨越 UV 接缝。"), - ("World space direction", "世界空间方向"), - ("World space normal", "世界空间法线"), - ("World-space normals of the high poly (or the low poly).", "高模(或低模)的世界空间法线。"), + ("World Space Normal", "世界空间法线"), ("Yellow / blue", "黄色 / 蓝色"), ("Zoom", "缩放"), ("a missing layer", "缺失的图层"), @@ -872,7 +843,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("transm", "透射"), ("{action} (undone)", "{action}(已撤销)"), ("{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}:添加到所选图层上方(或将其拖入图层堆栈或视口)"), - ("{name} ({n} triangles)", "{name}({n} 个三角形)"), ("{name} copy", "{name} 副本"), ("{n} bits", "{n} 位"), ( @@ -883,25 +853,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern}(缩放 {scale},种子 {seed})"), ("Template name", "模板名称"), ("Save current project as template", "将当前项目保存为模板"), - ("Spread angle", "扩散角度"), ("Distribution", "分布"), ("Cosine", "余弦"), ("Uniform", "均匀"), - ("Ignore backface", "忽略背面"), - ("Self occlusion", "自遮蔽"), - ("Only same mesh name", "仅相同网格名称"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "弯曲法线的光线沿用环境光遮蔽的遮挡物设置。"), - ("Sampling radius", "采样半径"), - ("0 picks a radius from the output size.", "0 表示根据输出尺寸选择半径。"), - ("Encoding", "编码"), - ("Signed (-1..1)", "有符号 (-1..1)"), - ("Positive (0..1)", "正值 (0..1)"), ("Normalization", "归一化"), - ("Bounding box", "包围盒"), - ("Bounding sphere", "包围球"), - ("Position normalized to the low poly's bounding box or sphere.", "按低模包围盒或包围球归一化的位置。"), - ("Base colors (textures, factors) and vertex colors of the high definition meshes.", "高精度网格的基础颜色(纹理、系数)和顶点颜色。"), - ("White where the high poly covers the low poly, times its alpha.", "高模覆盖低模处为白色,再乘以其 Alpha。"), // Settings › Interface: brightness and accent color. ("Brightness", "亮度"), ("Dark", "深色"), @@ -926,8 +881,6 @@ pub const TABLE: &[(&str, &str)] = &[ "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), ("Brushes", "笔刷库"), - ("My brushes", "我的笔刷"), - ("Use this brush (keeps its size)", "使用此笔刷(保留大小)"), ("Brush name", "笔刷名称"), ("Save current brush", "保存当前笔刷"), ("Start window", "启动窗口"), @@ -948,12 +901,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "未保存的更改"), ("Don't save", "不保存"), ("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"), - ("Skew correction", "倾斜校正"), - ("Paint skew in the 2D view", "在 2D 视图中绘制倾斜"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "在 2D 视图中拖动,绘制烘焙射线转向基础法线的位置;以值 0 绘制可擦除", - ), ("Radius", "半径"), ("Remove skew correction", "移除倾斜校正"), ("Twill weave", "斜纹织物"), @@ -973,4 +920,185 @@ pub const TABLE: &[(&str, &str)] = &[ "已在 MaterialCraft 中打开:在其中使用“文件 > 发送到 TextureCraft”即可带回更改", ), ("Parameters change in the desktop app, with MaterialCraft installed", "参数可在安装了 MaterialCraft 的桌面版中修改"), + ("Add High-Poly Meshes", "添加高模网格"), + ("All", "全部"), + ("Apply Diffusion", "应用扩散"), + ("Attenuation", "衰减"), + ("Auto Tonemapping", "自动色调映射"), + ("Average Normals", "平均法线"), + ("BBox", "包围盒"), + ("BSphere", "包围球"), + ("Mesh Map Bakers", "网格贴图烘焙器"), + ("Common Settings", "通用设置"), + ("Mesh Map Settings", "网格贴图设置"), + ("Check All", "全选"), + ("No Parameters", "无参数"), + ("Bake Selected Textures ({n})", "烘焙所选纹理({n})"), + ("By Mesh Name", "按网格名称"), + ("Cage", "笼形"), + ("Cage Scene", "笼形场景"), + ("Cage Type", "笼形类型"), + ("Color Generator", "颜色生成器"), + ("Color Source", "颜色来源"), + ("Common Parameters", "通用参数"), + ("Custom File", "自定义文件"), + ("Details", "细节"), + ("Dilation Width", "扩张宽度"), + ("Distance-Based", "基于距离"), + ("Edge Contrast", "边缘对比度"), + ("Edge Distance", "边缘距离"), + ("Edge Protection", "边缘保护"), + ("Enable Seams", "启用接缝"), + ("File ID", "文件 ID"), + ("Full Scene", "整个场景"), + ("Generate from Mesh", "从网格生成"), + ("Generate from Normal Map", "从法线贴图生成"), + ("Ground Plane", "地平面"), + ("Ground Plane Offset", "地平面偏移"), + ("High Poly Mesh Suffix", "高模网格后缀"), + ("High Poly Scene", "高模场景"), + ("High-Poly Parameters", "高模参数"), + ("Hue Shift", "色相偏移"), + ("Ignore Backface", "忽略背面"), + ("Ignore Backface Suffix", "忽略背面后缀"), + ("Include in Bake", "包含在烘焙中"), + ("Load Cage", "加载笼形"), + ("Lock Output Size", "锁定输出尺寸"), + ("Low Poly Mesh Suffix", "低模网格后缀"), + ("Manual", "手动"), + ("Material Color", "材质颜色"), + ("Max Frontal Distance", "最大前向距离"), + ("Max Occluder Distance", "最大遮挡物距离"), + ("Max Rear Distance", "最大后向距离"), + ("Mesh ID", "网格 ID"), + ("Method", "方法"), + ("Min Occluder Distance", "最小遮挡距离"), + ("Never", "从不"), + ("No High-Poly Meshes", "无高模网格"), + ("Normalization Scale", "归一化范围"), + ("Normalization Type", "归一化类型"), + ("Only Same Mesh Name", "仅相同网格名称"), + ("Output Size", "输出尺寸"), + ("Match", "匹配"), + ("Skew Correction Method", "偏斜校正方法"), + ("Mesh Normals Based", "基于网格法线"), + ("Face Normals Based", "基于面法线"), + ("Reset Painted Cage", "重置绘制的笼形"), + ("Paint Cage", "绘制笼形"), + ("Paint Skew Correction", "绘制倾斜校正"), + ("Per Material", "按材质"), + ("Random", "随机"), + ("Relative to Bounding Box", "相对于包围盒"), + ("Relative to Low Mesh", "相对于低模网格"), + ("Relative to Min/Max", "相对于最小值/最大值"), + ("Relative to Ray Distances", "相对于射线距离"), + ("Remove Cage", "移除笼形"), + ("Remove Skew Correction", "移除倾斜校正"), + ("Restore Defaults", "恢复默认值"), + ("Return to Painting Mode", "返回绘画模式"), + ("Sampling Radius", "采样半径"), + ("Scaling Divisor", "缩放除数"), + ("Seams Intensity", "接缝强度"), + ("Secondary Rays", "二次光线"), + ("Self Intersection", "自相交"), + ("Self Occlusion", "自遮蔽"), + ("Skew Correction", "倾斜校正"), + ("Smooth", "平滑"), + ("Spread Angle", "扩散角度"), + ("Submesh", "子网格"), + ("Use Low Poly Mesh as High Poly Mesh", "将低模用作高模"), + ("Value Bounds Max", "值上限"), + ("Value Bounds Min", "值下限"), + ("Vertex Color", "顶点颜色"), + ("Select the layer content", "选择图层内容"), + ("Paint layer", "绘画图层"), + ("Fill layer", "填充图层"), + ("1 effect", "1 个效果"), + ("{count} effects", "{count} 个效果"), + ("Mask effects", "遮罩效果"), + ("Content effects", "内容效果"), + ("Fold or unfold these effects", "折叠或展开这些效果"), + ("Remove resolution override", "移除分辨率覆盖"), + ("Texture set resolution", "纹理集分辨率"), + ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Angle span", "角度范围"), + ("Axis position", "轴位置"), + ("Count", "数量"), + ("Display", "显示"), + ("Hide while painting", "绘制时隐藏"), + ("Manipulator size", "操纵器大小"), + ("Mirror symmetry", "镜像对称"), + ("Radial settings", "径向设置"), + ("Radial symmetry", "径向对称"), + ("Show axis", "显示轴"), + ("Show axis position manipulator", "显示轴位置操纵器"), + ("Show cursor", "显示光标"), + ("Show intersection", "显示交线"), + ("Show plane", "显示平面"), + ("Symmetry", "对称"), + ("Symmetry color display", "对称显示颜色"), + ("Symmetry settings", "对称设置"), + ("Type", "类型"), + ("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", "保存时的最大内存"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存使用其余核心,并最多占用这一比例的可用内存。至少始终有一个核心工作。", + ), + ("Max project size on open", "打开项目的大小上限"), + ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), + ("Filter by type", "按类型筛选"), + ("All libraries", "所有库"), + ("Browse folders", "浏览文件夹"), + ("Starter assets", "内置资源"), + ("Your assets", "我的资源"), + ("Reset query", "重置查询"), + ("Refresh", "刷新"), + ("Saved searches", "已保存的搜索"), + ("Save the current search", "保存当前搜索"), + ("Delete", "删除"), + ("Filter by path", "按路径筛选"), + ("Hide non-applicable folders", "隐藏不适用的文件夹"), + ("Thumbnail size", "缩略图大小"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "列表"), + ("Procedurals", "程序纹理"), ]; 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/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs new file mode 100644 index 00000000..27dc5f67 --- /dev/null +++ b/crates/ui-egui/src/layer_panel.rs @@ -0,0 +1,144 @@ +//! State behind the Layers panel: the thumbnail service, the GPU textures made from its pictures, +//! which effect groups are folded, and the one place the preview size is decided. + +use std::collections::{HashMap, HashSet}; +use std::time::Duration; + +use egui::{Context, TextureHandle, TextureId, TextureOptions}; +use texturecraft_engine::Session; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; + +use crate::TextureCraftApp; + +/// Edge (points) of a layer's content and mask thumbnails. The Layers "Preview size" setting +/// plugs in by changing [`layer_preview_size`]; every row measure below derives from it. +pub(crate) const LAYER_PREVIEW_SIZE: f32 = 36.0; + +/// The thumbnail edge in points, read once per row. +pub(crate) fn layer_preview_size(_app: &TextureCraftApp) -> f32 { + LAYER_PREVIEW_SIZE +} + +/// Height of a layer row for thumbnails of `size`. +pub(crate) fn layer_row_height(size: f32) -> f32 { + (size + 12.0).max(48.0) +} + +/// Edge of an effect's stage thumbnail for layer thumbnails of `size` (18 to 28 points). +pub(crate) fn effect_preview_size(size: f32) -> f32 { + (size * 0.6).clamp(18.0, 28.0) +} + +/// Height of an effect row. +pub(crate) fn effect_row_height(size: f32) -> f32 { + (effect_preview_size(size) + 4.0).max(26.0) +} + +#[derive(Default)] +pub struct LayerPanel { + service: ThumbService, + textures: HashMap, + frame: u64, + /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. + pub(crate) folded: HashSet<(u64, bool)>, +} + +impl LayerPanel { + /// Start drawing the panel for this frame. + pub(crate) fn begin(&mut self, session: &Session, now: f64) { + self.frame += 1; + self.service.begin_frame(session, now); + + // Deleted layer IDs must not accumulate in panel state + self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); + } + + /// The texture of `target`, queuing its render (call only for rows that are on screen). + pub(crate) fn texture(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { + let view = self.service.get(session, target); + let image = view.image?; + let frame = self.frame; + if let Some((version, tex, used)) = self.textures.get_mut(&target) + && *version == view.version + { + *used = frame; + return Some(tex.id()); + } + let pixels = egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &image.rgba); + let tex = ctx.load_texture("layer-thumb", pixels, TextureOptions::LINEAR); + let id = tex.id(); + self.textures.insert(target, (view.version, tex, frame)); + Some(id) + } + + /// Finish the frame: collect pictures and ask for another frame while work is outstanding. + pub(crate) fn end(&mut self, ctx: &Context, session: &Session) { + if self.service.poll(session) { + ctx.request_repaint_after(Duration::from_millis(40)); + } + if self.textures.len() > CACHE_ENTRIES * 2 { + let frame = self.frame; + self.textures.retain(|_, (_, _, used)| *used + 1 >= frame); + } + } + + /// The service, for tests. + pub fn service(&self) -> &ThumbService { + &self.service + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Channel, LayerId}; + use texturecraft_engine::geom::primitives; + + #[test] + fn deleted_layers_release_their_fold_state() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let layer = session.selected_layer().unwrap(); + let mut panel = LayerPanel::default(); + panel.folded.extend([(layer.0, false), (layer.0, true)]); + panel.begin(&session, 0.0); + assert_eq!(panel.folded.len(), 2, "existing layers keep their view settings"); + + texturecraft_engine::execute(&mut session, "layer.remove", &serde_json::json!({"layer": layer.0})).unwrap(); + panel.begin(&session, 1.0); + + assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state"); + } + + #[test] + fn evicted_and_dropped_thumbnail_handles_release_textures() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let context = Context::default(); + let initial_textures = context.tex_manager().read().num_allocated(); + let mut panel = LayerPanel::default(); + let mut evicted = Vec::new(); + panel.begin(&session, 0.0); + + // Simulate scrolling through more textures than the UI cache retains + for index in 0..CACHE_ENTRIES * 2 + 1 { + let target = ThumbTarget::Content { layer: LayerId(index as u64), channel: Channel::BaseColor }; + let image = egui::ColorImage::filled([64, 64], egui::Color32::WHITE); + let texture = context.load_texture("layer-thumb", image, TextureOptions::LINEAR); + evicted.push(texture.id()); + panel.textures.insert(target, (1, texture, panel.frame)); + } + let kept = evicted.pop().unwrap(); + panel.begin(&session, 1.0); + panel.begin(&session, 2.0); + panel.textures.values_mut().find(|(_, texture, _)| texture.id() == kept).unwrap().2 = panel.frame; + panel.end(&context, &session); + + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures + 1); + assert!(evicted.iter().all(|id| context.tex_manager().read().meta(*id).is_none())); + assert!(context.tex_manager().read().meta(kept).is_some()); + + drop(panel); + + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures); + } +} diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs new file mode 100644 index 00000000..bff5d745 --- /dev/null +++ b/crates/ui-egui/src/levels_editor.rs @@ -0,0 +1,430 @@ +//! Levels handles over a histogram and output gradient, with labelled fields for exact values + +use egui::{Color32, CornerRadius, CursorIcon, Id, Pos2, Rect, Response, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use texturecraft_engine::core::Levels; + +use crate::i18n::tr; +use crate::levels_handle::LevelsHandle; +use crate::theme::Tokens; + +const HISTOGRAM_HEIGHT: f32 = 56.0; +const HANDLE_HEIGHT: f32 = 11.0; +const HANDLE_HALF_WIDTH: f32 = 5.0; + +/// Height of a handle's straight sides; the rest is its tip pointing at the track +const HANDLE_SIDE_HEIGHT: f32 = 6.0; + +/// A larger target than the painted pointer makes handles easier to grab +const HANDLE_TARGET_SIZE: f32 = 24.0; + +/// Fraction of the track moved by one arrow key press +const KEYBOARD_STEP: f32 = 0.01; + +const GRADIENT_HEIGHT: f32 = 8.0; +const GAP_BELOW_HISTOGRAM: f32 = 3.0; +const VALUE_ROW_HEIGHT: f32 = 16.0; +const VALUE_FONT_SIZE: f32 = 11.5; + +/// Padding of the histogram well around its bars +const WELL_PADDING: f32 = 3.0; + +/// Gray of the gamma handle, between the black input-low and white input-high handles +const GAMMA_HANDLE_GRAY: u8 = 128; + +/// Grid lines across the histogram, at these fractions of its width +const GRID_FRACTIONS: [f32; 3] = [0.25, 0.5, 0.75]; + +/// Decimals printed beside a handle; exact entry keeps the stored precision +const VALUE_DECIMALS: usize = 3; + +/// Space kept around a printed value; a value closer to one already printed is left out +const VALUE_SPACING: f32 = 2.0; + +/// Opacity of the shade over the histogram outside the input range +const OUTSIDE_RANGE_SHADE: f32 = 0.7; + +/// Opacity of the line at gamma, fainter than the input range's accent lines +const GAMMA_LINE_OPACITY: f32 = 0.6; + +/// Edits `levels` over histogram `counts`; `Some(merge)` per change, `merge` true for a drag's later frames +pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, counts: Option<&[u32]>, levels: &mut Levels) -> Option { + let height = VALUE_ROW_HEIGHT * 2.0 + HANDLE_HEIGHT * 2.0 + HISTOGRAM_HEIGHT + GAP_BELOW_HISTOGRAM + GRADIENT_HEIGHT; + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + let histogram_top = rect.top() + VALUE_ROW_HEIGHT + HANDLE_HEIGHT; + let gradient_top = output_handles_top(rect) - GRADIENT_HEIGHT; + let track = track(rect); + let id = ui.make_persistent_id(("levels_editor", id_salt)); + + // Gamma goes last so it stays grabbable between input handles that close in on it + let handles = [LevelsHandle::InputLow, LevelsHandle::InputHigh, LevelsHandle::Gamma, LevelsHandle::OutputLow, LevelsHandle::OutputHigh]; + forget_previous_editor(ui, id, &handles); + + let mut edit = None; + let mut responses = Vec::with_capacity(handles.len()); + let mut focus_value = None; + for handle in handles { + let x = track_x(&track, handle.position(levels)); + let top = handle_top(rect, handle); + let hit = Rect::from_center_size(pos2(x, top + HANDLE_HEIGHT / 2.0), vec2(HANDLE_TARGET_SIZE, HANDLE_TARGET_SIZE)); + let response = ui + .interact(hit, id.with(handle), Sense::click_and_drag()) + .on_hover_cursor(CursorIcon::ResizeHorizontal) + .on_hover_text(tr("Double-click or press Enter to edit")); + if response.drag_started() { + ui.data_mut(|data| data.remove_temp::(response.id)); + } + + if response.dragged() + && let Some(pointer) = response.interact_pointer_pos() + { + let mut next = *levels; + handle.set_position(&mut next, track_position(&track, pointer.x)); + if next != *levels { + *levels = next; + edit = Some(continues_drag(ui, response.id)); + } + } + + edit = edit.or(handle_keys(ui, &response, handle, levels)); + if response.double_clicked() || (response.has_focus() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) { + focus_value = Some(handle); + } + + let value = handle.value(levels); + response.widget_info(|| WidgetInfo::slider(true, f64::from(value), handle.label())); + let range = handle.value_range(levels); + ui.ctx().accesskit_node_builder(response.id, |node| { + use egui::accesskit::Action; + + node.set_min_numeric_value(f64::from(*range.start())); + node.set_max_numeric_value(f64::from(*range.end())); + node.add_action(Action::SetValue); + if value < *range.end() { + node.add_action(Action::Increment); + } + if value > *range.start() { + node.add_action(Action::Decrement); + } + }); + responses.push((handle, response)); + } + + let well = Rect::from_x_y_ranges(rect.x_range().shrink(HANDLE_HALF_WIDTH), histogram_top..=histogram_top + HISTOGRAM_HEIGHT); + paint_histogram(ui, well, counts.unwrap_or_default(), levels); + paint_output_gradient(ui, Rect::from_x_y_ranges(track, gradient_top..=gradient_top + GRADIENT_HEIGHT)); + paint_handles_and_values(ui, rect, &responses, levels); + + let cancel_typing = responses.iter().any(|(_, response)| response.is_pointer_button_down_on()); + let fields = [LevelsHandle::InputLow, LevelsHandle::Gamma, LevelsHandle::InputHigh, LevelsHandle::OutputLow, LevelsHandle::OutputHigh]; + let mut labels = Vec::with_capacity(fields.len()); + + // A shared label row keeps the fields aligned when translated names wrap + ui.columns(fields.len(), |columns| { + for (ui, handle) in columns.iter_mut().zip(fields) { + let label = + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| ui.label(egui::RichText::new(handle.label()).size(VALUE_FONT_SIZE))).inner; + labels.push(label.id); + } + }); + + let mut invalid = false; + ui.columns(fields.len(), |columns| { + for ((ui, handle), label) in columns.iter_mut().zip(fields).zip(labels) { + let (typed, field_invalid) = number_field(ui, id.with((handle, "value")), label, handle, levels, focus_value == Some(handle), cancel_typing); + edit = edit.or(typed); + invalid |= field_invalid; + } + }); + if invalid { + ui.colored_label(Tokens::get(ui.ctx()).warning, tr("Enter a finite number")); + } + + edit +} + +/// Properties shows one effect at a time; its old cursor, draft and drag state must not accumulate +fn forget_previous_editor(ui: &Ui, id: Id, handles: &[LevelsHandle]) { + let owner = ui.make_persistent_id("levels_editor_owner"); + ui.data_mut(|data| { + let previous = data.get_temp::(owner); + if previous == Some(id) { + return; + } + + if let Some(previous) = previous { + for handle in handles { + let field = previous.with((handle, "value")); + data.remove::(field); + data.remove::<(String, bool)>(field); + data.remove::(previous.with(handle)); + } + } + data.insert_temp(owner, id); + }); +} + +fn handle_top(rect: Rect, handle: LevelsHandle) -> f32 { + if LevelsHandle::INPUT.contains(&handle) { rect.top() + VALUE_ROW_HEIGHT } else { output_handles_top(rect) } +} + +fn output_handles_top(rect: Rect) -> f32 { + rect.bottom() - VALUE_ROW_HEIGHT - HANDLE_HEIGHT +} + +/// The x range the handles move along in the editor's `rect`, lined up with the histogram bars +fn track(rect: Rect) -> egui::Rangef { + rect.x_range().shrink(HANDLE_HALF_WIDTH + WELL_PADDING) +} + +fn track_x(track: &egui::Rangef, position: f32) -> f32 { + track.min + track.span() * position.clamp(0.0, 1.0) +} + +fn track_position(track: &egui::Rangef, x: f32) -> f32 { + ((x - track.min) / track.span().max(1.0)).clamp(0.0, 1.0) +} + +/// True once the drag of `id` has already changed a value, so its later changes share that undo step +fn continues_drag(ui: &Ui, id: Id) -> bool { + ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(id), true)) +} + +/// `value` with [`VALUE_DECIMALS`] decimals, trailing zeros dropped ("1", "0.25", "0.634") +fn shown_value(value: f32) -> String { + let fixed = format!("{value:.VALUE_DECIMALS$}"); + fixed.trim_end_matches('0').trim_end_matches('.').to_string() +} + +/// Where `handle`'s value of `size` goes: over an input handle, under an output one, inside `rect` +fn value_rect(rect: Rect, handle: LevelsHandle, levels: &Levels, size: egui::Vec2) -> Rect { + let x = track_x(&track(rect), handle.position(levels)); + let top = handle_top(rect, handle); + let placed = if LevelsHandle::INPUT.contains(&handle) { + egui::Align2::CENTER_BOTTOM.anchor_size(pos2(x, top), size) + } else { + egui::Align2::CENTER_TOP.anchor_size(pos2(x, top + HANDLE_HEIGHT), size) + }; + let shift = (rect.left() - placed.left()).max(0.0) + (rect.right() - placed.right()).min(0.0); + placed.translate(vec2(shift, 0.0)) +} + +/// The histogram in its well: quarter lines, the outside of the input range dimmed, lines at the handles +fn paint_histogram(ui: &Ui, well: Rect, counts: &[u32], levels: &Levels) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(well); + painter.rect(well, CornerRadius::same(tokens.radius), tokens.field, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + + let inner = well.shrink(WELL_PADDING); + let vertical_line = |x: f32, color: Color32| painter.line_segment([pos2(x, inner.top()), pos2(x, inner.bottom())], Stroke::new(1.0, color)); + for fraction in GRID_FRACTIONS { + vertical_line(track_x(&inner.x_range(), fraction), tokens.field_border); + } + + let fullest = counts.iter().copied().max().unwrap_or(0).max(1) as f32; + let bar_width = inner.width() / counts.len().max(1) as f32; + for (index, count) in counts.iter().enumerate() { + let bar_height = inner.height() * *count as f32 / fullest; + let x = inner.left() + index as f32 * bar_width; + painter.rect_filled(Rect::from_min_max(pos2(x, inner.bottom() - bar_height), pos2(x + bar_width, inner.bottom())), 0.0, tokens.text_dim); + } + + let x_at = |handle: LevelsHandle| track_x(&inner.x_range(), handle.position(levels)); + let (low, high) = (x_at(LevelsHandle::InputLow), x_at(LevelsHandle::InputHigh)); + let shade = tokens.field.gamma_multiply(OUTSIDE_RANGE_SHADE); + painter.rect_filled(Rect::from_x_y_ranges(inner.left()..=low, inner.y_range()), 0.0, shade); + painter.rect_filled(Rect::from_x_y_ranges(high..=inner.right(), inner.y_range()), 0.0, shade); + vertical_line(low, tokens.accent); + vertical_line(high, tokens.accent); + vertical_line(x_at(LevelsHandle::Gamma), tokens.text_dim.gamma_multiply(GAMMA_LINE_OPACITY)); +} + +/// A black-to-white strip: the output values the output handles pick from +fn paint_output_gradient(ui: &Ui, strip: Rect) { + let mut mesh = egui::Mesh::default(); + for (corner, color) in + [(strip.left_top(), Color32::BLACK), (strip.right_top(), Color32::WHITE), (strip.right_bottom(), Color32::WHITE), (strip.left_bottom(), Color32::BLACK)] + { + mesh.colored_vertex(corner, color); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + + let painter = ui.painter(); + painter.add(mesh); + painter.rect_stroke(strip, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), egui::StrokeKind::Outside); +} + +/// Each handle filled with its gray, the active one on top, and its value beside it, overlapping values left out +fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Response)], levels: &Levels) { + let track = track(rect); + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let priority = |response: &Response| (response.dragged(), response.hovered(), response.has_focus()); + + // Active handles last, so the one on top is the one the pointer grabs + let mut by_paint_order: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_paint_order.sort_by_key(|(_, response)| priority(response)); + for &(handle, ref response) in by_paint_order { + let x = track_x(&track, handle.position(levels)); + let fill = match handle { + LevelsHandle::InputLow => Color32::BLACK, + LevelsHandle::Gamma => Color32::from_gray(GAMMA_HANDLE_GRAY), + LevelsHandle::InputHigh => Color32::WHITE, + LevelsHandle::OutputLow | LevelsHandle::OutputHigh => Color32::from_gray((handle.value(levels).clamp(0.0, 1.0) * 255.0).round() as u8), + }; + let outline = if response.dragged() || response.has_focus() { + tokens.accent + } else if response.hovered() { + tokens.text_strong + } else { + tokens.text + }; + let points_down = LevelsHandle::INPUT.contains(&handle); + painter.add(egui::Shape::convex_polygon(handle_outline(x, handle_top(rect, handle), points_down), fill, Stroke::new(1.5, outline))); + } + + // Active values first, so a neighbour's overlapping value gives way to them + let font = egui::FontId::proportional(VALUE_FONT_SIZE); + let mut printed: Vec = Vec::new(); + let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_priority.sort_by_key(|(_, response)| std::cmp::Reverse(priority(response))); + for &(handle, ref response) in by_priority { + let color = if response.hovered() || response.has_focus() || response.dragged() { tokens.text_strong } else { tokens.text }; + let galley = painter.layout_no_wrap(shown_value(handle.value(levels)), font.clone(), color); + let text_rect = value_rect(rect, handle, levels, galley.size()); + if printed.iter().any(|other| other.expand(VALUE_SPACING).intersects(text_rect)) { + continue; + } + + painter.galley(text_rect.min, galley, color); + printed.push(text_rect); + } +} + +/// A pentagon pointer centred on `x`: flat side away from the track, tip touching it +fn handle_outline(x: f32, top: f32, points_down: bool) -> Vec { + let bottom = top + HANDLE_HEIGHT; + let (flat, side_end, tip) = if points_down { (top, top + HANDLE_SIDE_HEIGHT, bottom) } else { (bottom, bottom - HANDLE_SIDE_HEIGHT, top) }; + vec![ + pos2(x - HANDLE_HALF_WIDTH, flat), + pos2(x + HANDLE_HALF_WIDTH, flat), + pos2(x + HANDLE_HALF_WIDTH, side_end), + pos2(x, tip), + pos2(x - HANDLE_HALF_WIDTH, side_end), + ] +} + +/// Arrow keys move along the track; accessibility increment/decrement change the numeric value +fn handle_keys(ui: &Ui, response: &Response, handle: LevelsHandle, levels: &mut Levels) -> Option { + use egui::accesskit::{Action, ActionData}; + + let mut next = *levels; + if response.has_focus() { + ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() })); + let steps = ui.input(|input| input.num_presses(egui::Key::ArrowRight) as f32 - input.num_presses(egui::Key::ArrowLeft) as f32); + if steps != 0.0 { + handle.set_position(&mut next, handle.position(levels) + steps * KEYBOARD_STEP); + } + } + + ui.input(|input| { + let steps = input.num_accesskit_action_requests(response.id, Action::Increment) as f32 + - input.num_accesskit_action_requests(response.id, Action::Decrement) as f32; + if steps != 0.0 { + handle.set_value(&mut next, handle.value(levels) + steps * KEYBOARD_STEP); + } + for request in input.accesskit_action_requests(response.id, Action::SetValue) { + if let Some(ActionData::NumericValue(value)) = request.data { + handle.set_value(&mut next, value as f32); + } + } + }); + if next == *levels { + return None; + } + + *levels = next; + Some(false) +} + +/// Exact entry commits on Enter or focus loss; invalid input stays editable and Escape cancels +fn number_field(ui: &mut Ui, id: Id, label: Id, handle: LevelsHandle, levels: &mut Levels, focus: bool, cancel: bool) -> (Option, bool) { + let shown = handle.value(levels).to_string(); + let (mut text, mut invalid) = ui.data(|data| data.get_temp::<(String, bool)>(id)).unwrap_or_else(|| (shown.clone(), false)); + if focus || cancel { + text = shown.clone(); + invalid = false; + } + + let response = + ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(ui.available_width()).align(egui::Align2::CENTER_CENTER)).labelled_by(label); + if response.changed() { + invalid = false; + } + if focus { + let mut state = egui::text_edit::TextEditState::load(ui.ctx(), id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + state.store(ui.ctx(), id); + response.request_focus(); + ui.data_mut(|data| data.insert_temp(id, (text, false))); + return (None, false); + } + + // The app can consume Escape before the field sees it, so read the raw event + let escape = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if cancel || escape { + ui.data_mut(|data| data.remove::<(String, bool)>(id)); + ui.memory_mut(|memory| memory.surrender_focus(id)); + return (None, false); + } + + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(id, (text, invalid))); + return (None, invalid); + } + + // Discard abandoned input when a hidden editor reappears + ui.data_mut(|data| data.remove::<(String, bool)>(id)); + if !response.lost_focus() || text == shown { + return (None, false); + } + + let Some(value) = text.trim().parse::().ok().filter(|value| value.is_finite()) else { + response.request_focus(); + ui.data_mut(|data| data.insert_temp(id, (text, true))); + return (None, true); + }; + + let before = *levels; + handle.set_value(levels, value); + ((before != *levels).then_some(false), false) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn switching_effects_releases_old_field_and_drag_state() { + let context = egui::Context::default(); + let mut levels = Levels::default(); + for effect in 0..100 { + context + .run_ui(egui::RawInput::default(), |ui| { + levels_editor(ui, effect, None, &mut levels); + let id = ui.make_persistent_id(("levels_editor", effect)); + ui.data_mut(|data| { + data.insert_temp(id.with((LevelsHandle::Gamma, "value")), ("invalid draft".to_string(), true)); + data.insert_temp(id.with(LevelsHandle::Gamma), true); + }); + }) + .drop_without_applying_deltas(); + } + + context.data(|data| { + assert_eq!(data.count::(), 5, "only the current effect's fields remain"); + assert_eq!(data.count::<(String, bool)>(), 1, "only the current draft remains"); + assert_eq!(data.count::(), 1, "only the current drag state remains"); + }); + } +} diff --git a/crates/ui-egui/src/levels_handle.rs b/crates/ui-egui/src/levels_handle.rs new file mode 100644 index 00000000..8be37584 --- /dev/null +++ b/crates/ui-egui/src/levels_handle.rs @@ -0,0 +1,110 @@ +//! The five handles of the levels editor and how each one reads and moves a [`Levels`] + +use texturecraft_engine::core::Levels; + +use crate::i18n::tr; + +/// Narrowest gap the handles and typed values leave between the low and high handle of a pair +const MIN_HANDLE_GAP: f32 = 0.01; + +/// Gamma range of the handle and typed values: the engine's own, so the handle nearly reaches either input handle +const GAMMA_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + +/// One draggable value of a levels effect +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum LevelsHandle { + InputLow, + Gamma, + InputHigh, + OutputLow, + OutputHigh, +} + +impl LevelsHandle { + /// The handles above the histogram, left to right at the default levels + pub const INPUT: [LevelsHandle; 3] = [LevelsHandle::InputLow, LevelsHandle::Gamma, LevelsHandle::InputHigh]; + + /// The localized name shared by the handle and its number field + pub fn label(self) -> &'static str { + match self { + LevelsHandle::InputLow => tr("Input low"), + LevelsHandle::Gamma => tr("Gamma"), + LevelsHandle::InputHigh => tr("Input high"), + LevelsHandle::OutputLow => tr("Output low"), + LevelsHandle::OutputHigh => tr("Output high"), + } + } + + /// The stored value, before display rounding + pub fn value(self, levels: &Levels) -> f32 { + match self { + LevelsHandle::InputLow => levels.in_low, + LevelsHandle::Gamma => levels.gamma, + LevelsHandle::InputHigh => levels.in_high, + LevelsHandle::OutputLow => levels.out_low, + LevelsHandle::OutputHigh => levels.out_high, + } + } + + /// Where the handle sits along its track (0 left, 1 right); gamma 1 is halfway between the input handles + pub fn position(self, levels: &Levels) -> f32 { + match self { + LevelsHandle::Gamma => levels.in_low + input_span(levels) * 0.5f32.powf(levels.gamma), + _ => self.value(levels), + } + .clamp(0.0, 1.0) + } + + /// Moves the handle to `position` along its track (see [`Self::position`]) + pub fn set_position(self, levels: &mut Levels, position: f32) { + let value = match self { + LevelsHandle::Gamma => { + let span = input_span(levels).max(f32::EPSILON); + let fraction = ((position - levels.in_low) / span).clamp(f32::EPSILON, 1.0 - f32::EPSILON); + fraction.ln() / 0.5f32.ln() + } + _ => position, + }; + self.set_value(levels, value); + } + + /// Allowed values enforce ordered inputs and preserve inverted outputs + pub fn value_range(self, levels: &Levels) -> std::ops::RangeInclusive { + let (neighbour, is_lower) = match self { + LevelsHandle::InputLow => (levels.in_high, true), + LevelsHandle::InputHigh => (levels.in_low, false), + LevelsHandle::OutputLow => (levels.out_high, levels.out_low <= levels.out_high), + LevelsHandle::OutputHigh => (levels.out_low, levels.out_high < levels.out_low), + LevelsHandle::Gamma => return GAMMA_RANGE, + }; + + // Invalid project values must not become NaN clamp bounds + if !neighbour.is_finite() { + return 0.0..=1.0; + } + + // Saved inputs can cross; clamp each bound so editing them cannot panic + if is_lower { 0.0..=(neighbour - MIN_HANDLE_GAP).clamp(0.0, 1.0) } else { (neighbour + MIN_HANDLE_GAP).clamp(0.0, 1.0)..=1.0 } + } + + /// Sets a finite value without crossing the neighbouring endpoint + pub fn set_value(self, levels: &mut Levels, value: f32) { + if !value.is_finite() { + return; + } + + let range = self.value_range(levels); + let value = value.clamp(*range.start(), *range.end()); + match self { + LevelsHandle::InputLow => levels.in_low = value, + LevelsHandle::Gamma => levels.gamma = value, + LevelsHandle::InputHigh => levels.in_high = value, + LevelsHandle::OutputLow => levels.out_low = value, + LevelsHandle::OutputHigh => levels.out_high = value, + } + } +} + +fn input_span(levels: &Levels) -> f32 { + (levels.in_high - levels.in_low).max(0.0) +} diff --git a/crates/ui-egui/src/levels_properties.rs b/crates/ui-egui/src/levels_properties.rs new file mode 100644 index 00000000..d3673538 --- /dev/null +++ b/crates/ui-egui/src/levels_properties.rs @@ -0,0 +1,142 @@ +//! Properties of a levels effect: the levels editor, then the channel picker (content), Reset, Auto and Invert + +use std::sync::Arc; + +use egui::Ui; +use serde_json::json; +use texturecraft_engine::core::{Channel, ChannelKind, Layer, LayerId, Levels}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::levels_editor::levels_editor; +use crate::theme::caption; + +/// Buckets of the histogram, over 0..1 +const HISTOGRAM_BUCKETS: usize = 64; + +/// Share of the counted texels a bucket needs to hold for Auto to keep it in the input range +const AUTO_MIN_SHARE: f64 = 0.001; + +/// The properties of levels effect `effect_id` of `layer`; every edit goes through `effect.set` +pub(crate) fn levels_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId, levels: &Levels) { + ui.label(caption(tr("Levels"))); + + let is_content = layer.content_effects.iter().any(|effect| effect.id == effect_id); + let channels: Vec = + if is_content { layer.channels.keys().copied().filter(|channel| channel.kind() != ChannelKind::NormalMap).collect() } else { Vec::new() }; + let picked = egui::Id::unique(("levels_channel", effect_id.0)); + let channel = ui + .data(|data| data.get_temp(picked)) + .filter(|channel| channels.contains(channel)) + .or(channels.first().copied()) + .or(layer.channels.keys().next().copied()) + .unwrap_or(Channel::BaseColor); + let counts = histogram_counts(app, ui, effect_id, channel); + + let mut edited = *levels; + let mut edit = levels_editor(ui, effect_id, counts.as_ref().map(|counts| counts.as_slice()), &mut edited); + ui.horizontal(|ui| { + if !channels.is_empty() { + egui::ComboBox::from_id_salt(picked) + .selected_text(tr(channel.label())) + .show_ui(ui, |ui| { + for option in channels { + if ui.selectable_label(option == channel, tr(option.label())).clicked() { + ui.data_mut(|data| data.insert_temp(picked, option)); + } + } + }) + .response + .on_hover_text(tr("Channel")); + } + + // Right to left: the last button comes first + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Invert")).clicked() { + std::mem::swap(&mut edited.out_low, &mut edited.out_high); + edit = Some(false); + } + + let auto_range = counts.as_ref().and_then(|counts| auto_input_range(counts)); + let auto = ui.add_enabled(auto_range.is_some(), egui::Button::new(tr("Auto"))).on_hover_text(tr("Fit the input range to the histogram")); + if auto.clicked() + && let Some((low, high)) = auto_range + { + (edited.in_low, edited.in_high) = (low, high); + edit = Some(false); + } + + if ui.add_enabled(edited != Levels::default(), egui::Button::new(tr("Reset"))).clicked() { + edited = Levels::default(); + edit = Some(false); + } + }); + }); + + // Auto or Invert with nothing to change would add an empty undo step + if let Some(merge) = edit + && edited != *levels + { + let Levels { in_low, in_high, gamma, out_low, out_high } = edited; + app.run( + "effect.set", + json!({"effect": effect_id.0, "inLow": in_low, "inHigh": in_high, "gamma": gamma, "outLow": out_low, "outHigh": out_high, "merge": merge}), + ); + } +} + +/// The histogram levels effect `effect_id` remaps, recomputed after a change once no pointer button is held +fn histogram_counts(app: &TextureCraftApp, ui: &Ui, effect_id: LayerId, channel: Channel) -> Option>> { + let key = egui::Id::unique(("levels_histogram", effect_id.0, channel)); + let owner = ui.make_persistent_id("levels_histogram_owner"); + + // Selection changes the revision, so old effects' histograms cannot be reused + ui.data_mut(|data| { + let previous = std::mem::replace(data.get_temp_mut_or(owner, key), key); + if previous != key { + data.remove::<(u64, Arc>)>(previous); + } + }); + + let revision = app.session.revision; + match ui.data(|data| data.get_temp::<(u64, Arc>)>(key)) { + Some((cached, counts)) if cached == revision || ui.input(|input| input.pointer.any_down()) => Some(counts), + _ => app.session.effect_histogram(effect_id, channel, HISTOGRAM_BUCKETS).map(|counts| { + let counts = Arc::new(counts); + ui.data_mut(|data| data.insert_temp(key, (revision, counts.clone()))); + counts + }), + } +} + +/// The input range Auto picks: the first to the last bucket holding more than [`AUTO_MIN_SHARE`] of the texels +fn auto_input_range(counts: &[u32]) -> Option<(f32, f32)> { + let total: u64 = counts.iter().map(|&count| u64::from(count)).sum(); + let holds_enough = |count: &u32| f64::from(*count) > total as f64 * AUTO_MIN_SHARE; + let first = counts.iter().position(holds_enough)?; + let last = counts.iter().rposition(holds_enough)?; + let bucket_count = counts.len() as f32; + Some((first as f32 / bucket_count, (last + 1) as f32 / bucket_count)) +} + +#[cfg(test)] +mod tests { + use super::{HISTOGRAM_BUCKETS, auto_input_range}; + + #[test] + fn auto_skips_buckets_under_the_share() { + let mut counts = vec![0u32; HISTOGRAM_BUCKETS]; + counts[3] = 1; + counts[10] = 5_000; + counts[40] = 5_000; + counts[60] = 1; + + assert_eq!(auto_input_range(&counts), Some((10.0 / HISTOGRAM_BUCKETS as f32, 41.0 / HISTOGRAM_BUCKETS as f32))); + } + + #[test] + fn auto_has_nothing_to_fit_in_an_empty_histogram() { + assert_eq!(auto_input_range(&[0; HISTOGRAM_BUCKETS]), None); + assert_eq!(auto_input_range(&[]), None); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1d0841dc..1196947d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,28 +7,75 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod bake_job; +pub mod bake_mode; +mod bake_scene; +#[cfg(not(target_arch = "wasm32"))] +mod brush_preset_save; +mod color_selection_editor; pub mod control; +mod decal_drop; 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; +mod generator_panel; pub mod gpu; +mod grid_tile; pub mod i18n; +pub mod id_color_pick; pub mod keymap; +pub mod layer_panel; +mod levels_editor; +mod levels_handle; +mod levels_properties; +mod mask_preview_image; +mod material_preview_image; pub mod menus; +pub mod new_project_advanced; +mod orb_shape; pub mod parity; +mod path_hit; +mod path_surface_cache; +mod preview_image; +mod preview_request; +mod preview_worker; pub mod profile; +pub mod properties_popup; +mod rail_popup; pub mod render_mode; +mod resource_picker; +mod resource_picker_item; +mod running_bake; +pub mod saved_search; +mod screen_color_pick; pub mod shelf; +mod shelf_entry; +mod shelf_folders; +pub mod shelf_panes; +pub mod shelf_preview; +mod shelf_tabs; +mod shelf_toolbar; +pub mod shelf_view; +mod soft_box; pub mod state; +pub mod symmetry; 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; @@ -37,24 +84,25 @@ use serde_json::Value; use texturecraft_engine::Session; use texturecraft_engine::bake::Progress; +pub use bake_job::BakeJob; pub use control::ControlRequest; +pub use running_bake::RunningBake; 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, pub rx: std::sync::mpsc::Receiver>, } -/// A background bake of one or more texture sets. -pub struct BakeJob { - pub queue: Vec, - pub current: Option<(usize, Arc, std::sync::mpsc::Receiver>)>, - pub total: usize, - /// Bake only this map (an Auto-rebake); None bakes every ticked map. - pub only: Option, -} - /// A MaterialCraft material re-cooking on a worker thread (one per layer at a time). pub struct LinkCook { pub layer: texturecraft_engine::core::LayerId, @@ -63,6 +111,9 @@ pub struct LinkCook { pub rx: std::sync::mpsc::Receiver>>, } +/// The engine's refusal to paint while a bake shows (translated where it is toasted). +pub const PAINTING_PAUSED: &str = i18n::n_("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish."); + /// The browser build's notice when WebGPU is unavailable and wgpu fell back to WebGL2. pub const WEBGL_NOTICE: &str = i18n::n_( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", @@ -76,7 +127,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, @@ -86,6 +141,8 @@ pub struct TextureCraftApp { pub resize: Option, pub link_cooks: Vec, pub thumbs: thumbs::Thumbs, + /// The Layers panel's thumbnails and folded groups. + pub layer_panel: layer_panel::LayerPanel, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -101,8 +158,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. @@ -119,25 +182,47 @@ 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; + ui.prefs.apply_resource_limits(); + let mut app = TextureCraftApp { + camera_glide: None, session, ui, + ui_store, gpu, control: None, toasts: Vec::new(), @@ -146,6 +231,7 @@ impl TextureCraftApp { resize: None, link_cooks: Vec::new(), thumbs: thumbs::Thumbs::default(), + layer_panel: layer_panel::LayerPanel::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, @@ -154,7 +240,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, @@ -163,29 +252,53 @@ 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 { + self.ui.prefs.apply_resource_limits(); + + // 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 @@ -193,6 +306,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 } }); } @@ -203,13 +323,23 @@ impl TextureCraftApp { self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY }); } - /// Start baking texture sets in the background (one after another). + /// Start baking texture sets in the background, one after another. Invalid set indices + /// show an error without starting a preview or queuing any work. pub fn start_bake(&mut self, sets: Vec) { if self.bake.is_some() || sets.is_empty() { return; } + + // Restore the picker's view before the preview starts following baked maps + id_color_pick::IdColorPick::end(self); + + if let Err(error) = self.session.bake_preview_begin_for(&sets) { + self.toast(error.to_string(), true); + return; + } + let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total, only: None }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -261,23 +391,54 @@ impl TextureCraftApp { } } + /// Show at most one streamed map per frame, then apply the set as one undo step after + /// its map channel closes. Closing the preview alone does not stop the background bake. fn poll_bake(&mut self, ctx: &egui::Context) { - let Some(job) = self.bake.as_mut() else { return }; + // Leaving Bake mode puts the view mode back; the bake goes on + if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { + self.session.bake_preview_end(); + } + + let Some(job) = self.bake.as_mut() else { + // A preview whose bake is gone must not keep the view + self.session.bake_preview_end(); + return; + }; + + if job.mesh_id != self.session.mesh_id { + // The mesh was swapped under the job: stop it and drop its result. + if let Some(running) = &job.current { + running.progress.cancel.store(true, Ordering::Relaxed); + } + self.bake = None; + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); - if let Some((ts, _, rx)) = &job.current { - match rx.try_recv() { - Ok(Ok(out)) => { - let ts = *ts; + if let Some(running) = &job.current { + let set_index = running.set_index; + + // Show one map per poll so each reaches its own frame + // An empty channel can gain a map before the result arrives: wait for the sender to close + match running.maps.try_recv() { + Ok(map) => { + self.session.bake_preview_map(set_index, map); + return; + } + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => {} + } + + match running.receiver.try_recv() { + Ok(Ok(output)) => { job.current = None; - if let Err(e) = self.session.apply_bake(ts, out) { - self.session.bake_abandoned([ts]); - self.toast(e.to_string(), true); + if let Err(error) = self.session.apply_streamed_bake(set_index, output) { + self.toast(error.to_string(), true); } } - Ok(Err(e)) => { - let msg = e.to_string(); + Ok(Err(error)) => { self.cancel_bake(); - self.toast(msg, true); + self.toast(error.to_string(), true); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, @@ -288,58 +449,52 @@ impl TextureCraftApp { } } } + let Some(job) = self.bake.as_mut() else { return }; - if job.current.is_none() { - if job.queue.is_empty() { - self.bake = None; - self.toast(i18n::tr("Mesh maps baked"), false); - return; - } - let (ts, only) = (job.queue.remove(0), job.only); - self.session.begin_bake(ts); - match self.session.bake_task_for(ts, only) { - Ok(task) => { - let progress = Arc::new(Progress::new()); - let p = progress.clone(); - let rx = spawn_worker("texturecraft-bake", move || task.run(&p)); - if let Some(job) = self.bake.as_mut() { - job.current = Some((ts, progress, rx)); - } - } - Err(e) => { - self.session.bake_abandoned([ts]); - self.toast(e.to_string(), true); + + if job.queue.is_empty() { + self.bake = None; + self.session.bake_preview_end(); + self.toast(i18n::tr("Mesh maps baked"), false); + return; + } + + let set_index = job.queue.remove(0); + self.session.bake_preview_set_current(set_index); + match self.session.bake_task(set_index) { + Ok(task) => { + let progress = Arc::new(Progress::new()); + let worker_progress = progress.clone(); + let maps_total = task.maps().len(); + let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let worker_done = maps_done.clone(); + let (sender, maps) = std::sync::mpsc::channel(); + let receiver = spawn_worker("texturecraft-bake", move || { + task.run_streaming(&worker_progress, &mut |map| { + worker_done.fetch_add(1, Ordering::Relaxed); + let _ = sender.send(map); + }) + }); + + if let Some(job) = self.bake.as_mut() { + job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); } } + Err(error) => self.toast(error.to_string(), true), } } - /// Auto-rebake: when the chosen map's bake inputs changed, bake it again in the background - /// (one set after another, only that map), unless a bake or a stroke is running. - fn drive_auto_rebake(&mut self) { - // The web build runs a bake on the page's own thread, which would freeze the browser: there - // Auto-rebake is left to the manual command (`bake.autoRebake.run`). - if cfg!(target_arch = "wasm32") { - return; - } - if self.bake.is_some() || self.session.stroke_active() || self.session.auto_rebake.map.is_none() { - return; - } - let due = self.session.auto_rebake_due(); - if !due.is_empty() { - let total = due.len(); - self.bake = Some(BakeJob { queue: due, current: None, total, only: self.session.auto_rebake.map }); - } - } - - /// Stops the bake job (also after an error). The set being baked and the queued ones wait for - /// their next bake input change before Auto-rebake tries them again. + /// Cancel the active worker, discard queued sets and restore the view. The current set's + /// preview maps are discarded; previously applied sets keep their results and undo steps. pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - if let Some((_, p, _)) = &job.current { - p.cancel.store(true, Ordering::Relaxed); + + if let Some(running) = job.current { + running.progress.cancel.store(true, Ordering::Relaxed); } - self.session.bake_abandoned(job.current.map(|(ts, ..)| ts).into_iter().chain(job.queue)); + + // Only the current set is uncommitted; completed sets remain applied + self.session.bake_preview_end(); } /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when @@ -376,12 +531,35 @@ impl TextureCraftApp { } } + /// The map being baked and its position among the queued maps and texture sets. + pub fn bake_status(&self) -> Option { + let job = self.bake.as_ref()?; + let stage = self.session.bake_preview.as_ref()?.stage()?; + let map = i18n::tr(i18n::baked_map_label(stage.map)); + let (n, total) = (stage.position, stage.total); + if job.total > 1 { + let set = job.total - job.queue.len(); + return Some(i18n::trf( + "Baking {map} ({n}/{total}), texture set {set} of {sets}", + &[("map", &map), ("n", &n), ("total", &total), ("set", &set.max(1)), ("sets", &job.total)], + )); + } + + Some(i18n::trf("Baking {map} ({n}/{total})", &[("map", &map), ("n", &n), ("total", &total)])) + } + /// Bake progress 0..1 across all queued sets. pub fn bake_progress(&self) -> Option { let job = self.bake.as_ref()?; let done = job.total - job.queue.len() - usize::from(job.current.is_some()); - let cur = job.current.as_ref().map(|(_, p, _)| p.fraction()).unwrap_or(0.0); - Some(((done as f32 + cur) / job.total.max(1) as f32).clamp(0.0, 1.0)) + + // Each map is a bake of its own: its progress runs from 0 to 1 within the set's share + let current = job + .current + .as_ref() + .map(|running| (running.maps_done.load(Ordering::Relaxed) as f32 + running.progress.fraction()) / running.maps_total.max(1) as f32) + .unwrap_or(0.0); + Some(((done as f32 + current) / job.total.max(1) as f32).clamp(0.0, 1.0)) } } @@ -393,7 +571,7 @@ fn spawn_worker(name: &str, f: impl FnOnce() -> T + Send + 's let _ = tx.send(f()); }); if let Err(e) = spawned { - // The receiver reports a stopped worker. + // The receiver reports a stopped worker log::warn!("could not start {name}: {e}"); } rx @@ -401,7 +579,7 @@ fn spawn_worker(name: &str, f: impl FnOnce() -> T + Send + 's #[cfg(target_arch = "wasm32")] fn spawn_worker(_name: &str, f: impl FnOnce() -> T + Send + 'static) -> std::sync::mpsc::Receiver { - // shortcut: no threads on the web; the work runs on the UI thread (the window pauses). + // Web builds run the work synchronously because threads are unavailable let (tx, rx) = std::sync::mpsc::channel(); let _ = tx.send(f()); rx @@ -444,6 +622,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 { @@ -451,7 +663,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); } @@ -468,17 +681,21 @@ impl eframe::App for TextureCraftApp { theme::apply(ctx, style.0, style.1); self.styled = Some(style); } + self.step_camera_glide(ctx); + self.ui.prefs.apply_resource_limits(); 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 { web_files::dropped(self, ctx, f); } self.poll_bake(ctx); - self.drive_auto_rebake(); self.poll_resize(ctx); self.poll_link_cooks(ctx); - // The library shelf rescans when the window comes back (MaterialCraft may have sent a material). + self.thumbs.sync_images(&self.session.images, self.session.revision); + // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; @@ -497,39 +714,47 @@ 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. + // The Path tool's curve repaints (a preview while placed) as its points, brush or material change if let Err(e) = self.session.path_live() { - self.session.stop_path_edit(); + self.session.cancel_path(); self.toast(e.to_string(), true); } 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 { titlebar::show(self, ui); banner(self, ui); - toolbar::top_bar(self, ui); toolbar::status_bar(self, ui); toolbar::tool_shelf(self, ui); - // Bake settings take the Assets slot; a side panel only when Assets is closed. - if self.ui.mode == state::Mode::Baking && !self.ui.dock.is_open(docking::Panel::Assets) { - windows::bake_left(self, ui); + self.ui.sync_mode_dock(); + if self.ui.mode != state::Mode::Baking { + toolbar::rail(self, ui); } - toolbar::rail(self, ui); } 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) }); + // The dock keeps the cards' gutter from the bars and rails around it + 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 09f19c07..b5bafea5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -2,13 +2,15 @@ //! 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 texturecraft_engine::Tool; 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,13 +63,16 @@ 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", "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 Set List", "ui.view.textureSetList", None), + sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), sub("Window", "Views", "Texture Set Settings", "ui.view.textureSetSettings", None), sub("Window", "Save UI Layout", "Save current layout...", "ui.layout.save", None), it("Window", "Load UI Layout", "ui.layout.load", None), @@ -96,6 +101,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), ]; @@ -104,12 +111,27 @@ fn is_ui(id: &str) -> bool { id.starts_with("ui.") } -/// Whether an item can run now. +/// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { + if let Some(panel) = crate::docking::view_panel(id) { + return panel.available_in(app.ui.mode); + } + + if app.ui.mode != Mode::Painting && (id.starts_with("tool.") || id.starts_with("viewport.quickMask")) { + return false; + } + if is_ui(id) { return true; } - texturecraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok()) + + // Scripts may pick any tool, but the shelf and its shortcuts offer only those that can act + let tool = id.strip_prefix("tool.").and_then(|tool_id| Tool::ALL.into_iter().find(|tool| tool.id() == tool_id)); + if tool.is_some_and(|tool| !app.session.tool_usable(tool)) { + return false; + } + + texturecraft_engine::find(id).is_some_and(|command| (command.enabled)(&app.session).is_ok()) } /// Whether an id is implemented at all (parity report). @@ -117,22 +139,32 @@ pub fn implemented(id: &str) -> bool { is_ui(id) || texturecraft_engine::find(id).is_some() } -/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`). +/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`) pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { + if !enabled(app, id) { + return; + } + if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { return; } + if let Some(panel) = crate::docking::view_panel(id) { - app.ui.dock.toggle(panel); + if crate::rail_popup::is_rail_panel(panel) { + crate::rail_popup::toggle(app, panel); + } else { + app.ui.dock.toggle(panel); + } return; } + match id { "ui.newProject" => app.ui.windows.new_project = true, "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), - "ui.projectConfig" => app.ui.dock.focus(crate::docking::Panel::Display), + "ui.projectConfig" => crate::rail_popup::open(app, crate::docking::Panel::Display), "ui.settings" => app.ui.windows.settings = true, "ui.mode.bake" => app.ui.mode = Mode::Baking, "ui.mode.paint" => app.ui.mode = Mode::Painting, @@ -149,6 +181,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")), @@ -162,21 +196,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()); @@ -263,18 +282,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 { @@ -289,43 +325,70 @@ 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; } - ctx.input_mut(|i| { - let keys: Vec<_> = i.events.iter().filter_map(|e| clipboard_key(e, i.modifiers)).collect(); - i.events.extend(keys); + + #[cfg(not(target_arch = "wasm32"))] + if crate::updates_ui::blocks_input(app) { + return; + } + + // The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V + // Unless bound, Shift+Delete and Shift+Insert become Ctrl+X and Ctrl+V + ctx.input_mut(|input| { + 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(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) { - return; - } - let active = crate::keymap::active(&app.ui.keymap); - let mut fire: Vec<&str> = Vec::new(); - ctx.input_mut(|i| { - for (id, sc) in &active { - if i.consume_shortcut(sc) { - fire.push(*id); + + // Escape closes a dropdown before Properties, the rail popup, color picking or the stroke + let popup_open = egui::Popup::is_any_open(ctx); + + 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); } } - // Brush size and hardness: [ and ]. - let size_down = i.consume_key(Modifiers::NONE, Key::OpenBracket); - let size_up = i.consume_key(Modifiers::NONE, Key::CloseBracket); - if size_down || size_up { - let f = if size_up { 1.15 } else { 1.0 / 1.15 }; - app.session.tool.brush.size = (app.session.tool.brush.size * f).clamp(0.0005, 0.25); + + // [ 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 { 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 i.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 && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + app.ui.rail_panel = 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; + app.session.cancel_path(); } + commands }); - for id in fire { - if matches!(id, "layer.copy" | "layer.cut") - && let Some(layer) = app.session.selected_layer().and_then(|l| app.session.doc.project.layers.get(&l)) + + 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. + // Ctrl+V reaches the app only while the system clipboard holds text or an image ctx.copy_text(layer.name.clone()); } invoke(app, ctx, effect_command(app, id)); @@ -342,5 +405,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/path_hit.rs b/crates/ui-egui/src/path_hit.rs new file mode 100644 index 00000000..6b62f0f0 --- /dev/null +++ b/crates/ui-egui/src/path_hit.rs @@ -0,0 +1,17 @@ +//! What a pointer position in a view is over, for the Path tool + +use egui::Pos2; +use texturecraft_engine::core::LayerId; + +/// What a pointer position in a view is over, for the Path tool +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum PathHit { + /// A control point of the path being edited + Point(usize), + /// The edited path's curve: the segment starting at this point, and the nearest screen position on it + Curve(usize, Pos2), + /// Another stored path of the selected layer: (path sublayer, index) + Stored(LayerId, usize), + /// Nothing of a path + Miss, +} diff --git a/crates/ui-egui/src/path_surface_cache.rs b/crates/ui-egui/src/path_surface_cache.rs new file mode 100644 index 00000000..9b216083 --- /dev/null +++ b/crates/ui-egui/src/path_surface_cache.rs @@ -0,0 +1,46 @@ +//! Sampled path curves retained only while the viewport uses them. + +use std::collections::HashMap; +use std::sync::Arc; + +use egui::cache::CacheTrait; +use texturecraft_engine::Session; +use texturecraft_engine::core::{LayerId, PathShape}; +use texturecraft_engine::geom::glam::Vec3; + +pub(crate) type SurfaceCurve = Arc>>>; + +#[derive(Default)] +pub(crate) struct PathSurfaceCache { + // Mesh, effect and path index identify entries; the flag records use during this pass + curves: HashMap<(u64, LayerId, usize), (PathShape, SurfaceCurve, bool)>, +} + +impl PathSurfaceCache { + /// Reuse an unchanged curve and retain it for this pass; UV or missing paths have no surface curve + pub(crate) fn get(&mut self, session: &Session, effect: LayerId, index: usize) -> Option { + let shape = session.paths(effect)?.get(index)?; + let key = (session.mesh_id, effect, index); + if let Some((cached_shape, surface, used)) = self.curves.get_mut(&key) + && cached_shape == shape + { + *used = true; + return Some(Arc::clone(surface)); + } + + let surface = Arc::new(session.stored_path_surface(effect, index)?); + self.curves.insert(key, (shape.clone(), Arc::clone(&surface), true)); + Some(surface) + } +} + +impl CacheTrait for PathSurfaceCache { + fn update(&mut self) { + // egui calls this even when paths stop drawing, so hidden or deleted paths release their buffers + self.curves.retain(|_, (_, _, used)| std::mem::take(used)); + } + + fn len(&self) -> usize { + self.curves.len() + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs new file mode 100644 index 00000000..7e6469d6 --- /dev/null +++ b/crates/ui-egui/src/preview_image.rs @@ -0,0 +1,236 @@ +//! 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 a `size_px` square +pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage { + // Leave room around the S curve and cap work for a single preview + const STROKE_RADIUS_FRACTION: f32 = 0.11; + const CURVE_SAMPLE_STEP: f32 = 0.002; + const MIN_STAMP_SPACING_PX: f32 = 0.5; + const MAX_STAMPS: u32 = 2000; + const CURVE_HORIZONTAL_INSET: f32 = 0.15; + const CURVE_HORIZONTAL_SPAN: f32 = 0.7; + const CURVE_WAVE_AMPLITUDE: f32 = 0.22; + + let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let radius = size_px as f32 * STROKE_RADIUS_FRACTION; + let shape = Shape { alpha: brush.alpha, image, library, level: 0 }.at_radius(radius); + + // The horizontal inset and vertical wave keep the S curve inside the swatch + let curve = |t: f32| { + ( + size_px as f32 * (CURVE_HORIZONTAL_INSET + CURVE_HORIZONTAL_SPAN * t), + size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()), + ) + }; + let mut cover = vec![0f32; size_px * size_px]; + + // Odd multipliers decorrelate reproducible jitter across stamps and channels + let jitter_sample = |stamp_index: u32, channel: u32| { + (stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32 + }; + let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX); + let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + let mut last = curve(0.0); + + while t <= 1.0 && i < MAX_STAMPS { + let p = curve(t); + travelled += (p.0 - last.0).hypot(p.1 - last.1); + last = p; + t += CURVE_SAMPLE_STEP; + if travelled < step { + continue; + } + travelled = 0.0; + i += 1; + let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1)); + let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; + let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2); + let (cx, cy) = ( + p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0), + p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0), + ); + let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5)); + let (sin, cos) = angle.sin_cos(); + let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px)); + let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px)); + for y in y0..y1 { + for x in x0..x1 { + let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius); + let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow; + let coverage = &mut cover[y * size_px + x]; + *coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0)); + } + } + } + ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect()) +} + +/// Environment `name`'s panorama across a `size²` swatch, transparent above and below +pub fn environment_image(name: &str, size: usize) -> ColorImage { + let panorama = texturecraft_render::ibl::environment(name, u32::try_from(size).unwrap_or(u32::MAX)); + let (width, height) = (panorama.width as usize, panorama.height as usize); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let top = size.saturating_sub(height) / 2; + for (y, row) in panorama.data.chunks(width.max(1)).enumerate() { + for (x, linear) in row.iter().enumerate().take(size) { + let Some(pixel) = image.pixels.get_mut((top + y) * size + x) else { continue }; + + let [r, g, b] = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + *pixel = Color32::from_rgb(r, g, b); + } + } + image +} 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..e58901b4 --- /dev/null +++ b/crates/ui-egui/src/preview_worker.rs @@ -0,0 +1,239 @@ +//! 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(); + // Instrumented orb baking can take several minutes on coverage runners. + let timeout = if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + Duration::from_secs(120) + }; + while answers.len() < requests_sent && start.elapsed() < timeout { + 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/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs new file mode 100644 index 00000000..afe85f1a --- /dev/null +++ b/crates/ui-egui/src/rail_popup.rs @@ -0,0 +1,240 @@ +//! The rail's panels open in a popup beside their rail icon, one at a time; dragging its title docks or floats the panel + +use egui::{Id, Pos2, Rect, RichText, Sense, Ui}; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::tr; +use crate::state::Mode; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The rail's panels, top to bottom, with their icons and Window ▸ Views ids +pub(crate) const RAIL_PANELS: [(Panel, &str, &str); 5] = [ + (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), + (Panel::Display, ic::MONITOR, "ui.view.display"), + (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), + (Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"), + (Panel::Log, ic::FILE_TEXT, "ui.view.log"), +]; + +/// The popup reaches this far into the viewport, so it covers the panels between the viewport and the rail +const VIEWPORT_OVERHANG: f32 = 48.0; + +/// Narrowest the popup gets, when the viewport is not left of the rail's column +const POPUP_MIN_WIDTH: f32 = 320.0; + +/// Settings panels' popups fit their contents up to this height, then scroll +const SETTINGS_MAX_HEIGHT: f32 = 640.0; + +/// History and Log fill their popup, so it has one height +const LIST_HEIGHT: f32 = 400.0; + +/// Gap between the popup and the rail +const RAIL_GAP: f32 = 4.0; + +/// Size of the close button in the popup's title row +const TITLE_BUTTON_SIZE: f32 = 22.0; + +/// The popup's area, whose rect egui remembers between frames +fn area_id() -> Id { + Id::unique("rail_popup") +} + +/// Where the rail drew its strip on this frame +fn strip_id() -> Id { + Id::unique("rail_popup_strip") +} + +/// Where the rail drew each panel's icon on this frame +fn icons_id() -> Id { + Id::unique("rail_popup_icons") +} + +/// The panel whose popup title a drag left, and the title's rect, until the dock takes the drag over +fn pending_drag_id() -> Id { + Id::unique("rail_popup_pending_drag") +} + +/// Where the dock drew the viewport on this frame +fn viewport_id() -> Id { + Id::unique("rail_popup_viewport") +} + +/// Whether `panel` opens from the rail rather than in the dock +pub(crate) fn is_rail_panel(panel: Panel) -> bool { + RAIL_PANELS.iter().any(|(rail_panel, _, _)| *rail_panel == panel) +} + +/// Whether the rail's open popup is visible in the current UI mode +pub(crate) fn is_visible(app: &TextureCraftApp) -> bool { + app.ui.rail_panel.is_some() && !app.ui.hide_ui && app.ui.mode != Mode::Baking +} + +/// Record the rail's strip before its icons, so the popup can line up with them +pub(crate) fn begin_rail(ctx: &egui::Context, strip: Rect) { + ctx.data_mut(|data| { + data.insert_temp(strip_id(), strip); + data.insert_temp(icons_id(), Vec::<(Panel, Rect)>::new()); + }); +} + +/// Record where the rail drew `panel`'s icon +pub(crate) fn remember_icon(ctx: &egui::Context, panel: Panel, icon: Rect) { + ctx.data_mut(|data| data.get_temp_mut_or_default::>(icons_id()).push((panel, icon))); +} + +/// Record where the dock drew the viewport, whose right edge the popup reaches past +pub(crate) fn remember_viewport(ctx: &egui::Context, viewport: Rect) { + ctx.data_mut(|data| data.insert_temp(viewport_id(), viewport)); +} + +/// A rail icon or its Window ▸ Views item: open `panel` in the popup in place of the one there, or close it +pub(crate) fn toggle(app: &mut TextureCraftApp, panel: Panel) { + // Bake mode has no rail, and a panel in the dock (which then has no rail icon) is toggled there + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.dock.toggle(panel); + return; + } + + app.ui.rail_panel = if app.ui.rail_panel == Some(panel) { None } else { Some(panel) }; +} + +/// Open `panel` from the rail: in its popup, or where it is in the dock (bake mode has no rail) +pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) { + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.dock.focus(panel); + } else { + app.ui.rail_panel = Some(panel); + } +} + +/// Hand a drag that left the popup's title to the dock, once the dock has drawn the panel it floated +pub(crate) fn hand_drag_to_dock(ctx: &egui::Context, dock_area: Id) { + let Some((panel, title)) = ctx.data(|data| data.get_temp::<(Panel, Rect)>(pending_drag_id())) else { return }; + + ctx.data_mut(|data| data.remove::<(Panel, Rect)>(pending_drag_id())); + if ctx.input(|input| input.pointer.primary_down()) { + craft_ui::docking::begin_drag(ctx, dock_area, panel, title); + } +} + +/// A rail popup and its dismissing press cannot start a paint stroke or move a decal +pub(crate) fn blocks_paint_input(app: &TextureCraftApp, ctx: &egui::Context) -> bool { + let closing_id = area_id().with("closing"); + let pointer_active = ctx.input(|input| input.pointer.any_down() || input.pointer.any_released()); + if !pointer_active { + ctx.data_mut(|data| data.remove::(closing_id)); + } + + // Both views must ignore the release, which would otherwise start a single-dab stroke + let closing = ctx.data(|data| data.get_temp::(closing_id)).unwrap_or(false); + + // A shortcut may open the panel during a stroke; let that existing stroke finish + !app.session.stroke_active() && (is_visible(app) || closing) +} + +/// Draw the open popup beside its icon; a press outside it closes it, as for a menu (Escape does too, in `menus.rs`) +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + // The dock has drawn both views, so a released dismissal must not suppress the next click + if !ctx.input(|input| input.pointer.any_down()) { + ctx.data_mut(|data| data.remove::(area_id().with("closing"))); + } + + let Some(panel) = app.ui.rail_panel else { return }; + + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.rail_panel = None; + return; + } + + let strip = ctx.data(|data| data.get_temp::(strip_id())).unwrap_or(Rect::NOTHING); + let icons = ctx.data(|data| data.get_temp::>(icons_id())).unwrap_or_default(); + let Some(icon) = icons.iter().find(|(icon_panel, _)| *icon_panel == panel).map(|(_, rect)| *rect) else { + app.ui.rail_panel = None; + return; + }; + + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + if closed_by_input(ctx, shown, strip) { + app.ui.rail_panel = None; + let held = ctx.input(|input| input.pointer.any_down()); + ctx.data_mut(|data| data.insert_temp(area_id().with("closing"), held)); + return; + } + + let tokens = Tokens::get(ctx); + let frame = egui::Frame::popup(&ctx.global_style()).fill(tokens.panel).stroke(egui::Stroke::new(1.0, tokens.accent)); + let (top_right, width) = placement(ctx, strip, icon); + let mut closed = false; + let mut dragged_from = None; + egui::Area::new(area_id()).order(egui::Order::Foreground).pivot(egui::Align2::RIGHT_TOP).fixed_pos(top_right).show(ctx, |ui| { + frame.show(ui, |ui| { + ui.set_width(width - frame.total_margin().sum().x); + let title_top = ui.cursor().top(); + (closed, dragged_from) = title_row(ui, &tokens, panel); + ui.separator(); + + // Keep the title, frame and body on screen even when the window is shorter than the usual popup + let title_height = ui.cursor().top() - title_top; + let body_height = (ctx.content_rect().height() - frame.total_margin().sum().y - title_height).max(0.0); + body(app, ui, panel, body_height); + }); + }); + + if closed { + app.ui.rail_panel = None; + } else if let Some(title) = dragged_from { + app.ui.rail_panel = None; + let rect = shown.unwrap_or(title); + app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]); + ctx.data_mut(|data| data.insert_temp(pending_drag_id(), (panel, title))); + } +} + +/// The popup's top right corner, beside the rail and level with its icon, and its width (egui keeps the area on screen) +fn placement(ctx: &egui::Context, strip: Rect, icon: Rect) -> (Pos2, f32) { + let right = strip.left() - RAIL_GAP; + let viewport = ctx.data(|data| data.get_temp::(viewport_id())); + let width = viewport.map_or(POPUP_MIN_WIDTH, |viewport| right - (viewport.right() - VIEWPORT_OVERHANG)).max(POPUP_MIN_WIDTH); + (Pos2::new(right, icon.top()), width) +} + +/// A press outside the popup and the rail, unless in one of the popup's own dropdowns +fn closed_by_input(ctx: &egui::Context, shown: Option, strip: Rect) -> bool { + let pressed_at = ctx.input(|input| input.pointer.press_origin().filter(|_| input.pointer.any_pressed())); + + // A press on the rail is left to its icons, which switch or close the popup themselves + let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at))); + outside && !egui::Popup::is_any_open(ctx) +} + +/// The panel's contents: History and Log at one height, the settings panels as tall as their contents up to a limit +fn body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel, available_height: f32) { + // A child Ui, so the height limits start below the title row instead of moving the cursor back up to it + ui.scope(|ui| { + if matches!(panel, Panel::History | Panel::Log) { + ui.set_height(LIST_HEIGHT.min(available_height)); + } else { + // The area's remembered size would otherwise cap the height + ui.set_max_height(SETTINGS_MAX_HEIGHT.min(available_height)); + } + + crate::docking::panel_body(app, ui, panel); + }); +} + +/// The panel's name, which drags like a tab, and a close button: whether it was clicked, and where a drag started +fn title_row(ui: &mut Ui, tokens: &Tokens, panel: Panel) -> (bool, Option) { + let row = ui.horizontal(|ui| { + ui.label(RichText::new(tr(panel.name())).strong().color(tokens.text_strong)); + ui.add_space((ui.available_width() - TITLE_BUTTON_SIZE).max(0.0)); + icon_button(ui, ic::X, tr("Close"), false, TITLE_BUTTON_SIZE) + }); + + let (row, close) = (row.response.rect, row.inner); + let title = Rect::from_min_max(row.min, egui::pos2(close.rect.left(), row.bottom())); + let drag = ui.interact(title, ui.scope_id().with("rail_popup_title"), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); + (close.clicked(), drag.drag_started().then_some(title)) +} diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 8228f51a..cef71ed1 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -14,9 +14,11 @@ use std::sync::{Mutex, PoisonError}; use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor}; use egui::{Color32, ColorImage, Rect, RichText, TextureHandle, TextureOptions, Ui, vec2}; +use texturecraft_engine::compose::ImageRes; use texturecraft_engine::geom::{Bvh, Mesh, OrbitCamera}; use texturecraft_render::displace::trace_geometry; use texturecraft_render::gpu_trace::GpuTracer; +use texturecraft_render::ibl::EnvImage; use texturecraft_render::readback::Readback; use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer}; use texturecraft_render::{Renderer, wgpu}; @@ -25,6 +27,15 @@ use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; use crate::theme::Tokens; +mod frame_floor; +mod motion; +mod spp_control; +#[cfg(test)] +mod tests; + +use motion::Motion; +use spp_control::{SppControl, rescale_spp}; + /// A finished pass, ready to show. struct Frame { width: u32, @@ -132,9 +143,76 @@ struct GpuView { out_view: wgpu::TextureView, texture: egui::TextureId, status: Arc>, - /// Samples per pixel per frame: grows while frames are quick, halves when they are slow. + /// Samples per pixel per frame: grows while frames are quick, decreases when they are slow. spp: u32, + /// What steers `spp`. + spp_control: SppControl, read: Arc>, + /// An image of this render was resolved into `texture` at least once, so a restart keeps + /// showing it (the previous camera's frame) until the new samples replace it. + has_image: bool, + /// The egui texture of the last image traced at the smaller moving size, shown instead of + /// `texture` while the full-size render is too grainy (see [`holds_previous`]). + held: Option, + /// When `held` started being shown (egui time, seconds): a restart while it is up (a display + /// slider dragged) resets `started`, so the hold is timed from this instead. + held_since: f64, +} + +/// While the camera moves, the GPU render is traced at this fraction of the view size per axis +/// (the image is stretched to the view). A quarter of the pixels means about four times the samples +/// per pixel in the same frame time, so an orbit shows a smooth image instead of one or two noisy +/// samples; a faster GPU affords more samples (see `GpuView::spp`) at the same size. +const MOVING_SCALE: f32 = 0.5; + +/// Seconds without a camera change after which the render returns to the full view size. +const MOTION_SETTLE_S: f64 = 0.2; + +/// While textures load, new tiles are taken into the render at most this often (seconds). Each +/// time restarts the render, so taking them in every frame leaves it forever one or two samples +/// deep (raw noise) until loading ends; this lets about a third of a second of samples build up +/// between restarts, at the price of a little delay before a new tile shows. +const LOADING_RESTART_S: f64 = 0.35; + +/// Most samples per frame while textures load (see [`LOADING_RESTART_S`]). The frame time is +/// then the compositor's, not the tracer's, so the count is not steered by it: it stays where it +/// was, at most this (cheap at the smaller loading size). +const LOADING_MAX_SPP: u32 = 8; + +/// Whether textures are still loading: tiles wait to be composited, or composited ones to be +/// uploaded (the GPU render copies the uploaded display textures). +fn textures_loading(session: &texturecraft_engine::Session) -> bool { + session.pending_tiles() > 0 || session.caches.iter().any(|cache| !cache.upload.is_empty()) +} + +/// Whether changed textures are taken into the render now: always, except while loading, when at +/// most every [`LOADING_RESTART_S`]. +fn take_in_textures(loading: bool, now: f64, last_sync: f64) -> bool { + !loading || now - last_sync >= LOADING_RESTART_S +} + +/// When the render returns to full size after the camera stops, the soft image traced while it +/// moved stays on screen until the full-size render has this many samples (it starts from none, +/// and its first few samples are grainy)... +const SETTLE_HOLD_SAMPLES: u32 = 8; + +/// ...or for this many seconds at most, so a slow GPU never leaves the soft image up for long. +const SETTLE_HOLD_MAX_S: f64 = 0.5; + +/// Whether the image from before the view returned to full size is still shown: the full-size +/// render has `samples` samples after `elapsed` seconds. +fn holds_previous(samples: u32, elapsed: f64) -> bool { + samples < SETTLE_HOLD_SAMPLES && elapsed < SETTLE_HOLD_MAX_S +} + +/// Trace fewer pixels while the camera is moving, keeping tiny views at their original size. +fn traced_size(full: (u32, u32), moving: bool) -> (u32, u32) { + if !moving { + return full; + } + + let scale = |dimension: u32| ((dimension as f32 * MOVING_SCALE) as u32).clamp(16.min(dimension), dimension); + (scale(full.0), scale(full.1)) } /// The GPU tracer in egui's callback resources. @@ -144,6 +222,8 @@ struct TraceState { key: String, /// Samples in the resolved image (None: resolve again). resolved: Option, + /// When the tracer last took in changed textures (egui time, seconds). + last_sync: f64, } /// Traced geometry and the key of what it was built from. @@ -157,45 +237,75 @@ pub struct RenderView { /// Why the GPU tracer failed on the scene of this key (the CPU renders it instead). gpu_error: Option<(String, String)>, texture: Option, + motion: Motion, shown: Option<(u32, u32, Vec)>, samples: u32, elapsed: f64, /// The traced geometry (displaced or not) and what it was built from: changes to the display /// alone don't rebuild it. geometry: Mutex>, + /// The traced environment and what it was built from (see [`EnvKey`]): building one takes a + /// while, and the scene is rebuilt on every display change. + env: Mutex)>>, } +/// The display's environment name and its retained imported image (None: built-in). +type EnvKey = (String, Option>); + /// Viewport resolution of a CPU render (the web renders at half size: it has one thread). fn render_size(rect: Rect) -> (u32, u32) { let scale = if cfg!(target_arch = "wasm32") { 0.5 } else { 1.0 }; ((rect.width() * scale).max(16.0) as u32, (rect.height() * scale).max(16.0) as u32) } +/// Build a scene while retaining unchanged geometry and the decoded environment. fn trace_scene(app: &TextureCraftApp) -> TraceScene { - let s = &app.session; - let d = &s.doc.project.display; - let sets: Vec = s + let session = &app.session; + let display = &session.doc.project.display; + let sets: Vec = session .doc .project .texture_sets .iter() - .zip(&s.caches) - .map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() }) + .zip(&session.caches) + .map(|(set, cache)| TraceSet { material: set.material, composite: cache.composite.clone(), height_strength: set.atlas_height_strength() }) .collect(); - let env_image = d.environment_resource().and_then(|n| s.images.get(n)); - let revisions: Vec = s.caches.iter().map(|c| c.revision).collect(); - let strengths: Vec = sets.iter().map(|t| t.height_strength).collect(); - let key = format!("{}|{revisions:?}|{strengths:?}|{}", s.mesh_id, d.displacement); + let env_image = display.environment_resource().and_then(|n| session.images.get(n)); + + // Only displaced geometry depends on the composites (their heights) + let revisions: Vec = if display.displacement { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; + let strengths: Vec = sets.iter().map(|set| set.height_strength).collect(); + let key = format!("{}|{revisions:?}|{strengths:?}|{}", session.mesh_id, display.displacement); let mut cached = app.render.geometry.lock().unwrap_or_else(PoisonError::into_inner); let (mesh, bvh) = match cached.as_ref() { - Some((k, m, b)) if *k == key => (m.clone(), b.clone()), + Some((cached_key, mesh, bvh)) if *cached_key == key => (mesh.clone(), bvh.clone()), _ => { - let (m, b) = trace_geometry(&s.mesh, &s.bvh, &sets, d); - *cached = Some((key, m.clone(), b.clone())); - (m, b) + let (mesh, bvh) = trace_geometry(&session.mesh, &session.bvh, &sets, display); + *cached = Some((key, mesh.clone(), bvh.clone())); + (mesh, bvh) } }; - TraceScene::for_display(mesh, bvh, sets, d, env_image.map(|i| i.as_ref())) + drop(cached); + + let mut env_cached = app.render.env.lock().unwrap_or_else(PoisonError::into_inner); + let same_image = |source: &Option>| match (source, env_image) { + (Some(cached), Some(current)) => Arc::ptr_eq(cached, current), + (None, None) => true, + _ => false, + }; + let env = match env_cached.as_ref() { + Some(((name, source), environment)) if *name == display.environment && same_image(source) => environment.clone(), + _ => { + let environment = Arc::new(TraceScene::display_env(display, env_image.map(|image| image.as_ref()))); + + // Retaining the source prevents a later image from reusing its cached identity + let env_key = (display.environment.clone(), env_image.cloned()); + *env_cached = Some((env_key, environment.clone())); + environment + } + }; + + TraceScene::for_display_env(mesh, bvh, sets, display, env) } fn settings(app: &TextureCraftApp) -> TraceSettings { @@ -217,16 +327,26 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { } } -/// What the traced scene depends on. -fn scene_key(app: &TextureCraftApp) -> String { - let s = &app.session; - let revisions: Vec = s.caches.iter().map(|c| c.revision).collect(); - format!("{}|{revisions:?}|{:?}", s.mesh_id, s.doc.project.display) +/// What the traced scene depends on. `composites`: the texture-set composites too (their +/// revisions bump with every composited chunk, so while textures load this changes every frame). +fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String { + let revisions: Vec = if composites { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; + let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength())).collect(); + + format!("{}|{revisions:?}|{sets:?}|{:?}", session.mesh_id, session.doc.project.display) } -/// What the render depends on; a change restarts it. -fn key(app: &TextureCraftApp, size: (u32, u32)) -> String { - format!("{}|{:?}|{size:?}|{:?}", scene_key(app), app.session.camera, app.ui.render) +/// [`scene_key`] of the GPU render. It takes texture changes in by copying the display textures +/// when their content changes (throttled while textures load, see [`take_in_textures`]), so the +/// composites only count when they displace the geometry. Restarting on every composited chunk +/// would rebuild the scene and reset the render every frame of a load. +fn gpu_scene_key(session: &texturecraft_engine::Session) -> String { + scene_key(session, session.doc.project.display.displacement) +} + +/// What the render of scene `scene_key` depends on; a change restarts it. +fn key(app: &TextureCraftApp, scene_key: &str, size: (u32, u32)) -> String { + format!("{scene_key}|{:?}|{size:?}|{:?}", app.session.camera, app.ui.render) } fn start(app: &TextureCraftApp, ctx: &egui::Context, key: String, size: (u32, u32)) -> Job { @@ -269,40 +389,53 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { overlay(app, ui, rect, on_gpu); } +/// Advance the CPU render and keep the last completed image visible during restarts. fn show_cpu(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { let ctx = ui.ctx().clone(); let size = render_size(rect); - let k = key(app, size); - if app.render.job.as_ref().is_none_or(|j| j.key != k) { - app.render.job = Some(start(app, &ctx, k, size)); + + // The CPU tracer reads the composites themselves: every change restarts it + let render_key = key(app, &scene_key(&app.session, true), size); + if app.render.job.as_ref().is_none_or(|job| job.key != render_key) { + app.render.job = Some(start(app, &ctx, render_key, size)); app.render.samples = 0; } + let now = ctx.input(|i| i.time); if let Some(job) = app.render.job.as_mut() { #[cfg(target_arch = "wasm32")] { - if let Some(f) = job.work.step_for(30.0) { - *job.latest.lock().unwrap_or_else(PoisonError::into_inner) = Some(f); + if let Some(frame) = job.work.step_for(30.0) { + *job.latest.lock().unwrap_or_else(PoisonError::into_inner) = Some(frame); } if job.work.tracer.samples < job.work.max_samples { ctx.request_repaint(); } } - if let Some(f) = job.latest.lock().unwrap_or_else(PoisonError::into_inner).take() { - let img = ColorImage::from_rgba_unmultiplied([f.width as usize, f.height as usize], &f.rgba); + if let Some(frame) = job.latest.lock().unwrap_or_else(PoisonError::into_inner).take() { + let image = ColorImage::from_rgba_unmultiplied([frame.width as usize, frame.height as usize], &frame.rgba); match app.render.texture.as_mut() { - Some(t) => t.set(img, TextureOptions::LINEAR), - None => app.render.texture = Some(ctx.load_texture("render-view", img, TextureOptions::LINEAR)), + Some(texture) => texture.set(image, TextureOptions::LINEAR), + None => app.render.texture = Some(ctx.load_texture("render-view", image, TextureOptions::LINEAR)), } - app.render.samples = f.samples; + app.render.samples = frame.samples; app.render.elapsed = now - job.started; - app.render.shown = Some((f.width, f.height, f.rgba)); + app.render.shown = Some((frame.width, frame.height, frame.rgba)); } } - let shown = app.render.texture.as_ref().filter(|_| app.render.samples > 0).map(TextureHandle::id); + + let shown = app.render.texture.as_ref().map(TextureHandle::id); paint(ui, rect, shown); } +/// Whether the view shows the render image rather than the "Starting render..." placeholder. +/// `has_image`: an earlier frame of this render is on screen. A restart (the camera moved) resets +/// the sample count to 0 but keeps that frame up, so orbiting doesn't flash the placeholder. +/// Only the very first frame, before anything was traced, has nothing to show. +fn show_image(has_image: bool, samples: u32) -> bool { + has_image || samples > 0 +} + /// The render, or a placeholder until its first samples. fn paint(ui: &Ui, rect: Rect, texture: Option) { let tk = Tokens::get(ui.ctx()); @@ -320,96 +453,165 @@ fn paint(ui: &Ui, rect: Rect, texture: Option) { /// Trace on the GPU; false when it can't (no compute shaders, or it failed on this scene). fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { - let Some(rs) = app.render_state.clone() else { return false }; - let scene_key = scene_key(app); - if !GpuTracer::supported(&rs.device) || app.render.gpu_error.as_ref().is_some_and(|(k, _)| *k == scene_key) { + let Some(render_state) = app.render_state.clone() else { return false }; + let scene_key = gpu_scene_key(&app.session); + if !GpuTracer::supported(&render_state.device) || app.render.gpu_error.as_ref().is_some_and(|(k, _)| *k == scene_key) { return false; } + app.render.gpu_error = None; if app.render.job.take().is_some() { app.render.texture = None; app.render.shown = None; } + let ctx = ui.ctx().clone(); let now = ctx.input(|i| i.time); - let size = (rect.width().max(16.0) as u32, rect.height().max(16.0) as u32); - let key = key(app, size); - let mut g = match app.render.gpu.take() { - Some(g) if g.size == size => g, + let full = (rect.width().max(16.0) as u32, rect.height().max(16.0) as u32); + let loading = textures_loading(&app.session); + let moving = app.render.motion.moving(&app.session.camera, now, loading); + if moving { + // Come back and restore the full size once the camera has been still, even with no input + ctx.request_repaint_after(std::time::Duration::from_secs_f64(MOTION_SETTLE_S)); + } + + let size = traced_size(full, moving); + let key = key(app, &scene_key, size); + let mut previous = app.render.gpu.take(); + if let Some(view) = previous.as_mut() { + // Read the completed callback before resizing replaces its status + view.has_image |= view.status.lock().unwrap_or_else(PoisonError::into_inner).samples > 0; + } + + let mut view = match previous { + Some(view) if view.size == size => view, old => { - let out = GpuTracer::output_texture(&rs.device, size.0, size.1); + let out = GpuTracer::output_texture(&render_state.device, size.0, size.1); let out_view = out.create_view(&Default::default()); - // A resized view keeps its scene and egui texture id. - let (texture, scene_key, scene) = match old { + + // A resized view keeps its scene and egui texture id + let old_has_image = old.as_ref().is_some_and(|previous| previous.has_image); + let old_spp = old.as_ref().map_or(1, |previous| rescale_spp(previous.spp, previous.size, size)); + let mut held_since = old.as_ref().map_or(now, |previous| previous.held_since); + let growing = old.as_ref().is_some_and(|previous| u64::from(previous.size.0) * u64::from(previous.size.1) < u64::from(size.0) * u64::from(size.1)); + let mut held = None; + let (texture, scene_key, scene, spp_control) = match old { + // Returning to full size: the old image stays up under its own texture id + Some(old) if growing && old.has_image => { + let mut renderer = render_state.renderer.write(); + if let Some(texture) = old.held { + renderer.free_texture(&texture); + } + + held = Some(old.texture); + held_since = now; + (renderer.register_native_texture(&render_state.device, &out_view, wgpu::FilterMode::Linear), old.scene_key, old.scene, old.spp_control) + } Some(old) => { - rs.renderer.write().update_egui_texture_from_wgpu_texture(&rs.device, &out_view, wgpu::FilterMode::Linear, old.texture); - (old.texture, old.scene_key, old.scene) + let mut renderer = render_state.renderer.write(); + if let Some(texture) = old.held { + renderer.free_texture(&texture); + } + + renderer.update_egui_texture_from_wgpu_texture(&render_state.device, &out_view, wgpu::FilterMode::Linear, old.texture); + (old.texture, old.scene_key, old.scene, old.spp_control) } None => ( - rs.renderer.write().register_native_texture(&rs.device, &out_view, wgpu::FilterMode::Linear), + render_state.renderer.write().register_native_texture(&render_state.device, &out_view, wgpu::FilterMode::Linear), scene_key.clone(), Arc::new(trace_scene(app)), + SppControl::default(), ), }; - GpuView { size, scene_key, scene, key: String::new(), started: now, out, out_view, texture, status: Arc::default(), spp: 1, read: Arc::default() } + + GpuView { + size, + scene_key, + scene, + key: String::new(), + started: now, + out, + out_view, + texture, + status: Arc::default(), + spp: old_spp, + spp_control, + read: Arc::default(), + has_image: old_has_image, + held, + held_since, + } } }; + let (samples, error) = { - let mut st = g.status.lock().unwrap_or_else(PoisonError::into_inner); - if g.key != key { - st.samples = 0; + let mut status = view.status.lock().unwrap_or_else(PoisonError::into_inner); + if view.key != key { + status.samples = 0; } - (st.samples, st.error.take()) + + (status.samples, status.error.take()) }; - if let Some(e) = error { - log::warn!("GPU path tracing failed, rendering on the CPU: {e}"); - app.render.gpu_error = Some((scene_key, e)); - app.render.gpu = Some(g); + + if let Some(error) = error { + log::warn!("GPU path tracing failed, rendering on the CPU: {error}"); + app.render.gpu_error = Some((scene_key, error)); + app.render.gpu = Some(view); return false; } - if g.key != key { - g.key = key.clone(); - g.started = now; + + if view.key != key { + view.key = key.clone(); + view.started = now; } - if g.scene_key != scene_key { - g.scene = Arc::new(trace_scene(app)); - g.scene_key = scene_key; + if view.scene_key != scene_key { + view.scene = Arc::new(trace_scene(app)); + view.scene_key = scene_key; } + let max_samples = app.ui.render.max_samples.max(1); if samples < max_samples { - // Keep the UI near 60 fps: more samples while frames are quick, half as many when slow. - let dt = ctx.input(|i| i.stable_dt); - g.spp = if dt > 1.0 / 40.0 { - (g.spp / 2).max(1) - } else if dt < 1.0 / 60.0 { - (g.spp + 1).min(16) - } else { - g.spp - }; - app.render.elapsed = now - g.started; + // Loading time includes compositing, so it cannot reliably steer the tracer's sample count + view.spp = if loading { view.spp.min(LOADING_MAX_SPP) } else { view.spp_control.next(view.spp, f64::from(ctx.input(|i| i.stable_dt))) }; + app.render.elapsed = now - view.started; ctx.request_repaint(); } + app.render.samples = samples; - if poll_read(app, &rs.device, &g) { + if poll_read(app, &render_state.device, &view) { ctx.request_repaint(); } - let cb = TraceCallback { + + let callback = TraceCallback { key, - scene: g.scene.clone(), + scene: view.scene.clone(), camera: app.session.camera, settings: settings(app), display: display(app), max_samples, - spp: g.spp, + spp: view.spp, + loading, + now, size, - out: g.out.clone(), - out_view: g.out_view.clone(), - status: g.status.clone(), - read: g.read.clone(), + out: view.out.clone(), + out_view: view.out_view.clone(), + status: view.status.clone(), + read: view.read.clone(), }; - ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, cb)); - paint(ui, rect, (samples > 0).then_some(g.texture)); - app.render.gpu = Some(g); + ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, callback)); + if let Some(held) = view.held { + let elapsed = now - view.held_since; + if holds_previous(samples, elapsed) { + // A render capped below the hold threshold still needs a frame to release the image + ctx.request_repaint_after(std::time::Duration::from_secs_f64((SETTLE_HOLD_MAX_S - elapsed).max(0.0))); + } else { + render_state.renderer.write().free_texture(&held); + view.held = None; + } + } + + paint(ui, rect, show_image(view.has_image, samples).then_some(view.held.unwrap_or(view.texture))); + app.render.gpu = Some(view); true } @@ -461,6 +663,9 @@ struct TraceCallback { display: TraceDisplay, max_samples: u32, spp: u32, + /// Textures are still loading (see [`LOADING_RESTART_S`]) and the egui time of this frame. + loading: bool, + now: f64, size: (u32, u32), out: wgpu::Texture, out_view: wgpu::TextureView, @@ -469,41 +674,51 @@ struct TraceCallback { } impl TraceCallback { + /// Synchronize scene data, add samples and resolve the frame for the UI. fn run( &self, - st: &mut TraceState, + state: &mut TraceState, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, renderer: &Renderer, ) -> Result<(), String> { - let t = &mut st.tracer; - if !st.scene.as_ref().is_some_and(|s| Arc::ptr_eq(s, &self.scene)) { - t.set_scene(device, queue, &self.scene)?; - st.scene = Some(self.scene.clone()); + let tracer = &mut state.tracer; + if !state.scene.as_ref().is_some_and(|scene| Arc::ptr_eq(scene, &self.scene)) { + tracer.set_scene(device, queue, &self.scene)?; + state.scene = Some(self.scene.clone()); } - if t.sync_materials(device, queue, encoder, renderer)? || st.key != self.key { - t.reset(device, encoder, self.size.0, self.size.1)?; - st.key.clone_from(&self.key); - st.resolved = None; + + let sync_textures = take_in_textures(self.loading, self.now, state.last_sync); + if sync_textures { + state.last_sync = self.now; } - let done = t.samples(); - if done < self.max_samples { - t.pass(device, queue, encoder, &self.camera, &self.settings, self.spp.min(self.max_samples - done)); + if (sync_textures && tracer.sync_materials(device, queue, encoder, renderer)?) || state.key != self.key { + tracer.reset(device, encoder, self.size.0, self.size.1)?; + state.key.clone_from(&self.key); + state.resolved = None; } - if st.resolved != Some(t.samples()) { - t.resolve(device, queue, encoder, &self.display, &self.out_view); - st.resolved = Some(t.samples()); + + let samples = tracer.samples(); + if samples < self.max_samples { + tracer.pass(device, queue, encoder, &self.camera, &self.settings, self.spp.min(self.max_samples - samples)); } + if state.resolved != Some(tracer.samples()) { + tracer.resolve(device, queue, encoder, &self.display, &self.out_view); + state.resolved = Some(tracer.samples()); + } + let mut read = self.read.lock().unwrap_or_else(PoisonError::into_inner); if matches!(*read, Read::Wanted) { *read = Read::Copied(Readback::new(device, encoder, &self.out)); } + Ok(()) } } impl CallbackTrait for TraceCallback { + /// Submit tracing work and report its samples or failure to the next UI frame. fn prepare( &self, device: &wgpu::Device, @@ -514,7 +729,7 @@ impl CallbackTrait for TraceCallback { ) -> Vec { let state = match resources.remove::() { Some(st) => Ok(st), - None => GpuTracer::new(device).map(|tracer| TraceState { tracer, scene: None, key: String::new(), resolved: None }), + None => GpuTracer::new(device).map(|tracer| TraceState { tracer, scene: None, key: String::new(), resolved: None, last_sync: f64::MIN }), }; let result = state.and_then(|mut st| { let r = match resources.get::() { @@ -538,14 +753,21 @@ impl CallbackTrait for TraceCallback { /// Free the GPU render (its texture and the tracer's scene memory; the pipelines stay). fn drop_gpu(app: &mut TextureCraftApp) { - let Some(g) = app.render.gpu.take() else { return }; - if let Some(rs) = &app.render_state { - let mut r = rs.renderer.write(); - r.free_texture(&g.texture); - if let Some(st) = r.callback_resources.get_mut::() { - st.tracer.release(); - (st.scene, st.resolved) = (None, None); - st.key.clear(); + let Some(view) = app.render.gpu.take() else { return }; + if let Some(render_state) = &app.render_state { + let mut renderer = render_state.renderer.write(); + renderer.free_texture(&view.texture); + if let Some(held) = view.held { + renderer.free_texture(&held); + } + + if let Some(state) = renderer.callback_resources.get_mut::() { + state.tracer.release(); + (state.scene, state.resolved) = (None, None); + state.key.clear(); + + // The materials went with the release: the next render takes textures in at once + state.last_sync = f64::MIN; } } } @@ -611,11 +833,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/render_mode/frame_floor.rs b/crates/ui-egui/src/render_mode/frame_floor.rs new file mode 100644 index 00000000..442003a5 --- /dev/null +++ b/crates/ui-egui/src/render_mode/frame_floor.rs @@ -0,0 +1,33 @@ +//! Recent frame-time baseline for adaptive sampling. + +/// Frames over which [`FrameFloor`] keeps the quickest frame time. +pub(super) const FLOOR_FRAMES: usize = 30; + +/// The range the quickest frame time is held to (seconds): from 75 frames a second to 30, so a +/// run of slow frames never makes slow look normal. The quick end matters as much: frames that +/// are not paced by the display (or tiny ones while little is traced) can take 3 ms, and taking +/// that as the baseline cuts the samples per frame to one at the first frame that does real work, +/// which left the render grainy for seconds. Below this, frames count as quick, not as the target. +pub(super) const FLOOR_RANGE_S: (f64, f64) = (1.0 / 75.0, 1.0 / 30.0); + +/// The quickest of the last [`FLOOR_FRAMES`] frame times: about the display's refresh interval +/// while the GPU keeps up. +#[derive(Default)] +pub(super) struct FrameFloor { + recent: std::collections::VecDeque, +} + +impl FrameFloor { + /// Record frame time `frame_seconds` (seconds); the quickest recent one, within [`FLOOR_RANGE_S`]. + pub(super) fn push(&mut self, frame_seconds: f64) -> f64 { + if frame_seconds.is_finite() && frame_seconds > 0.0 { + if self.recent.len() >= FLOOR_FRAMES { + self.recent.pop_front(); + } + + self.recent.push_back(frame_seconds); + } + + self.recent.iter().copied().fold(FLOOR_RANGE_S.1, f64::min).clamp(FLOOR_RANGE_S.0, FLOOR_RANGE_S.1) + } +} diff --git a/crates/ui-egui/src/render_mode/motion.rs b/crates/ui-egui/src/render_mode/motion.rs new file mode 100644 index 00000000..500b730e --- /dev/null +++ b/crates/ui-egui/src/render_mode/motion.rs @@ -0,0 +1,36 @@ +//! Camera and texture-loading activity used to select render resolution. + +use texturecraft_engine::geom::OrbitCamera; + +use super::MOTION_SETTLE_S; + +/// Whether the camera is moving, for [`super::MOVING_SCALE`]. +#[derive(Default)] +pub(super) struct Motion { + /// The camera as last seen (compared, never parsed). + camera: String, + /// When it last changed. The first frame counts as a change: a render that has just started + /// begins at the smaller size too (four times the samples at once, so it opens smooth + /// instead of as raw one-sample noise) and grows to full size like after any move. + last_change: Option, +} + +impl Motion { + /// Record `camera` at time `now` (seconds); true while it changed within [`MOTION_SETTLE_S`]. + /// `loading`: textures are still being composited. Each finished tile restarts the render, so + /// like a moving camera it keeps being redone from no samples, and is traced small for the + /// same reason (four times the samples per restart). + pub(super) fn moving(&mut self, camera: &OrbitCamera, now: f64, loading: bool) -> bool { + if loading { + self.last_change = Some(now); + } + + let camera_key = format!("{camera:?}"); + if self.camera != camera_key { + self.last_change = Some(now); + self.camera = camera_key; + } + + self.last_change.is_some_and(|last_change| now - last_change < MOTION_SETTLE_S) + } +} diff --git a/crates/ui-egui/src/render_mode/spp_control.rs b/crates/ui-egui/src/render_mode/spp_control.rs new file mode 100644 index 00000000..3c676f3a --- /dev/null +++ b/crates/ui-egui/src/render_mode/spp_control.rs @@ -0,0 +1,73 @@ +//! Adaptive samples per pixel for the GPU render. + +use super::frame_floor::FrameFloor; + +/// Most samples per pixel one frame adds. +pub(super) const MAX_SPP: u32 = 16; + +/// A frame quicker than this many times the quickest recent one adds one more sample next time. +/// With vsync, frames come at the display's refresh rate however light they are, so the limits +/// are relative to it (a fixed 1/90 s never let a 60 Hz display grow at all). +const SPP_GROW_BELOW: f64 = 1.25; + +/// A frame at least this many times the quickest recent one (a missed refresh with vsync is two; +/// wide enough that ordinary variation in a busy frame does not cut) cuts the samples per frame (by a +/// quarter, by the same ratio the frame overshoots when that is larger), so a slow frame is +/// followed by a short one, not a long one. With vsync a frame that misses the refresh takes two. +const SPP_CUT_ABOVE: f64 = 1.75; + +/// Frames after a cut during which the samples per frame do not grow again, so they settle +/// below the limit instead of climbing straight back to the frame that missed it (a hitch every +/// few frames). +pub(super) const SPP_GROW_PAUSE_FRAMES: u32 = 6; + +/// Samples per pixel for the next frame, from the last frame's time `frame_seconds` and the quickest recent +/// one `floor` (seconds; see [`FrameFloor`]): one more while frames are quick, fewer when slow, +/// steady in between and for [`SPP_GROW_PAUSE_FRAMES`] after a cut (`since_cut` frames ago). +/// Steady between the two limits is what stops the count from climbing until the GPU backs up, +/// jumping down, and climbing again. +pub(super) fn next_spp(spp: u32, frame_seconds: f64, floor: f64, since_cut: u32) -> u32 { + let cut_above = floor * SPP_CUT_ABOVE; + if frame_seconds >= cut_above { + let by_ratio = (f64::from(spp) * cut_above / frame_seconds) as u32; + by_ratio.min(spp * 3 / 4).max(1) + } else if frame_seconds < floor * SPP_GROW_BELOW && since_cut >= SPP_GROW_PAUSE_FRAMES { + (spp + 1).min(MAX_SPP) + } else { + spp + } +} + +/// What steers the GPU render's samples per pixel per frame (see [`next_spp`]). +pub(super) struct SppControl { + floor: FrameFloor, + /// Frames since the samples per frame were last cut. + since_cut: u32, +} + +impl Default for SppControl { + /// A new render may grow from its first frame. + fn default() -> SppControl { + SppControl { floor: FrameFloor::default(), since_cut: SPP_GROW_PAUSE_FRAMES } + } +} + +impl SppControl { + /// The samples per frame after a frame of `frame_seconds` seconds traced with `spp`. + pub(super) fn next(&mut self, spp: u32, frame_seconds: f64) -> u32 { + let floor = self.floor.push(frame_seconds); + let next = next_spp(spp, frame_seconds, floor, self.since_cut); + self.since_cut = if next < spp { 0 } else { self.since_cut.saturating_add(1) }; + + next + } +} + +/// Samples per frame after the traced size changed from `old` to `new` pixels (frame time is +/// about proportional to samples times pixels). +pub(super) fn rescale_spp(spp: u32, old: (u32, u32), new: (u32, u32)) -> u32 { + let old_pixels = u64::from(old.0) * u64::from(old.1); + let new_pixels = (u64::from(new.0) * u64::from(new.1)).max(1); + + ((u64::from(spp) * old_pixels / new_pixels).max(1) as u32).min(MAX_SPP) +} diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs new file mode 100644 index 00000000..247acd98 --- /dev/null +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -0,0 +1,349 @@ +//! Rendering-mode cache and frame-lifecycle regressions. + +use super::frame_floor::{FLOOR_FRAMES, FLOOR_RANGE_S, FrameFloor}; +use super::spp_control::{MAX_SPP, SPP_GROW_PAUSE_FRAMES, SppControl, next_spp, rescale_spp}; +use super::{ + LOADING_RESTART_S, MOTION_SETTLE_S, Motion, OrbitCamera, SETTLE_HOLD_MAX_S, SETTLE_HOLD_SAMPLES, gpu_scene_key, holds_previous, scene_key, show_image, + take_in_textures, textures_loading, traced_size, +}; +use texturecraft_engine::Session; +use texturecraft_engine::geom::primitives; + +/// A small, fully composed sphere avoids unrelated texture-loading transitions. +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + session.update(); + + session +} + +/// Bump-strength edits invalidate GPU scene data even without displaced geometry. +#[test] +fn height_strength_changes_restart_the_gpu_scene_without_displacement() { + let mut session = session(); + let before = gpu_scene_key(&session); + assert!(!session.doc.project.display.displacement); + + texturecraft_engine::execute(&mut session, "textureSet.settings", &serde_json::json!({"heightStrength": 5.0})).unwrap(); + session.update(); + + assert_ne!(gpu_scene_key(&session), before, "the GPU shader must receive the new bump strength"); +} + +/// Keeping an imported image alive prevents its cached identity from being reused for another image. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn environment_cache_retains_source_identity_until_replaced() { + use std::sync::Arc; + use texturecraft_engine::compose::ImageRes; + + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); + app.session.doc.project.display.environment = "resource:environment".into(); + let source = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]; 2], srgb: false }); + let original_source = Arc::downgrade(&source); + app.session.images.insert("environment".into(), source); + let first = super::trace_scene(&app).env; + assert!(Arc::ptr_eq(&first, &super::trace_scene(&app).env), "unchanged images reuse the decoded environment"); + + let replacement = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[0.0, 1.0, 0.0, 1.0]; 2], srgb: false }); + app.session.images.insert("environment".into(), replacement.clone()); + + assert!(original_source.upgrade().is_some(), "the cache must retain its source so its address cannot be reused"); + let second = super::trace_scene(&app).env; + assert!(!Arc::ptr_eq(&first, &second)); + assert_ne!(first.data, second.data, "replacing the image changes the lighting"); + assert!(Arc::ptr_eq(&second, &super::trace_scene(&app).env)); + assert!(original_source.upgrade().is_none(), "replacing the cache releases the previous source"); + + app.session.images.insert("renamed".into(), replacement); + app.session.doc.project.display.environment = "resource:renamed".into(); + assert!(!Arc::ptr_eq(&second, &super::trace_scene(&app).env), "the environment name is also part of the key"); +} + +/// Create one harness device, skipping unavailable or non-compute backends. +#[cfg(not(target_arch = "wasm32"))] +fn gpu_app() -> Option { + use eframe::egui_wgpu::{RenderState, RendererOptions, WgpuConfiguration}; + use egui_kittest::wgpu::{WgpuTestRenderer, default_wgpu_setup}; + + let setup = default_wgpu_setup(); + let instance = pollster::block_on(setup.new_instance()); + let configuration = WgpuConfiguration { wgpu_setup: setup, ..Default::default() }; + let render_state = match pollster::block_on(RenderState::create(&configuration, &instance, None, RendererOptions::PREDICTABLE)) { + Ok(render_state) => render_state, + Err(error) => { + eprintln!("skipping: could not create the harness GPU device: {error}"); + return None; + } + }; + + let adapter = render_state.adapter.get_info(); + if !super::GpuTracer::supported(&render_state.device) { + eprintln!("skipping: harness adapter {} ({:?}) cannot run the GPU tracer", adapter.name, adapter.backend); + return None; + } + + eprintln!("GPU lifecycle test adapter: {} ({:?})", adapter.name, adapter.backend); + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut app = egui_kittest::Harness::builder() + .with_size(egui::vec2(800.0, 600.0)) + .renderer(WgpuTestRenderer::from_render_state(render_state)) + .build_eframe(|context| crate::TextureCraftApp::new(context, session())) + .into_state(); + app.session.update(); + for cache in &mut app.session.caches { + cache.upload.clear(); + } + + Some(app) +} + +/// Build a GPU rendering frame at a controlled time without executing its callback. +#[cfg(not(target_arch = "wasm32"))] +fn draw_gpu(app: &mut crate::TextureCraftApp, context: &egui::Context, time: f64) -> egui::FullOutput { + context.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + assert!(super::show_gpu(app, ui, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(128.0, 96.0)))); + }) +} + +/// A first completed callback must survive a slow frame's switch to full resolution. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn settling_after_the_first_gpu_frame_keeps_its_image() { + let Some(mut app) = gpu_app() else { return }; + + let context = egui::Context::default(); + draw_gpu(&mut app, &context, 0.0).drop_without_applying_deltas(); + let view = app.render.gpu.as_ref().unwrap(); + let previous_texture = view.texture; + + // The callback finishes the first frame before a slow frame returns to the UI + view.status.lock().unwrap().samples = 1; + assert!(!view.has_image); + + draw_gpu(&mut app, &context, MOTION_SETTLE_S + 0.1).drop_without_applying_deltas(); + + let view = app.render.gpu.as_ref().unwrap(); + assert_eq!(view.size, (128, 96)); + assert!(view.has_image, "resizing must read the completed callback before replacing its status"); + assert_eq!(view.held, Some(previous_texture)); +} + +/// A finished low-sample render must wake again to release its retained preview. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_low_sample_limit_schedules_the_held_image_timeout() { + let Some(mut app) = gpu_app() else { return }; + + app.ui.render.max_samples = 1; + let context = egui::Context::default(); + draw_gpu(&mut app, &context, 0.0).drop_without_applying_deltas(); + let view = app.render.gpu.as_mut().unwrap(); + view.has_image = true; + view.status.lock().unwrap().samples = 1; + let settled_at = MOTION_SETTLE_S + 0.1; + draw_gpu(&mut app, &context, settled_at).drop_without_applying_deltas(); + app.render.gpu.as_ref().unwrap().status.lock().unwrap().samples = 1; + + for frame in 1..=5 { + let output = draw_gpu(&mut app, &context, settled_at + f64::from(frame) * 0.01); + let delay = output.viewport_output[&egui::ViewportId::ROOT].repaint_delay; + output.drop_without_applying_deltas(); + assert!(delay.as_secs_f64() <= SETTLE_HOLD_MAX_S, "a finished render must wake to release its held image: {delay:?}"); + } + + draw_gpu(&mut app, &context, settled_at + SETTLE_HOLD_MAX_S + 0.01).drop_without_applying_deltas(); + assert!(app.render.gpu.as_ref().unwrap().held.is_none()); +} + +/// Every composited chunk bumps a revision. The CPU render restarts on it (it reads the +/// composites); the GPU render does not (it copies the display textures when they change, +/// throttled while loading) unless the heights displace its geometry. +#[test] +fn composited_chunks_restart_the_gpu_render_only_when_displaced() { + let mut session = session(); + let (cpu, gpu) = (scene_key(&session, true), gpu_scene_key(&session)); + session.caches[0].revision += 1; + + assert_ne!(scene_key(&session, true), cpu); + assert_eq!(gpu_scene_key(&session), gpu, "the GPU scene is kept while textures load"); + + session.doc.project.display.displacement = true; + let displaced = gpu_scene_key(&session); + session.caches[0].revision += 1; + + assert_ne!(gpu_scene_key(&session), displaced, "displaced geometry follows the heights"); +} + +/// Loading lasts until the composited tiles are uploaded too (the GPU render reads them). +#[test] +fn textures_load_until_their_tiles_are_uploaded() { + let mut session = session(); + session.caches[0].upload.clear(); + assert!(!textures_loading(&session)); + + session.caches[0].upload.insert((0, 0)); + assert!(textures_loading(&session), "a tile waits to be uploaded"); + + session.caches[0].upload.clear(); + session.caches[0].invalidate_all(); + assert!(textures_loading(&session), "tiles wait to be composited"); +} + +/// Orbiting restarts the render every frame (samples back to 0): the last image stays up. +#[test] +fn a_restart_keeps_the_previous_image_on_screen() { + assert!(show_image(true, 0), "restart with an earlier frame must not show the placeholder"); + assert!(show_image(true, 5)); + assert!(show_image(false, 1)); +} + +/// Motion halves each dimension without shrinking already tiny views. +#[test] +fn a_moving_camera_traces_smaller_and_a_still_one_at_full_size() { + assert_eq!(traced_size((1600, 900), false), (1600, 900)); + assert_eq!(traced_size((1600, 900), true), (800, 450)); + + // Tiny views are never made smaller than they are or than 16 pixels + assert_eq!(traced_size((10, 10), true), (10, 10)); + assert_eq!(traced_size((20, 400), true), (16, 200)); +} + +/// Camera changes and unfinished uploads keep the preview small until activity settles. +#[test] +fn motion_starts_on_a_camera_change_and_settles_after_a_moment() { + let mut motion = Motion::default(); + let mut camera = OrbitCamera::default(); + assert!(motion.moving(&camera, 0.0, false), "a render that just started opens at the smaller size"); + assert!(!motion.moving(&camera, 1.0, false)); + + camera.yaw += 0.1; + assert!(motion.moving(&camera, 2.0, false)); + assert!(motion.moving(&camera, 2.0 + MOTION_SETTLE_S * 0.5, false)); + assert!(!motion.moving(&camera, 2.0 + MOTION_SETTLE_S * 1.5, false)); + + assert!(motion.moving(&camera, 5.0, true), "textures still loading count as motion"); + assert!(motion.moving(&camera, 5.0 + MOTION_SETTLE_S * 0.5, false), "and settle a moment after they finish"); + assert!(!motion.moving(&camera, 5.0 + MOTION_SETTLE_S * 1.5, false)); +} + +/// Either sufficient samples or the deadline replaces the retained preview. +#[test] +fn the_soft_image_stays_until_the_full_size_render_has_samples_or_time_runs_out() { + assert!(holds_previous(0, 0.0)); + assert!(holds_previous(SETTLE_HOLD_SAMPLES - 1, SETTLE_HOLD_MAX_S * 0.5)); + assert!(!holds_previous(SETTLE_HOLD_SAMPLES, 0.0), "enough samples: show the new render"); + assert!(!holds_previous(0, SETTLE_HOLD_MAX_S), "a slow GPU: don't hold it forever"); +} + +/// Sampling grows gradually, holds through jitter and cuts promptly on overload. +#[test] +fn samples_per_frame_grow_slowly_hold_in_between_and_drop_fast() { + let (floor, free) = (1.0 / 144.0, SPP_GROW_PAUSE_FRAMES); + + assert_eq!(next_spp(4, floor, floor, free), 5, "frames at the refresh rate: one more"); + assert_eq!(next_spp(MAX_SPP, floor, floor, free), MAX_SPP); + assert_eq!(next_spp(4, floor, floor, 0), 4, "just after a cut: no growth yet"); + assert_eq!(next_spp(6, floor * 1.4, floor, free), 6, "between the limits: steady"); + assert_eq!(next_spp(8, floor * 2.5, floor, free), 5, "slow frame: cut by the overshoot (8 * 1.75/2.5), more than a quarter"); + assert_eq!(next_spp(8, floor * 1.7, floor, free), 8, "a little slow: steady, not a cut (cuts are for real overload)"); + assert_eq!(next_spp(8, floor * 1.8, floor, free), 6, "slightly over the limit: a quarter fewer"); + assert_eq!(next_spp(8, floor * 20.0, floor, free), 1, "very slow frame: by the overshoot, at least one"); + assert_eq!(next_spp(1, floor * 20.0, floor, free), 1); +} + +/// With vsync on a 60 Hz display every frame takes ~16.7 ms however light: that is the +/// refresh, not a slow GPU, so the samples grow; a missed refresh (two intervals) cuts them. +#[test] +fn samples_per_frame_grow_at_60_hz_and_drop_on_a_missed_refresh() { + let refresh_seconds = 1.0 / 60.0; + let mut control = SppControl::default(); + let mut spp = 2; + + for _ in 0..10 { + spp = control.next(spp, refresh_seconds); + } + + assert_eq!(spp, 12, "one more per frame at the refresh rate"); + + let cut = control.next(spp, 2.0 * refresh_seconds); + assert!(cut < spp && cut >= spp / 2, "a missed refresh cuts: {spp} -> {cut}"); + + // No climb straight back to the frame that missed: steady for a while, then growth again + let mut after = cut; + for _ in 0..SPP_GROW_PAUSE_FRAMES - 1 { + after = control.next(after, refresh_seconds); + } + + assert_eq!(after, cut, "steady after the cut"); + + for _ in 0..3 { + after = control.next(after, refresh_seconds); + } + + assert!(after > cut, "then it grows again"); +} + +/// Frames that are not paced by the display (or take almost no work) can be a few ms; a frame +/// that then does real work must not read as slow and cut the samples to one (the render was +/// left grainy for seconds). +#[test] +fn a_few_very_quick_frames_do_not_collapse_the_samples_per_frame() { + let mut control = SppControl::default(); + for _ in 0..5 { + control.next(4, 0.003); + } + + let working_seconds = 0.012; + let mut spp = 4; + + for _ in 0..10 { + spp = control.next(spp, working_seconds); + } + + assert!(spp >= 4, "12 ms frames after 3 ms ones are fine: {spp}"); +} + +/// Invalid timings are ignored and old timings expire within the bounded window. +#[test] +fn the_frame_floor_is_the_quickest_recent_frame_within_range() { + let mut floor = FrameFloor::default(); + + assert_eq!(floor.push(1.0 / 60.0), 1.0 / 60.0); + assert_eq!(floor.push(0.05), 1.0 / 60.0, "a slow frame does not raise it"); + assert_eq!(floor.push(f64::NAN), 1.0 / 60.0, "a broken time is ignored"); + assert_eq!(floor.push(0.0001), FLOOR_RANGE_S.0, "never below the quick end of the range"); + + for _ in 0..FLOOR_FRAMES { + floor.push(0.2); + } + + assert_eq!(floor.push(0.2), FLOOR_RANGE_S.1, "only recent frames count, and at most 1/30 s"); +} + +/// Resolution changes preserve approximate tracing work within the sample limits. +#[test] +fn samples_per_frame_follow_the_pixel_count_when_the_size_changes() { + assert_eq!(rescale_spp(12, (500, 400), (1000, 800)), 3, "four times the pixels: a quarter of the samples"); + assert_eq!(rescale_spp(3, (1000, 800), (500, 400)), 12); + assert_eq!(rescale_spp(1, (500, 400), (1000, 800)), 1, "never below one"); + assert_eq!(rescale_spp(16, (100, 100), (10, 10)), MAX_SPP, "never above the cap"); +} + +/// Loading throttles texture synchronization without delaying the first or settled update. +#[test] +fn loading_textures_are_taken_in_at_a_limited_rate() { + assert!(take_in_textures(false, 1.0, 1.0), "not loading: every frame"); + assert!(!take_in_textures(true, 1.0 + LOADING_RESTART_S * 0.5, 1.0)); + assert!(take_in_textures(true, 1.0 + LOADING_RESTART_S, 1.0)); + assert!(take_in_textures(true, 0.0, f64::MIN), "the first frame always"); +} + +/// The placeholder appears only before the first image has been traced. +#[test] +fn nothing_traced_yet_shows_the_placeholder() { + assert!(!show_image(false, 0)); +} 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/running_bake.rs b/crates/ui-egui/src/running_bake.rs new file mode 100644 index 00000000..512af28a --- /dev/null +++ b/crates/ui-egui/src/running_bake.rs @@ -0,0 +1,15 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::Progress; + +/// The texture set baking on a worker thread: its progress, its result and the maps it finishes +/// on the way (the 3D view shows one per UI poll). +pub struct RunningBake { + pub set_index: usize, + pub progress: Arc, + pub receiver: std::sync::mpsc::Receiver>, + pub maps: std::sync::mpsc::Receiver, + /// Maps finished so far, and how many the set makes. + pub maps_done: Arc, + pub maps_total: usize, +} diff --git a/crates/ui-egui/src/saved_search.rs b/crates/ui-egui/src/saved_search.rs new file mode 100644 index 00000000..ec6181b8 --- /dev/null +++ b/crates/ui-egui/src/saved_search.rs @@ -0,0 +1,12 @@ +//! A shelf query the user saved in the Saved searches pane + +use serde::{Deserialize, Serialize}; + +/// The search text, tab and library folder of a saved shelf query, under the name it lists as +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SavedSearch { + pub name: String, + pub filter: String, + pub tab: usize, + pub path: Vec, +} diff --git a/crates/ui-egui/src/screen_color_pick.rs b/crates/ui-egui/src/screen_color_pick.rs new file mode 100644 index 00000000..3cd752d5 --- /dev/null +++ b/crates/ui-egui/src/screen_color_pick.rs @@ -0,0 +1,94 @@ +//! An eyedropper button: after it is pressed, the next click anywhere in the window picks the color shown there + +use std::sync::{Arc, Mutex}; + +use egui::{Id, Pos2, Ui}; +use egui_phosphor::regular as icon; + +use crate::widgets::icon_button; + +/// Where the pick in progress is kept between frames +const PICK_ID: &str = "screen_color_pick"; + +/// Where a screenshot callback leaves the sampled sRGB color for the button that asked for it +type SampledSlot = Arc>>; + +/// The pick in progress: which button started it, and the color its screenshot sampled once that arrives +#[derive(Clone, Default)] +struct ScreenColorPick { + target: Option, + /// Filled by the screenshot callback with the target and the sRGB color under the click + sampled: SampledSlot, +} + +/// An eyedropper button for the linear RGB color `linear`, `size` points square; a picked color lands in `linear` a frame or two after the click +pub fn eyedropper(ui: &mut Ui, id: Id, linear: &mut [f32; 3], tooltip: &str, size: f32) { + let key = Id::unique(PICK_ID); + let mut pick: ScreenColorPick = ui.data(|data| data.get_temp(key)).unwrap_or_default(); + let picking = pick.target == Some(id); + + let button = icon_button(ui, icon::EYEDROPPER, tooltip, picking, size); + if button.clicked() { + pick.target = if picking { None } else { Some(id) }; + } else if picking { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + let (clicked, escaped, pointer) = + ui.input(|input| (input.pointer.primary_clicked(), input.key_pressed(egui::Key::Escape), input.pointer.interact_pos())); + if escaped { + pick.target = None; + } else if clicked && let Some(point) = pointer { + request_sample(ui.ctx(), id, point, pick.sampled.clone()); + pick.target = None; + } + } + + let landed = pick.sampled.lock().ok().and_then(|mut sampled| sampled.take_if(|(target, _)| *target == id)); + if let Some((_, srgb)) = landed { + *linear = srgb.map(|channel| texturecraft_engine::texel::srgb_to_linear(f32::from(channel) / 255.0)); + } + + ui.data_mut(|data| data.insert_temp(key, pick)); +} + +/// Screenshot the next frame and put the color at `point` (in points) into `sampled` for `target` +fn request_sample(ctx: &egui::Context, target: Id, point: Pos2, sampled: SampledSlot) { + let pixels_per_point = ctx.pixels_per_point(); + let repaint = ctx.clone(); + let callback = egui::ScreenshotCallback::new(move |image| { + if let (Some(color), Ok(mut slot)) = (pixel_at(&image, point, pixels_per_point), sampled.lock()) { + *slot = Some((target, color)); + } + repaint.request_repaint(); + }); + ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback)); + ctx.request_repaint(); +} + +/// The sRGB color of `image` under `point` (in points at `pixels_per_point`); `None` outside it +fn pixel_at(image: &egui::ColorImage, point: Pos2, pixels_per_point: f32) -> Option<[u8; 3]> { + let (x, y) = ((point.x * pixels_per_point).floor(), (point.y * pixels_per_point).floor()); + let [width, height] = image.size; + if !(x >= 0.0 && y >= 0.0 && (x as usize) < width && (y as usize) < height) { + return None; + } + + let color = image.pixels.get(y as usize * width + x as usize)?; + Some([color.r(), color.g(), color.b()]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pixel_under_the_point_is_sampled_at_the_display_scale() { + let mut image = egui::ColorImage::filled([4, 2], egui::Color32::BLACK); + image.pixels[4 + 3] = egui::Color32::from_rgb(10, 20, 30); + + assert_eq!(pixel_at(&image, egui::pos2(1.6, 0.6), 2.0), Some([10, 20, 30])); + assert_eq!(pixel_at(&image, egui::pos2(0.2, 0.2), 2.0), Some([0, 0, 0])); + for outside in [egui::pos2(-0.1, 0.0), egui::pos2(2.0, 0.0), egui::pos2(0.0, 1.0), egui::pos2(f32::NAN, 0.0)] { + assert_eq!(pixel_at(&image, outside, 2.0), None, "{outside:?}"); + } + } +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 8f75452b..c32de5f6 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -1,26 +1,61 @@ -//! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart -//! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. -//! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas -//! and textures drag onto the layer stack, a layer row, the viewport or the brush properties -//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there. +//! The Assets panel: built-in, saved and project assets in one grid by type, library and search, dragged onto the layer stack, the views or the brush use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -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::materials::MATERIALS; -use texturecraft_engine::paint::alphas; -use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; -use texturecraft_engine::smart_masks::SMART_MASKS; -use texturecraft_render::ibl::ENVIRONMENTS; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use crate::TextureCraftApp; +use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; +use crate::shelf_entry::ShelfEntry; +use crate::shelf_preview::ShelfPreview; +use crate::shelf_view::ShelfView; use crate::theme::Tokens; -use crate::widgets::{dnd_release, icon_button}; +use crate::thumbs::Thumbs; +use crate::widgets::dnd_release; + +/// The gap between tiles in points (their sizes are [`ShelfView`]'s) +const TILE_GAP: f32 = 2.0; +/// The gap after a grid or a list of rows, in points +const SECTION_GAP: f32 = 6.0; +/// The gap between the type row and asset grid, in points +const TYPE_GRID_GAP: f32 = 4.0; +/// The saved material hint's font size, in points +#[cfg(not(target_arch = "wasm32"))] +const HINT_SIZE: f32 = 10.0; +/// The name of a saved material whose file name isn't text +const SAVED_MATERIAL_NAME: &str = "material"; +/// Corner radius of a tile's hover and selection highlights, in points +const TILE_ROUNDING: f32 = 3.0; +/// The last clicked or right-clicked tile's [`ShelfEntry::identity`], kept in egui's memory under this id +const SELECTED_TILE: &str = "shelf_selected_tile"; +/// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points +const SELECTED_OUTLINE_WIDTH: f32 = 1.5; +const IN_USE_OUTLINE_WIDTH: f32 = 1.0; +/// The randomness badge's dot radius, dot spacing and inset from the thumbnail's corner, in points +const BADGE_DOT_RADIUS: f32 = 1.3; +const BADGE_DOT_SPACING: f32 = 3.6; +const BADGE_INSET: f32 = 2.5; +/// The randomness badge's dot colour and its rim's width (points) and colour +const BADGE_DOT_FILL: Color32 = Color32::from_gray(205); +const BADGE_DOT_RIM: f32 = 0.8; +const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170); +/// 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 { @@ -30,22 +65,21 @@ pub(crate) enum Tab { Filters, Brushes, Alphas, - Procedurals, - Environments, + /// Procedural patterns and the project's images Textures, + Environments, } -/// The shelf tabs: icon and (English, translated where shown) name. -pub(crate) const TABS: [(Tab, &str, &str); 9] = [ +/// The shelf tabs: icon and (English, translated where shown) name +pub(crate) const TABS: [(Tab, &str, &str); 8] = [ (Tab::Materials, ic::SPHERE, "Materials"), (Tab::Smart, ic::STACK, "Smart materials"), (Tab::Masks, ic::CIRCLE_HALF, "Smart masks"), (Tab::Filters, ic::FUNNEL, "Filters"), (Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"), (Tab::Alphas, ic::SHAPES, "Alphas"), - (Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"), - (Tab::Environments, ic::SUN_HORIZON, "Environments"), (Tab::Textures, ic::IMAGE, "Textures"), + (Tab::Environments, ic::SUN_HORIZON, "Environments"), ]; /// A shelf asset: built in (by id), a saved smart material (file path) or an image resource. @@ -64,6 +98,11 @@ impl Asset { pub fn is_material(&self) -> bool { matches!(self, Asset::Material(_) | Asset::Library(_)) } + + /// Assets a 3D view drop puts on the texture set under the pointer + pub fn goes_onto_set(&self) -> bool { + self.is_material() || matches!(self, Asset::Texture(_)) + } } /// The drag-and-drop payload of a shelf tile. @@ -86,7 +125,7 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { && content && let Some(name) = unpainted_paint_layer(app) { - // Otherwise the filter seems to do nothing: it has nothing to change yet. + // Otherwise the filter seems to do nothing: it has nothing to change yet app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false); } return; @@ -119,83 +158,179 @@ 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 (decals where they drop, on that set) View3d, } -/// Make `resp` a drop target for shelf assets `zone` accepts: outline it while one hovers, -/// apply it on release. -pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, zone: DropZone) { - let tk = Tokens::get(ui.ctx()); - let accepts = |d: &ShelfDrag| match d.asset { +/// The texture set under the pointer while a shelf material or image is dragged over the 3D view `response`: the set a drop there goes to +pub fn 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.goes_onto_set())?; + 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 or image goes to the texture set under the pointer, highlighted by the view itself ([`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; + } + + if zone == DropZone::View3d { + DecalDrop::show_menu(app, ui, response); + } + + let tokens = Tokens::get(ui.ctx()); + let accepts = |drag: &ShelfDrag| match drag.asset { Asset::Alpha(_) => true, Asset::Material(_) | Asset::Library(_) => zone != DropZone::Brush, Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - if resp.dnd_hover_payload::().is_some_and(|d| accepts(&d)) { - ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set(); + 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(|i| i.pointer.interact_pos()); - if let Some(d) = dnd_release::(resp) - && accepts(&d) - { - match (&d.asset, pointer) { - (Asset::Texture(name), Some(p)) => { - let (q, vp) = (p - resp.rect.min, resp.rect.size()); - app.run("layer.add.decal", json!({"image": name, "x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); - } - (asset, _) => apply(app, asset), + + let pointer = ui.input(|input| input.pointer.interact_pos()); + let Some(drag) = dnd_release::(response).filter(|drag| accepts(drag)) else { return }; + + match (&drag.asset, pointer) { + // The background takes nothing + (Asset::Texture(name), Some(position)) => { + let Some(texture_set) = set_under_pointer(app, ui, response) else { return }; + + let drop = DecalDrop { + image: name.clone(), + texture_set, + view_position: position - response.rect.min, + view_size: response.rect.size(), + camera: app.session.camera, + screen_position: position, + }; + drop.open(ui); } + (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 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| { - 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() { - 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.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. - 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), - Tab::Smart => { - materials(app, ui, &ctx, &filter, true, title); - library(app, ui, &filter); + scan_library(app); + scan_brushes(app); + let all = ShelfEntry::all(app); + let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all)); + + // A folder that is gone (its last image removed) shows everything again + if !paths.iter().any(|path| path.starts_with(&app.ui.shelf_path)) { + app.ui.shelf_path.clear(); + } + + let folder = app.ui.shelf_path.clone(); + let picked_tab = app.ui.shelf_tab; + let searched: Vec = all.into_iter().filter(|entry| entry.matches(&filter)).collect(); + let mut applicable = crate::shelf_folders::paths(searched.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))); + let matching: Vec = searched.into_iter().filter(|entry| entry.in_folder(&folder)).collect(); + let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + + // Saved smart materials list under the grid rather than as tiles, so they count apart + let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + let saved_materials_matching = saved_materials_matching(app, &filter); + if in_user_library && let Some(smart) = TABS.iter().position(|(tab, _, _)| *tab == Tab::Smart).and_then(|smart| counts.get_mut(smart)) { + *smart += saved_materials_matching; + } + if saved_materials_matching > 0 && crate::shelf_tabs::shows(picked_tab, Tab::Smart) { + applicable.push(vec![crate::shelf_entry::USER.to_string()]); + } + + crate::shelf_folders::breadcrumb(app, ui, &paths); + search_field(app, ui); + crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu); + ui.add_space(TYPE_GRID_GAP); + + let tab = app.ui.shelf_tab; + let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); + let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); + entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); + + // The toolbar has its own strip at the panel's bottom, so nothing above it can push it out + let area = ui.available_rect_before_wrap(); + let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top()); + let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top)); + let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect).layout(egui::Layout::left_to_right(egui::Align::Min)), |ui| { + if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) { + ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(vec2(width, grid_rect.height())); + crate::shelf_panes::column(app, ui, &paths, &applicable); + }); + ui.separator(); + } + + // Saved smart materials are files in the user's library, without folders of their own + let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); + grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter); + }); + ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); + drag_preview(&ctx); +} + +/// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` +fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { + let view = app.ui.shelf_view; + let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE))); + egui::ScrollArea::vertical() + .id_salt("shelf_scroll") + .auto_shrink([false, false]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible) + .max_height(height) + .show(ui, |ui| { + tiles(ui, |ui| { + for entry in entries { + let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str())); + entry_tile(app, ui, ctx, entry, view, is_selected); } - Tab::Masks => smart_masks(app, ui, &ctx, &filter, title), - Tab::Filters => filters(app, ui, &ctx, &filter, title), - Tab::Brushes => brushes(app, ui, &ctx, &filter, title), - Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title), - Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title), - Tab::Environments => environments(app, ui, &filter, title), - Tab::Textures => textures(app, ui, &ctx, &filter, title), + }); + if saved_materials { + library(app, ui, filter); } + }); +} + +/// How many of the user's saved smart materials match `filter` (none until the library is read) +fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize { + app.library.iter().flatten().filter(|path| matches(filter, &[saved_material_name(path)])).count() +} + +/// The search field: a live filter on names (and categories) with a clear button while it has text +fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); + let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x }; + let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width); + ui.add(field); + if !app.ui.shelf_filter.is_empty() && ui.add(egui::Button::new(ic::X).frame(false)).on_hover_text(tr("Clear")).clicked() { + app.ui.shelf_filter.clear(); } }); - drag_preview(&ctx); } /// The dragged asset's name next to the pointer. @@ -210,31 +345,26 @@ 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)) } -fn title(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - 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); + ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP); body(ui); }); - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } /// 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) { @@ -244,49 +374,38 @@ fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'st out } -/// 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(); - if shown.is_empty() { +/// Read the user's saved smart materials (desktop library folder) unless they are already listed +#[cfg(not(target_arch = "wasm32"))] +fn scan_library(app: &mut TextureCraftApp) { + if app.library.is_some() { return; } - title(ui, name); - for cat in categories(&shown, |m| m.category) { - header(ui, cat); - 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() { - apply(app, &asset); - } - } - }); - } + + let saved_material = |path: &std::path::PathBuf| path.extension().is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT); + let mut files: Vec = + std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_material).collect()).unwrap_or_default(); + files.sort(); + app.library = Some(files); } -/// The user's saved smart materials (desktop library folder). +#[cfg(target_arch = "wasm32")] +fn scan_library(_: &mut TextureCraftApp) {} + +/// A saved smart material's name: its file name without the extension +fn saved_material_name(path: &std::path::Path) -> &str { + path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME) +} + +/// The user's saved smart materials matching `filter`, as rows under the grid #[cfg(not(target_arch = "wasm32"))] fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { - let tk = Tokens::get(ui.ctx()); - if app.library.is_none() { - let mut files: Vec = std::fs::read_dir(crate::library_dir()) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tcmat" || x == MCMAT_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.library = Some(files); - } + let tokens = Tokens::get(ui.ctx()); let files = app.library.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("material").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); + let shown: Vec<_> = files.iter().filter(|path| matches(filter, &[saved_material_name(path)])).collect(); if !filter.is_empty() && shown.is_empty() { return; } + ui.horizontal(|ui| { header(ui, tr("My smart materials")); if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { @@ -294,277 +413,245 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { } }); if files.is_empty() { - ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(10.0).color(tk.text_dim)); + ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(HINT_SIZE).color(tokens.text_dim)); } - for f in shown { - let (label, asset) = (name(f), Asset::Library(f.display().to_string())); - // MaterialCraft materials (sent from MaterialCraft) show a graph. - let glyph = if f.extension().is_some_and(|x| x == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; - let r = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { + + for path in shown { + let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string())); + + // MaterialCraft materials (sent from MaterialCraft) show a graph + let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; + let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { ui.label(crate::i18n::trf( "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", - &[("file", &f.display())], + &[("file", &path.display())], )); }); - if r.drag_started() { - r.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); + if response.drag_started() { + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); } - if r.clicked() { + if response.clicked() { apply(app, &asset); } } - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = SMART_MASKS.iter().filter(|m| matches(filter, &[m.label, m.id])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - tiles(ui, |ui| { - 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() { - apply(app, &asset); - } - } - }); -} - -/// The filter library, grouped: a click adds the filter to the selected layer's content (or its -/// mask when the mask is selected), a drop onto a layer to that layer's content. -fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = FILTERS.iter().filter(|f| matches(filter, &[f.label, f.group, f.id, tr(f.label), tr(f.group)])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - for group in categories(&shown, |f| f.group) { - header(ui, tr(group)); - 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() { - apply(app, &asset); - } - } - }); - } -} - -/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke -/// (alpha, spacing, flow, jitters…) and keeps its size. -fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect(); - if !shown.is_empty() { - title(ui, name); - for cat in categories(&shown, |p| p.category) { - header(ui, cat); - 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() { - app.run("brush.preset.apply", json!({"preset": p.id})); - } - } - }); - } - } - my_brushes(app, ui, filter); -} - -/// The user's saved brush presets (desktop brushes folder) and saving the current brush there. +/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { +fn scan_brushes(app: &mut TextureCraftApp) { use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; - let dir = crate::user_dir("brushes"); - if app.brushes.is_none() { - let mut files: Vec = std::fs::read_dir(&dir) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.brushes = Some(files); - } - let files = app.brushes.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); - if !filter.is_empty() && shown.is_empty() { + + if app.brushes.is_some() { return; } - ui.horizontal(|ui| { - header(ui, tr("My brushes")); - if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { - app.brushes = None; - } - }); - for f in shown { - if ui - .add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f)))) - .on_hover_text(tr("Use this brush (keeps its size)")) - .clicked() - { - app.run("brush.preset.load", json!({"path": f.display().to_string()})); - } - } - ui.horizontal(|ui| { - let id = ui.make_persistent_id("brush_preset_name"); - let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); - ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0)); - let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); - if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { - let path = dir.join(format!("{file}.{BRUSH_EXT}")); - // A folder that can't be made fails the save, which reports it. - let _ = std::fs::create_dir_all(&dir); - if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { - new_name.clear(); - app.brushes = None; - } - } - ui.data_mut(|d| d.insert_temp(id, new_name)); - }); - ui.add_space(6.0); + + let mut files: Vec = std::fs::read_dir(crate::user_dir("brushes")) + .map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect()) + .unwrap_or_default(); + files.sort(); + app.brushes = Some(files); } #[cfg(target_arch = "wasm32")] -fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} +fn scan_brushes(_: &mut TextureCraftApp) {} -/// The built-in alpha library, grouped by category; the brush's alpha is outlined. -fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let tk = Tokens::get(ctx); - let shown: Vec<&'static alphas::LibraryAlpha> = alphas::library().iter().filter(|a| matches(filter, &[&a.label, a.category, &a.id])).collect(); - if shown.is_empty() { +/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { + // An image removed this frame has nothing to show + if let ShelfEntry::Image(name) = entry + && !app.session.images.contains_key(name) + { return; } - title(ui, name); - let brush = &app.session.tool.brush; - let current = if brush.alpha_image.is_none() { brush.alpha_library.clone() } else { None }; - for cat in categories(&shown, |a| a.category) { - header(ui, cat); - tiles(ui, |ui| { - 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)); - 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); - } - if r.clicked() { - apply(app, &asset); - } + + let texture = entry.thumbnail(app, ctx); + let asset = entry.asset(); + let session = &app.session; + let response = tile_in_view( + ui, + &mut app.thumbs, + texture.as_ref(), + |thumbs| match entry { + ShelfEntry::SavedBrush(path) => Some(thumbs.saved_brush_preview(path, &session.images)), + _ => entry.preview(session), + }, + entry.label(), + asset.as_ref(), + view, + ); + + if selected || entry.in_use(app) { + let tokens = Tokens::get(ctx); + let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH }; + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tokens.accent), egui::StrokeKind::Inside); + } + + if entry.includes_randomness() { + randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); + } + + if response.clicked() || response.secondary_clicked() { + let (kind, id) = entry.identity(); + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(SELECTED_TILE), (kind.to_string(), id.to_string()))); + } + if response.clicked() { + entry.activate(app); + } + + if let ShelfEntry::Image(name) = entry { + response.context_menu(|ui| { + if ui.button(tr("Add as decal (view center)")).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } + if ui.button(tr("Remove resource")).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); } }); } } -fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec = ProceduralKind::ALL.into_iter().filter(|k| matches(filter, &[k.label(), tr(k.label())])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - 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() { - 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]})); - } - } - }); +/// Asset tile with optional dragging and a larger hover preview, at the medium size +pub(crate) fn tile( + ui: &mut Ui, + thumbs: &mut Thumbs, + texture: Option<&egui::TextureHandle>, + preview: impl FnOnce() -> ShelfPreview, + label: &str, + drag: Option<&Asset>, +) -> egui::Response { + tile_in_view(ui, thumbs, texture, |_| Some(preview()), label, drag, ShelfView::Medium) } -fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str) { - let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - for env in shown { - let on = app.session.doc.project.display.environment == **env; - if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() { - app.run("display.set", json!({"environment": env})); - } - } - ui.add_space(6.0); -} - -fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let tk = Tokens::get(ctx); - let names: Vec = app.session.doc.resources.keys().filter(|n| matches(filter, &[n])).cloned().collect(); - if !filter.is_empty() && names.is_empty() { - return; - } - ui.horizontal(|ui| { - title(ui, name); - if ui.small_button(tr("Import...")).clicked() { - crate::menus::invoke(app, ctx, "resource.import"); - } - }); - if names.is_empty() { - ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim)); - } - 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)); - if r.clicked() { - apply(app, &asset); - } - r.context_menu(|ui| { - if ui.button(tr("Add as decal (view center)")).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); - } - if ui.button(tr("Remove resource")).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); - } - }); - } - }); -} - -/// 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 { - let tk = Tokens::get(ui.ctx()); +/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover +fn tile_in_view( + ui: &mut Ui, + thumbs: &mut Thumbs, + texture: Option<&egui::TextureHandle>, + preview: impl FnOnce(&mut Thumbs) -> Option, + label: &str, + drag: Option<&Asset>, + view: ShelfView, +) -> egui::Response { + let tokens = 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, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag - && resp.drag_started() + && response.drag_started() { - resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); } - let p = ui.painter(); - if resp.hovered() || resp.dragged() { - p.rect_filled(rect, 3.0, tk.row_hover); + + let painter = ui.painter(); + if response.hovered() || response.dragged() { + painter.rect_filled(rect, TILE_ROUNDING, tokens.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 = view.thumbnail_rect(rect); + thumbnail(painter, texture, image_rect, &tokens); + if view.name_beside() { + let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP; + let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + } else { + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text); + } + + let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; + response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) +} + +/// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness +fn randomness_badge(painter: &egui::Painter, thumbnail: egui::Rect) { + let corner = thumbnail.right_bottom() - vec2(BADGE_INSET, BADGE_INSET); + for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] { + painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR)); + } +} + +/// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name) +fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color)); + job.wrap = egui::text::TextWrapping::truncate_at_width(width); + job +} + +/// 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); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_long_label_stays_on_one_line_ending_in_an_ellipsis() { + let width = 60.0; + let mut laid_out = None; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE))); + }); + + // The font atlas upload is not under test + output.textures_delta.clear(); + let galley = laid_out.unwrap(); + + assert_eq!(galley.rows.len(), 1); + assert!(galley.size().x <= width); + assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); + } } diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs new file mode 100644 index 00000000..2ea615a6 --- /dev/null +++ b/crates/ui-egui/src/shelf_entry.rs @@ -0,0 +1,270 @@ +//! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies + +use std::path::PathBuf; + +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; +use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; +use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{Asset, Tab, apply}; +use crate::shelf_preview::ShelfPreview; + +/// The name of a saved brush whose file name isn't text +const SAVED_BRUSH_NAME: &str = "brush"; + +/// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines +const SEED_PROBES: usize = 4; +const SEED_PROBE_OFFSET: f32 = 0.13; +/// A smaller difference between the two seeds' samples is rounding +const SEED_TOLERANCE: f32 = 1e-4; + +/// The libraries' ids: the open project's images, the built-in assets, the user's saved assets +pub(crate) const PROJECT: &str = "project"; +pub(crate) const STARTER: &str = "starter"; +pub(crate) const USER: &str = "user"; +/// The libraries in the picker's order: id and (English, translated where shown) name +pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")]; + +/// A shelf tile's asset +pub(crate) enum ShelfEntry { + Material(&'static SmartMaterial), + SmartMask(&'static SmartMask), + Filter(&'static FilterDef), + Brush(&'static BrushPreset), + /// A brush preset file the user saved + SavedBrush(PathBuf), + Alpha(&'static LibraryAlpha), + Procedural(ProceduralKind), + /// A built-in lighting environment, by name + Environment(&'static str), + /// An image resource of the project, by name + Image(String), +} + +impl ShelfEntry { + /// Every built-in asset, the user's saved brushes and the project's images + pub(crate) fn all(app: &TextureCraftApp) -> Vec { + let built_in = MATERIALS + .iter() + .map(ShelfEntry::Material) + .chain(SMART_MASKS.iter().map(ShelfEntry::SmartMask)) + .chain(FILTERS.iter().map(ShelfEntry::Filter)) + .chain(PRESETS.iter().map(ShelfEntry::Brush)) + .chain(alphas::library().iter().map(ShelfEntry::Alpha)) + .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) + .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); + let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush); + let images = app.session.doc.resources.keys().filter(|name| app.session.images.contains_key(*name)).cloned().map(ShelfEntry::Image); + built_in.chain(saved).chain(images).collect() + } + + /// The tab that lists the asset + pub(crate) fn tab(&self) -> Tab { + match self { + ShelfEntry::Material(material) if material.smart => Tab::Smart, + ShelfEntry::Material(_) => Tab::Materials, + ShelfEntry::SmartMask(_) => Tab::Masks, + ShelfEntry::Filter(_) => Tab::Filters, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes, + ShelfEntry::Alpha(_) => Tab::Alphas, + ShelfEntry::Procedural(_) => Tab::Textures, + ShelfEntry::Environment(_) => Tab::Environments, + ShelfEntry::Image(_) => Tab::Textures, + } + } + + /// The asset's identity across frames: its kind and id + pub(crate) fn identity(&self) -> (&'static str, &str) { + match self { + ShelfEntry::Material(material) => ("material", material.id), + ShelfEntry::SmartMask(mask) => ("mask", mask.id), + ShelfEntry::Filter(filter) => ("filter", filter.id), + ShelfEntry::Brush(preset) => ("brush", preset.id), + ShelfEntry::SavedBrush(path) => ("saved-brush", path.to_str().unwrap_or_default()), + ShelfEntry::Alpha(alpha) => ("alpha", &alpha.id), + ShelfEntry::Procedural(kind) => ("procedural", kind.label()), + ShelfEntry::Environment(name) => ("environment", name), + ShelfEntry::Image(name) => ("image", name), + } + } + + /// Where the asset lives: its library id ([`LIBRARIES`]), its type's folder, then its category if it has one (names in English, shown through `tr`) + pub(crate) fn path(&self) -> Vec<&str> { + let (library, folder, category) = match self { + ShelfEntry::Material(material) if material.smart => (STARTER, "Smart materials", Some(material.category)), + ShelfEntry::Material(material) => (STARTER, "Materials", Some(material.category)), + ShelfEntry::SmartMask(_) => (STARTER, "Smart masks", None), + ShelfEntry::Filter(filter) => (STARTER, "Filters", Some(filter.group)), + ShelfEntry::Brush(preset) => (STARTER, "Brushes", Some(preset.category)), + ShelfEntry::SavedBrush(_) => (USER, "Brushes", None), + ShelfEntry::Alpha(alpha) => (STARTER, "Alphas", Some(alpha.category)), + ShelfEntry::Procedural(_) => (STARTER, "Procedurals", None), + ShelfEntry::Environment(_) => (STARTER, "Environments", None), + ShelfEntry::Image(_) => (PROJECT, "Textures", None), + }; + [library, folder].into_iter().chain(category).collect() + } + + /// Whether the asset is in folder `path` (a library id, then folder names) or below it + pub(crate) fn in_folder(&self, path: &[String]) -> bool { + let own = self.path(); + path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have) + } + + /// The name under the tile, translated where the asset's name is + pub(crate) fn label(&self) -> &str { + match self { + ShelfEntry::Material(material) => material.label, + ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME), + ShelfEntry::SmartMask(mask) => mask.label, + ShelfEntry::Filter(filter) => tr(filter.label), + ShelfEntry::Brush(preset) => preset.label, + ShelfEntry::Alpha(alpha) => &alpha.label, + ShelfEntry::Procedural(kind) => tr(kind.label()), + ShelfEntry::Environment(name) => name, + ShelfEntry::Image(name) => name, + } + } + + /// Whether `filter` (lowercase) matches the asset's name, id or category, in English or translated + pub(crate) fn matches(&self, filter: &str) -> bool { + let texts: &[&str] = match self { + ShelfEntry::Material(material) => &[material.label, material.category, material.id], + ShelfEntry::SavedBrush(_) => &[self.label()], + ShelfEntry::SmartMask(mask) => &[mask.label, mask.id], + ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)], + ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], + ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id], + ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())], + ShelfEntry::Environment(name) => &[name], + ShelfEntry::Image(name) => &[name], + }; + crate::shelf::matches(filter, texts) + } + + /// The thumbnail, or None while it renders + pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option { + match self { + ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id), + ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), + ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), + ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), + ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path, &app.session.images), + ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), + ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), + ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), + ShelfEntry::Image(name) => { + let image = app.session.images.get(name).cloned()?; + Some(app.thumbs.image(ctx, name, &image)) + } + } + } + + /// What the hover popup renders; None for an image that is gone + pub(crate) fn preview(&self, session: &Session) -> Option { + Some(match self { + ShelfEntry::Material(material) => ShelfPreview::material(material.id), + ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), + ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), + ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), + ShelfEntry::SavedBrush(path) => ShelfPreview::saved_brush(path, &session.images), + ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), + ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), + ShelfEntry::Environment(name) => ShelfPreview::Environment(name), + ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), session.images.get(name).cloned()?), + }) + } + + /// The drag payload's asset; brushes and procedurals don't drag + pub(crate) fn asset(&self) -> Option { + match self { + ShelfEntry::Material(material) => Some(Asset::Material(material.id)), + ShelfEntry::SmartMask(mask) => Some(Asset::SmartMask(mask.id)), + ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), + ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), + ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, + } + } + + /// Whether the tile is outlined as in use: the brush's library alpha, the shown environment + pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool { + match self { + ShelfEntry::Alpha(alpha) => { + let brush = &app.session.tool.brush; + brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + } + ShelfEntry::Environment(name) => app.session.doc.project.display.environment == *name, + _ => false, + } + } + + /// Whether applying the asset gives a different result per random seed (the tile's dots badge) + pub(crate) fn includes_randomness(&self) -> bool { + match self { + ShelfEntry::Procedural(kind) => SEEDED_PROCEDURALS.contains(kind), + _ => false, + } + } + + /// What a click on the tile does + pub(crate) fn activate(&self, app: &mut TextureCraftApp) { + match self { + ShelfEntry::Brush(preset) => { + app.run("brush.preset.apply", json!({"preset": preset.id})); + } + ShelfEntry::SavedBrush(path) => { + app.run("brush.preset.load", json!({"path": path.display().to_string()})); + } + ShelfEntry::Procedural(kind) => { + app.run("layer.add.fill", json!({"name": kind.label()})); + app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); + } + ShelfEntry::Environment(name) => { + app.run("display.set", json!({"environment": name})); + } + entry => { + if let Some(asset) = entry.asset() { + apply(app, &asset); + } + } + } + } +} + +/// The procedurals whose pattern depends on the seed, worked out once +static SEEDED_PROCEDURALS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| ProceduralKind::ALL.into_iter().filter(|kind| seed_changes(*kind)).collect()); + +/// Whether procedural `kind` samples differently under two seeds +fn seed_changes(kind: ProceduralKind) -> bool { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let sample = |seed: u32, i: usize| { + let uv = Vec2::new((i % SEED_PROBES) as f32 / SEED_PROBES as f32, (i / SEED_PROBES) as f32 / SEED_PROBES as f32) + SEED_PROBE_OFFSET; + procedural(&Procedural { seed, ..Procedural::new(kind) }, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }) + }; + (0..SEED_PROBES * SEED_PROBES).any(|i| (sample(1, i) - sample(2, i)).abs() > SEED_TOLERANCE) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_seeded_procedurals_include_randomness() { + let seeded = &*SEEDED_PROCEDURALS; + assert!(seeded.contains(&ProceduralKind::Clouds), "{seeded:?}"); + assert!(!seeded.contains(&ProceduralKind::Checker), "{seeded:?}"); + } +} diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs new file mode 100644 index 00000000..e581f480 --- /dev/null +++ b/crates/ui-egui/src/shelf_folders.rs @@ -0,0 +1,95 @@ +//! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree + +use std::collections::BTreeSet; + +use egui::{RichText, Ui}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_entry::{LIBRARIES, ShelfEntry}; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The breadcrumb arrows' size relative to an icon button +const ARROW_SCALE: f32 = 0.8; + +/// The folder paths of `entries`, each a library id then folder names +pub(crate) fn paths<'a>(entries: impl IntoIterator) -> Vec> { + let unique_paths: BTreeSet> = entries.into_iter().map(ShelfEntry::path).collect(); + + unique_paths.into_iter().map(|segments| segments.into_iter().map(str::to_string).collect()).collect() +} + +/// `paths` and every library, even one with nothing in it (the picker always lists them all) +pub(crate) fn with_every_library(mut paths: Vec>) -> Vec> { + paths.extend(LIBRARIES.iter().map(|(id, _)| vec![id.to_string()])); + paths.sort(); + paths.dedup(); + paths +} + +/// The folders right below `prefix` (libraries in their usual order, folders by name) +pub(crate) fn children(paths: &[Vec], prefix: &[String]) -> Vec { + let mut children = Vec::new(); + for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) { + if let Some(child) = path.get(prefix.len()) + && !children.contains(child) + { + children.push(child.clone()); + } + } + + if prefix.is_empty() { + children.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); + } + children +} + +/// A folder's shown name: libraries by their name, folders (type and category names) translated +pub(crate) fn name(level: usize, segment: &str) -> &str { + match LIBRARIES.iter().find(|(id, _)| *id == segment) { + Some((_, library)) if level == 0 => tr(library), + _ => tr(segment), + } +} + +/// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside +pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let tokens = Tokens::get(ui.ctx()); + let size = ui.spacing().interact_size.y * ARROW_SCALE; + let mut picked: Option> = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = ui.spacing().item_spacing.x * 0.5; + let path = app.ui.shelf_path.clone(); + for level in 0..=path.len() { + let options = children(paths, &path[..level]); + if level > 0 && options.is_empty() { + break; + } + + let current = path.get(level); + let response = icon_button(ui, egui_phosphor::regular::CARET_RIGHT, tr("Browse folders"), false, size); + egui::Popup::menu(&response).show(|ui| { + if level == 0 && ui.selectable_label(current.is_none(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + for option in &options { + if ui.selectable_label(current == Some(option), name(level, option)).clicked() { + picked = Some(path[..level].iter().cloned().chain([option.clone()]).collect()); + } + } + }); + + let shown = match current { + Some(segment) => name(level, segment), + None if level == 0 => tr("All libraries"), + None => continue, + }; + ui.label(RichText::new(shown).strong().color(tokens.text_strong)); + } + }); + + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs new file mode 100644 index 00000000..b643d21f --- /dev/null +++ b/crates/ui-egui/src/shelf_panes.rs @@ -0,0 +1,175 @@ +//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::saved_search::SavedSearch; +use crate::shelf::TABS; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The panes' column width as a fraction of the panel, and its least width in points +const COLUMN_FRACTION: f32 = 0.45; +const COLUMN_MIN_WIDTH: f32 = 110.0; +/// Maximum share of the column used by saved searches while both panes are open +const SAVED_SEARCHES_HEIGHT_FRACTION: f32 = 0.45; +/// The pane header's caption size in points +const HEADER_SIZE: f32 = 10.0; + +/// Which side panes are open +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfPanes { + pub saved_searches: bool, + pub filter_by_path: bool, + /// Filter by path lists only the folders with assets matching the search and tab + pub hide_non_applicable: bool, +} + +/// The toolbar's buttons that open and close the panes +pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let panes = &mut app.ui.shelf_panes; + if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() { + panes.saved_searches = !panes.saved_searches; + } + if icon_button(ui, ic::TREE_STRUCTURE, tr("Filter by path"), panes.filter_by_path, size).clicked() { + panes.filter_by_path = !panes.filter_by_path; + } +} + +/// The width of the panes' column in a panel `width` wide, or None while no pane is open +pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option { + let panes = &app.ui.shelf_panes; + (panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) +} + +/// The open panes, top to bottom; the tree shows `paths`, or `applicable` while it hides folders with nothing matching +pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec], applicable: &[Vec]) { + // Names past the narrow column end in "…" rather than breaking mid-word + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + if app.ui.shelf_panes.saved_searches { + saved_searches(app, ui); + } + if app.ui.shelf_panes.filter_by_path { + if app.ui.shelf_panes.saved_searches { + ui.separator(); + } + let shown = if app.ui.shelf_panes.hide_non_applicable { applicable } else { paths }; + filter_by_path(app, ui, shown); + } +} + +/// "All libraries", then each library's folders as a tree; a click shows that folder +fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let size = ui.spacing().interact_size.y; + header(ui, tr("Filter by path"), |ui| { + let hiding = app.ui.shelf_panes.hide_non_applicable; + if icon_button(ui, ic::EYE_SLASH, tr("Hide non-applicable folders"), hiding, size).clicked() { + app.ui.shelf_panes.hide_non_applicable = !hiding; + } + }); + + let mut picked = None; + egui::ScrollArea::vertical().id_salt("shelf_path_tree").auto_shrink([false, true]).show(ui, |ui| { + if ui.selectable_label(app.ui.shelf_path.is_empty(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + folders(ui, paths, &[], &app.ui.shelf_path, &mut picked); + }); + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} + +/// The folders below `prefix`: one with folders inside opens and closes, a click on a name picks it +fn folders(ui: &mut Ui, paths: &[Vec], prefix: &[String], current: &[String], picked: &mut Option>) { + for child in crate::shelf_folders::children(paths, prefix) { + let path: Vec = prefix.iter().cloned().chain([child.clone()]).collect(); + let name = crate::shelf_folders::name(prefix.len(), &child); + let selected = current == path.as_slice(); + if crate::shelf_folders::children(paths, &path).is_empty() { + ui.indent(("shelf_path_leaf", &path), |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }); + continue; + } + + let id = ui.make_persistent_id(("shelf_path", &path)); + let open_by_default = current.starts_with(&path); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, open_by_default) + .show_header(ui, |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }) + .body(|ui| folders(ui, paths, &path, current, picked)); + } +} + +/// A pane's caption with a button at its right +fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button); + }); +} + +/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one +fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { + let size = ui.spacing().interact_size.y; + let current = current_query(app); + header(ui, tr("Saved searches"), |ui| { + if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() && !app.ui.shelf_saved_searches.contains(¤t) { + app.ui.shelf_saved_searches.push(current.clone()); + } + }); + + let everything = current.filter.is_empty() && current.path.is_empty() && current.tab == crate::shelf_tabs::NO_TYPE; + if ui.selectable_label(everything, tr("All")).clicked() { + crate::shelf_toolbar::reset_query(app); + } + + let mut deleted = None; + let max_height = if app.ui.shelf_panes.filter_by_path { ui.available_height() * SAVED_SEARCHES_HEIGHT_FRACTION } else { ui.available_height() }; + let row_height = ui.spacing().interact_size.y; + let total_rows = app.ui.shelf_saved_searches.len(); + egui::ScrollArea::vertical().id_salt("shelf_saved_searches").max_height(max_height).show_rows(ui, row_height, total_rows, |ui, visible_rows| { + for i in visible_rows { + let Some(saved) = app.ui.shelf_saved_searches.get(i) else { continue }; + + let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path; + let response = ui.selectable_label(same, &saved.name); + if response.clicked() { + (app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone()); + } + response.context_menu(|ui| { + if ui.button(tr("Delete")).clicked() { + deleted = Some(i); + ui.close(); + } + }); + } + }); + + if let Some(i) = deleted { + app.ui.shelf_saved_searches.remove(i); + } +} + +/// The shelf's query, named after its search text, else its folder, else its tab +fn current_query(app: &TextureCraftApp) -> SavedSearch { + let (filter, tab, path) = (app.ui.shelf_filter.clone(), app.ui.shelf_tab, app.ui.shelf_path.clone()); + let name = if !filter.is_empty() { + filter.clone() + } else if let Some(folder) = path.last() { + crate::shelf_folders::name(path.len() - 1, folder).to_string() + } else { + TABS.get(tab).map_or(tr("All"), |(_, _, label)| tr(label)).to_string() + }; + SavedSearch { name, filter, tab, path } +} diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs new file mode 100644 index 00000000..65639daf --- /dev/null +++ b/crates/ui-egui/src/shelf_preview.rs @@ -0,0 +1,179 @@ +//! Shelf assets and their preview renderers + +use std::path::PathBuf; +use std::sync::Arc; + +use egui::ColorImage; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::compose::ImageStore; +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, environment_image, image_preview, procedural_image, sphere_image, stroke_preview}; + +/// Larger brush preset files aren't read (the `brush.preset.load` command's limit) +#[cfg(not(target_arch = "wasm32"))] +const MAX_SAVED_BRUSH_BYTES: u64 = 1 << 20; + +/// The asset a shelf tile previews +#[derive(Clone)] +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), + /// A brush preset file the user saved, its stroke along an S curve + SavedBrush { path: PathBuf, settings: Option, image: Option> }, + /// An image resource by name + Image(String, Arc), + /// A built-in lighting environment's panorama + Environment(&'static str), +} + +impl ShelfPreview { + /// Resolve a saved brush's image alpha while the project images are available + pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { + let settings = read_saved_brush(path); + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)).cloned(); + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings, image } + } + + /// 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::SavedBrush { path, .. } => format!("saved-brush:{}", path.display()), + ShelfPreview::Image(name, _) => format!("image:{name}"), + ShelfPreview::Environment(name) => format!("environment:{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, None)), + ShelfPreview::SavedBrush { settings, image, .. } => { + let settings = settings.as_ref()?; + if settings.alpha_image.is_some() && image.is_none() { + return None; + } + Some(stroke_preview(settings, size, image.as_deref())) + } + ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + ShelfPreview::Environment(name) => Some(environment_image(name, size)), + } + } +} + +/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files) +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option { + use std::io::Read as _; + + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|file| file.take(MAX_SAVED_BRUSH_BYTES + 1).read_to_end(&mut bytes)).ok()?; + if bytes.len() as u64 > MAX_SAVED_BRUSH_BYTES { + return None; + } + + serde_json::from_slice::(&bytes).ok().map(|settings| settings.sanitized()) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option { + None +} + +#[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)), + ShelfPreview::Environment(texturecraft_engine::core::project::ENVIRONMENTS[0]), + ]; + 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); + } + } + + #[test] + fn saved_brush_preview_uses_its_project_image_alpha() { + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let transparent = Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[1.0, 1.0, 1.0, 0.0]; 4], srgb: false }); + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings.clone()), image: Some(transparent) }; + + assert!(preview.image(64).is_some_and(|image| image.pixels.iter().all(|pixel| pixel.r() == 0))); + let missing = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings), image: None }; + assert!(missing.image(64).is_none()); + } +} diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs new file mode 100644 index 00000000..5898a943 --- /dev/null +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -0,0 +1,72 @@ +//! The shelf's type row: one icon per type (none picked shows every type), greyed without matches, one dropdown when narrow + +use egui::{Ui, vec2}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{TABS, Tab}; +use crate::widgets::{icon_button, icon_dropdown_button}; + +/// The gap between the row's icons in points +const ICON_GAP: f32 = 2.0; +/// The size of the dot that marks the collapsed row's dropdown while a type is picked, in points +const FILTER_DOT_RADIUS: f32 = 2.5; + +/// `app.ui.shelf_tab` while no type is picked: every type shows +pub(crate) const NO_TYPE: usize = TABS.len(); + +/// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) { + let size = ui.spacing().interact_size.y; + + // The type icons and one icon after them + let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP); + let mut picked = app.ui.shelf_tab.min(NO_TYPE); + + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(ICON_GAP, ICON_GAP); + if ui.available_width() >= row_width { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + // The picked type stays clickable so it can be unpicked + let empty = i != picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled_ui(!empty, |ui| icon_button(ui, icon, tr(label), i == picked, size)).inner.clicked() { + picked = if i == picked { NO_TYPE } else { i }; + } + } + } else { + collapsed(ui, &mut picked, counts, size); + } + + let rest = ui.available_width() - size; + ui.add_space(rest.max(0.0)); + trailing(app, ui, size); + }); + app.ui.shelf_tab = picked; +} + +/// One dropdown listing the types, dotted while one is picked +fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) { + let filtering = *picked != NO_TYPE; + let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size); + let response = response.on_hover_text(tr("Filter by type")); + if filtering { + let tokens = crate::theme::Tokens::get(ui.ctx()); + let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS); + ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tokens.accent); + } + + egui::Popup::menu(&response).show(|ui| { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + let empty = i != *picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled(!empty, egui::Button::selectable(i == *picked, format!("{icon} {}", tr(label)))).clicked() { + *picked = if i == *picked { NO_TYPE } else { i }; + ui.close(); + } + } + }); +} + +/// Whether `tab` (an index into [`TABS`], or [`NO_TYPE`]) shows assets of type `kind` +pub(crate) fn shows(tab: usize, kind: Tab) -> bool { + TABS.get(tab).is_none_or(|(shown, _, _)| *shown == kind) +} diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs new file mode 100644 index 00000000..5e185bf9 --- /dev/null +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -0,0 +1,50 @@ +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right + +use egui::Ui; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// The gap above the toolbar in points +const GAP_ABOVE: f32 = 4.0; + +/// The toolbar's height for a `ui` (one icon button and the gap above it) +pub(crate) fn height(ui: &Ui) -> f32 { + ui.spacing().interact_size.y + GAP_ABOVE +} + +/// The toolbar +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + let size = ui.spacing().interact_size.y; + ui.add_space(GAP_ABOVE); + ui.horizontal(|ui| { + crate::shelf_panes::toggles(app, ui, size); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), "resource.import"); + } + if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() { + reset_query(app); + } + if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() { + refresh(app); + } + }); + }); +} + +/// Show every asset again: no search, no type picked, all libraries +pub(crate) fn reset_query(app: &mut TextureCraftApp) { + app.ui.shelf_filter.clear(); + app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE; + app.ui.shelf_path.clear(); +} + +/// Read the user's saved assets from disk again and redraw their thumbnails +fn refresh(app: &mut TextureCraftApp) { + app.library = None; + app.brushes = None; + app.thumbs.forget_saved_files(); +} diff --git a/crates/ui-egui/src/shelf_view.rs b/crates/ui-egui/src/shelf_view.rs new file mode 100644 index 00000000..036c498b --- /dev/null +++ b/crates/ui-egui/src/shelf_view.rs @@ -0,0 +1,83 @@ +//! How the shelf shows its assets: small, medium or large tiles, or a list (the menu at the type row's end) + +use egui::{Rect, Ui, Vec2, vec2}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::grid_tile::GridTile; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// A list row's height and its thumbnail's size, in points +const LIST_ROW_HEIGHT: f32 = 30.0; +const LIST_THUMBNAIL_SIZE: f32 = 26.0; +/// The gap between a list row's thumbnail and its name, in points +pub(crate) const LIST_NAME_GAP: f32 = 6.0; + +/// The shelf's tile size, or the list +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ShelfView { + Small, + /// A 68 x 78 grid step, as in the reference + #[default] + Medium, + Large, + List, +} + +/// The views in the menu's order: icon and (English, translated where shown) name +const VIEWS: [(ShelfView, &str, &str); 4] = [ + (ShelfView::Small, ic::GRID_NINE, "Small"), + (ShelfView::Medium, ic::GRID_FOUR, "Medium"), + (ShelfView::Large, ic::SQUARE, "Large"), + (ShelfView::List, ic::LIST, "List"), +]; + +impl ShelfView { + /// A grid tile's measurements; None for the list + fn grid(self) -> Option { + match self { + ShelfView::Small => Some(GridTile { width: 50.0, height: 58.0, thumbnail_size: 44.0, thumbnail_center_y: 23.0 }), + ShelfView::Medium => Some(GridTile { width: 66.0, height: 76.0, thumbnail_size: 60.0, thumbnail_center_y: 31.0 }), + ShelfView::Large => Some(GridTile { width: 88.0, height: 100.0, thumbnail_size: 82.0, thumbnail_center_y: 42.0 }), + ShelfView::List => None, + } + } + + /// A tile's size in a grid `width` points wide (a list row spans it) + pub(crate) fn tile_size(self, width: f32) -> Vec2 { + match self.grid() { + Some(tile) => vec2(tile.width, tile.height), + None => vec2(width.max(LIST_ROW_HEIGHT), LIST_ROW_HEIGHT), + } + } + + /// Where the thumbnail goes in the tile `rect` + pub(crate) fn thumbnail_rect(self, rect: Rect) -> Rect { + match self.grid() { + Some(tile) => Rect::from_center_size(rect.center_top() + vec2(0.0, tile.thumbnail_center_y), vec2(tile.thumbnail_size, tile.thumbnail_size)), + None => Rect::from_center_size(rect.left_center() + vec2(LIST_ROW_HEIGHT * 0.5, 0.0), vec2(LIST_THUMBNAIL_SIZE, LIST_THUMBNAIL_SIZE)), + } + } + + /// Whether the name sits right of the thumbnail (a list) rather than under it + pub(crate) fn name_beside(self) -> bool { + self == ShelfView::List + } +} + +/// The view menu button: its icon is the current view's +pub(crate) fn menu(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let current = app.ui.shelf_view; + let icon = VIEWS.iter().find(|(view, _, _)| *view == current).map_or(ic::GRID_FOUR, |(_, icon, _)| icon); + let response = icon_button(ui, icon, tr("Thumbnail size"), false, size); + egui::Popup::menu(&response).show(|ui| { + for (view, icon, label) in VIEWS { + if ui.selectable_label(view == current, format!("{icon} {}", tr(label))).clicked() { + app.ui.shelf_view = view; + ui.close(); + } + } + }); +} 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 b4831be7..4b0c321d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,10 +1,13 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; +use crate::saved_search::SavedSearch; +use crate::shelf_panes::ShelfPanes; +use crate::shelf_view::ShelfView; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -118,6 +121,13 @@ pub struct Prefs { /// Where autosaves, smart materials, presets, templates and layouts go (desktop; read at /// startup). Empty or relative: `Documents/TextureCraft`. pub data_folder: String, + /// Cores a project save leaves to the UI; Settings bounds this to the available logical CPUs + /// (desktop). At least one save worker always runs. + pub reserved_cores: u32, + /// Maximum decompressed project size accepted on open, in GiB (at least one). + pub project_open_limit_gib: u32, + /// Percent of the free RAM a project save may hold at once (desktop; 1 to 100). + pub save_ram_percent: u8, } impl Default for Prefs { @@ -132,10 +142,22 @@ impl Default for Prefs { system_title_bar: false, start_window: true, data_folder: String::new(), + reserved_cores: 1, + project_open_limit_gib: texturecraft_engine::formats::DEFAULT_PROJECT_OPEN_LIMIT_GIB, + save_ram_percent: 50, } } } +impl Prefs { + /// Apply resource preferences before commands or file workers can start. + pub fn apply_resource_limits(&self) { + texturecraft_engine::formats::set_project_open_limit_gib(self.project_open_limit_gib); + #[cfg(not(target_arch = "wasm32"))] + texturecraft_engine::formats::set_save_resources(self.reserved_cores as usize, self.save_ram_percent); + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NewProject { pub mesh: String, @@ -151,6 +173,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 { @@ -167,6 +195,8 @@ impl Default for NewProject { uv_tiles: None, template: default_template(), template_name: String::new(), + normal_format: None, + baked_maps: Vec::new(), } } } @@ -232,13 +262,36 @@ 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 = 2; + #[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, + /// The panel open against the icon rail, if any; not saved, so the app starts with the rail closed + #[serde(skip)] + pub rail_panel: Option, + #[serde(default = "Dock::for_baking")] + 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, @@ -247,9 +300,21 @@ pub struct UiState { /// Channel whose blending the layer rows show. pub layer_channel: Channel, pub shelf_filter: String, - /// The asset shelf's open tab. + /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] pub shelf_tab: usize, + /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) + #[serde(default)] + pub shelf_path: Vec, + /// The asset shelf's tile size, or its list + #[serde(default)] + pub shelf_view: ShelfView, + /// The asset shelf's open side panes + #[serde(default)] + pub shelf_panes: ShelfPanes, + /// The asset shelf's saved queries, in the order they were saved + #[serde(default)] + pub shelf_saved_searches: Vec, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -273,42 +338,55 @@ pub struct UiState { /// Custom keyboard shortcuts (item id → "Ctrl+Shift+E", "" = none) over the defaults. #[serde(default)] pub keymap: Keymap, - /// The baker whose parameters bake mode shows (None: the common parameters). - #[serde(default)] - pub bake_baker: Option, /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] - pub skew_brush: SkewBrush, -} - -/// Settings of the skew correction brush (radius in UV units). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct SkewBrush { - pub on: bool, - pub radius: f32, - /// 1 turns the rays onto the base normal, 0 erases. - pub value: f32, - pub hardness: f32, -} - -impl Default for SkewBrush { - fn default() -> Self { - SkewBrush { on: false, radius: 0.03, value: 1.0, hardness: 0.5 } - } + pub bake_paint_brush: crate::bake_mode::BakePaintBrush, + /// How the 3D view shows symmetry + #[serde(default)] + pub symmetry: crate::symmetry::SymmetryDisplay, + /// The Baking Visualization panel's settings, under a key of their own since the reference defaults: older saved ones start over + #[serde(default, rename = "baking_visualization")] + pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } impl UiState { - /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export - /// settings and recent files. + /// 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); + self.dock_is_baking = baking; + } + } + + /// 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, settings, files and shelf query pub fn adopt_layout(&mut self, layout: UiState) { let keep = std::mem::replace(self, layout); self.new_project = keep.new_project; self.export = keep.export; self.recent = keep.recent; - self.shelf_filter = keep.shelf_filter; self.prefs = keep.prefs; self.keymap = keep.keymap; self.rename = None; + + // The shelf's search, type and folder are one query, and saved searches are the user's own + self.shelf_filter = keep.shelf_filter; + self.shelf_tab = keep.shelf_tab; + self.shelf_path = keep.shelf_path; + self.shelf_saved_searches = keep.shelf_saved_searches; } } @@ -317,7 +395,13 @@ impl Default for UiState { UiState { mode: Mode::Painting, layout: ViewLayout::Split, + split_ratio: default_split_ratio(), dock: Dock::default(), + rail_panel: None, + 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, @@ -325,6 +409,10 @@ impl Default for UiState { layer_channel: Channel::BaseColor, shelf_filter: String::new(), shelf_tab: 0, + shelf_path: Vec::new(), + shelf_view: ShelfView::default(), + shelf_panes: ShelfPanes::default(), + shelf_saved_searches: Vec::new(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, @@ -336,8 +424,9 @@ impl Default for UiState { export: ExportUi::default(), recent: Vec::new(), keymap: Keymap::new(), - bake_baker: None, - skew_brush: SkewBrush::default(), + bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + symmetry: crate::symmetry::SymmetryDisplay::default(), + bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), } } } @@ -353,13 +442,27 @@ mod tests { ui.keymap.insert("file.save".into(), "F5".into()); let mut layout = UiState::default(); layout.dock.close(crate::docking::Panel::Assets); + ui.adopt_layout(layout); + assert!(!ui.dock.is_open(crate::docking::Panel::Assets)); assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); } + #[test] + fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() { + let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; + let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() }; + ui.shelf_saved_searches.push(saved.clone()); + + ui.adopt_layout(UiState::default()); + + assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice())); + assert_eq!(ui.shelf_saved_searches, [saved]); + } + #[test] fn the_data_folder_is_an_absolute_choice_or_documents_texturecraft() { let default = crate::data_folder(""); @@ -370,6 +473,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/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs new file mode 100644 index 00000000..a3964660 --- /dev/null +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -0,0 +1,132 @@ +//! Symmetry: the toolbar toggle and settings popup, and what the 3D view draws for it + +mod ribbons; +mod settings_popup; +mod symmetry_display; +mod symmetry_drag; +mod symmetry_intersection; +mod symmetry_manipulator; +mod symmetry_manipulator_arrow; +mod view_overlay; + +use egui::Ui; +use egui_phosphor::regular as ic; +use texturecraft_engine::Tool; +use texturecraft_engine::paint::Symmetry; + +pub use symmetry_display::SymmetryDisplay; +pub(crate) use view_overlay::{manipulator_hovered, manipulator_input, overlay, scene_overlay}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::{icon_badge_dropdown_button, icon_button}; + +/// Radial copies a brush gets when radial symmetry is enabled +const DEFAULT_RADIAL_COUNT: u8 = 6; + +/// Whether `tool` paints symmetry copies +pub(crate) fn applies_to(tool: Tool) -> bool { + matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Clone | Tool::Path) +} + +/// Whether the 3D view shows symmetry now: not while the active tool can't act on the selection +pub(crate) fn shown(app: &TextureCraftApp) -> bool { + let tool = app.session.tool.tool; + app.ui.mode == crate::state::Mode::Painting && applies_to(tool) && app.session.tool_usable(tool) && app.session.tool.brush.symmetry.any() +} + +/// The world axes any active mirror plane or radial axis can move along, even while symmetry is disabled +pub(crate) fn movable_axes(symmetry: &Symmetry) -> [bool; 3] { + let mirrors = [symmetry.x, symmetry.y, symmetry.z]; + let radial_axis = symmetry.axis_index(); + [0, 1, 2].map(|axis| mirrors[axis] || (symmetry.radial > 1 && axis != radial_axis)) +} + +/// The toolbar's Symmetry toggle: turning it on with nothing set mirrors on X +fn toggle(symmetry: &mut Symmetry) { + if symmetry.any() { + symmetry.enabled = false; + return; + } + + symmetry.enabled = true; + if !symmetry.x && !symmetry.y && !symmetry.z && symmetry.radial <= 1 { + symmetry.x = true; + } +} + +/// Apply changed symmetry settings through the same command used by scripts and agents +fn apply(app: &mut TextureCraftApp, symmetry: Symmetry) { + if symmetry == app.session.tool.brush.symmetry { + return; + } + + app.run( + "tool.brush", + serde_json::json!({ + "symmetryOn": symmetry.enabled, + "symmetryX": symmetry.x, + "symmetryY": symmetry.y, + "symmetryZ": symmetry.z, + "symmetryRadial": symmetry.radial, + "symmetryAxis": (["x", "y", "z"][symmetry.axis_index()]), + "symmetryOffset": symmetry.offset, + "symmetryAngleSpan": symmetry.angle_span, + }), + ); +} + +/// The Symmetry toggle and the settings button with its popup +pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry"), app.session.tool.brush.symmetry.any(), button_size).clicked() { + let mut symmetry = app.session.tool.brush.symmetry; + toggle(&mut symmetry); + apply(app, symmetry); + } + + // No tooltip on the settings button; the label still names it for screen readers + let popup_id = ui.make_persistent_id("symmetry_settings"); + let mut open = ui.data(|data| data.get_temp::(popup_id)).unwrap_or(false); + let response = icon_badge_dropdown_button(ui, ic::FLIP_HORIZONTAL, ic::GEAR, tr("Symmetry settings"), open, button_size); + if response.clicked() { + open = !open; + } + + // egui's single popup slot is needed by the color picker inside this popup + let shown = egui::Popup::from_response(&response) + .id(popup_id) + .open_bool(&mut open) + .close_behavior(egui::PopupCloseBehavior::IgnoreClicks) + .show(|ui| settings_popup::show(app, ui)); + + // A click outside the popup and the dropdowns it opens (foreground layers too) closes it + if let Some(shown) = shown + && !response.clicked() + && ui.input(|input| input.pointer.any_click()) + && let Some(at) = ui.input(|input| input.pointer.interact_pos()) + && ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground) + { + open = false; + } + + ui.data_mut(|data| data.insert_temp(popup_id, open)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn combined_symmetry_can_move_every_active_plane_and_axis() { + for enabled in [true, false] { + for axis in 0..3 { + let symmetry = Symmetry { enabled, x: axis == 0, y: axis == 1, z: axis == 2, radial: 5, axis, ..Symmetry::default() }; + + let movable = movable_axes(&symmetry); + + assert_eq!(movable, [true; 3], "the mirror plane still moves along the radial axis: {symmetry:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/symmetry/ribbons.rs b/crates/ui-egui/src/symmetry/ribbons.rs new file mode 100644 index 00000000..24b49c51 --- /dev/null +++ b/crates/ui-egui/src/symmetry/ribbons.rs @@ -0,0 +1,35 @@ +//! Lines drawn into the 3D view as thin quads + +use egui::Rect; +use texturecraft_engine::geom::glam::{Mat4, Vec3}; +use texturecraft_render::OverlayQuad; + +use crate::TextureCraftApp; + +/// Height of the view in normalized device coordinates (−1 to 1) +const NDC_HEIGHT: f32 = 2.0; + +/// Lines drawn as thin quads turned to face the camera, a steady width on screen +pub(crate) struct Ribbons { + eye: Vec3, + view_proj: Mat4, + /// World units per screen point at clip-space w = 1 + world_per_point: f32, +} + +impl Ribbons { + pub(crate) fn new(app: &TextureCraftApp, rect: Rect) -> Self { + let camera = &app.session.camera; + let view_proj = camera.view_proj(rect.width() / rect.height().max(1.0)); + let ndc_per_unit = view_proj.row(1).truncate().length(); + Ribbons { eye: camera.eye(), view_proj, world_per_point: NDC_HEIGHT / (rect.height() * ndc_per_unit).max(f32::EPSILON) } + } + + /// The line from `from` to `to`, `width` points wide + pub(crate) fn quad(&self, from: Vec3, to: Vec3, width: f32, color: [f32; 3], opacity: f32) -> OverlayQuad { + let middle = (from + to) * 0.5; + let clip_w = (self.view_proj * middle.extend(1.0)).w.max(0.0); + let side = (to - from).cross(self.eye - middle).normalize_or_zero() * (clip_w * self.world_per_point * width * 0.5); + OverlayQuad { corners: [from - side, to - side, to + side, from + side], color, opacity } + } +} diff --git a/crates/ui-egui/src/symmetry/settings_popup.rs b/crates/ui-egui/src/symmetry/settings_popup.rs new file mode 100644 index 00000000..4d11e82a --- /dev/null +++ b/crates/ui-egui/src/symmetry/settings_popup.rs @@ -0,0 +1,143 @@ +//! The symmetry settings popup: independent mirror and radial copies, their position and display + +use egui::{Align, Color32, Layout, Stroke, Ui, vec2}; +use texturecraft_engine::paint::{FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Symmetry}; + +use super::{DEFAULT_RADIAL_COUNT, movable_axes}; +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::{color_swatch, section, slider}; + +/// The popup's width (points) +const POPUP_WIDTH: f32 = 340.0; + +/// Width of the radial Axis row's label column +const LABEL_WIDTH: f32 = 64.0; + +const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; + +/// Space between the mirror section and the radial toggle +const SECTIONS_GAP: f32 = 4.0; + +/// The color square's width (points) and the Manipulator size slider's range +const COLOR_SWATCH_WIDTH: f32 = 48.0; +const MANIPULATOR_SIZES: std::ops::RangeInclusive = 0.1..=1.0; + +/// Side of the radial copies preview beside the Count and Angle span sliders +const PREVIEW_SIZE: f32 = 96.0; + +/// The popup's content, applying brush changes through the engine and display preferences in place +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + ui.set_width(POPUP_WIDTH); + let (minimum, maximum) = app.session.mesh.bounds(); + let half_extent = (maximum - minimum) * 0.5; + let display = &mut app.ui.symmetry; + let mut edited = app.session.tool.brush.symmetry; + let symmetry = &mut edited; + section(ui, "symmetry_mirror", tr("Mirror symmetry"), true, |ui| { + ui.horizontal(|ui| { + let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); + for (name, enabled) in AXIS_NAMES.into_iter().zip([&mut symmetry.x, &mut symmetry.y, &mut symmetry.z]) { + ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { + ui.checkbox(enabled, name); + }); + } + }); + }); + ui.add_space(SECTIONS_GAP); + + let mut radial = symmetry.radial > 1; + if ui.checkbox(&mut radial, tr("Radial symmetry")).changed() { + symmetry.radial = if radial { DEFAULT_RADIAL_COUNT } else { 0 }; + } + + if radial { + section(ui, "symmetry_radial", tr("Radial settings"), true, |ui| { + labelled_row(ui, tr("Axis"), |ui| { + let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); + for (axis, name) in AXIS_NAMES.into_iter().enumerate() { + ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { + ui.radio_value(&mut symmetry.axis, axis as u8, name); + }); + } + }); + ui.horizontal_top(|ui| { + let sliders_width = ui.available_width() - PREVIEW_SIZE - ui.spacing().item_spacing.x; + ui.allocate_ui_with_layout(vec2(sliders_width, PREVIEW_SIZE), Layout::top_down(Align::Min), |ui| { + let mut count = f32::from(symmetry.radial); + if slider(ui, tr("Count"), &mut count, 2.0..=f32::from(MAX_RADIAL_COPIES), 0).changed() { + symmetry.radial = count.round() as u8; + } + slider(ui, tr("Angle span"), &mut symmetry.angle_span, 0.0..=FULL_TURN_DEGREES, 0); + }); + copies_preview(ui, symmetry, super::view_overlay::color(display.color, u8::MAX)); + }); + }); + } + + let movable = movable_axes(symmetry); + section(ui, "symmetry_axis_position", tr("Axis position"), true, |ui| { + for (axis, name) in AXIS_NAMES.into_iter().enumerate() { + ui.add_enabled_ui(movable[axis], |ui| slider(ui, name, &mut symmetry.offset[axis], -half_extent[axis]..=half_extent[axis], 2)); + } + }); + + section(ui, "symmetry_display", tr("Display"), true, |ui| { + ui.horizontal(|ui| { + ui.label(tr("Symmetry color display")); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| color_swatch(ui, "symmetry_color", &mut display.color, COLOR_SWATCH_WIDTH)); + }); + if symmetry.x || symmetry.y || symmetry.z { + ui.checkbox(&mut display.show_plane, tr("Show plane")); + } + if radial { + ui.checkbox(&mut display.show_axis, tr("Show axis")); + } + ui.checkbox(&mut display.show_intersection, tr("Show intersection")); + ui.checkbox(&mut display.show_cursor, tr("Show cursor")); + ui.indent("symmetry_hide_while_painting", |ui| { + ui.add_enabled(display.show_cursor, egui::Checkbox::new(&mut display.hide_while_painting, tr("Hide while painting"))); + }); + ui.checkbox(&mut display.show_manipulator, tr("Show axis position manipulator")); + ui.add_enabled_ui(display.show_manipulator, |ui| slider(ui, tr("Manipulator size"), &mut display.manipulator_size, MANIPULATOR_SIZES, 1)); + }); + + super::apply(app, edited); +} + +/// A row with `label` in a fixed-width column and the control filling the rest +fn labelled_row(ui: &mut Ui, label: &str, control: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + let height = ui.spacing().interact_size.y; + ui.allocate_ui_with_layout(vec2(LABEL_WIDTH, height), Layout::left_to_right(Align::Center), |ui| { + ui.set_min_width(LABEL_WIDTH); + ui.label(label); + }); + control(ui); + }); +} + +/// Where the radial copies go, on the view's backdrop: the stroke in white on the right, its copies in `copy_color` +fn copies_preview(ui: &mut Ui, symmetry: &Symmetry, copy_color: Color32) { + const RING_FRACTION: f32 = 0.32; + const DOT_RADIUS: f32 = 3.0; + const CROSS_HALF: f32 = 4.0; + const CORNER_RADIUS: f32 = 2.0; + + let tokens = crate::theme::Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(PREVIEW_SIZE, PREVIEW_SIZE), egui::Sense::hover()); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, CORNER_RADIUS, tokens.viewport); + + let center = rect.center(); + let ring = PREVIEW_SIZE * RING_FRACTION; + let cross = Stroke::new(1.0, tokens.viewport_text); + painter.line_segment([center - vec2(CROSS_HALF, 0.0), center + vec2(CROSS_HALF, 0.0)], cross); + painter.line_segment([center - vec2(0.0, CROSS_HALF), center + vec2(0.0, CROSS_HALF)], cross); + for copy in 0..symmetry.radial { + // Screen y points down: positive angles turn counter-clockwise + let angle = symmetry.radial_angle(copy); + let at = center + vec2(angle.cos(), -angle.sin()) * ring; + painter.circle_filled(at, DOT_RADIUS, if copy == 0 { Color32::WHITE } else { copy_color }); + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_display.rs b/crates/ui-egui/src/symmetry/symmetry_display.rs new file mode 100644 index 00000000..5ef64405 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_display.rs @@ -0,0 +1,41 @@ +//! How the 3D view shows symmetry: the settings popup's Display section + +use serde::{Deserialize, Serialize}; + +/// The manipulator size the popup starts at; the manipulator's measurements are given at this size +pub(crate) const DEFAULT_MANIPULATOR_SIZE: f32 = 0.4; + +/// Display settings for the symmetry plane, axis, intersection, cursors and manipulator +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SymmetryDisplay { + /// Linear RGB of everything drawn for symmetry + pub color: [f32; 3], + /// Mirror: a see-through plane between the two sides + pub show_plane: bool, + /// Radial: a see-through line along the axis + pub show_axis: bool, + /// Where the plane cuts the mesh (a line) or the axis meets it (a point) + pub show_intersection: bool, + /// A brush cursor at every copy of the cursor + pub show_cursor: bool, + pub hide_while_painting: bool, + pub show_manipulator: bool, + /// Manipulator scale; [`DEFAULT_MANIPULATOR_SIZE`] draws it at its base size + pub manipulator_size: f32, +} + +impl Default for SymmetryDisplay { + fn default() -> Self { + SymmetryDisplay { + color: [1.0, 0.0, 0.0], + show_plane: false, + show_axis: false, + show_intersection: true, + show_cursor: true, + hide_while_painting: true, + show_manipulator: false, + manipulator_size: DEFAULT_MANIPULATOR_SIZE, + } + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_drag.rs b/crates/ui-egui/src/symmetry/symmetry_drag.rs new file mode 100644 index 00000000..5c5b39f5 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_drag.rs @@ -0,0 +1,12 @@ +//! A symmetry manipulator drag in progress + +use egui::Pos2; + +/// Kept in egui's memory between the frames of one drag +#[derive(Clone, Copy, Debug)] +pub(crate) struct SymmetryDrag { + /// The world axes the grabbed handle moves along + pub(crate) axes: [bool; 3], + pub(crate) from: Pos2, + pub(crate) start_offset: [f32; 3], +} diff --git a/crates/ui-egui/src/symmetry/symmetry_intersection.rs b/crates/ui-egui/src/symmetry/symmetry_intersection.rs new file mode 100644 index 00000000..2099d304 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_intersection.rs @@ -0,0 +1,50 @@ +//! Where a mirror plane cuts the mesh, kept between frames + +use std::sync::Arc; + +use texturecraft_engine::geom::Mesh; +use texturecraft_engine::geom::glam::Vec3; + +/// The segments where the plane `p[axis] = position` crosses the mesh's triangles +#[derive(Clone, Debug)] +pub(crate) struct SymmetryIntersection { + mesh_id: u64, + axis: usize, + position: f32, + pub(crate) segments: Arc>, +} + +impl SymmetryIntersection { + /// Every triangle's crossing with the plane (mesh `mesh_id`, the plane `p[axis] = position`) + pub(crate) fn compute(mesh: &Mesh, mesh_id: u64, axis: usize, position: f32) -> Self { + let mut segments = Vec::new(); + for triangle in 0..mesh.triangle_count() { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(&first), Some(&second), Some(&third)) = (mesh.positions.get(first), mesh.positions.get(second), mesh.positions.get(third)) else { + continue; + }; + + let corners = [first, second, third]; + + // Each edge whose ends lie on opposite sides crosses the plane once + let side = |corner: usize| corners[corner][axis] - position; + let mut crossings = [Vec3::ZERO; 2]; + let mut count = 0; + for (start, end) in [(0, 1), (1, 2), (2, 0)] { + if (side(start) < 0.0) != (side(end) < 0.0) && count < crossings.len() { + crossings[count] = corners[start].lerp(corners[end], side(start) / (side(start) - side(end))); + count += 1; + } + } + if count == crossings.len() { + segments.push(crossings); + } + } + SymmetryIntersection { mesh_id, axis, position, segments: Arc::new(segments) } + } + + /// Whether this is the cut of mesh `mesh_id` by the plane `p[axis] = position` + pub(crate) fn is_for(&self, mesh_id: u64, axis: usize, position: f32) -> bool { + self.mesh_id == mesh_id && self.axis == axis && self.position == position + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_manipulator.rs b/crates/ui-egui/src/symmetry/symmetry_manipulator.rs new file mode 100644 index 00000000..ce691988 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_manipulator.rs @@ -0,0 +1,194 @@ +//! The axis position manipulator: arrows at the symmetry origin that move it + +use egui::{Pos2, Rect, Vec2}; +use texturecraft_engine::geom::glam::Vec3; + +use super::symmetry_display::DEFAULT_MANIPULATOR_SIZE; +use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; +use crate::TextureCraftApp; + +/// Arrow length at the default manipulator size, as a fraction of the view height +const ARROW_LENGTH: f32 = 0.1; + +/// Gap between the center and where the shafts start (points at the default size) +const SHAFT_GAP: f32 = 5.0; + +/// Cone length and base radius (points at the default size, at the origin's depth) +pub(crate) const CONE_LENGTH: f32 = 15.0; +pub(crate) const CONE_RADIUS: f32 = 5.0; + +/// Radial: the square handle spans this part of the arrows, clear of the shafts +const SQUARE_FROM: f32 = 0.16; +const SQUARE_TO: f32 = 0.46; + +/// How far (fraction of the mesh diagonal, at least a minimum) the screen scale is measured along each axis +const PROBE_FRACTION: f32 = 0.01; +const MIN_PROBE: f32 = 1e-4; + +/// Shortest on-screen axis (points per world unit) the manipulator offers a handle for +const MIN_SCREEN_SCALE: f32 = 1e-3; + +/// Grab radius around an arrow and around the center (points, at least this at any size) +const GRAB_RADIUS: f32 = 7.0; + +/// The manipulator as the 3D view shows it this frame +#[derive(Clone, Debug)] +pub(crate) struct SymmetryManipulator { + pub(crate) center: Pos2, + pub(crate) arrows: Vec, + /// Radial: a square between the two arrows that moves the axis along both + pub(crate) square: Option<[Pos2; 4]>, + /// World units per screen point at the origin + pub(crate) world_per_point: f32, + /// The manipulator size relative to the default: every measurement scales with it + pub(crate) scale: f32, + /// Screen points per world unit along X, Y and Z at the origin + screen_per_unit: [Vec2; 3], +} + +impl SymmetryManipulator { + /// Handles along the axes the plane or axis can move on, or None when the manipulator is hidden + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + let symmetry = app.session.tool.brush.symmetry; + if !app.ui.symmetry.show_manipulator || !super::shown(app) { + return None; + } + + let project = |point: Vec3| crate::viewport::project(app, rect, point); + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + let center = project(origin)?; + let step = ((hi - lo).length() * PROBE_FRACTION).max(MIN_PROBE); + let screen_per_unit = [Vec3::X, Vec3::Y, Vec3::Z].map(|axis| project(origin + axis * step).map_or(Vec2::ZERO, |point| (point - center) / step)); + + // Sized in points at the origin's depth, so the arrows keep their size on screen but still turn in 3D + let right = app.session.camera.forward().cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let points_per_unit = project(origin + right * step).map_or(0.0, |point| (point - center).length() / step); + if points_per_unit <= MIN_SCREEN_SCALE { + return None; + } + + let world_per_point = 1.0 / points_per_unit; + let scale = app.ui.symmetry.manipulator_size / DEFAULT_MANIPULATOR_SIZE; + let length = rect.height() * ARROW_LENGTH * scale * world_per_point; + + let movable = super::movable_axes(&symmetry); + let signs: &[f32] = if symmetry.radial_mode() { &[1.0] } else { &[1.0, -1.0] }; + let arrows: Vec = (0..3) + .filter(|axis| movable[*axis] && screen_per_unit[*axis].length() > MIN_SCREEN_SCALE) + .flat_map(|axis| signs.iter().map(move |sign| (axis, [Vec3::X, Vec3::Y, Vec3::Z][axis] * *sign))) + .filter_map(|(axis, direction)| { + let tip_world = origin + direction * length; + let base_world = origin + direction * (length - CONE_LENGTH * scale * world_per_point); + let start = project(origin + direction * SHAFT_GAP * scale * world_per_point)?; + Some(SymmetryManipulatorArrow { axis, direction, start, base: project(base_world)?, tip: project(tip_world)?, base_world, tip_world }) + }) + .collect(); + + let square = match movable_pair(&movable) { + Some((first, second)) if symmetry.radial_mode() => { + let corner = |along_first: f32, along_second: f32| { + let mut point = origin; + (point[first], point[second]) = (origin[first] + along_first * length, origin[second] + along_second * length); + project(point) + }; + let (from, to) = (SQUARE_FROM, SQUARE_TO); + match [corner(from, from), corner(to, from), corner(to, to), corner(from, to)] { + [Some(near), Some(along_first), Some(far), Some(along_second)] => Some([near, along_first, far, along_second]), + _ => None, + } + } + _ => None, + }; + Some(SymmetryManipulator { center, arrows, square, world_per_point, scale, screen_per_unit }) + } + + /// The axes the handle under `point` moves along: the center and the square move along all movable axes (two at most) + pub(crate) fn grab(&self, point: Pos2) -> Option<[bool; 3]> { + let mut all = [false; 3]; + self.arrows.iter().for_each(|arrow| all[arrow.axis] = true); + let grab_radius = GRAB_RADIUS * self.scale.max(1.0); + + // The center moves along all movable axes, which a screen drag can only do for two of them + let center_grabs = all.iter().filter(|axis| **axis).count() <= 2 && point.distance(self.center) <= grab_radius; + if center_grabs || self.square.is_some_and(|square| inside(&square, point)) { + return Some(all); + } + + let arrow = self.arrows.iter().find(|arrow| distance_to_segment(point, arrow.start, arrow.tip) <= grab_radius)?; + let mut axes = [false; 3]; + axes[arrow.axis] = true; + Some(axes) + } + + /// The world offset change that follows a pointer move of `moved` along `axes` + pub(crate) fn world_delta(&self, axes: [bool; 3], moved: Vec2) -> Vec3 { + let picked: Vec = (0..3).filter(|axis| axes[*axis]).collect(); + let mut delta = Vec3::ZERO; + match picked.as_slice() { + [axis] => { + let along = self.screen_per_unit[*axis]; + delta[*axis] = moved.dot(along) / along.length_sq().max(MIN_SCREEN_SCALE); + } + [first, second] => { + // Solve moved = a * first_axis + b * second_axis on screen + let (first_axis, second_axis) = (self.screen_per_unit[*first], self.screen_per_unit[*second]); + let determinant = first_axis.x * second_axis.y - first_axis.y * second_axis.x; + if determinant.abs() > MIN_SCREEN_SCALE { + delta[*first] = (moved.x * second_axis.y - moved.y * second_axis.x) / determinant; + delta[*second] = (first_axis.x * moved.y - first_axis.y * moved.x) / determinant; + } + } + _ => {} + } + delta + } +} + +/// The two movable axes, when there are two +fn movable_pair(movable: &[bool; 3]) -> Option<(usize, usize)> { + let picked: Vec = (0..3).filter(|axis| movable[*axis]).collect(); + match picked.as_slice() { + [first, second] => Some((*first, *second)), + _ => None, + } +} + +fn distance_to_segment(point: Pos2, from: Pos2, to: Pos2) -> f32 { + let along = to - from; + let fraction = ((point - from).dot(along) / along.length_sq().max(f32::EPSILON)).clamp(0.0, 1.0); + point.distance(from + along * fraction) +} + +/// Whether `point` is inside the convex quad `corners` +fn inside(corners: &[Pos2; 4], point: Pos2) -> bool { + let side = |index: usize| { + let (start, end) = (corners[index], corners[(index + 1) % 4]); + (end - start).x * (point - start).y - (end - start).y * (point - start).x + }; + let sides = [side(0), side(1), side(2), side(3)]; + sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) +} + +#[cfg(test)] +mod tests { + use egui::pos2; + + use super::*; + + #[test] + fn a_two_axis_drag_splits_the_move_between_both_axes() { + let manipulator = SymmetryManipulator { + center: pos2(0.0, 0.0), + arrows: Vec::new(), + square: None, + world_per_point: 1.0, + scale: 1.0, + screen_per_unit: [Vec2::new(10.0, 0.0), Vec2::new(0.0, -10.0), Vec2::ZERO], + }; + + let delta = manipulator.world_delta([true, true, false], Vec2::new(20.0, -30.0)); + + assert!((delta - Vec3::new(2.0, 3.0, 0.0)).length() < 1e-5, "{delta}"); + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs b/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs new file mode 100644 index 00000000..29d5144e --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs @@ -0,0 +1,18 @@ +//! One arrow of the symmetry manipulator + +use egui::Pos2; +use texturecraft_engine::geom::glam::Vec3; + +/// An arrow along one world axis, in 3D (so it foreshortens) and where it lands on screen +#[derive(Clone, Copy, Debug)] +pub(crate) struct SymmetryManipulatorArrow { + pub(crate) axis: usize, + /// The world axis, pointing toward the tip + pub(crate) direction: Vec3, + /// Where the shaft starts, just off the center, and where it meets the cone + pub(crate) start: Pos2, + pub(crate) base: Pos2, + pub(crate) tip: Pos2, + pub(crate) base_world: Vec3, + pub(crate) tip_world: Vec3, +} diff --git a/crates/ui-egui/src/symmetry/view_overlay.rs b/crates/ui-egui/src/symmetry/view_overlay.rs new file mode 100644 index 00000000..3ceb5be6 --- /dev/null +++ b/crates/ui-egui/src/symmetry/view_overlay.rs @@ -0,0 +1,314 @@ +//! What the 3D view draws for symmetry: the plane or axis, where they meet the mesh, the cursor copies and the manipulator + +use egui::{Color32, PointerButton, Pos2, Rect, Response, Stroke, Ui}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_render::OverlayQuad; + +use super::ribbons::Ribbons; +use super::shown; +use super::symmetry_drag::SymmetryDrag; +use super::symmetry_intersection::SymmetryIntersection; +use super::symmetry_manipulator::SymmetryManipulator; +use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; +use crate::TextureCraftApp; + +/// The plane reaches this far past the mesh, as a fraction of its size +const PLANE_MARGIN: f32 = 0.05; +const PLANE_OPACITY: f32 = 0.18; + +/// The radial axis line's width (points) and opacity +const AXIS_WIDTH: f32 = 1.5; +const AXIS_OPACITY: f32 = 0.85; + +/// The intersection line's opacity +const LINE_OPACITY: f32 = 0.9; + +/// A point counts as visible when nothing is in front of it by more than this fraction of the mesh diagonal +const VISIBILITY_TOLERANCE: f32 = 2e-3; + +/// Width of the cut line and radius of the radial axis points (points) +const INTERSECTION_WIDTH: f32 = 1.5; +const INTERSECTION_POINT_RADIUS: f32 = 3.0; + +/// Manipulator arrows along X, Y and Z (the view-corner axis colors, a little softer) +const AXIS_COLORS: [Color32; 3] = [Color32::from_rgb(0xd8, 0x60, 0x4f), Color32::from_rgb(0x6c, 0xbc, 0x5a), Color32::from_rgb(0x5a, 0x8c, 0xe0)]; + +/// Arrow shaft width, its dark halo and the halo's extra width (points at the default size) +const SHAFT_WIDTH: f32 = 2.2; +const SHAFT_HALO: Color32 = Color32::from_black_alpha(128); +const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; + +/// Faces around a cone +const CONE_SEGMENTS: usize = 20; + +/// Cone faces facing the camera more than this (cosine) are tinted toward white, the others toward black +const CONE_LIT_FROM: f32 = 0.55; + +/// How strongly the cone faces' tint follows their facing, toward white and toward black +const CONE_LIGHTEN: f32 = 0.9; +const CONE_DARKEN: f32 = 0.8; + +/// The center: a small disc in the arrows' material, its rim shaded and its middle lit like the cones +const CENTER_RADIUS: f32 = 4.0; +const CENTER_LIT_RADIUS: f32 = 0.6; +const CENTER_SHADE: f32 = 0.3; +const CENTER_LIGHT: f32 = 0.25; + +/// The radial square at rest and the opacity of its accent fill when active +const SQUARE_EDGE_WIDTH: f32 = 1.3; +const SQUARE_FILL: Color32 = Color32::from_rgba_premultiplied(40, 40, 40, 40); +const SQUARE_EDGE: Color32 = Color32::from_rgba_premultiplied(190, 190, 190, 190); +const SQUARE_ACTIVE_OPACITY: f32 = 0.45; + +/// `linear` RGB as a screen color with `alpha` +pub(super) fn color(linear: [f32; 3], alpha: u8) -> Color32 { + let [r, g, b] = linear.map(|channel| (texturecraft_engine::texel::linear_to_srgb(channel.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(r, g, b, alpha) +} + +/// The planes, the axis and where the planes cut the mesh, drawn by the renderer: the mesh hides them pixel by pixel where it is in front +pub(crate) fn scene_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> Vec { + if !shown(app) { + return Vec::new(); + } + + let symmetry = app.session.tool.brush.symmetry; + let display = app.ui.symmetry; + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + let ribbon = Ribbons::new(app, rect); + let mut quads = Vec::new(); + + for (axis, on) in [symmetry.x, symmetry.y, symmetry.z].into_iter().enumerate() { + if !on { + continue; + } + + if display.show_plane { + let margin = (hi - lo) * PLANE_MARGIN; + let (lo, hi) = (lo - margin, hi + margin); + let (u, v) = ((axis + 1) % 3, (axis + 2) % 3); + let corner = |at_u: f32, at_v: f32| { + let mut point = origin; + (point[u], point[v]) = (at_u, at_v); + point + }; + let corners = [corner(lo[u], lo[v]), corner(hi[u], lo[v]), corner(hi[u], hi[v]), corner(lo[u], hi[v])]; + quads.push(OverlayQuad { corners, color: display.color, opacity: PLANE_OPACITY }); + } + if display.show_intersection { + let segments = intersection(app, ui, axis, origin[axis]); + quads.extend(segments.iter().map(|[from, to]| ribbon.quad(*from, *to, INTERSECTION_WIDTH, display.color, LINE_OPACITY))); + } + } + + if display.show_axis && symmetry.radial_mode() { + let direction = symmetry.radial_axis(); + let reach = (hi - lo).length() * 0.5; + quads.push(ribbon.quad(origin - direction * reach, origin + direction * reach, AXIS_WIDTH, display.color, AXIS_OPACITY)); + } + + quads +} + +/// Whether `point` is on the mesh's surface where the camera sees it: in the air (a copy that missed the mesh) or hidden behind the mesh, it is not +fn on_visible_surface(app: &TextureCraftApp, rect: Rect, point: Vec3, tolerance: f32) -> bool { + let camera = &app.session.camera; + let aspect = rect.width() / rect.height().max(1.0); + let Some(ndc) = camera.project(point, aspect) else { return false }; + + let ray = camera.ray(ndc.truncate(), aspect); + let distance = (point - ray.origin).dot(ray.dir); + app.session.bvh.closest(ray.origin, ray.dir, f32::MAX).is_some_and(|hit| (hit.t - distance).abs() <= tolerance) +} + +/// Over the 3D view: where the planes or axis meet the mesh, copies of the brush `cursor` (position, normal) and the manipulator +pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, cursor: Option<(Vec3, Vec3)>) { + if !shown(app) { + return; + } + + let symmetry = app.session.tool.brush.symmetry; + let display = app.ui.symmetry; + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + + // Bounds scan the mesh's vertices; every cursor copy shares these measurements + let diagonal = (hi - lo).length(); + let tolerance = diagonal * VISIBILITY_TOLERANCE; + let brush_radius = app.session.tool.brush.size * diagonal; + + let painter = ui.painter_at(rect); + let line = Stroke::new(INTERSECTION_WIDTH, color(display.color, u8::MAX)); + let project = |point: Vec3| crate::viewport::project(app, rect, point); + + // The planes' lines are drawn in the scene (see scene_overlay); where the radial axis enters the mesh, from either end, is drawn here + if display.show_intersection && symmetry.radial_mode() { + let axis = symmetry.radial_axis(); + let reach = diagonal; + for (start, direction) in [(origin - axis * reach, axis), (origin + axis * reach, -axis)] { + if let Some(hit) = app.session.bvh.closest(start, direction, reach * 2.0) + && let point = start + direction * hit.t + && on_visible_surface(app, rect, point, tolerance) + && let Some(at) = project(point) + { + painter.circle_filled(at, INTERSECTION_POINT_RADIUS, line.color); + } + } + } + + let painting = app.session.stroke_active(); + if display.show_cursor + && !(display.hide_while_painting && painting) + && let Some((position, normal)) = cursor + { + for map in symmetry.transforms().iter().skip(1) { + let copy = origin + *map * (position - origin); + if on_visible_surface(app, rect, copy, tolerance) { + crate::viewport::brush_cursor(app, ui, rect, copy, (*map * normal).normalize_or_zero(), brush_radius); + } + } + } + + if let Some(manipulator) = SymmetryManipulator::of(app, rect) { + draw_manipulator(app, ui, rect, &painter, &manipulator); + } +} + +/// Where the mirror plane `p[axis] = position` cuts the mesh, recomputed only when it moves +fn intersection(app: &TextureCraftApp, ui: &Ui, axis: usize, position: f32) -> std::sync::Arc> { + let id = egui::Id::unique("symmetry_intersection").with(axis); + let mesh_id = app.session.mesh_id; + let cached = ui.ctx().data(|data| data.get_temp::(id)).filter(|cached| cached.is_for(mesh_id, axis, position)); + let current = cached.unwrap_or_else(|| { + let computed = SymmetryIntersection::compute(&app.session.mesh, mesh_id, axis, position); + ui.ctx().data_mut(|data| data.insert_temp(id, computed.clone())); + computed + }); + current.segments +} + +/// The manipulator: the radial square, the arrows with their cones and the center; copper where hovered or dragged +fn draw_manipulator(app: &TextureCraftApp, ui: &Ui, rect: Rect, painter: &egui::Painter, manipulator: &SymmetryManipulator) { + let accent = crate::theme::Tokens::get(ui.ctx()).viewport_accent; + let hovered = ui.ctx().pointer_hover_pos().and_then(|pointer| manipulator.grab(pointer)); + let dragging = ui.ctx().data(|data| data.get_temp::(drag_id())).map(|drag| drag.axes); + let highlighted = dragging.or(hovered).unwrap_or_default(); + let all_highlighted = manipulator.arrows.iter().all(|arrow| highlighted[arrow.axis]); + let tint = |axis: usize| if highlighted[axis] { accent } else { AXIS_COLORS[axis] }; + + if let Some(square) = manipulator.square { + let fill = if all_highlighted { accent.gamma_multiply(SQUARE_ACTIVE_OPACITY) } else { SQUARE_FILL }; + let edge = if all_highlighted { accent } else { SQUARE_EDGE }; + painter.add(egui::Shape::convex_polygon(square.to_vec(), fill, Stroke::new(SQUARE_EDGE_WIDTH * manipulator.scale, edge))); + } + + for arrow in &manipulator.arrows { + let color = tint(arrow.axis); + painter.line_segment([arrow.start, arrow.base], Stroke::new((SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) * manipulator.scale, SHAFT_HALO)); + painter.line_segment([arrow.start, arrow.base], Stroke::new(SHAFT_WIDTH * manipulator.scale, color)); + cone(app, rect, painter, arrow, manipulator.world_per_point * super::symmetry_manipulator::CONE_RADIUS * manipulator.scale, color); + } + + let center_color = if all_highlighted { accent } else { manipulator.arrows.first().map_or(AXIS_COLORS[0], |arrow| AXIS_COLORS[arrow.axis]) }; + painter.circle_filled(manipulator.center, CENTER_RADIUS * manipulator.scale, center_color.lerp_to_gamma(Color32::BLACK, CENTER_SHADE)); + painter.circle_filled(manipulator.center, CENTER_RADIUS * CENTER_LIT_RADIUS * manipulator.scale, center_color.lerp_to_gamma(Color32::WHITE, CENTER_LIGHT)); +} + +/// A flat-shaded 3D cone over `arrow`'s head: faces facing the camera lighter, back to front +fn cone(app: &TextureCraftApp, rect: Rect, painter: &egui::Painter, arrow: &SymmetryManipulatorArrow, radius: f32, color: Color32) { + let camera = &app.session.camera; + let (eye, forward) = (camera.eye(), camera.forward()); + let side = arrow.direction.any_orthonormal_vector(); + let up = arrow.direction.cross(side); + let rim: Vec = (0..CONE_SEGMENTS) + .map(|segment| { + let angle = segment as f32 / CONE_SEGMENTS as f32 * std::f32::consts::TAU; + arrow.base_world + (side * angle.cos() + up * angle.sin()) * radius + }) + .collect(); + + // Each face: its corners, its depth and how much it faces the camera + let mut faces: Vec<(Vec, f32, f32)> = (0..CONE_SEGMENTS) + .map(|segment| { + let (rim_start, rim_end) = (rim[segment], rim[(segment + 1) % CONE_SEGMENTS]); + let middle = (rim_start + rim_end + arrow.tip_world) / 3.0; + let normal = (rim_end - rim_start).cross(arrow.tip_world - rim_start).normalize_or_zero(); + (vec![arrow.tip_world, rim_start, rim_end], (middle - eye).dot(forward), normal.dot((eye - middle).normalize_or_zero())) + }) + .collect(); + faces.push((rim.clone(), (arrow.base_world - eye).dot(forward), (-arrow.direction).dot((eye - arrow.base_world).normalize_or_zero()))); + faces.sort_by(|(_, nearer, _), (_, farther, _)| farther.total_cmp(nearer)); + + // One plain triangle mesh: anti-aliased polygons smear thin edge-on faces into long hairlines + let mut mesh = egui::Mesh::default(); + for (corners, _, facing) in faces { + let Some(points) = corners.iter().map(|corner| crate::viewport::project(app, rect, *corner)).collect::>>() else { + continue; + }; + + let facing = facing.max(0.0); + let fill = if facing > CONE_LIT_FROM { + color.lerp_to_gamma(Color32::WHITE, (facing - CONE_LIT_FROM) * CONE_LIGHTEN) + } else { + color.lerp_to_gamma(Color32::BLACK, (CONE_LIT_FROM - facing) * CONE_DARKEN) + }; + let first = mesh.vertices.len() as u32; + points.iter().for_each(|point| mesh.colored_vertex(*point, fill)); + for corner in 1..points.len().saturating_sub(1) as u32 { + mesh.add_triangle(first, first + corner, first + corner + 1); + } + } + painter.add(egui::Shape::mesh(mesh)); +} + +fn drag_id() -> egui::Id { + egui::Id::unique("symmetry_manipulator_drag") +} + +/// Whether the pointer is on a manipulator handle or dragging one (the brush cursor hides then) +pub(crate) fn manipulator_hovered(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> bool { + let dragging = ui.ctx().data(|data| data.get_temp::(drag_id())).is_some(); + let hovered = + ui.ctx().pointer_hover_pos().is_some_and(|pointer| SymmetryManipulator::of(app, rect).is_some_and(|manipulator| manipulator.grab(pointer).is_some())); + dragging || hovered +} + +/// Drags on the manipulator move the symmetry origin. Returns whether a drag owns the pointer +pub(crate) fn manipulator_input(app: &mut TextureCraftApp, ui: &Ui, response: &Response, rect: Rect) -> bool { + let ctx = ui.ctx(); + let manipulator = SymmetryManipulator::of(app, rect); + let mut drag = ctx.data(|data| data.get_temp::(drag_id())); + if response.drag_started_by(PointerButton::Primary) + && let (Some(manipulator), Some(from)) = (&manipulator, ctx.input(|input| input.pointer.press_origin())) + && let Some(axes) = manipulator.grab(from) + { + drag = Some(SymmetryDrag { axes, from, start_offset: app.session.tool.brush.symmetry.offset }); + } + + let dragging = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary); + let (Some(manipulator), Some(drag)) = (manipulator, drag.filter(|_| dragging)) else { + ctx.data_mut(|data| data.remove::(drag_id())); + if let (Some(manipulator), Some(hover)) = (SymmetryManipulator::of(app, rect), response.hover_pos()) + && manipulator.grab(hover).is_some() + { + ctx.set_cursor_icon(egui::CursorIcon::Move); + } + + return false; + }; + + if let Some(pointer) = response.interact_pointer_pos() { + let (lo, hi) = app.session.mesh.bounds(); + let half_extent = (hi - lo) * 0.5; + let moved = Vec3::from(drag.start_offset) + manipulator.world_delta(drag.axes, pointer - drag.from); + let offset = moved.clamp(-half_extent, half_extent).to_array(); + if offset != app.session.tool.brush.symmetry.offset { + app.run("tool.brush", serde_json::json!({"symmetryOffset": offset})); + } + } + + ctx.data_mut(|data| data.insert_temp(drag_id(), drag)); + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + true +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a2d85712..9a7bda37 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,254 +1,326 @@ -//! 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 std::path::{Path, PathBuf}; +use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; +use texturecraft_engine::compose::{ImageRes, ImageStore}; 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, BrushSettings, 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 = 64; +/// 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; +/// The [`ShelfPreview::key`] prefix of the user's saved files +const SAVED_FILE_KEY_PREFIX: &str = "saved-"; +/// Largest stencil preview dimension in pixels +const STENCIL_MAX_SIZE_PX: f32 = 1024.0; +/// Big hover previews kept at most (the least recently shown go first) +const BIG_PREVIEWS_KEPT: usize = 32; + +/// Parsed settings, weak image identity and preview revision for a saved brush +type SavedBrushCacheEntry = (Option, Option>, u64); + +/// 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). + /// Parsed settings, weak image identity and preview revision for each saved brush + saved_brush_previews: HashMap, + /// Refresh generation; queued results from earlier generations must not match new requests + saved_files_epoch: u64, + images: HashMap, TextureHandle)>, + images_revision: Option, + /// (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). - pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { + /// 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, image: &Arc) -> TextureHandle { let key = format!("stencil:{name}"); - if let Some(t) = self.images.get(&key) { - return t.clone(); + if let Some((cached_image, texture)) = self.images.get(&key) + && cached_image.ptr_eq(&Arc::downgrade(image)) + { + return texture.clone(); } - let scale = (1024.0 / img.width.max(img.height).max(1) as f32).min(1.0); - let (w, h) = (((img.width as f32 * scale) as usize).max(1), ((img.height as f32 * scale) as usize).max(1)); - let mut ci = ColorImage::filled([w, h], Color32::TRANSPARENT); + + let scale = (STENCIL_MAX_SIZE_PX / image.width.max(image.height).max(1) as f32).min(1.0); + let (w, h) = (((image.width as f32 * scale) as usize).max(1), ((image.height as f32 * scale) as usize).max(1)); + let mut color_image = ColorImage::filled([w, h], Color32::TRANSPARENT); for y in 0..h { for x in 0..w { - let s = img.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); - let enc = |v: f32| if img.srgb { (v.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(v) * 255.0) as u8 }; - ci.pixels[y * w + x] = Color32::from_rgba_unmultiplied(enc(s[0]), enc(s[1]), enc(s[2]), (s[3].clamp(0.0, 1.0) * 255.0) as u8); + let sample = image.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); + let encode = |value: f32| { + if image.srgb { (value.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(value) * 255.0) as u8 } + }; + color_image.pixels[y * w + x] = + Color32::from_rgba_unmultiplied(encode(sample[0]), encode(sample[1]), encode(sample[2]), (sample[3].clamp(0.0, 1.0) * 255.0) as u8); } } - let t = ctx.load_texture(key.clone(), ci, TextureOptions::LINEAR); - self.images.insert(key, t.clone()); - t + + let texture = ctx.load_texture(key.clone(), color_image, TextureOptions::LINEAR); + self.images.insert(key, (Arc::downgrade(image), texture.clone())); + texture } - /// Cached preview of an image resource (64 px, nearest downsample). - 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(); + /// Cached preview of an image resource (64 px, letterboxed) + pub fn image(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { + if let Some((cached_image, texture)) = self.images.get(name) + && cached_image.ptr_eq(&Arc::downgrade(image)) + { + return texture.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); - self.images.insert(name.to_string(), t.clone()); - t + + let texture = ctx.load_texture(format!("res_{name}"), image_preview(image, IMAGE_PX), TextureOptions::LINEAR); + self.images.insert(name.to_string(), (Arc::downgrade(image), texture.clone())); + texture } - /// 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()); + /// Release previews for deleted or replaced resources after a session change + pub fn sync_images(&mut self, images: &ImageStore, revision: u64) { + if self.images_revision == Some(revision) { + return; } + + self.images_revision = Some(revision); + self.images.retain(|key, (cached_image, _)| { + let name = key.strip_prefix("stencil:").unwrap_or(key); + images.get(name).is_some_and(|image| cached_image.ptr_eq(&Arc::downgrade(image))) + }); + } + + /// 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 false; + } + + self.budget.1 += renders; + true + } + + /// 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 = self.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) + } + + /// 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) + } + + /// 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, + } + } + + /// 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; + } + } + } + + /// 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 = self.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) + } + + /// 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(&self.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), + } + } + + /// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk + pub fn forget_saved_files(&mut self) { + self.saved_files_epoch = self.saved_files_epoch.wrapping_add(1); + let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX); + self.shelf.retain(|key, _| current(key)); + self.rendered.retain(|key, _| current(key)); + self.big_shown.retain(current); + self.saved_brush_previews.clear(); + } + + /// 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 lighting environment's panorama + pub fn environment(&mut self, ctx: &egui::Context, name: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX) + } + + /// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable + pub fn saved_brush(&mut self, ctx: &egui::Context, path: &Path, images: &ImageStore) -> Option { + let key = format!("saved-brush:{}", path.display()); + let cached_preview = self.saved_brush_previews.contains_key(path).then(|| self.saved_brush_preview(path, images)); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); + } + if !self.spend_budget(ctx, 1) { return None; } - self.budget.1 += 1; - let t = ctx.load_texture(format!("thumb_{key}"), render(), TextureOptions::LINEAR); - self.shelf.insert(key, t.clone()); - Some(t) + + let preview = cached_preview.unwrap_or_else(|| self.saved_brush_preview(path, images)); + let image = preview.image(SWATCH_PX).unwrap_or_else(|| ColorImage::filled([SWATCH_PX, SWATCH_PX], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) } - /// 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())) - } - - /// 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) - }) - } - - /// 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())) - } - - /// 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); - } - 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()) - }) - } - - /// 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)) - } -} - -/// `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; + /// Reuse parsed settings until refresh; rebuild previews when their project image changes + pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview { + let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None, 0)); + let (settings, previous_image, revision) = cached; + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)); + let image_changed = match (previous_image.as_ref(), image) { + (Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)), + (None, None) => false, + _ => true, + }; + *previous_image = image.map(Arc::downgrade); + if image_changed { + *revision = revision.wrapping_add(1); + let key = format!("saved-brush:{}", path.display()); + let rendered_prefix = format!("{key}@"); + self.shelf.remove(&key); + self.rendered.retain(|rendered, _| !rendered.starts_with(&rendered_prefix)); + self.big_shown.retain(|rendered| !rendered.starts_with(&rendered_prefix)); } - 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)); - } + + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() } + } + + /// A saved-brush key also identifies the refresh and image version of its request + fn worker_key(&self, preview: &ShelfPreview, size_px: usize) -> String { + let key = format!("{}@{size_px}", preview.key()); + if let ShelfPreview::SavedBrush { path, .. } = preview { + let revision = self.saved_brush_previews.get(path).map_or(0, |(_, _, revision)| *revision); + format!("{key}#{}:{revision}", self.saved_files_epoch) + } else { + key } } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) + + /// 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) + } } /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). @@ -304,3 +376,186 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use crate::orb_shape::OrbShape; + + static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + + #[test] + fn saved_brush_refresh_discards_old_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("refreshed.tcbrush"), settings: None, image: None }; + + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + thumbs.forget_saved_files(); + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, None), (old_key, Some(ColorImage::filled([8, 8], Color32::RED)))]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, &preview, 8).is_none(), "an old completion must not replace the current failed result"); + } + + #[test] + fn saved_brush_image_replacement_preserves_current_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let path = PathBuf::from("changed-alpha.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + thumbs.saved_brush_previews.insert(path.clone(), (Some(settings), None, 0)); + let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let mut images: ImageStore = [("alpha.png".into(), image(0.2))].into(); + + let old_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, old_preview, 8).is_none()); + images.insert("alpha.png".into(), image(0.8)); + let current_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, current_preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, Some(ColorImage::filled([8, 8], Color32::RED))), (old_key, None)]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, ¤t_preview, 8).is_some(), "the current completion must survive an old failure"); + } + + #[test] + fn saved_brush_file_read_waits_for_the_thumbnail_budget() { + let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + thumbs.budget = (context.cumulative_pass_nr(), PER_FRAME); + + assert!(thumbs.saved_brush(&context, &path, &ImageStore::new()).is_none()); + assert!(thumbs.saved_brush_previews.is_empty(), "a deferred thumbnail has not read its file"); + + std::fs::remove_file(&path).unwrap(); + } + + #[test] + fn saved_brush_settings_are_read_once_until_refresh() { + let path = + std::env::temp_dir().join(format!("texturecraft-brush-preview-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let mut thumbs = Thumbs::default(); + let images = ImageStore::new(); + + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. })); + std::fs::remove_file(&path).unwrap(); + assert!( + matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }), + "cached settings avoid a second file read" + ); + + thumbs.forget_saved_files(); + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: None, .. }), "refresh reads the file again"); + } + + #[test] + fn saved_brush_cache_releases_old_images_on_change_and_refresh() { + const IMAGE_SIDE: u32 = 512; + const IMAGE_TEXELS: usize = IMAGE_SIDE as usize * IMAGE_SIDE as usize; + const IMAGE_BYTES: usize = IMAGE_TEXELS * std::mem::size_of::<[f32; 4]>(); + + let mut thumbs = Thumbs::default(); + let first_path = PathBuf::from("first.tcbrush"); + let second_path = PathBuf::from("second.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let old_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[1.0; 4]; IMAGE_TEXELS], srgb: false }); + let other_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.5; 4]; IMAGE_TEXELS], srgb: false }); + let old_weak = Arc::downgrade(&old_image); + let other_weak = Arc::downgrade(&other_image); + assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + + thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None, 0)); + thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None, 0)); + let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into(); + drop(thumbs.saved_brush_preview(&first_path, &images)); + images.insert("alpha.png".into(), other_image.clone()); + drop(thumbs.saved_brush_preview(&second_path, &images)); + drop(old_image); + drop(other_image); + assert!(old_weak.upgrade().is_none(), "cached settings do not retain a replaced image"); + assert!(other_weak.upgrade().is_some(), "the project still owns its current image"); + eprintln!( + "saved brush cache after first replacement: 0 of {IMAGE_BYTES} old image bytes retained, {} current image strong owners", + Arc::strong_count(&images["alpha.png"]) + ); + + let replacement = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.0; 4]; IMAGE_TEXELS], srgb: false }); + images.insert("alpha.png".into(), replacement); + drop(thumbs.saved_brush_preview(&first_path, &images)); + assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image"); + eprintln!("saved brush cache after second replacement: 0 of {IMAGE_BYTES} previous image bytes retained"); + + thumbs.forget_saved_files(); + assert!(thumbs.saved_brush_previews.is_empty(), "refresh releases parsed brush settings"); + } + + #[test] + fn replacing_an_image_rebuilds_its_preview() { + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + + let first_image = image(0.2); + let replacement_image = image(0.8); + let first = thumbs.image(&context, "sample.png", &first_image); + let second = thumbs.image(&context, "sample.png", &replacement_image); + + assert_ne!(first.id(), second.id(), "a replaced resource must update its preview"); + } + + #[test] + fn removing_resources_releases_their_previews() { + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + let mut images = ImageStore::new(); + for index in 0..3 { + let name = format!("image-{index}"); + images.insert(name, Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[index as f32; 4]; 4], srgb: false })); + } + + for (name, image) in &images { + drop(thumbs.image(&context, name, image)); + } + let cached_pixel_bytes = |thumbs: &Thumbs| thumbs.images.values().map(|(_, texture)| texture.size()[0] * texture.size()[1] * 4).sum::(); + let before_count = thumbs.images.len(); + let before_pixel_bytes = cached_pixel_bytes(&thumbs); + images.remove("image-0"); + images.remove("image-1"); + thumbs.sync_images(&images, 1); + let after_count = thumbs.images.len(); + let after_pixel_bytes = cached_pixel_bytes(&thumbs); + + eprintln!("cached previews: {before_count} -> {after_count}; texture pixel bytes: {before_pixel_bytes} -> {after_pixel_bytes}"); + assert_eq!((before_count, after_count), (3, 1)); + assert!(after_pixel_bytes < before_pixel_bytes); + assert!(thumbs.images.contains_key("image-2")); + + images.insert("image-3".into(), Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[0.7; 4]; 4], srgb: false })); + drop(thumbs.image(&context, "image-3", &images["image-3"])); + thumbs.sync_images(&images, 2); + assert_eq!(thumbs.images.len(), 2); + + images.clear(); + thumbs.sync_images(&images, 3); + eprintln!("cached previews after clearing resources: {}", thumbs.images.len()); + assert!(thumbs.images.is_empty()); + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 03ef13d0..ce998917 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,222 +8,478 @@ 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}; -pub fn tool_icon(t: Tool) -> &'static str { - match t { +const BAR_SPACING: f32 = 10.0; +const COMPACT_BAR_SPACING: f32 = 4.0; +const BAR_SEPARATOR_WIDTH: f32 = 6.0; + +/// Height of the top bar, in points +const BAR_HEIGHT: f32 = 40.0; + +/// Padding inside the top bar card on its left and right, in points +const BAR_PADDING: egui::Margin = egui::Margin::symmetric(8, 0); + +pub fn tool_icon(tool: Tool) -> &'static str { + match tool { Tool::Paint => ic::PAINT_BRUSH, Tool::Eraser => ic::ERASER, - Tool::Projection => ic::PROJECTOR_SCREEN, + Tool::Projection => ic::CUBE_FOCUS, Tool::PolygonFill => ic::POLYGON, Tool::Smudge => ic::FINGERPRINT, Tool::Clone => ic::STAMP, Tool::ColorPicker => ic::EYEDROPPER, - Tool::Path => ic::PATH, - Tool::GeometryMask => ic::CUBE_FOCUS, + Tool::Path => ic::PEN_NIB_STRAIGHT, + Tool::GeometryMask => ic::SELECTION_SLASH, } } -pub fn top_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::top("tool_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tk, egui::Margin { left: GUTTER, right: GUTTER, top: GUTTER, bottom: 0 }, egui::Margin::symmetric(8, 0), |ui| { - ui.horizontal_centered(|ui| { - ui.spacing_mut().item_spacing.x = 10.0; - if app.ui.mode == Mode::Baking { - ui.label(RichText::new(tr("Bake Mesh Maps")).color(tk.text_strong)); +/// 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(BAR_HEIGHT).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, BAR_PADDING, |ui| { + 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; } - let tool = app.session.tool.tool; - ui.label(RichText::new(tool_icon(tool)).size(15.0).color(tk.text_strong)).on_hover_text(tool.label()); - let b = &mut app.session.tool.brush; - match tool { - Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { - let mut size = b.size / 0.25 * 100.0; - if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { - b.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); - } - let mut flow = b.flow * 100.0; - if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { - b.flow = flow / 100.0; - } - let mut op = b.opacity * 100.0; - if bar_slider(ui, tr("Stroke opacity"), &mut op, 0.0..=100.0, 110.0).changed() { - b.opacity = op / 100.0; - } - let mut sp = b.spacing * 100.0; - if bar_slider(ui, tr("Spacing"), &mut sp, 1.0..=200.0, 100.0).changed() { - b.spacing = sp / 100.0; - } - ui.separator(); - let lazy_on = b.lazy > 0.0; - if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { - b.lazy = if lazy_on { 0.0 } else { 20.0 }; - } - if lazy_on { - let mut d = b.lazy; - if bar_slider(ui, tr("Distance"), &mut d, 1.0..=200.0, 90.0).changed() { - b.lazy = d; - } - } - ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), b.symmetry.x, 24.0).clicked() { - b.symmetry.x = !b.symmetry.x; - } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), b.symmetry.y, 24.0).clicked() { - b.symmetry.y = !b.symmetry.y; - } - if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), b.particles.enabled, 24.0).clicked() { - b.particles.enabled = !b.particles.enabled; - } - if tool == Tool::Smudge { - ui.separator(); - let mut st = app.session.tool.smudge_strength * 100.0; - if bar_slider(ui, tr("Strength"), &mut st, 0.0..=100.0, 100.0).changed() { - app.session.tool.smudge_strength = (st / 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(tk.text_dim)); - } - if tool == Tool::Path { - ui.separator(); - path_controls(app, ui); - } - } - Tool::PolygonFill => { - use texturecraft_engine::FillMode; - for (m, 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 == m, 24.0).clicked() { - app.session.tool.fill_mode = m; - } - } - } - Tool::ColorPicker => { - ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tk.text_dim)); - } - Tool::GeometryMask => { - ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tk.text_dim)); + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if !scroll_views { + view_buttons(app, ui); + if app.session.tool_usable(app.session.tool.tool) { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); } } - 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 (l, 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 == l, 24.0).clicked() { - app.ui.layout = l; - } - } - 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.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). -pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let path = &mut app.session.tool.path; - if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, 24.0).clicked() { - path.closed = !path.closed; +/// 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); } - 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() { - 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")))) - .on_hover_text(tr("Paint the path with the brush (Enter)")) - .clicked() - { - app.run("tool.path", json!({"commit": true})); - } - if ui.add_enabled(has_points, egui::Button::new(format!("{} {}", ic::X, tr("Cancel")))).on_hover_text(tr("Remove the path (Esc)")).clicked() { - app.run("tool.path", json!({"clear": true})); + + 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| { + // A tool that can't act on the selection leaves the bar, as the shelf greys it + let tool_usable = app.session.tool_usable(app.session.tool.tool); + if tool_usable { + tool_controls(app, ui, tokens); + } + if scroll_views { + if tool_usable { + 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::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, button_size).clicked() { + brush.particles.enabled = !brush.particles.enabled; + } + if crate::symmetry::applies_to(tool) { + crate::symmetry::toolbar_controls(app, ui); + } + + 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 = &app.session.tool.path; + let (closed, fill) = (path.closed, path.fill); + let selected = path.selected.is_some_and(|i| i < path.points.len()); + let has_points = !path.points.is_empty(); + if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() { + app.session.set_path_closed(!closed); + } + + let fill_tip = if closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; + if icon_button(ui, ic::PAINT_BUCKET, fill_tip, fill, button_size).clicked() { + app.session.set_path_fill(!fill); + } + + if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() { + app.session.remove_selected_path_point(); + } + + if ui.add_enabled_ui(has_points, |ui| icon_button(ui, ic::CHECK, tr("Apply"), false, button_size)).inner.clicked() { + app.run("tool.path", json!({"commit": true})); + } +} + +/// Shelf order of the tools; their shortcut keys follow `Tool::ALL` +const SHELF_TOOLS: [Tool; 9] = + [Tool::Paint, Tool::Eraser, Tool::Path, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::GeometryMask]; + +/// The tools Baking keeps on its shelf, greyed +const BAKING_SHELF_TOOLS: [Tool; 3] = [Tool::Paint, Tool::Eraser, Tool::PolygonFill]; + +/// Width of the tool shelf, in points +const SHELF_WIDTH: f32 = 40.0; + +/// Size of a shelf button, in points +const SHELF_BUTTON_SIZE: f32 = 28.0; + +/// Vertical gap between shelf buttons, in points +const SHELF_BUTTON_SPACING: f32 = 3.0; + +/// Space on each side of the lines between shelf groups, in points +const SHELF_GROUP_GAP: f32 = 6.0; + +/// Padding inside the shelf card around its buttons, in points (sides, then top and bottom) +const SHELF_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); + pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tk, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { - ui.spacing_mut().item_spacing.y = 3.0; - let painting = app.ui.mode == Mode::Painting; - for t in Tool::ALL { - let selected = painting && app.session.tool.tool == t; - let hint = tip(&app.ui.keymap, tr(t.label()), &format!("tool.{}", t.id())); - if icon_button(ui, tool_icon(t), &hint, selected, 28.0).clicked() { - app.ui.mode = Mode::Painting; - app.run("tool.select", json!({"tool": t.id()})); + let tokens = Tokens::get(ui.ctx()); + egui::Panel::left("tool_shelf").resizable(false).exact_size(SHELF_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + // The tools start level with the panels' contents, below their tab strips + let top = GUTTER + crate::docking::TAB_HEIGHT as i8; + card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top, bottom: GUTTER }, SHELF_PADDING, |ui| { + ui.spacing_mut().item_spacing.y = SHELF_BUTTON_SPACING; + + // Rendering has nothing to paint, so its shelf keeps only the buttons below the tools + let tools: &[Tool] = match app.ui.mode { + Mode::Painting => &SHELF_TOOLS, + Mode::Baking => &BAKING_SHELF_TOOLS, + Mode::Rendering => &[], + }; + if !tools.is_empty() { + for &tool in tools { + let command = format!("tool.{}", tool.id()); + let hint = tip(&app.ui.keymap, tr(tool.label()), &command); + let (usable, selected) = match app.ui.mode { + // In bake mode Paint is the cage or skew brush while one of them is being painted + Mode::Baking => { + let bake_brush = tool == Tool::Paint && app.ui.bake_paint_brush.on; + (bake_brush, bake_brush) + } + // A greyed tool never shows as selected, even while it stays equipped + _ => { + let usable = crate::menus::enabled(app, &command); + (usable, usable && app.session.tool.tool == tool) + } + }; + let button = ui.add_enabled_ui(usable, |ui| icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(tr(tool.label())).clicked() && app.ui.mode == Mode::Painting { + app.run("tool.select", json!({"tool": tool.id()})); + } } + + ui.add_space(SHELF_GROUP_GAP); + ui.separator(); + ui.add_space(SHELF_GROUP_GAP); } - ui.add_space(6.0); - ui.separator(); - ui.add_space(6.0); - let q = &app.session.quick_mask; - for (id, icon, label, on) in [ - ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), q.enabled), - ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), q.editing), - ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), q.inverted), + + let quick_mask = &app.session.quick_mask; + for (command, icon, label, selected) in [ + ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled), + ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing), + ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, id), on, 28.0).clicked() { - app.run(id, json!({})); + let hint = tip(&app.ui.keymap, label, command); + let button = ui.add_enabled_ui(crate::menus::enabled(app, command), |ui| icon_button(ui, icon, &hint, selected, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(label).clicked() { + app.run(command, json!({})); } } - ui.add_space(6.0); + + ui.add_space(SHELF_GROUP_GAP); ui.separator(); - ui.add_space(6.0); - if icon_button(ui, ic::ATOM, &tip(&app.ui.keymap, tr("Bake mesh maps"), "ui.mode.bake"), app.ui.mode == Mode::Baking, 28.0).clicked() { - app.ui.mode = if app.ui.mode == Mode::Baking { Mode::Painting } else { Mode::Baking }; - } - if icon_button(ui, ic::APERTURE, &tip(&app.ui.keymap, tr("Rendering, path traced"), "ui.mode.render"), app.ui.mode == Mode::Rendering, 28.0) - .clicked() + ui.add_space(SHELF_GROUP_GAP); + let painting = app.ui.mode == Mode::Painting; + if ui.add_enabled_ui(painting, |ui| icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, SHELF_BUTTON_SIZE)).inner.clicked() { - app.ui.mode = if app.ui.mode == Mode::Rendering { Mode::Painting } else { Mode::Rendering }; - } - if icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, 28.0).clicked() { app.ui.dock.focus(Panel::Assets); } }); }); } +/// Width of the icon rail beside the dock +const RAIL_WIDTH: f32 = 38.0; + +/// Size of the rail's icons +const RAIL_ICON_SIZE: f32 = 26.0; + +/// Gap between the rail's icons +const RAIL_ICON_GAP: f32 = 4.0; + +/// Padding inside the rail's card around its icons, as the tool shelf's +const RAIL_CARD_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); + +/// The icon rail: Export, then the rail panels that are not in the dock, each opening its popup pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::right("rail").resizable(false).exact_size(38.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tk, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { - ui.spacing_mut().item_spacing.y = 4.0; - if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, 26.0).clicked() { + let tokens = Tokens::get(ui.ctx()); + egui::Panel::right("rail").resizable(false).exact_size(RAIL_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + card(ui, &tokens, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, RAIL_CARD_PADDING, |ui| { + ui.spacing_mut().item_spacing.y = RAIL_ICON_GAP; + crate::rail_popup::begin_rail(ui.ctx(), ui.max_rect()); + if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE).clicked() { app.ui.windows.export = !app.ui.windows.export; } - for (panel, icon, id) in [ - (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), - (Panel::Display, ic::MONITOR, "ui.view.display"), - (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), - (Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, tr(panel.name()), id), app.ui.dock.is_visible(panel), 26.0).clicked() { - app.ui.dock.toggle(panel); + + // A panel in the dock, docked or floating, leaves the rail until it is closed there + for (panel, icon, id) in crate::rail_popup::RAIL_PANELS { + if app.ui.dock.is_open(panel) { + continue; + } + + let response = icon_button(ui, icon, &tip(&app.ui.keymap, tr(panel.name()), id), app.ui.rail_panel == Some(panel), RAIL_ICON_SIZE); + crate::rail_popup::remember_icon(ui.ctx(), panel, response.rect); + if response.clicked() { + crate::rail_popup::toggle(app, panel); } } }); 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..7bd1a539 --- /dev/null +++ b/crates/ui-egui/src/ui_state_store.rs @@ -0,0 +1,681 @@ +//! 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"; +/// Textures moved from index 8 to index 6 when procedurals joined that type +const LEGACY_TEXTURES_TAB: usize = 8; +const TEXTURES_TAB: usize = 6; + +/// 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 = decode_json_ui(&bytes); + 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 mut ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if let Some(ui) = &mut ui { + migrate_shelf_tab(ui, ron_has_shelf_path(&text)); + } + 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()) + } + } + } +} + +/// Old saved states have no shelf path, so their former Textures index needs remapping +fn migrate_shelf_tab(ui: &mut UiState, has_shelf_path: bool) { + if ui.shelf_tab == LEGACY_TEXTURES_TAB && !has_shelf_path { + ui.shelf_tab = TEXTURES_TAB; + } +} + +/// Decode JSON settings and map the old Textures index only when its new fields are absent +fn decode_json_ui(bytes: &[u8]) -> Option { + let mut ui = serde_json::from_slice::(bytes).ok()?; + if ui.shelf_tab == LEGACY_TEXTURES_TAB { + let has_shelf_path = serde_json::from_slice::(bytes) + .ok() + .and_then(|state| state.as_object().map(|fields| fields.contains_key("shelf_path"))) + .unwrap_or(true); + migrate_shelf_tab(&mut ui, has_shelf_path); + } + Some(ui) +} + +/// Ignore user text while looking for the field in legacy RON settings +fn ron_has_shelf_path(text: &str) -> bool { + let bytes = text.as_bytes(); + let mut quoted = false; + let mut escaped = false; + for (index, byte) in bytes.iter().enumerate() { + if quoted { + if escaped { + escaped = false; + } else if *byte == b'\\' { + escaped = true; + } else if *byte == b'"' { + quoted = false; + } + } else if *byte == b'"' { + quoted = true; + } else if bytes[index..].starts_with(b"shelf_path:") && (index == 0 || matches!(bytes[index - 1], b',' | b'(' | b' ' | b'\n')) { + return true; + } + } + false +} + +/// The UI state saved in `file`, if it reads +pub fn read(file: &Path) -> Option { + decode_json_ui(&read_bytes(file).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 legacy_ron_textures_index_migrates_to_the_combined_type() { + let mut storage = MemoryStorage::default(); + let legacy = include_str!("../tests/fixture/ui_state_before_json.ron") + .replace("shelf_tab:0", "shelf_tab:8") + .replace("shelf_filter:\"\"", "shelf_filter:\"shelf_path:\""); + assert!(legacy.contains("shelf_tab:8") && !ron_has_shelf_path(&legacy)); + storage.values.insert(RON_STORAGE_KEY.into(), legacy); + + let loaded = UiStateStore::default().load(Some(&storage)).expect("the legacy state loads"); + + assert_eq!(loaded.shelf_tab, TEXTURES_TAB); + } + + #[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..20736bdd --- /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, mesh_id: 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 a809c341..6fd29db0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1,21 +1,26 @@ //! The 3D viewport and the 2D UV view: navigation, painting input, brush cursor and the GPU //! callbacks that render them. -use std::sync::Mutex; +use std::sync::{Arc, 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::decal_drop::DecalDrop; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; +use crate::path_hit::PathHit; +use crate::path_surface_cache::{PathSurfaceCache, SurfaceCurve}; 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,69 +39,265 @@ 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 tk = Tokens::get(ui.ctx()); - let aux = match app.session.view { - _ if app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), - ViewMode::MeshMap(m) => Some(crate::gpu::AuxView::MeshMap(m)), + let mode = app.ui.mode; + let bake_painting = mode == crate::state::Mode::Baking + && app.ui.bake_paint_brush.on + && !app.session.bake_meshes.high.is_empty() + && app.session.doc.project.texture_sets.get(app.session.ts()).is_some_and(|texture_set| { + let settings = &texture_set.bake; + match app.ui.bake_paint_brush.target { + texturecraft_engine::core::BakePaintTarget::Skew => settings.skew_applies(), + texturecraft_engine::core::BakePaintTarget::Cage => { + !settings.high_poly.use_low_as_high && settings.cage.kind == texturecraft_engine::core::CageType::DistanceBased + } + } + }); + app.ui.bake_paint_brush.on = bake_painting; + + if !app.ui.hide_ui { + crate::toolbar::paint_bar(app, ui); + } + + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + // A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture. + let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) { + ui.data_mut(|data| { + let endpoint = data.get_temp(stroke_end); + data.remove::(stroke_end); + endpoint + }) + } else { + None + }; + finish_unavailable_tool_gestures(app, pending_2d_endpoint); + crate::id_color_pick::IdColorPick::end_when_stale(app); + let tokens = Tokens::get(ui.ctx()); + 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)), + _ if mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)), _ => None, }; - let mut sync = PendingSync(Some(aux)); - let full = ui.max_rect(); - let mode = app.ui.mode; + let mut sync = PendingSync(Some(aux_view)); + let full = ui.available_rect_before_wrap(); path_keys(app, ui); - // Bake mode shows the 3D view alone, except while the skew brush needs the 2D view to paint in. - let skew_painting = mode == crate::state::Mode::Baking && app.ui.skew_brush.on; - let layout = if mode == crate::state::Mode::Painting || skew_painting { app.ui.layout } else { ViewLayout::Only3D }; + + // 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 mid = full.center().x; - let left = Rect::from_min_max(full.min, pos2(mid - 1.0, full.max.y)); - let right = Rect::from_min_max(pos2(mid + 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(mid, full.top()), pos2(mid, full.bottom())], Stroke::new(2.0, tk.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() { crate::render_mode::stop(app); } - // Keep drawing while the 3D view accumulates anti-aliasing samples (it stops on its own). + if mode == crate::state::Mode::Baking { + crate::bake_mode::bake_bar(app, ui.ctx(), full); + crate::bake_mode::bake_warnings(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; + +/// Width of the UV tile outlines, in points +const UV_TILE_OUTLINE_WIDTH: f32 = 1.0; + +/// The texture set name in the 2D view's bottom-right corner: its inset from the corner and its text size, in points +const SET_NAME_INSET: egui::Vec2 = vec2(10.0, 10.0); +const SET_NAME_TEXT_SIZE: f32 = 11.0; + +/// 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 bake brush cursor's outline: width in points and white alpha +const BAKE_PAINT_CURSOR_STROKE: f32 = 1.0; +const BAKE_PAINT_CURSOR_ALPHA: u8 = 200; + +/// A UDIM tile label: its offset from the tile's top-left corner and its text size, in points +const UV_TILE_LABEL_OFFSET: egui::Vec2 = vec2(6.0, 4.0); +const UV_TILE_LABEL_SIZE: f32 = 11.0; + +/// The projection stencil's dashed outline: width, white alpha, dash and gap, in points +const STENCIL_OUTLINE_STROKE: f32 = 1.0; +const STENCIL_OUTLINE_ALPHA: u8 = 120; +const STENCIL_OUTLINE_DASH: f32 = 5.0; +const STENCIL_OUTLINE_GAP: f32 = 4.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); +} + +/// The shader's view modes (`Shade::view_mode`): the material, one channel, the aux texture (mesh map, mask or quick mask), the UV checker +const VIEW_MODE_MATERIAL: u32 = 0; +const VIEW_MODE_CHANNEL: u32 = 1; +const VIEW_MODE_AUX_TEXTURE: u32 = 2; +const VIEW_MODE_UV_CHECKER: u32 = 3; + fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { - _ if app.session.quick_mask.editing => (2, 0), - ViewMode::Material => (0, 0), - ViewMode::Channel(c) => (1, c.index() as u32), - ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0), - ViewMode::UvChecker => (3, 0), + _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (VIEW_MODE_AUX_TEXTURE, 0), + ViewMode::Material => (VIEW_MODE_MATERIAL, 0), + ViewMode::Channel(selected_channel) => (VIEW_MODE_CHANNEL, selected_channel.index() as u32), + ViewMode::MeshMap(_) | ViewMode::Mask(_) => (VIEW_MODE_AUX_TEXTURE, 0), + ViewMode::UvChecker => (VIEW_MODE_UV_CHECKER, 0), }; - let ts = app.session.ts(); - let hs = app.session.doc.project.texture_sets.get(ts).map(|t| t.atlas_height_strength()).unwrap_or(1.0); + 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 = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { - height_strength: hs, + 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 or image 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::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(); @@ -154,45 +355,86 @@ 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; 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; + +/// Where `view_header` draws its pickers in a view of `rect`; `None` when the view is too narrow. +fn view_header_rect(rect: Rect) -> Option { + (rect.width() >= VIEW_HEADER_WIDTH).then(|| { + Rect::from_min_size(rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP), vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)) + }) +} + +/// 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)); + let Some(header) = view_header_rect(rect) else { return }; 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(); @@ -200,24 +442,39 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); - let label = 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| { - if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() { + + // Bake mode lights the project mesh with the neutral material unless the painted one is asked for + let baking = app.ui.mode == crate::state::Mode::Baking; + let neutral = baking && app.session.view == ViewMode::Material && app.ui.bake_visualization.neutral_shown; + let label = match app.session.view { + _ if neutral => "Neutral Material".to_owned(), + 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(|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 baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() { + app.ui.bake_visualization.neutral_shown = true; + app.run("viewport.view", json!({"mode": "material"})); + } + if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() { + // Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone + app.ui.bake_visualization.neutral_shown &= !baking; 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()})); + if baking { + mesh_map_entries(app, ui); + return; + } + + 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(m.label()))])).clicked() { - app.run("viewport.view", json!({"mode": format!("map:{}", m.id())})); - } - } + mesh_map_entries(app, ui); ui.separator(); if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { app.run("viewport.view", json!({"mode": "uvChecker"})); @@ -225,6 +482,16 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { }); } +/// The view picker's entries that show one baked mesh map +fn mesh_map_entries(app: &mut TextureCraftApp, ui: &mut Ui) { + 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())})); + } + } +} + fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { let tk = Tokens::get(ui.ctx()); let o = pos2(rect.left() + 28.0, rect.bottom() - 28.0); @@ -249,222 +516,354 @@ 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 = ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); - let stencil_drag = s_held && app.session.tool.stencil.is_some(); + // 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(); + + // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise + let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; + let stencil_drag = s_held && stencil_moves && 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 { - let b = &mut app.session.tool.brush; - b.size = (b.size * (1.0 + scroll * 0.002)).clamp(0.0005, 0.25); + if shift && app.ui.mode == crate::state::Mode::Painting { + // A tool that can't act keeps its size: its controls are hidden + if tool_acts(app) { + let brush = &mut app.session.tool.brush; + 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 + && stencil_moves + && 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. + + // A dismissing click cannot paint or place a decal through the rail popup + let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx()); + + // Decal placement: a click moves the decal being placed there, unless it dismisses a waiting image drop's menu 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() + && !rail_popup + && !DecalDrop::blocks_input(ui.ctx()) + && 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. - let painting = app.ui.mode == crate::state::Mode::Painting + + crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + let popup = app.properties_popup.is_some() || rail_popup; + + // 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() + && !DecalDrop::blocks_input(ui.ctx()) + && decal_input(app, ui, &response, rect); + let symmetry_drag = !alt + && !adjusting + && !s_held + && !v_held + && !focus_pick + && !popup + && placing.is_none() + && !picking_id_color + && touch.is_none() + && !DecalDrop::blocks_input(ui.ctx()) + && !decal_drag + && crate::symmetry::manipulator_input(app, ui, &response, rect); + + // A handle owns a new click, but a stroke already under way must still finish over it + let symmetry_handle = !app.session.stroke_active() && crate::symmetry::manipulator_hovered(app, ui, rect); + + // Painting + let painting = tool_acts(app) + && !popup && !alt && !adjusting && !s_held && !v_held && !focus_pick && placing.is_none() + && !picking_id_color && touch.is_none() - && !decal_drag; + && !decal_drag + && !symmetry_drag + && !symmetry_handle + && !DecalDrop::blocks_input(ui.ctx()); 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, (rect, 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(tr(&error.to_string()).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(), + overlay: crate::symmetry::scene_overlay(app, ui, rect), }; 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. - if app.ui.mode == crate::state::Mode::Painting + // Shelf drops: a material goes above the selection of the set under the pointer, an image opens the decal menu there, an alpha goes 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 + let mut symmetry_cursor = None; + if tool_acts(app) && !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.session.tool.tool != Tool::Path || adjusting) + && !crate::symmetry::manipulator_hovered(app, ui, rect) + && 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); + let (bounds_min, bounds_max) = app.session.mesh.bounds(); + let radius = app.session.tool.brush.size * (bounds_max - bounds_min).length(); + brush_cursor(app, ui, rect, hit.pos, hit.nrm, radius); + symmetry_cursor = Some((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); + + if tool_acts(app) && path_tool { + path_overlay(app, ui, rect, &response, false, show); } + crate::symmetry::overlay(app, ui, rect, symmetry_cursor); 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 { + // Setup meshes can cover the low-poly map preview; keep the switches for when setup resumes + if app.ui.mode != crate::state::Mode::Baking || app.session.bake_preview_active() { + return None; + } + + Some(app.ui.bake_visualization.visualization(app.session.ts())) +} + /// What a drag on the selected decal's frame does. #[derive(Clone, Copy, Debug, PartialEq)] enum DecalGrab { @@ -487,16 +886,18 @@ impl DecalGrab { } } -/// A decal handle being dragged (kept in egui's memory between frames). +/// A decal handle being dragged (kept in egui's memory between frames) #[derive(Clone, Copy, Debug)] struct DecalDrag { layer: texturecraft_engine::core::LayerId, + /// The mask fill effect holding the decal, when it was placed as a mask + effect: Option, grab: DecalGrab, - /// Where the drag started, the decal's center on screen and the decal then. + /// Where the drag started, the decal's center on screen and the decal then from: Pos2, center: Pos2, start: texturecraft_engine::core::Decal, - /// The drag made its undo step: later updates merge into it. + /// The drag made its undo step: later updates merge into it stepped: bool, } @@ -507,34 +908,56 @@ fn decal_drag_id() -> egui::Id { /// Screen distance from the top edge to the rotation handle (points). const DECAL_KNOB: f32 = 24.0; -/// The selected decal layer (its content, not its mask) as the 3D view shows it. +/// The selected decal (a decal layer's content, or a mask decal effect) as the 3D view shows it struct DecalFrame { layer: texturecraft_engine::core::LayerId, + /// The selected mask fill effect holding the decal, when it was placed as a mask + effect: Option, decal: texturecraft_engine::core::Decal, - /// Top left, top right, bottom right, bottom left. + /// Top left, top right, bottom right, bottom left corners: [Pos2; 4], center: Pos2, - /// The middle of the top edge and the rotation handle above it. + /// The middle of the top edge and the rotation handle above it top: Pos2, knob: Pos2, } impl DecalFrame { fn of(app: &TextureCraftApp, rect: Rect) -> Option { + use texturecraft_engine::StackTarget; use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; - use texturecraft_engine::core::{Fill, LayerKind, Projection}; - if app.ui.mode != crate::state::Mode::Painting || app.session.target != texturecraft_engine::StackTarget::Content { + use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; + + if app.ui.mode != crate::state::Mode::Painting { return None; } - let p = &app.session.doc.project; - let layer = app.session.selected_layer().and_then(|id| p.content_layer(id))?; - let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; - let [a, b, c, d] = decal_corners(decal)?.map(|q| project(app, rect, q)); - let corners = [a?, b?, c?, d?]; + + let layers = &app.session.doc.project; + let selected = app.session.selected_layer()?; + let (layer, effect, decal) = match app.session.target { + StackTarget::Content => { + let layer = layers.content_layer(selected)?; + let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; + + (layer.id, None, decal) + } + StackTarget::Effect(effect) => { + // Only the selected layer's effective mask may supply a decal frame, including an instance's inherited mask + let owner = layers.mask_owner(selected); + let mask = layers.layer(owner).ok()?.mask.as_ref()?; + let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; + let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; + + (owner, Some(effect), decal) + } + StackTarget::Mask => return None, + }; + let [top_left, top_right, bottom_right, bottom_left] = decal_corners(decal)?.map(|corner| project(app, rect, corner)); + let corners = [top_left?, top_right?, bottom_right?, bottom_left?]; let center = project(app, rect, decal_axes(decal)?.0)?; let top = corners[0].lerp(corners[1], 0.5); let knob = top + (top - center).normalized() * DECAL_KNOB; - Some(DecalFrame { layer: layer.id, decal: *decal, corners, center, top, knob }) + Some(DecalFrame { layer, effect, decal: *decal, corners, center, top, knob }) } /// The handle under screen point `p`. @@ -555,57 +978,66 @@ impl DecalFrame { } } -/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates -/// live). Returns whether a decal drag owns the pointer. +/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates live); returns whether a decal drag owns the pointer fn decal_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, rect: Rect) -> bool { let ctx = ui.ctx(); let frame = DecalFrame::of(app, rect); - let mut drag = ctx.data(|d| d.get_temp::(decal_drag_id())).filter(|d| frame.as_ref().is_some_and(|f| f.layer == d.layer)); + let on_frame = |drag: &DecalDrag| frame.as_ref().is_some_and(|frame| frame.layer == drag.layer && frame.effect == drag.effect); + let mut drag = ctx.data(|data| data.get_temp::(decal_drag_id())).filter(on_frame); if resp.drag_started_by(PointerButton::Primary) - && let (Some(f), Some(from)) = (&frame, ctx.input(|i| i.pointer.press_origin())) - && let Some(grab) = f.grab(from) + && let (Some(frame), Some(from)) = (&frame, ctx.input(|input| input.pointer.press_origin())) + && let Some(grab) = frame.grab(from) { - drag = Some(DecalDrag { layer: f.layer, grab, from, center: f.center, start: f.decal, stepped: false }); + drag = Some(DecalDrag { layer: frame.layer, effect: frame.effect, grab, from, center: frame.center, start: frame.decal, stepped: false }); } - let Some(mut d) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { - ctx.data_mut(|m| m.remove::(decal_drag_id())); - if let (Some(f), Some(h)) = (&frame, resp.hover_pos()) - && let Some(g) = f.grab(h) + + let Some(mut drag) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { + ctx.data_mut(|data| data.remove::(decal_drag_id())); + if let (Some(frame), Some(hover)) = (&frame, resp.hover_pos()) + && let Some(grab) = frame.grab(hover) { - ctx.set_cursor_icon(g.cursor(false)); + ctx.set_cursor_icon(grab.cursor(false)); } return false; }; - ctx.set_cursor_icon(d.grab.cursor(true)); - if let Some(p) = resp.interact_pointer_pos().filter(|_| ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO)) { - let mut params = match d.grab { + + ctx.set_cursor_icon(drag.grab.cursor(true)); + if let Some(pointer) = resp.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) { + let mut params = match drag.grab { DecalGrab::Move => { - let q = d.center + (p - d.from) - rect.left_top(); - let vp = app.session.viewport; - json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}) + let target = drag.center + (pointer - drag.from) - rect.left_top(); + let viewport = app.session.viewport; + json!({"x": target.x, "y": target.y, "viewport": [viewport.x, viewport.y]}) } DecalGrab::Scale => { - let k = (p - d.center).length() / (d.from - d.center).length().max(1.0); - json!({"size": [d.start.size[0] * k, d.start.size[1] * k]}) + let scale = (pointer - drag.center).length() / (drag.from - drag.center).length().max(1.0); + json!({"size": [drag.start.size[0] * scale, drag.start.size[1] * scale]}) } DecalGrab::Rotate => { - // Screen y points down: counter-clockwise angles turn the decal's right toward its up. - let angle = |v: egui::Vec2| (-v.y).atan2(v.x).to_degrees(); - json!({"rotation": d.start.rotation + angle(p - d.center) - angle(d.from - d.center)}) + // Screen y points down: counter-clockwise angles turn the decal's right toward its up + let angle = |offset: egui::Vec2| (-offset.y).atan2(offset.x).to_degrees(); + json!({"rotation": drag.start.rotation + angle(pointer - drag.center) - angle(drag.from - drag.center)}) } }; - params["layer"] = json!(d.layer.0); - params["merge"] = json!(d.stepped); - // Off the mesh while moving: the decal waits where it is. - d.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); + params["layer"] = json!(drag.layer.0); + if let Some(effect) = drag.effect { + params["effect"] = json!(effect.0); + } + params["merge"] = json!(drag.stepped); + // Off the mesh while moving: the decal waits where it is + drag.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); } - ctx.data_mut(|m| m.insert_temp(decal_drag_id(), d)); + ctx.data_mut(|data| data.insert_temp(decal_drag_id(), drag)); true } /// The frame of the selected decal layer over the 3D view with its handles (and a hint while /// placing it): outline, corner handles, the rotation handle and the projection direction. fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { + if app.ui.mode != crate::state::Mode::Painting { + return; + } + let tk = Tokens::get(ui.ctx()); use texturecraft_engine::core::{Fill, LayerKind, Projection}; let p = &app.session.doc.project; @@ -654,71 +1086,198 @@ fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { } } -/// Draw the projection stencil over the 3D view. +/// Draw the projection stencil in Paint Mode fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { - if app.session.tool.tool != Tool::Projection { + if !tool_acts(app) || app.session.tool.tool != Tool::Projection { return; } - let Some(st) = app.session.tool.stencil.clone() else { return }; - let Some(img) = app.session.images.get(&st.image).cloned() else { return }; - let tex = app.thumbs.stencil(ui.ctx(), &st.image, &img); + let Some(stencil) = app.session.tool.stencil.clone() else { return }; + let Some(image) = app.session.images.get(&stencil.image).cloned() else { return }; + + // Where the stencil's corners land on screen + let texture = app.thumbs.stencil(ui.ctx(), &stencil.image, &image); let aspect = rect.width() / rect.height().max(1.0); - let (center, half, rot) = st.placement(img.width as f32 / img.height.max(1) as f32, aspect); - let to_screen = |nx: f32, ny: f32| pos2(rect.left() + (nx * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ny * 0.5) * rect.height()); - let (sn, cs) = rot.sin_cos(); - let corner = |lx: f32, ly: f32| { - let (x, y) = (lx * half[0], ly * half[1]); - to_screen(center[0] + x * cs - y * sn, center[1] + x * sn + y * cs) + let (center, half_size, rotation) = stencil.placement(image.width as f32 / image.height.max(1) as f32, aspect); + let to_screen = |x: f32, y: f32| pos2(rect.left() + (x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - y * 0.5) * rect.height()); + let (sine, cosine) = rotation.sin_cos(); + let corner = |x: f32, y: f32| { + let (x, y) = (x * half_size[0], y * half_size[1]); + to_screen(center[0] + x * cosine - y * sine, center[1] + x * sine + y * cosine) }; - let tint = Color32::from_white_alpha((st.opacity * 255.0) as u8); - let mut mesh = egui::Mesh::with_texture(tex.id()); - for (lx, ly, u, v) in [(-1.0, 1.0, 0.0, 0.0), (1.0, 1.0, 1.0, 0.0), (1.0, -1.0, 1.0, 1.0), (-1.0, -1.0, 0.0, 1.0)] { - mesh.vertices.push(egui::epaint::Vertex { pos: corner(lx, ly), uv: pos2(u, v), color: tint }); + + let tint = Color32::from_white_alpha((stencil.opacity * f32::from(u8::MAX)) as u8); + let mut mesh = egui::Mesh::with_texture(texture.id()); + for (x, y, u, v) in [(-1.0, 1.0, 0.0, 0.0), (1.0, 1.0, 1.0, 0.0), (1.0, -1.0, 1.0, 1.0), (-1.0, -1.0, 0.0, 1.0)] { + mesh.vertices.push(egui::epaint::Vertex { pos: corner(x, y), uv: pos2(u, v), color: tint }); } mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); - let p = ui.painter_at(rect); - p.add(egui::Shape::mesh(mesh)); + let painter = ui.painter_at(rect); + painter.add(egui::Shape::mesh(mesh)); + let outline = vec![corner(-1.0, 1.0), corner(1.0, 1.0), corner(1.0, -1.0), corner(-1.0, -1.0), corner(-1.0, 1.0)]; - p.add(egui::Shape::dashed_line(&outline, Stroke::new(1.0, Color32::from_white_alpha(120)), 5.0, 4.0)); + let outline_stroke = Stroke::new(STENCIL_OUTLINE_STROKE, Color32::from_white_alpha(STENCIL_OUTLINE_ALPHA)); + painter.add(egui::Shape::dashed_line(&outline, outline_stroke, STENCIL_OUTLINE_DASH, STENCIL_OUTLINE_GAP)); } -/// A world point on screen in the 3D view `rect` (None behind the camera). -fn project(app: &TextureCraftApp, rect: Rect, p: Vec3) -> Option { - let n = app.session.camera.project(p, rect.width() / rect.height().max(1.0))?; - Some(pos2(rect.left() + (n.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - n.y * 0.5) * rect.height())) +/// A world point on screen in the 3D view `rect` (None behind the camera) +pub(crate) fn project(app: &TextureCraftApp, rect: Rect, point: Vec3) -> Option { + let ndc = app.session.camera.project(point, rect.width() / rect.height().max(1.0))?; + Some(pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height())) } -/// Control point grab radius (points). +/// Control point and curve grab radius (points) const HANDLE_GRAB: f32 = 8.0; +/// Opacity of the selected layer's other stored paths +const PATH_STORED_OPACITY: f32 = 0.55; +/// Opacity of a curve where the mesh hides it +const PATH_HIDDEN_OPACITY: f32 = 0.5; +/// A control point counts as hidden when the surface under it is this much closer (relative) +const PATH_HIDDEN_DEPTH: f32 = 0.01; +/// The Path tool's pointer glyph size (points) +const PATH_CURSOR_SIZE: f32 = 18.0; +/// A path's line and the dark outline under it (points) +const PATH_LINE_WIDTH: f32 = 1.4; +const PATH_OUTLINE_WIDTH: f32 = 3.0; +/// Where the view hint sits from the view's bottom left corner, and its text size (points) +const PATH_HINT_OFFSET: egui::Vec2 = vec2(56.0, -12.0); +const PATH_HINT_FONT_SIZE: f32 = 12.0; +/// The pen pointer's drop shadow, and the space before its insert plus (points) +const PATH_CURSOR_SHADOW_OFFSET: egui::Vec2 = vec2(1.0, 1.0); +const PATH_CURSOR_PLUS_GAP: f32 = 1.0; +/// The insert plus beside the pen pointer, relative to the pen's size +const PATH_CURSOR_PLUS_SCALE: f32 = 0.6; +/// Space kept right of the view hint, and its narrowest wrap width (points) +const PATH_HINT_MARGIN: f32 = 8.0; +const PATH_HINT_MIN_WIDTH: f32 = 80.0; +/// How much a control point marker grows under the pointer, and when selected (points) +const PATH_POINT_HOVER_GROWTH: f32 = 1.5; +const PATH_POINT_SELECTED_GROWTH: f32 = 0.5; +/// Control point marker radius (points) +const PATH_POINT_RADIUS: f32 = 3.0; +/// Curve sampling step on screen (points) +const PATH_SCREEN_STEP: f32 = 3.0; -/// Path tool keys: Enter applies the path, Backspace removes its last point (Esc, handled with -/// the global shortcuts, cancels it). +/// Path tool keys: Enter applies the path, Backspace removes the selected (or last) point; Esc is a global shortcut fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { - if app.ui.mode != crate::state::Mode::Painting - || app.session.tool.tool != Tool::Path - || app.session.tool.path.points.is_empty() - || ui.ctx().egui_wants_keyboard_input() - { + #[cfg(not(target_arch = "wasm32"))] + if crate::updates_ui::blocks_input(app) { return; } - let (enter, back) = ui.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::Enter), i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace))); + + if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || ui.ctx().egui_wants_keyboard_input() { + return; + } + + let (enter, backspace) = + ui.input_mut(|input| (input.consume_key(egui::Modifiers::NONE, egui::Key::Enter), input.consume_key(egui::Modifiers::NONE, egui::Key::Backspace))); if enter { app.run("tool.path", json!({"commit": true})); } - if back { - app.session.tool.path.points.pop(); + if backspace { + app.session.remove_selected_path_point(); } } -/// Path tool input in a view (`uv`: the 2D view). Pressing on a control point drags it, -/// elsewhere adds a point (and drags it); clicking the first point of an open path closes it. -/// `place` maps a pointer position to a path point (None off the surface), `show` a path point -/// to the screen. +/// The selected layer's stored paths except the edited one: (path sublayer, index, path) +fn other_paths(app: &TextureCraftApp) -> Vec<(texturecraft_engine::core::LayerId, usize, texturecraft_engine::PathState)> { + let s = &app.session; + let Some(layer) = s.selected_layer().and_then(|id| s.doc.project.layer(id).ok()) else { return Vec::new() }; + let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|m| m.effects.iter())); + effects + .flat_map(|e| s.stored_path_states(e.id).into_iter().enumerate().map(move |(i, path)| (e.id, i, path))) + .filter(|(e, i, _)| s.tool.path.editing != Some((*e, *i))) + .collect() +} + +/// The screen curve through `points` per segment, each starting on its first point +fn screen_segments(points: &[Pos2], closed: bool) -> Vec> { + let pts: Vec = points.iter().map(|p| Vec2::new(p.x, p.y)).collect(); + texturecraft_engine::paint::spline_segments(&pts, closed, PATH_SCREEN_STEP) + .into_iter() + .zip(points) + .map(|(samples, first)| std::iter::once(*first).chain(samples.into_iter().map(|v| pos2(v.x, v.y))).collect()) + .collect() +} + +/// A path's curve in a view per segment: screen position and whether the mesh leaves it visible (None off the mesh or screen) +type ScreenCurve = Vec>>; + +/// The nearest segment of `curve` within grab distance of `at`, with the nearest position on it +fn segment_near(curve: &ScreenCurve, at: Pos2) -> Option<(usize, Pos2)> { + let nearest = |segment: &Vec>| { + segment.windows(2).filter_map(|w| Some(closest_on_line(w[0]?.0, w[1]?.0, at))).min_by(|a, b| a.distance(at).total_cmp(&b.distance(at))) + }; + curve + .iter() + .enumerate() + .filter_map(|(i, segment)| nearest(segment).map(|p| (i, p))) + .filter(|(_, p)| p.distance(at) < HANDLE_GRAB) + .min_by(|a, b| a.1.distance(at).total_cmp(&b.1.distance(at))) +} + +/// `path`'s curve in a view; a 3D curve lies where its paint lands, and without `depth_test` (hit tests) every sample counts as visible +fn curve_on_screen( + app: &TextureCraftApp, + ui: &Ui, + (rect, uv, depth_test): (Rect, bool, bool), + path: &texturecraft_engine::PathState, + stored: Option<(texturecraft_engine::core::LayerId, usize)>, + show: &impl Fn(&TextureCraftApp, Vec3) -> Option, +) -> ScreenCurve { + if uv { + let Some(points) = path.points.iter().map(|p| show(app, *p)).collect::>>() else { return Vec::new() }; + return screen_segments(&points, path.closed).into_iter().map(|segment| segment.into_iter().map(|at| Some((at, true))).collect()).collect(); + } + let s = &app.session; + let surface = stored + .and_then(|(eid, index)| stored_surface(app, ui, eid, index)) + .unwrap_or_else(|| Arc::new(s.path_surface(&path.points, path.closed, s.camera, s.viewport))); + surface + .iter() + .map(|segment| segment.iter().map(|p| p.and_then(|p| show(app, p).map(|at| (at, !depth_test || path_point_visible(app, rect, p, at))))).collect()) + .collect() +} + +/// Sample the stored curve once while visible, invalidating it when the path or mesh changes +fn stored_surface(app: &TextureCraftApp, ui: &Ui, eid: texturecraft_engine::core::LayerId, index: usize) -> Option { + ui.memory_mut(|memory| memory.caches.cache::().get(&app.session, eid, index)) +} + +/// The point of the segment `a`–`b` nearest to `p` +fn closest_on_line(a: Pos2, b: Pos2, p: Pos2) -> Pos2 { + let ab = b - a; + let t = if ab.length_sq() > 0.0 { ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + a + ab * t +} + +/// What `at` is over in a view (`uv`: the 2D view); `show` maps a path point to the screen +fn path_hit(app: &TextureCraftApp, ui: &Ui, (rect, uv): (Rect, bool), at: Pos2, show: &impl Fn(&TextureCraftApp, Vec3) -> Option) -> PathHit { + let path = &app.session.tool.path; + if path.uv == uv { + if let Some(i) = path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) { + return PathHit::Point(i); + } + if let Some((i, on)) = segment_near(&curve_on_screen(app, ui, (rect, uv, false), path, path.editing, show), at) { + return PathHit::Curve(i, on); + } + } + for (eid, i, other) in other_paths(app) { + if other.uv == uv + && (other.points.iter().any(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) + || segment_near(&curve_on_screen(app, ui, (rect, uv, false), &other, Some((eid, i)), show), at).is_some()) + { + return PathHit::Stored(eid, i); + } + } + PathHit::Miss +} + +/// Path tool presses in a view: select and drag a point, insert on the curve, open another path, close on the first point, or add a point fn path_input( app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, - uv: bool, + (rect, uv): (Rect, bool), place: impl Fn(&TextureCraftApp, Pos2) -> Option, show: impl Fn(&TextureCraftApp, Vec3) -> Option, ) { @@ -728,89 +1287,319 @@ fn path_input( && let Some(at) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()) { let path = &app.session.tool.path; - let near = if path.uv == uv { path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) } else { None }; - match near { - Some(0) if clicked && !path.closed && path.points.len() >= 3 => app.session.tool.path.closed = true, - Some(i) => ui.data_mut(|d| { - d.insert_temp(drag_id, i); - }), - None => match place(app, at) { - Some(p) => { - app.session.tool.path.push(p, uv); - let last = app.session.tool.path.points.len().saturating_sub(1); - ui.data_mut(|d| { - d.insert_temp(drag_id, last); - }); + let (closed, len) = (path.closed, path.points.len()); + let hit = path_hit(app, ui, (rect, uv), at, &show); + + let grab = match hit { + PathHit::Point(0) if clicked && !closed && len >= 3 => { + app.session.set_path_closed(true); + None + } + PathHit::Point(i) => { + app.session.select_path_point(i); + Some(i) + } + PathHit::Stored(eid, index) => { + app.run("path.edit", json!({"effect": eid.0, "index": index})); + None + } + hit => match place(app, if let PathHit::Curve(_, on) = hit { on } else { at }) { + Some(p) => match hit { + PathHit::Curve(i, _) => app.session.insert_path_point(i + 1, p), + _ => app.session.append_path_point(p, uv), + }, + None => { + app.toast(tr("Place path points on the mesh"), false); + None } - None => app.toast(tr("Place path points on the mesh"), false), }, + }; + if let Some(i) = grab { + ui.data_mut(|d| d.insert_temp(drag_id, (i, true))); } } + if resp.dragged_by(PointerButton::Primary) - && let Some(i) = ui.data(|d| d.get_temp::(drag_id)) + && let Some((index, begin_drag)) = ui.data(|data| data.get_temp::<(usize, bool)>(drag_id)) && let Some(p) = resp.interact_pointer_pos().and_then(|pos| place(app, pos)) - && let Some(q) = app.session.tool.path.points.get_mut(i) + && app.session.move_path_point(index, p, begin_drag) { - *q = p; + ui.data_mut(|data| data.insert_temp(drag_id, (index, false))); } + if !resp.is_pointer_button_down_on() { - ui.data_mut(|d| d.remove::(drag_id)); + ui.data_mut(|data| data.remove::<(usize, bool)>(drag_id)); } } -/// The path being edited: its curve, control points (the first one in the accent color) and, -/// while open, a dashed preview of the next segment. +/// Is path point `p` (on screen at `at`) in front of the mesh in the 3D view `rect`? +fn path_point_visible(app: &TextureCraftApp, rect: Rect, p: Vec3, at: Pos2) -> bool { + let eye = app.session.camera.eye(); + let local = Vec2::new(at.x - rect.left(), at.y - rect.top()); + app.session.pick(local, app.session.viewport).is_none_or(|hit| hit.pos.distance(eye) >= p.distance(eye) * (1.0 - PATH_HIDDEN_DEPTH)) +} + +/// Draw `curve` in `color` over a dark outline, as a faint line where the mesh hides it +fn draw_path_curve(painter: &egui::Painter, curve: &ScreenCurve, color: Color32) { + let draw = |run: &mut Vec, shown: bool| { + if run.len() > 1 { + // Hidden parts are a ghost line: no outline, half strength + if shown { + painter.add(egui::Shape::line(run.clone(), Stroke::new(PATH_OUTLINE_WIDTH, Color32::from_black_alpha(140)))); + } + painter.add(egui::Shape::line( + std::mem::take(run), + Stroke::new(PATH_LINE_WIDTH, if shown { color } else { color.gamma_multiply(PATH_HIDDEN_OPACITY) }), + )); + } + run.clear(); + }; + for segment in curve { + // Runs of samples the view shows (or hides) alike, joined at the sample where that changes + let (mut run, mut shown) = (Vec::new(), true); + for sample in segment { + match *sample { + Some((at, visible)) => { + if visible != shown && !run.is_empty() { + run.push(at); + draw(&mut run, shown); + } + shown = visible; + run.push(at); + } + None => draw(&mut run, shown), + } + } + draw(&mut run, shown); + } +} + +/// The layer's other paths (lit under the pointer), then the edited path with its points, the next segment's preview and the pen cursor fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Response, uv: bool, show: impl Fn(&TextureCraftApp, Vec3) -> Option) { let tk = Tokens::get(ui.ctx()); - let p = ui.painter_at(rect); - let path = &app.session.tool.path; - let hint = tr("Path: click adds a point, drag moves it, Enter applies, Esc cancels"); - p.text(rect.left_bottom() + vec2(56.0, -12.0), egui::Align2::LEFT_BOTTOM, hint, egui::FontId::proportional(12.0), tk.viewport_text); - if path.uv != uv { - return; - } - let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); - let pts: Vec = handles.iter().map(|h| Vec2::new(h.x, h.y)).collect(); - let curve: Vec = texturecraft_engine::paint::spline(&pts, path.closed, 3.0).into_iter().map(|v| pos2(v.x, v.y)).collect(); - let color = if path.closed && path.fill { tk.viewport_accent } else { Color32::from_white_alpha(230) }; - p.add(egui::Shape::line(curve.clone(), Stroke::new(3.0, Color32::from_black_alpha(140)))); - p.add(egui::Shape::line(curve, Stroke::new(1.4, color))); + let painter = ui.painter_at(rect); + let hint = tr("Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels"); + // Wrapped to the view: the hint is longer than a narrow split view + let at = rect.left_bottom() + PATH_HINT_OFFSET; + let wrap = (rect.right() - at.x - PATH_HINT_MARGIN).max(PATH_HINT_MIN_WIDTH); + let hint = painter.layout(hint.to_string(), egui::FontId::proportional(PATH_HINT_FONT_SIZE), tk.viewport_text, wrap); + painter.galley(at - vec2(0.0, hint.size().y), hint, tk.viewport_text); + let hover = resp.hover_pos(); - if !path.closed - && let (Some(last), Some(to)) = (handles.last(), hover) + let hit = hover.map(|at| (at, path_hit(app, ui, (rect, uv), at, &show))); + for (eid, i, other) in other_paths(app).iter().filter(|(_, _, other)| other.uv == uv) { + let curve = curve_on_screen(app, ui, (rect, uv, true), other, Some((*eid, *i)), &show); + // The path a click opens lights up + let opened = matches!(hit, Some((_, PathHit::Stored(e, n))) if (e, n) == (*eid, *i)); + draw_path_curve(&painter, &curve, if opened { Color32::WHITE } else { Color32::WHITE.gamma_multiply(PATH_STORED_OPACITY) }); + } + + let path = &app.session.tool.path; + if path.uv == uv { + draw_path_curve(&painter, &curve_on_screen(app, ui, (rect, uv, true), path, path.editing, &show), tk.viewport_accent); + let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); + if !path.closed + && !handles.is_empty() + && let Some((to, PathHit::Miss)) = hit + { + let mut next = handles.clone(); + next.push(to); + if let Some(segment) = screen_segments(&next, false).last() { + rubber_band(ui, rect, segment); + } + } + + for (index, point) in path.points.iter().enumerate() { + let Some(handle) = show(app, *point) else { continue }; + + // Keep the point's original index when earlier points project behind the camera + let hovered = hover.is_some_and(|m| m.distance(handle) < HANDLE_GRAB); + let radius = if hovered { PATH_POINT_RADIUS + PATH_POINT_HOVER_GROWTH } else { PATH_POINT_RADIUS }; + if path.selected == Some(index) { + painter.circle(handle, radius + PATH_POINT_SELECTED_GROWTH, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(160))); + } else { + painter.circle(handle, radius, Color32::from_black_alpha(110), Stroke::new(1.0, Color32::from_white_alpha(if hovered { 230 } else { 150 }))); + } + } + } + + if let Some((at, hit)) = hit + && !ui.input(|i| i.modifiers.command) { - rubber_band(ui, rect, *last, to); - } - for (i, h) in handles.iter().enumerate() { - let r = if hover.is_some_and(|m| m.distance(*h) < HANDLE_GRAB) { 5.5 } else { 4.0 }; - p.circle(*h, r, if i == 0 { tk.viewport_accent } else { Color32::WHITE }, Stroke::new(1.5, Color32::from_black_alpha(180))); + if let PathHit::Curve(_, on) = hit { + // Where the click inserts its point + painter.circle(on, PATH_POINT_RADIUS, Color32::from_black_alpha(60), Stroke::new(1.0, Color32::from_white_alpha(110))); + } + path_cursor(ui, &painter, at, matches!(hit, PathHit::Curve(..))); } } -/// Dashed preview of a straight segment. -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)); +/// The Path tool's pointer: a pen with its nib at `at`, and a plus when a click inserts a point +fn path_cursor(ui: &Ui, painter: &egui::Painter, at: Pos2, insert: bool) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + let glyph = |icon: &str, size: f32, color: Color32| painter.layout_no_wrap(icon.to_string(), egui::FontId::proportional(size), color); + for (offset, color) in [(PATH_CURSOR_SHADOW_OFFSET, Color32::from_black_alpha(200)), (egui::Vec2::ZERO, Color32::WHITE)] { + // The pen's nib is the bottom left corner of the drawn glyph + let pen = glyph(egui_phosphor::regular::PEN_NIB, PATH_CURSOR_SIZE, color); + let origin = at + offset - pen.mesh_bounds.left_bottom().to_vec2(); + let right = origin + pen.mesh_bounds.right_bottom().to_vec2(); + painter.galley(origin, pen, color); + if insert { + let plus = glyph(egui_phosphor::regular::PLUS, PATH_CURSOR_SIZE * PATH_CURSOR_PLUS_SCALE, color); + painter.galley(right + vec2(PATH_CURSOR_PLUS_GAP, 0.0) - plus.mesh_bounds.left_top().to_vec2(), plus, color); + } + } } -/// V held with the Clone tool in painting mode: clicks set the clone source. +/// Dashed curve preview clipped segment by segment to bound offscreen dash allocation +fn rubber_band(ui: &Ui, rect: Rect, line: &[Pos2]) { + let painter = ui.painter_at(rect); + let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + let mut distance = 0.0; + for pair in line.windows(2) { + if let Some(visible) = visible_dashes(rect, pair[0], pair[1]) { + // Continue the dash pattern across sampled curve segments and clipped portions + let phase = (distance + pair[0].distance(visible[0])) % period; + for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { + // Draw any dash already in progress without extending behind this curve segment + if phase > 0.0 && phase < RUBBER_BAND_DASH { + let direction = visible[1] - visible[0]; + let end = visible[0] + direction.normalized() * (RUBBER_BAND_DASH - phase).min(direction.length()); + painter.line_segment([visible[0], end], stroke); + } + let offset = if phase == 0.0 { 0.0 } else { period - phase }; + painter.add(egui::Shape::dashed_line_with_offset(&visible, stroke, &[RUBBER_BAND_DASH], &[RUBBER_BAND_GAP], offset)); + } + } + distance = (distance + pair[0].distance(pair[1])) % period; + } +} + +/// 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 fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { - app.ui.mode == crate::state::Mode::Painting - && app.session.tool.tool == Tool::Clone - && ui.input(|i| i.key_down(egui::Key::V)) - && !ui.ctx().egui_wants_keyboard_input() + tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(egui::Key::V)) && !ui.ctx().egui_wants_keyboard_input() } /// Crosshair where the Clone tool reads from. fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { - let tk = Tokens::get(ui.ctx()); - let Some(c) = project(app, rect, pos) else { return }; - let p = ui.painter_at(rect); - for (w, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, tk.viewport_accent)] { - p.circle_stroke(c, 7.0, Stroke::new(w, color)); - p.line_segment([c - vec2(11.0, 0.0), c + vec2(11.0, 0.0)], Stroke::new(w, color)); - p.line_segment([c - vec2(0.0, 11.0), c + vec2(0.0, 11.0)], Stroke::new(w, color)); + let tokens = Tokens::get(ui.ctx()); + let Some(center) = project(app, rect, pos) else { return }; + + let painter = ui.painter_at(rect); + for (stroke_width, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, tokens.viewport_accent)] { + painter.circle_stroke(center, 7.0, Stroke::new(stroke_width, color)); + painter.line_segment([center - vec2(11.0, 0.0), center + vec2(11.0, 0.0)], Stroke::new(stroke_width, color)); + painter.line_segment([center - vec2(0.0, 11.0), center + vec2(0.0, 11.0)], Stroke::new(stroke_width, color)); + } +} + +/// Whether the active tool can act on the selection now: a greyed tool ignores clicks, keys and drags in the views +fn tool_acts(app: &TextureCraftApp) -> bool { + app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool) +} + +/// Both views must close gestures even when the selection disables their input handlers. +fn finish_unavailable_tool_gestures(app: &mut TextureCraftApp, pending_2d_endpoint: Option) { + if !tool_acts(app) { + if app.session.stroke_active() { + match app.session.end_stroke() { + Ok(()) => { + if let Some(endpoint) = pending_2d_endpoint { + app.last_paint_uv = Some(endpoint); + } + } + Err(error) => app.toast(error.to_string(), true), + } + } + app.session.end_polygon_fill_box(); } } @@ -819,15 +1608,13 @@ fn brush_tool(t: Tool) -> bool { matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) } -/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a -/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True -/// while Ctrl is held with a brush tool and no stroke is under way. -fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool { - let held = - app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command); - if held && let Some(right) = brush_drag_button(resp) { - adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta())); +/// Ctrl (Cmd on macOS) + drag changes the brush instead of painting: true while it applies (see `adjust_brush`) +fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) -> bool { + let held = tool_acts(app) && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|input| input.modifiers.command); + if held && let Some(right) = brush_drag_button(response) { + adjust_brush(&mut app.session.tool.brush, right, ui.input(|input| input.pointer.delta())); } + held } @@ -839,66 +1626,82 @@ fn brush_drag_button(resp: &egui::Response) -> Option { /// While a Ctrl+drag changes the brush, its values beside where the drag began (drawn over the /// view; the tool bar and Properties show them too). -fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjusting: bool) { - let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return }; - let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return }; - // The pointer would cover the values; the brush cursor stays where the drag began. - ui.ctx().set_cursor_icon(egui::CursorIcon::None); - let b = &app.session.tool.brush; - let text = if right { - format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0) +fn brush_readout(app: &TextureCraftApp, ui: &Ui, response: &egui::Response, adjusting: bool) { + let Some(right_drag) = brush_drag_button(response).filter(|_| adjusting) else { return }; + let Some(press_origin) = ui.input(|input| input.pointer.press_origin()) else { return }; + + // Keep the values clear of the pointer and the brush cursor at its press origin + if ui.input(|input| input.pointer.latest_pos()).is_some_and(|pointer| response.rect.contains(pointer)) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } + + let brush = &app.session.tool.brush; + let text = if right_drag { + format!("{} {:.1} {} {:.0}", tr("Size"), brush.size / 0.25 * 100.0, tr("Hardness"), brush.hardness * 100.0) } else { - format!("{} {:.0} {} {:.0}°", tr("Flow"), b.flow * 100.0, tr("Angle"), b.angle) + format!("{} {:.0} {} {:.0}°", tr("Flow"), brush.flow * 100.0, tr("Angle"), brush.angle) }; - let tk = Tokens::get(ui.ctx()); - let p = ui.painter_at(resp.rect); - let g = p.layout_no_wrap(text, egui::FontId::proportional(12.0), tk.text_strong); - let r = Rect::from_min_size(at + vec2(18.0, -30.0), g.size()).expand2(vec2(6.0, 3.0)); - p.rect_filled(r, 3.0, tk.panel); - p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong); + + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(response.rect); + let galley = painter.layout_no_wrap(text, egui::FontId::proportional(12.0), tokens.text_strong); + let readout_rect = Rect::from_min_size(press_origin + vec2(18.0, -30.0), galley.size()).expand2(vec2(6.0, 3.0)); + painter.rect_filled(readout_rect, 3.0, tokens.panel); + painter.galley(readout_rect.min + vec2(6.0, 3.0), galley, tokens.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; } } -fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) { - let (lo, hi) = app.session.mesh.bounds(); - let r = app.session.tool.brush.size * (hi - lo).length(); - let t = nrm.any_orthonormal_vector(); - let b = nrm.cross(t); - let to_screen = |p: Vec3| project(app, rect, p); - let mut pts = Vec::with_capacity(49); - for k in 0..=48 { - let a = k as f32 / 48.0 * std::f32::consts::TAU; - if let Some(s) = to_screen(pos + (t * a.cos() + b * a.sin()) * r) { - pts.push(s); +pub(crate) fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, position: Vec3, normal: Vec3, radius: f32) { + const CIRCLE_SEGMENTS: usize = 48; + + let tangent = normal.any_orthonormal_vector(); + let bitangent = normal.cross(tangent); + let to_screen = |point: Vec3| project(app, rect, point); + let mut outline = Vec::with_capacity(CIRCLE_SEGMENTS + 1); + for segment in 0..=CIRCLE_SEGMENTS { + let angle = segment as f32 / CIRCLE_SEGMENTS as f32 * std::f32::consts::TAU; + if let Some(screen) = to_screen(position + (tangent * angle.cos() + bitangent * angle.sin()) * radius) { + outline.push(screen); } } - let p = ui.painter_at(rect); - p.add(egui::Shape::line(pts.clone(), Stroke::new(2.5, Color32::from_black_alpha(140)))); - p.add(egui::Shape::line(pts, Stroke::new(1.2, Color32::from_white_alpha(230)))); - let h = app.session.tool.brush.hardness; - if h > 0.05 { + + let painter = ui.painter_at(rect); + painter.add(egui::Shape::line(outline.clone(), Stroke::new(2.5, Color32::from_black_alpha(140)))); + painter.add(egui::Shape::line(outline, Stroke::new(1.2, Color32::from_white_alpha(230)))); + + let hardness = app.session.tool.brush.hardness; + if hardness > 0.05 { let mut inner = Vec::new(); - for k in 0..=48 { - let a = k as f32 / 48.0 * std::f32::consts::TAU; - if let Some(s) = to_screen(pos + (t * a.cos() + b * a.sin()) * r * h) { - inner.push(s); + for segment in 0..=CIRCLE_SEGMENTS { + let angle = segment as f32 / CIRCLE_SEGMENTS as f32 * std::f32::consts::TAU; + if let Some(screen) = to_screen(position + (tangent * angle.cos() + bitangent * angle.sin()) * radius * hardness) { + inner.push(screen); } } - p.add(egui::Shape::dashed_line(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); + painter.add(egui::Shape::dashed_line(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); } - if let Some(c) = to_screen(pos) { - p.circle_filled(c, 1.5, Color32::WHITE); + + if let Some(center) = to_screen(position) { + painter.circle_filled(center, 1.5, Color32::WHITE); } } @@ -920,9 +1723,9 @@ fn pen_pressure(ui: &Ui) -> f32 { ui.data_mut(|d| d.insert_temp(id, f)); f } - // A pen lifts with no pressure, and a tap paints on that frame: keep its contact pressure. + // A pen lifts with no pressure, so keep its contact pressure for a tap Some((egui::TouchPhase::End, None)) => ui.data(|d| d.get_temp(id)).unwrap_or(1.0), - // A touch without pressure (a finger) must not inherit an earlier pen's. + // A finger must not inherit an earlier pen's pressure Some((egui::TouchPhase::Start, None)) => { ui.data_mut(|d| d.remove_temp::(id)); 1.0 @@ -931,143 +1734,280 @@ 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; } } - 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())); + + // Conversions between the view's points and the texture set's UV space + let texture_set_index = app.session.ts(); + let set = app.session.doc.project.texture_sets.get(texture_set_index); + 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 skew_on = app.ui.mode == crate::state::Mode::Baking && app.ui.skew_brush.on && !alt; - if skew_on { - skew_input(app, ui, &resp, &to_uv); + + 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, &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 = tool_acts(app) + && app.properties_popup.is_none() + && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) + && !alt + && !adjusting + && !v_held + && !picking_id_color + && !DecalDrop::blocks_input(ui.ctx()); + 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, (rect, 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], - kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, + size: frame_size_in_pixels(ui, rect), + kind: ViewKind::Uv { ts: texture_set_index, 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(), + overlay: Vec::new(), }; 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 set = app.session.doc.project.texture_sets.get(texture_set_index); + let outline = |tile: Rect| { + painter.rect_stroke(tile, 0.0, Stroke::new(UV_TILE_OUTLINE_WIDTH, 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() + UV_TILE_LABEL_OFFSET, + egui::Align2::LEFT_TOP, + udim.to_string(), + egui::FontId::proportional(UV_TILE_LABEL_SIZE), + 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); + if tool_acts(app) && path_tool { + 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 { - skew_overlay(app, ui, &painter, to(0.0, 1.0), to(1.0, 0.0)); - if skew_on && let Some(hover) = resp.hover_pos() { - let r = (to(app.ui.skew_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(BAKE_PAINT_CURSOR_STROKE, Color32::from_white_alpha(BAKE_PAINT_CURSOR_ALPHA))); } } - brush_readout(app, ui, &resp, adjusting); + + // Match the 3D view's stamp size and hardness + let show_brush_cursor = tool_acts(app) && !alt && !v_held; + let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)); + if show_brush_cursor + && !path_tool + && brush_tool(app.session.tool.tool) + && !response.dragged_by(PointerButton::Middle) + // Egui keeps hover during drags; adjustment may continue outside the view + && (adjusting || pointer_in_view) + // Keep the brush outline at the press origin while adjusting + && let Some(cursor_center) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } + // Header pickers need the normal pointer + && !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(cursor_center)) + { + // Match the pressure-scaled radius used by continue_stroke_uv + let radius_points = + (to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(BRUSH_CURSOR_MIN_RADIUS_POINTS); + if pointer_in_view { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } + brush_cursor_2d(&painter, cursor_center, radius_points, app.session.tool.brush.hardness); + } + 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(texture_set_index).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); + let name_position = rect.right_bottom() - SET_NAME_INSET; + ui.painter().text(name_position, egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(SET_NAME_TEXT_SIZE), tokens.viewport_text); +} + +/// Smallest visible 2D brush outline, in points +const BRUSH_CURSOR_MIN_RADIUS_POINTS: f32 = 1.5; + +/// Hardness ring segments, balancing smoothness and per-frame shape work +const BRUSH_CURSOR_RING_SEGMENTS: usize = 48; + +/// Smaller hardness rings overlap the center dot +const BRUSH_CURSOR_MIN_RING_HARDNESS: f32 = 0.05; + +/// The brush outline and hardness ring around `center`, with `radius_points` in screen points +fn brush_cursor_2d(painter: &egui::Painter, center: egui::Pos2, radius_points: f32, hardness: f32) { + painter.circle_stroke(center, radius_points, Stroke::new(2.5, Color32::from_black_alpha(140))); + painter.circle_stroke(center, radius_points, Stroke::new(1.2, Color32::from_white_alpha(230))); + if hardness > BRUSH_CURSOR_MIN_RING_HARDNESS { + let inner_ring: Vec = (0..=BRUSH_CURSOR_RING_SEGMENTS) + .map(|point_index| { + let angle = point_index as f32 / BRUSH_CURSOR_RING_SEGMENTS as f32 * std::f32::consts::TAU; + center + vec2(angle.cos(), angle.sin()) * radius_points * hardness + }) + .collect(); + painter.add(egui::Shape::dashed_line(&inner_ring, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); + } + painter.circle_filled(center, 1.5, Color32::WHITE); +} + +/// 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_mut(|data| { + let endpoint = data.get_temp(stroke_end); + data.remove::(stroke_end); + endpoint + }); + } + 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). -fn skew_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { - let last = ui.scope_id().with("skew_last"); - let brush = app.ui.skew_brush; +fn bake_paint_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { + let last = ui.scope_id().with(("bake_paint_last", app.session.ts(), app.ui.bake_paint_brush.target as u8)); + let brush = app.ui.bake_paint_brush; let started = resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary); if !(started || resp.dragged_by(PointerButton::Primary)) { return; @@ -1076,16 +2016,20 @@ fn skew_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: let uv = to_uv(p); let previous: Option<[f32; 2]> = if started { None } else { ui.data(|d| d.get_temp(last)) }; let points: Vec<[f32; 2]> = previous.into_iter().chain([[uv.x, uv.y]]).collect(); - if app.run("bake.skew.paint", json!({"points": points, "radius": brush.radius, "value": brush.value, "hardness": brush.hardness})).is_some() { + let command = match brush.target { + texturecraft_engine::core::BakePaintTarget::Skew => "bake.skew.paint", + texturecraft_engine::core::BakePaintTarget::Cage => "bake.cage.paint", + }; + if app.run(command, json!({"points": points, "radius": brush.radius, "value": brush.value, "hardness": brush.hardness, "continue": !started})).is_some() { ui.data_mut(|d| d.insert_temp(last, [uv.x, uv.y])); } } /// The skew map as a translucent orange layer over the UV square from `top_left` to `bottom_right`. -fn skew_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, top_left: egui::Pos2, bottom_right: egui::Pos2) { - let Some(k) = app.session.bake_meshes.skew.as_ref().filter(|k| k.values.len() > 1) else { return }; - let key = (app.session.bake_meshes.skew_rev, std::sync::Arc::as_ptr(k) as usize); - let id = ui.scope_id().with("skew_overlay_texture"); +fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, top_left: egui::Pos2, bottom_right: egui::Pos2) { + let Some(k) = app.session.doc.bake_paint.get(&(app.session.ts(), app.ui.bake_paint_brush.target)).filter(|k| k.values.len() > 1) else { return }; + let key = (app.session.revision, std::sync::Arc::as_ptr(k) as usize); + let id = ui.scope_id().with("bake_paint_overlay_texture"); let cached: Option<((u64, usize), egui::TextureHandle)> = ui.data(|d| d.get_temp(id)); let tex = match cached { Some((c, t)) if c == key => t, @@ -1097,13 +2041,284 @@ fn skew_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, top_lef for y in 0..oh { for x in 0..ow { let v = k.values.get((y * h / oh) * w + x * w / ow).copied().unwrap_or(0.0).clamp(0.0, 1.0); + let v = match app.ui.bake_paint_brush.target { + texturecraft_engine::core::BakePaintTarget::Skew => v, + texturecraft_engine::core::BakePaintTarget::Cage => 1.0 - v, + }; rgba.extend_from_slice(&[255, 140, 40, (v * 170.0) as u8]); } } - let tex = ui.ctx().load_texture("skew_overlay", egui::ColorImage::from_rgba_unmultiplied([ow, oh], &rgba), egui::TextureOptions::NEAREST); + let tex = ui.ctx().load_texture("bake_paint_overlay", egui::ColorImage::from_rgba_unmultiplied([ow, oh], &rgba), egui::TextureOptions::NEAREST); ui.data_mut(|d| d.insert_temp(id, (key, tex.clone()))); tex } }; 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::*; + + #[test] + fn unavailable_tools_finish_strokes_and_box_fills() { + use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives}; + + for tool in [Tool::Paint, Tool::PolygonFill] { + let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.session.tool.tool = tool; + let history = app.session.history_labels().len(); + if tool == Tool::Paint { + app.session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + assert!(app.session.stroke_active()); + } else { + assert!(app.session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0); + } + app.session.target = StackTarget::Effect(LayerId(u64::MAX)); + assert!(!tool_acts(app)); + finish_unavailable_tool_gestures(app, None); + assert!(!app.session.stroke_active()); + assert_eq!(app.session.history_labels().len(), history + 1); + assert_eq!(app.session.end_polygon_fill_box(), 0, "the interrupted box is already closed"); + finish_unavailable_tool_gestures(app, None); + assert_eq!(app.session.history_labels().len(), history + 1, "cleanup records the gesture only once"); + } + } + + #[test] + fn stored_surfaces_release_after_a_frame_without_paths() { + use texturecraft_engine::{core::EffectKind, execute, geom::primitives}; + + let mut session = Session::new_project("Path cache", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + session.viewport = Vec2::splat(400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + let result = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(result["committed"]["effect"].as_u64().unwrap()); + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") }; + paths.resize(8, paths[0].clone()); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let context = egui::Context::default(); + let mut previous = Vec::>>>>::new(); + + // Every path in the selection stays warm, and leaving it releases every sampled buffer + for _ in 0..4 { + let output = context.run_ui(Default::default(), |ui| { + for index in 0..8 { + let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); + assert!(surface.iter().map(Vec::len).sum::() > 10); + if let Some(cached) = previous.get(index) { + assert!(Arc::ptr_eq(&cached.upgrade().unwrap(), &surface), "unchanged paths must not be resampled"); + } else { + previous.push(Arc::downgrade(&surface)); + } + } + }); + + // This cache lifecycle test has no renderer to consume texture updates + output.drop_without_applying_deltas(); + } + + let EffectKind::Path(paths) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") }; + for path in paths { + path.viewport = [800.0, 800.0]; + } + let output = context.run_ui(Default::default(), |ui| { + for (index, previous) in previous.iter_mut().enumerate() { + let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); + assert!(previous.upgrade().is_none(), "editing a path releases its obsolete samples"); + *previous = Arc::downgrade(&surface); + } + }); + output.drop_without_applying_deltas(); + + for _ in 0..2 { + context.run_pass(Default::default(), |_| {}).drop_without_applying_deltas(); + } + + assert!(previous.iter().all(|surface| surface.upgrade().is_none()), "unused path surfaces must be freed while the window stays open"); + } + + /// A selected mask decal on the ball, with another texture set available for selection tests + fn decal_frame_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> { + let session = + Session::new_project("Decal selection", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = harness.state_mut().session.import_resource_bytes("decal.png", png).unwrap(); + harness.state_mut().run("layer.add.decal", json!({"image": image, "channel": "mask", "size": 0.5})).unwrap(); + harness.run_steps(2); + assert_eq!(harness.state().session.ts(), 0); + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + harness + } + + /// Move a primary-button drag through enough frames to reach the viewport's decal handles + fn drag_decal_handle(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.hover_at(from); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from.lerp(to, step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + } + + #[test] + fn decal_frame_rejects_a_stale_effect_after_failed_layer_selection() { + use texturecraft_engine::{StackTarget, execute}; + + for texture_set in [0, 1] { + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + execute(session, "textureSet.select", &json!({"ts": texture_set})).unwrap(); + let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + + let selected = execute(session, "layer.select", &json!({"layer": other, "target": effect.0})); + + assert!(selected.is_err()); + assert_eq!(session.ts(), texture_set); + assert_eq!(session.selected_layer().unwrap().0, other.as_u64().unwrap()); + assert_eq!(session.target, StackTarget::Effect(effect), "the failed selection leaves the previous effect target"); + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "a stale effect must not show a decal frame"); + + drag_decal_handle(&mut harness, original.corners[1], original.center + (original.corners[1] - original.center) * 1.5); + drag_decal_handle(&mut harness, original.knob, original.knob + vec2(40.0, 0.0)); + + let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind; + assert!( + matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Decal(decal), .. } if *decal == original.decal) + ); + } + } + + #[test] + fn decal_frame_keeps_an_instances_inherited_mask_effect_editable() { + use texturecraft_engine::execute; + + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + + // The source effect remains a valid inherited target when selection changes to its instance + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + + assert_eq!(session.ts(), 1); + assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); + let inherited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal)); + + drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5); + + let edited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source"); + } + + #[test] + fn decal_frame_rejects_a_source_mask_overridden_by_the_selected_instance() { + use texturecraft_engine::execute; + + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + execute(session, "mask.add.black", &json!({"layer": instance})).unwrap(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "an override hides the source's mask decal"); + } + + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn decal_frame_selection_snapshots() { + use texturecraft_engine::execute; + + 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 mut harness = decal_frame_app(true); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + harness.run_steps(6); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap(); + + let session = &mut harness.state_mut().session; + let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err()); + harness.run_steps(6); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none()); + harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap(); + } + + #[test] + fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.ui.mode = crate::state::Mode::Baking; + let before = bake_visualization(app).unwrap(); + assert!(before.high_poly.shown && before.cage_shown()); + + app.start_bake(vec![0]); + + assert!(bake_visualization(app).is_none(), "setup overlays must not obscure the finished map"); + for show in [texturecraft_engine::PreviewShow::Pin(BakedMap::Normal), texturecraft_engine::PreviewShow::Material] { + app.session.bake_preview_show(show).unwrap(); + assert!(bake_visualization(app).is_none()); + } + + app.cancel_bake(); + + assert_eq!(bake_visualization(app), Some(before)); + } + + 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 5e000fa8..bdf0bb7a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -4,6 +4,7 @@ use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle}; use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2}; +use crate::i18n::tr; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -29,35 +30,46 @@ pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::R } fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { - let tk = Tokens::get(ui.ctx()); - let (lo, hi) = (*range.start(), *range.end()); - let w = ui.available_width(); + let tokens = Tokens::get(ui.ctx()); + let (minimum, maximum) = (*range.start(), *range.end()); + let width = ui.available_width(); + let font = egui::TextStyle::Body.resolve(ui.style()); + let value_width = [minimum, maximum] + .into_iter() + .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) + .fold(44.0, f32::max); let mut edit = None; let field = ui .horizontal(|ui| { - ui.label(RichText::new(label).color(tk.text)); + ui.label(RichText::new(label).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - let shown = format!("{:.*}", decimals, value); - // What is typed lives here while the field has focus (`value` is re-read every frame). - let mut text = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| shown.clone()); - let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE)); - if r.has_focus() { - ui.data_mut(|d| d.insert_temp(id, text.clone())); + let shown = format!("{value:.decimals$}"); + // Keep unfinished input while the document value is re-read each frame + let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); + let response = ui.add( + egui::TextEdit::singleline(&mut text) + .id(id) + .font(font) + .desired_width(value_width) + .align(egui::Align2::RIGHT_CENTER) + .frame(egui::Frame::NONE), + ); + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(id, text.clone())); } else { - ui.data_mut(|d| d.remove_temp::(id)); - // Escape unfocuses the field before the app's shortcuts may consume the key, so - // look at the raw input. - let escape = ui.input(|i| i.raw.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); - // Leaving the field unchanged (or with Escape) keeps the value as it is. - if r.lost_focus() + ui.data_mut(|data| data.remove_temp::(id)); + // Escape can lose focus before the app consumes the key + let escape = + ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if response.lost_focus() && !escape && text != shown - && let Ok(v) = text.trim().parse::() - && v.is_finite() - && v.clamp(lo, hi) != *value + && let Ok(parsed) = text.trim().parse::() + && parsed.is_finite() + && parsed.clamp(minimum, maximum) != *value { - *value = v.clamp(lo, hi); + *value = parsed.clamp(minimum, maximum); edit = Some(false); } } @@ -66,34 +78,33 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang .inner }) .inner; - let (rect, mut resp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); - if resp.is_pointer_button_down_on() { - // Using the track drops what was typed in the field (a drag does not take its focus). - ui.data_mut(|d| d.remove_temp::(field)); - ui.memory_mut(|m| m.surrender_focus(field)); + let (rect, mut response) = ui.allocate_exact_size(vec2(width, 14.0), Sense::click_and_drag()); + if response.is_pointer_button_down_on() { + ui.data_mut(|data| data.remove_temp::(field)); + ui.memory_mut(|memory| memory.surrender_focus(field)); } if edit.is_some() { - // A typed value is a change for `slider`'s callers too. - resp.mark_changed(); + response.mark_changed(); } - if (resp.dragged() || resp.clicked()) - && let Some(p) = resp.interact_pointer_pos() + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() { - let t = ((p.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); - let v = lo + (hi - lo) * t; - if (v - *value).abs() > f32::EPSILON { - *value = v; - resp.mark_changed(); - // Whether this drag already applied a value (cleared when it ends). - edit = Some(ui.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::(resp.id), true))); + let fraction = ((pointer.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); + let next = minimum + (maximum - minimum) * fraction; + if (next - *value).abs() > f32::EPSILON { + *value = next; + response.mark_changed(); + // Later frames of one drag share its undo step + edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); } } - if resp.drag_stopped() || resp.clicked() { - ui.data_mut(|d| d.remove_temp::(resp.id)); + if response.drag_stopped() || response.clicked() { + ui.data_mut(|data| data.remove_temp::(response.id)); } - let t = if hi > lo { ((*value - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 }; - track(ui, &resp, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, t, 2.0, 4.5); - (resp, edit) + + let fraction = if maximum > minimum { ((*value - minimum) / (maximum - minimum)).clamp(0.0, 1.0) } else { 0.0 }; + track(ui, &response, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, fraction, 2.0, 4.5); + (response, edit) } /// A small inline slider for the top tool bar: "Label value" above a short track. @@ -132,31 +143,6 @@ fn track(ui: &Ui, resp: &Response, x: std::ops::RangeInclusive, y: f32, t: p.circle(egui::pos2(xk, y), knob, tk.panel, Stroke::new(1.5, ring)); } -/// A histogram of `counts` (buckets over 0..1, scaled to the fullest) in a field-colored well -/// the width of the panel, the part of 0..1 outside `range` dimmed. -pub fn histogram(ui: &mut Ui, counts: &[u32], range: (f32, f32)) -> Response { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover()); - let p = ui.painter_at(rect); - p.rect(rect, CornerRadius::same(tk.radius), tk.field, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let inner = rect.shrink(3.0); - let max = counts.iter().copied().max().unwrap_or(0).max(1) as f32; - let w = inner.width() / counts.len().max(1) as f32; - for (i, c) in counts.iter().enumerate() { - let h = inner.height() * *c as f32 / max; - let x = inner.left() + i as f32 * w; - p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, inner.bottom() - h), egui::pos2(x + w, inner.bottom())), 0.0, tk.text_dim); - } - let x = |t: f32| inner.left() + inner.width() * t.clamp(0.0, 1.0); - let shade = tk.field.gamma_multiply(0.7); - p.rect_filled(egui::Rect::from_x_y_ranges(inner.left()..=x(range.0), inner.y_range()), 0.0, shade); - p.rect_filled(egui::Rect::from_x_y_ranges(x(range.1)..=inner.right(), inner.y_range()), 0.0, shade); - for t in [range.0, range.1] { - p.line_segment([egui::pos2(x(t), inner.top()), egui::pos2(x(t), inner.bottom())], Stroke::new(1.0, tk.accent)); - } - resp -} - /// One line of `text` cut with "…" to fit `max_width`, for list rows that shrink with their panel. pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color: Color32, max_width: f32) -> std::sync::Arc { let mut job = egui::text::LayoutJob::simple_singleline(text.into(), egui::FontId::proportional(size), color); @@ -164,25 +150,82 @@ 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; + +/// Caret glyph size, and how far its center sits from the right edge, as fractions of the button height +const CARET_SCALE: f32 = 0.34; +const CARET_INSET_SCALE: f32 = 0.25; + +/// 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 { + 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); + }) +} + +/// An `icon_dropdown_button` whose icon carries a small `badge` glyph at its lower right (e.g. a gear for a feature's settings) +pub fn icon_badge_dropdown_button(ui: &mut Ui, icon: &str, badge: &str, label: &str, selected: bool, size: f32) -> Response { + // Badge glyph size and inset, as fractions of the height + const BADGE_SCALE: f32 = 0.5; + const BADGE_INSET_SCALE: f32 = 0.24; + // The icon shrinks a little and moves up and left, making room for the badge + const ICON_WITH_BADGE_SCALE: f32 = 0.78; + const ICON_SHIFT_SCALE: f32 = 0.09; + + 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 badge_center = rect.left_top() + vec2(size - size * BADGE_INSET_SCALE, size - size * BADGE_INSET_SCALE); + let caret_center = rect.right_center() - vec2(size * CARET_INSET_SCALE, 0.0); + ui.painter().text( + icon_center - vec2(size, size) * ICON_SHIFT_SCALE, + egui::Align2::CENTER_CENTER, + icon, + egui::FontId::proportional(size * ICON_SCALE * ICON_WITH_BADGE_SCALE), + color, + ); + ui.painter().text(badge_center, egui::Align2::CENTER_CENTER, badge, egui::FontId::proportional(size * BADGE_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). @@ -207,26 +250,115 @@ pub fn combo(ui: &mut Ui, label: &str, selected: impl Into, me .inner } -/// A collapsible section header with a chevron ("> Size"). +pub(crate) fn section_chevron(ui: &Ui, is_open: bool) -> RichText { + let chevron = if is_open { + egui_phosphor::regular::CARET_DOWN + } else if ui.style().right_to_left { + egui_phosphor::regular::CARET_LEFT + } else { + egui_phosphor::regular::CARET_RIGHT + }; + RichText::new(chevron).size(10.0).color(Tokens::get(ui.ctx()).text_dim) +} + +/// A collapsible section header with a chevron pub fn section(ui: &mut Ui, id: &str, title: &str, default_open: bool, body: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); + collapsible_section(ui, id, title, default_open, None, body); +} + +/// A [`section`] whose header ends in a reset icon, inert while `at_default`; true when clicked +pub fn section_with_reset(ui: &mut Ui, id: &str, title: &str, default_open: bool, at_default: bool, body: impl FnOnce(&mut Ui)) -> bool { + collapsible_section(ui, id, title, default_open, Some(at_default), body) +} + +/// Glyph size of a section header's reset icon +const SECTION_RESET_ICON_SIZE: f32 = 14.0; + +/// How much of `text_dim` the reset icon keeps while its section is at its defaults +const SECTION_RESET_AT_DEFAULT_OPACITY: f32 = 0.4; + +/// Gap between the reset icon's glyph and its keyboard focus outline +const SECTION_RESET_FOCUS_MARGIN: f32 = 2.0; + +/// Corner radius of the reset icon's keyboard focus outline +const SECTION_RESET_FOCUS_CORNER_RADIUS: u8 = 3; + +/// The header row and body of [`section`]; `reset_at_default` adds the reset icon +fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, reset_at_default: Option, body: impl FnOnce(&mut Ui)) -> bool { + let tokens = Tokens::get(ui.ctx()); let id = ui.make_persistent_id(id); - let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); - let open = state.is_open(); - let resp = ui - .horizontal(|ui| { - let chev = if open { egui_phosphor::regular::CARET_DOWN } else { egui_phosphor::regular::CARET_RIGHT }; - ui.label(RichText::new(chev).size(10.0).color(tk.text_dim)); - ui.label(RichText::new(title).strong().color(tk.text_strong)); - }) - .response - .interact(Sense::click()); - if resp.clicked() { - state.toggle(ui); + let mut collapsing_state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); + + // Register focus from creation so the next frame does not clear the header's focus + let mut header_builder = egui::UiBuilder::new().id_salt(id.with("header")).sense(Sense::click()); + if reset_at_default.is_some() { + // Earlier controls can widen the content beyond the UI's original visible bounds + let visible_bounds = ui.stack().max_rect.intersect(ui.clip_rect()); + let mut header_bounds = ui.available_rect_before_wrap(); + header_bounds.min.x = header_bounds.min.x.max(visible_bounds.min.x); + header_bounds.max.x = header_bounds.max.x.min(visible_bounds.max.x).max(header_bounds.min.x); + header_builder = header_builder.max_rect(header_bounds); } - state.show_body_unindented(ui, |ui| { + + let mut reset_rect = None; + let header = ui.scope_builder(header_builder, |ui| { + ui.horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, collapsing_state.is_open())).selectable(false)); + let title = egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false); + if reset_at_default.is_some() { + let icon_size = vec2(SECTION_RESET_ICON_SIZE, SECTION_RESET_ICON_SIZE); + let title_width = (ui.available_width() - icon_size.x - ui.spacing().item_spacing.x).max(0.0); + + // Long titles must not extend into the reset target in narrow panels + ui.allocate_ui_with_layout(vec2(title_width, icon_size.y), *ui.layout(), |ui| { + ui.set_width(title_width); + ui.add(title.truncate()); + }); + reset_rect = Some(ui.allocate_exact_size(icon_size, Sense::hover()).0); + } else { + ui.add(title); + } + }); + }); + if header.response.clicked() { + collapsing_state.toggle(ui); + } + + // Registered after the header so the icon, not the header, takes its clicks + let mut reset_clicked = false; + if let (Some(at_default), Some(rect)) = (reset_at_default, reset_rect) { + // At the defaults the icon is inert, so Tab skips it + let sense = if at_default { Sense::CLICK } else { Sense::click() }; + let response = ui.interact(rect, id.with("reset"), sense).on_hover_text(tr("Reset to defaults")); + + // A focused reset must identify its section without relying on nearby visual text + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !at_default, format_args!("{title}: {}", tr("Reset to defaults")))); + + let focused = response.has_focus(); + let color = if at_default { + tokens.text_dim.gamma_multiply(SECTION_RESET_AT_DEFAULT_OPACITY) + } else if response.hovered() || focused { + tokens.text_strong + } else { + tokens.text_dim + }; + let font = egui::FontId::proportional(SECTION_RESET_ICON_SIZE); + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, egui_phosphor::regular::CLOCK_COUNTER_CLOCKWISE, font, color); + + // Enter or Space on the focused icon resets, so keyboard focus needs an outline + if focused { + let outline = rect.expand(SECTION_RESET_FOCUS_MARGIN); + ui.painter().rect_stroke(outline, CornerRadius::same(SECTION_RESET_FOCUS_CORNER_RADIUS), ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } + + reset_clicked = response.clicked() && !at_default; + } + + collapsing_state.show_body_unindented(ui, |ui| { ui.indent(id.with("in"), body); }); + + reset_clicked } /// A channel chip ("color", "metal", "rough"…): toggled = the accent-tinted well. diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8ecab281..8d573899 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,21 +1,22 @@ -//! Floating windows, the dockable panel bodies (display, shader, history, log) and the bake mode -//! panels. +//! Floating windows and dockable display, shader, history and log panels use egui::{Color32, RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake_cmds; +use texturecraft_engine::core::ToneMapping; use texturecraft_engine::core::project::ENV_RESOURCE_PREFIX; -use texturecraft_engine::core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion, ToneMapping}; 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}; +use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { start(app, ctx); @@ -26,9 +27,6 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] export_mesh(app, ctx); - if app.ui.mode == Mode::Baking { - bake_bar(app, ctx); - } unsaved(app, ctx); } @@ -41,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"))] @@ -150,10 +196,14 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { if ui.checkbox(&mut ortho, tr("Orthographic")).changed() { app.run("camera.set", json!({"ortho": ortho})); } - ui.horizontal(|ui| { - ui.label(tr("Tone mapping")); - ui.selectable_value(&mut d.tone_mapping, ToneMapping::Linear, tr("Linear")); - ui.selectable_value(&mut d.tone_mapping, ToneMapping::AcesFilmic, tr("ACES filmic")); + let tone_mapping_name = |tone_mapping: ToneMapping| match tone_mapping { + ToneMapping::Linear => tr("Linear"), + ToneMapping::AcesFilmic => tr("ACES filmic"), + }; + combo(ui, tr("Tone mapping"), tone_mapping_name(d.tone_mapping), |ui| { + for tone_mapping in [ToneMapping::Linear, ToneMapping::AcesFilmic] { + ui.selectable_value(&mut d.tone_mapping, tone_mapping, tone_mapping_name(tone_mapping)); + } }); cameras(app, ui); ui.add_space(6.0); @@ -171,7 +221,6 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { }); ui.add_space(6.0); ui.label(caption(tr("Viewer settings"))); - slider(ui, tr("Ambient occlusion intensity"), &mut d.ao_intensity, 0.0..=1.0, 2); ui.checkbox(&mut app.ui.wireframe_3d, tr("Show wireframe in the 3D view")); ui.checkbox(&mut app.ui.uv_wireframe, tr("Show UV wireframe in the 2D view")); ui.checkbox(&mut d.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)")); @@ -219,18 +268,23 @@ fn cameras(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// The Shader Settings panel body (a dock tab). +/// Wide enough for the longer shader model name +const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; + +/// Width of the scatter color swatch +const SCATTER_SWATCH_WIDTH: f32 = 44.0; + +/// Index of refraction slider range: air to well past diamond (2.42) +const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = 1.0..=3.0; + +/// The Shader Settings panel body (a dock tab) pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let mut d = app.session.doc.project.display.clone(); - let before = d.clone(); - let model = |sg: bool| if sg { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; - egui::ComboBox::from_id_salt("shader_model").width(260.0).selected_text(model(d.spec_gloss)).show_ui(ui, |ui| { - for sg in [false, true] { - ui.selectable_value(&mut d.spec_gloss, sg, model(sg)); - } - }); - let channels = if d.spec_gloss { + let tokens = Tokens::get(ui.ctx()); + let mut display = app.session.doc.project.display.clone(); + let before = display.clone(); + + let model_name = |spec_gloss: bool| if spec_gloss { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; + let channels = if display.spec_gloss { tr("Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).") } else { tr("Base color, Metallic, Roughness and Specular level.") @@ -241,80 +295,101 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { let optional = tr( "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", ); - ui.label(RichText::new(format!("{model_text} {channels} {optional}")).color(tk.text_dim)); + + egui::ComboBox::from_id_salt("shader_model") + .width(SHADER_MODEL_COMBO_WIDTH) + .selected_text(model_name(display.spec_gloss)) + .show_ui(ui, |ui| { + for spec_gloss in [false, true] { + ui.selectable_value(&mut display.spec_gloss, spec_gloss, model_name(spec_gloss)); + } + }) + .response + .on_hover_text(format!("{model_text} {channels} {optional}")); ui.add_space(6.0); - ui.checkbox(&mut d.parallax, tr("Parallax occlusion (height channel)")) + + ui.checkbox(&mut display.parallax, tr("Parallax occlusion (height channel)")) .on_hover_text(tr("Offsets the textures by the height channel, at the height to normal strength")); - ui.checkbox(&mut d.displacement, tr("Displacement (height channel)")).on_hover_text(tr( + ui.checkbox(&mut display.displacement, tr("Displacement (height channel)")).on_hover_text(tr( "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", )); + slider(ui, tr("AO intensity"), &mut display.ao_intensity, 0.0..=1.0, 2); ui.add_space(6.0); - ui.label(caption(tr("Subsurface scattering"))); - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Scatter color")).color(tk.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| color_swatch(ui, "shader_scatter_color", &mut d.scatter_color, 44.0)) - }) - .response - .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); - slider(ui, tr("Scatter radius"), &mut d.scatter_radius, 0.0..=1.0, 3) - .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); - ui.add_space(6.0); - ui.label(caption(tr("Transmission"))); - slider(ui, tr("Index of refraction"), &mut d.ior, 1.0..=3.0, 2) - .on_hover_text(tr("How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42")); - if d != before { - app.session.doc.project.display = d; - } - let ts = app.session.ts(); - if let Some(set) = app.session.doc.project.texture_sets.get(ts) { - let mut hs = set.height_strength; - if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2) { - app.run("textureSet.settings", json!({"ts": ts, "heightStrength": hs, "merge": merge})); - } - } - let mut ao = app.session.doc.project.display.ao_intensity; - if slider(ui, tr("AO intensity"), &mut ao, 0.0..=1.0, 2).changed() { - app.session.doc.project.display.ao_intensity = ao; + + section(ui, "shader_subsurface", tr("Subsurface scattering"), true, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Scatter color")).color(tokens.text)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + color_swatch(ui, "shader_scatter_color", &mut display.scatter_color, SCATTER_SWATCH_WIDTH) + }) + }) + .response + .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); + slider(ui, tr("Scatter radius"), &mut display.scatter_radius, 0.0..=1.0, 3) + .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); + }); + section(ui, "shader_transmission", tr("Transmission"), true, |ui| { + slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + )); + }); + + if display != before { + app.session.doc.project.display = display; } } -/// The History panel body (a dock tab). +/// The History panel body (a dock tab) pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); - // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative. + // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; - egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - let n = done.len() as i64; - let rows = std::iter::once(RichText::new(tr("Project opened")).color(tk.text_dim)) - .chain(done.iter().map(RichText::new)) - .chain(undone.iter().map(|l| RichText::new(trf("{action} (undone)", &[("action", l)])).color(tk.text_dim))); - for (i, text) in rows.enumerate() { - // Row i is the state after i steps. - let steps = n - i as i64; - if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - jump = steps; + + // Bottom up: the Undo and Redo row keeps its place under a list that fills the rest of the panel + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { + app.run("edit.undo", json!({})); } - } + if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { + app.run("edit.redo", json!({})); + } + }); + + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + let done_count = done.len() as i64; + let rows = std::iter::once(RichText::new(tr("Project opened")).color(tokens.text_dim)) + .chain(done.iter().map(RichText::new)) + .chain(undone.iter().map(|label| RichText::new(trf("{action} (undone)", &[("action", label)])).color(tokens.text_dim))); + for (row, text) in rows.enumerate() { + // Each row is the state after that many steps + let steps = done_count - row as i64; + if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { + // Point history is consumed before the document rows shown here + jump = if steps >= 0 { + app.session.history_undo_steps(steps as usize) as i64 + } else { + -(app.session.history_redo_steps((-steps) as usize) as i64) + }; + } + } + }); + }); }); + if jump > 0 { app.run("edit.undo", json!({ "steps": jump })); } else if jump < 0 { app.run("edit.redo", json!({ "steps": -jump })); } - ui.horizontal(|ui| { - if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { - app.run("edit.undo", json!({})); - } - if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { - app.run("edit.redo", json!({})); - } - }); } /// What the start window was asked for. enum Start { Menu(&'static str), + #[cfg(not(target_arch = "wasm32"))] Recent(String), Close, } @@ -324,7 +399,9 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.start { return; } - let tk = Tokens::get(ctx); + + #[cfg(not(target_arch = "wasm32"))] + let tokens = Tokens::get(ctx); let mut open = true; let mut action = None; dialog("start", "TextureCraft", &mut open).min_width(380.0).show(ctx, |ui| { @@ -336,11 +413,12 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { action = Some(Start::Menu("file.open")); } }); + #[cfg(not(target_arch = "wasm32"))] if file_dialogs_available() { ui.add_space(8.0); ui.label(caption(tr("Recent projects"))); if app.ui.recent.is_empty() { - ui.label(RichText::new(tr("No recent projects yet")).color(tk.text_dim)); + ui.label(RichText::new(tr("No recent projects yet")).color(tokens.text_dim)); } for path in &app.ui.recent { let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path); @@ -364,15 +442,17 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); }); - if let Some(a) = action { + + if let Some(action) = action { app.ui.windows.start = false; - match a { + match action { Start::Menu(id) => crate::menus::invoke(app, ctx, id), #[cfg(not(target_arch = "wasm32"))] Start::Recent(path) => open_path(app, &path), - _ => {} + Start::Close => {} } } + if !open { app.ui.windows.start = false; } @@ -382,24 +462,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(); @@ -407,22 +491,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; } } }); @@ -441,20 +523,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(); @@ -463,6 +545,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() { @@ -475,15 +559,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,11 +576,32 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { } } +#[cfg(not(target_arch = "wasm32"))] +fn settings_resources(ctx: &egui::Context) -> (u32, u64) { + let id = egui::Id::unique("settings_resources"); + let now = ctx.input(|input| input.time); + ctx.request_repaint_after(std::time::Duration::from_secs(1)); + + // Query the operating system once a second while Settings is open, rather than every frame + if let Some((sampled_at, cores, available_ram_bytes)) = ctx.data(|data| data.get_temp::<(f64, u32, u64)>(id)) + && (0.0..1.0).contains(&(now - sampled_at)) + { + return (cores, available_ram_bytes); + } + + let (cores, available_ram_bytes) = texturecraft_engine::formats::available_save_resources(); + let cores = u32::try_from(cores).unwrap_or(u32::MAX); + ctx.data_mut(|data| data.insert_temp(id, (now, cores, available_ram_bytes))); + (cores, available_ram_bytes) +} + fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); 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. @@ -505,7 +611,7 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(tr("Language")); let current = crate::i18n::current(); egui::ComboBox::from_id_salt("language").width(180.0).height(320.0).selected_text(current.name).show_ui(ui, |ui| { - for (l, ok) in LANGUAGES.iter().zip(drawable) { + for (l, ok) in LANGUAGES.iter().zip(drawable).filter(|(l, _)| crate::i18n::available(l.code)) { let item = egui::Button::selectable(l.code == current.code, if ok { l.name } else { l.english }); if ui.add_enabled(ok, item).on_disabled_hover_text(tr("No font on this system can show this language")).clicked() { p.language = l.code.to_owned(); @@ -570,14 +676,40 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + ui.label(caption(tr("Project"))); #[cfg(not(target_arch = "wasm32"))] - { - ui.label(caption(tr("Project"))); - form("settings_project").show(ui, |ui| { + let (available_cores, available_ram_bytes) = settings_resources(ctx); + form("settings_project").show(ui, |ui| { + #[cfg(not(target_arch = "wasm32"))] + { ui.label(tr("Autosave every")); ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))); ui.end_row(); - }); + let label = ui.label(tr("Cores kept for the UI")); + ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label.id); + ui.end_row(); + } + + let label = ui.label(tr("Max project size on open")); + ui.add(egui::DragValue::new(&mut p.project_open_limit_gib).range(1..=u32::MAX).suffix(" GiB")) + .labelled_by(label.id) + .on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects.")); + ui.end_row(); + + #[cfg(not(target_arch = "wasm32"))] + { + let label = ui.label(tr("Max RAM while saving")); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label.id); + let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); + ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); + }); + ui.end_row(); + } + }); + #[cfg(not(target_arch = "wasm32"))] + { + ui.label(RichText::new(tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")).small().color(tk.text_dim)); ui.label( RichText::new(trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])) .small() @@ -590,10 +722,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(); @@ -618,10 +748,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 = [ @@ -632,18 +769,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; @@ -669,326 +808,15 @@ fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.about = open; } -/// The Log panel body (a dock tab). +/// The Log panel body (a dock tab) pub(crate) fn log(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().max_height(300.0).stick_to_bottom(true).show(ui, |ui| { - for l in &app.session.log { - ui.label(RichText::new(l).monospace()); + egui::ScrollArea::vertical().auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + for line in &app.session.log { + ui.label(RichText::new(line).monospace()); } }); } -// --------------------------------------------------------------------------------------------- -// Bake mode ("Bake Mesh Maps": texture sets, bakers, common and per-map parameters) - -pub fn bake_left(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::left("bake_left").resizable(true).default_size(320.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - crate::theme::card( - ui, - &tk, - egui::Margin { left: crate::theme::GUTTER, right: 0, top: crate::theme::GUTTER, bottom: crate::theme::GUTTER }, - egui::Margin::symmetric(8, 6), - |ui| bake_body(app, ui), - ); - }); -} - -/// The bake settings, scrollable (the Assets dock slot shows them in bake mode). -pub fn bake_body(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().id_salt("bake_body").auto_shrink([false; 2]).show(ui, |ui| bake_panel(app, ui)); -} - -fn bake_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(caption(tr("Texture set list"))); - for i in 0..app.session.set_count() { - let Some(t) = app.session.doc.project.texture_sets.get(i) else { continue }; - let (name, res, mut on) = (t.name.clone(), t.bake.resolution, t.bake.enabled); - ui.horizontal(|ui| { - if ui.checkbox(&mut on, "").on_hover_text(tr("Bake with \"Bake selected textures\"")).changed() { - app.run("bake.settings", json!({ "ts": i, "enabled": on })); - } - if ui.selectable_label(i == app.session.ts(), format!("{name} ({res}x{res})")).clicked() { - app.run("textureSet.select", json!({ "ts": i })); - } - }); - } - ui.separator(); - let ts = app.session.ts(); - let Some(before) = app.session.doc.project.texture_sets.get(ts).map(|t| t.bake.clone()) else { return }; - let mut b = before.clone(); - let mut selected = app.ui.bake_baker; - ui.label(caption(tr("Mesh map bakers"))); - if ui.selectable_label(selected.is_none(), format!("{} {}", ic::GEAR, tr("Common parameters"))).clicked() { - selected = None; - } - for m in BakedMap::ALL { - ui.horizontal(|ui| { - let mut on = b.maps.contains(&m); - if ui.checkbox(&mut on, "").changed() { - if on { - b.maps.insert(m); - } else { - b.maps.remove(&m); - } - } - if ui.selectable_label(selected == Some(m), tr(m.label())).clicked() { - selected = Some(m); - } - }); - } - app.ui.bake_baker = selected; - ui.separator(); - match selected { - None => common_params(app, ui, &mut b), - Some(m) => { - let mut auto = app.session.auto_rebake.map == Some(m); - if ui - .checkbox(&mut auto, tr("Auto-rebake")) - .on_hover_text(tr("Bake this map again by itself when its bake settings, the low poly or the high polys change")) - .changed() - { - app.run("bake.autoRebake", if auto { json!({ "map": m.id() }) } else { json!({ "off": true }) }); - } - map_params(ui, m, &mut b) - } - } - if b.direction == [0.0; 3] { - b.direction = before.direction; - } - if b != before { - let mut p = bake_cmds::settings_params(&b); - p["ts"] = ts.into(); - app.run("bake.settings", p); - } -} - -fn hint(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(text).color(tk.text_dim).size(11.0)); -} - -fn common_params(app: &mut TextureCraftApp, ui: &mut Ui, b: &mut BakeSettings) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Common parameters"))); - combo(ui, tr("Output size"), format!("{}", b.resolution), |ui| { - for r in [256u32, 512, 1024, 2048, 4096, 8192] { - ui.selectable_value(&mut b.resolution, r, format!("{r}")); - } - }); - combo( - ui, - tr("Antialiasing"), - match b.antialiasing { - 2 => tr("Subsampling 2x2"), - 4 => tr("Subsampling 4x4"), - 8 => tr("Subsampling 8x8"), - _ => tr("None"), - }, - |ui| { - for (v, l) in [(1u32, tr("None")), (2, tr("Subsampling 2x2")), (4, tr("Subsampling 4x4")), (8, tr("Subsampling 8x8"))] { - ui.selectable_value(&mut b.antialiasing, v, l); - } - }, - ); - let mut dil = b.dilation as f32; - if slider(ui, tr("Dilation width"), &mut dil, 0.0..=64.0, 0).changed() { - b.dilation = dil as u32; - } - - ui.add_space(6.0); - ui.label(RichText::new(tr("High definition meshes")).strong().color(tk.text_strong)); - let ctx = ui.ctx().clone(); - let highs: Vec<(String, usize)> = app.session.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect(); - let mut remove = None; - for (i, (name, tris)) in highs.iter().enumerate() { - ui.horizontal(|ui| { - ui.label(trf("{name} ({n} triangles)", &[("name", name), ("n", tris)])); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button(ui, ic::TRASH, tr("Remove"), false, 18.0).clicked() { - remove = Some(i); - } - }); - }); - } - if highs.is_empty() { - hint(ui, tr("None: the low poly is its own high poly.")); - } - if let Some(i) = remove { - app.run("bake.highPoly.remove", json!({ "index": i })); - } - if ui.button(format!("{} {}", ic::PLUS, tr("Add high definition meshes"))).clicked() { - crate::web_files::import_bake_mesh(app, &ctx, false); - } - ui.checkbox(&mut b.use_low_as_high, tr("Use low poly mesh as high poly mesh")); - choice(ui, tr("Match"), &mut b.matching, &[(BakeMatch::Always, tr("Always")), (BakeMatch::ByMeshName, tr("By mesh name"))]); - if b.matching == BakeMatch::ByMeshName { - for (label, suffix) in [(tr("Low poly mesh suffix"), &mut b.low_suffix), (tr("High poly mesh suffix"), &mut b.high_suffix)] { - ui.horizontal(|ui| { - ui.label(label); - ui.add(egui::TextEdit::singleline(suffix).desired_width(80.0)); - }); - } - } - slider(ui, tr("Max frontal distance"), &mut b.max_frontal, 0.0..=0.2, 3); - slider(ui, tr("Max rear distance"), &mut b.max_rear, 0.0..=0.2, 3); - hint(ui, tr("Relative to the bounding box diagonal.")); - ui.checkbox(&mut b.average_normals, tr("Average normals")); - - ui.add_space(6.0); - let cage = app.session.bake_meshes.cage.as_ref().map(|c| c.name.clone()); - ui.horizontal(|ui| { - ui.label(trf("Cage: {name}", &[("name", &cage.as_deref().unwrap_or(tr("none")))])); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if cage.is_some() && icon_button(ui, ic::TRASH, tr("Remove the cage"), false, 18.0).clicked() { - app.run("bake.cage.clear", json!({})); - } - if icon_button(ui, ic::FOLDER_OPEN, tr("Load a cage (the low poly, inflated)"), false, 18.0).clicked() { - crate::web_files::import_bake_mesh(app, &ctx, true); - } - }); - }); - - ui.add_space(6.0); - skew_section(app, ui); - - ui.add_space(6.0); - if ui.button(tr("Apply to all texture sets")).on_hover_text(tr("Copy these bake settings to every texture set")).clicked() { - let mut p = bake_cmds::settings_params(b); - p["ts"] = "all".into(); - if let Some(o) = p.as_object_mut() { - o.remove("enabled"); - } - app.run("bake.settings", p); - } -} - -/// Skew correction: paint a map over the UV atlas that turns the bake rays onto the base normal. -fn skew_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(caption(tr("Skew correction"))); - let has = app.session.bake_meshes.skew.is_some(); - let mut brush = app.ui.skew_brush; - ui.checkbox(&mut brush.on, tr("Paint skew in the 2D view")) - .on_hover_text(tr("Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase")); - if brush.on { - slider(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3); - slider(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2); - slider(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); - } - if brush.on && !app.ui.skew_brush.on && app.ui.layout == crate::state::ViewLayout::Only3D { - app.ui.layout = crate::state::ViewLayout::Split; - } - app.ui.skew_brush = brush; - if has && ui.button(tr("Remove skew correction")).clicked() { - app.run("bake.skew.clear", json!({})); - } -} - -/// A combo box picking one of `options` (value, label). -fn choice(ui: &mut Ui, label: &str, value: &mut T, options: &[(T, &str)]) { - let shown = options.iter().find(|(v, _)| v == value).map_or("", |(_, l)| *l); - combo(ui, label, shown, |ui| { - for (v, l) in options { - ui.selectable_value(value, *v, *l); - } - }); -} - -/// Ray count and length of a secondary-ray map; its cone too when `cone`. -fn ray_params(ui: &mut Ui, r: &mut RaySettings, cone: bool) { - let mut rays = r.rays as f32; - if slider(ui, tr("Secondary rays"), &mut rays, 4.0..=256.0, 0).changed() { - r.rays = rays as u32; - } - slider(ui, tr("Max occluder distance"), &mut r.max_distance, 0.01..=1.0, 2); - if cone { - slider(ui, tr("Spread angle"), &mut r.spread, 0.0..=180.0, 0); - } -} - -fn map_params(ui: &mut Ui, m: BakedMap, b: &mut BakeSettings) { - ui.label(caption(tr(m.label()))); - match m { - BakedMap::AmbientOcclusion => { - ray_params(ui, &mut b.ao, true); - choice(ui, tr("Distribution"), &mut b.ao.distribution, &[(RayDistribution::Cosine, tr("Cosine")), (RayDistribution::Uniform, tr("Uniform"))]); - ui.checkbox(&mut b.ao_ignore_backface, tr("Ignore backface")); - choice( - ui, - tr("Self occlusion"), - &mut b.ao_self_occlusion, - &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only same mesh name"))], - ); - } - BakedMap::Thickness => ray_params(ui, &mut b.thickness, true), - BakedMap::BentNormal => { - ray_params(ui, &mut b.bent_normal, false); - hint(ui, tr("Bent normal rays follow the ambient occlusion's occluder settings.")); - } - BakedMap::Curvature => { - slider(ui, tr("Strength"), &mut b.curvature_strength, 0.1..=4.0, 2); - ui.checkbox(&mut b.curvature_from_normal, tr("From normal map")); - if b.curvature_from_normal { - let mut radius = b.curvature_radius as f32; - if slider(ui, tr("Sampling radius"), &mut radius, 0.0..=16.0, 0).changed() { - b.curvature_radius = radius as u32; - } - hint(ui, tr("0 picks a radius from the output size.")); - } - hint(ui, tr("From normal map: curvature of the baked normal map's detail instead of the mesh.")); - } - BakedMap::WorldDirection => { - for (axis, v) in ["X", "Y", "Z"].iter().zip(b.direction.iter_mut()) { - slider(ui, &trf("Direction {axis}", &[("axis", axis)]), v, -1.0..=1.0, 2); - } - choice( - ui, - tr("Encoding"), - &mut b.direction_mode, - &[(DirectionMode::Signed, tr("Signed (-1..1)")), (DirectionMode::Positive, tr("Positive (0..1)"))], - ); - hint(ui, tr("White where the surface faces the direction, black where it faces away.")); - } - BakedMap::Position => { - choice( - ui, - tr("Normalization"), - &mut b.position_mode, - &[(PositionMode::BoundingBox, tr("Bounding box")), (PositionMode::BoundingSphere, tr("Bounding sphere"))], - ); - hint(ui, tr("Position normalized to the low poly's bounding box or sphere.")); - } - BakedMap::Normal => hint(ui, tr("Tangent-space normals of the high definition meshes.")), - BakedMap::WorldNormal => hint(ui, tr("World-space normals of the high poly (or the low poly).")), - BakedMap::Id => hint(ui, tr("One color per mesh part.")), - BakedMap::Height => hint(ui, tr("High poly height between the max rear (black) and max frontal (white) distances.")), - BakedMap::Opacity => hint(ui, tr("White where the high poly covers the low poly, times its alpha.")), - BakedMap::ColorMap => hint(ui, tr("Base colors (textures, factors) and vertex colors of the high definition meshes.")), - } -} - -fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context) { - egui::Area::new(egui::Id::unique("bake_bar")).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -40.0)).show(ctx, |ui| { - ui.horizontal(|ui| { - if let Some(p) = app.bake_progress() { - ui.add(egui::ProgressBar::new(p).desired_width(220.0).show_percentage()); - if ui.button(tr("Cancel")).clicked() { - app.cancel_bake(); - } - } else { - let sets: Vec = app.session.doc.project.texture_sets.iter().enumerate().filter(|(_, t)| t.bake.enabled).map(|(i, _)| i).collect(); - let label = trf("Bake selected textures ({n})", &[("n", &sets.len())]); - if ui.add_enabled(!sets.is_empty(), primary_button(ui, &label)).clicked() { - app.start_bake(sets); - } - } - if ui.button(tr("Return to painting mode")).clicked() { - app.ui.mode = Mode::Painting; - } - }); - }); -} - // --------------------------------------------------------------------------------------------- // Files (wired to texturecraft-formats once it lands) @@ -997,14 +825,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) { @@ -1017,28 +848,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. @@ -1052,10 +884,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() => { @@ -1065,83 +898,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) { @@ -1229,10 +1105,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(); @@ -1413,3 +1291,97 @@ 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)); + // These dialog tests query English labels, independently of the system locale. + h.state_mut().ui.prefs.language = "en".into(); + 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_preview.rs b/crates/ui-egui/tests/bake_preview.rs new file mode 100644 index 00000000..1703abde --- /dev/null +++ b/crates/ui-egui/tests/bake_preview.rs @@ -0,0 +1,186 @@ +//! Bake mode: while a bake runs the 3D view shows the maps landing on the model, the previous view +//! mode comes back when the bake ends, is cancelled or Bake mode is left, and painting is paused. + +use egui_kittest::Harness; +use texturecraft_engine::ViewMode; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; + +const MAPS: [BakedMap; 3] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Height]; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.ao.parameters.rays.rays = 8; + texture_set.bake.maps.select(MAPS); + } + + session.view = ViewMode::UvChecker; + let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + harness +} + +/// Frames until the bake is gone, with the view mode after each one. +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) -> Vec { + let mut seen = Vec::new(); + for _ in 0..4000 { + harness.run_steps(1); + seen.push(harness.state().session.view); + if harness.state().bake.is_none() { + return seen; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + + panic!("the bake did not finish"); +} + +#[test] +fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { + let mut harness = harness(); + + harness.state_mut().start_bake(vec![0]); + + // Right away: the first map shows, still neutral + assert_eq!(harness.state().session.view, ViewMode::MeshMap(MAPS[0])); + harness.run_steps(1); + assert!(harness.state().bake_status().is_some_and(|status| status.contains("/3")), "the status line names the stage"); + let seen = run_to_the_end(&mut harness); + + // Every requested map was shown at some frame, in request order + let mut shown: Vec = Vec::new(); + for view in seen { + if let ViewMode::MeshMap(map) = view + && shown.last() != Some(&map) + { + shown.push(map); + } + } + assert_eq!(shown, MAPS); + assert_eq!(harness.state().session.view, ViewMode::UvChecker, "the mode in use before the bake is back"); + assert!(!harness.state().session.bake_preview_active()); + assert!(MAPS.iter().all(|map| harness.state().session.doc.baked[&0].maps.contains_key(map))); +} + +#[test] +fn cancelling_restores_the_view_and_leaves_the_document_alone() { + let mut harness = harness(); + let before = harness.state().session.doc.baked.get(&0).cloned(); + + harness.state_mut().start_bake(vec![0]); + harness.run_steps(2); + + assert!(harness.state().session.bake_preview_active()); + let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0)); + assert!(harness.state_mut().session.begin_stroke(at, viewport, 1.0).is_err(), "painting is paused"); + harness.state_mut().cancel_bake(); + harness.run_steps(2); + + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(!harness.state().session.bake_preview_active() && harness.state().bake.is_none()); + assert_eq!(harness.state().session.doc.baked.get(&0).cloned(), before); +} + +#[test] +fn leaving_bake_mode_closes_the_preview_but_the_bake_goes_on() { + let mut harness = harness(); + + harness.state_mut().start_bake(vec![0]); + harness.run_steps(2); + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(2); + + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(!harness.state().session.bake_preview_active()); + run_to_the_end(&mut harness); + + assert!(harness.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Height), "the bake finished and was applied"); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); +} + +#[test] +fn the_painting_message_is_a_translated_key() { + assert_eq!(texturecraft_ui_egui::PAINTING_PAUSED, texturecraft_engine::bake_preview::PAINTING_PAUSED); +} + +#[test] +fn a_ready_result_waits_for_the_map_stream_to_close() { + use std::sync::{Arc, atomic::AtomicUsize, mpsc}; + use texturecraft_engine::bake::Progress; + use texturecraft_ui_egui::{BakeJob, RunningBake}; + + let mut harness = harness(); + let before = harness.state().session.doc.baked.clone(); + let mut task = harness.state().session.bake_task(0).unwrap(); + task.tracer = None; + let mut finished_maps = Vec::new(); + let output = task.run_streaming(&Progress::new(), &mut |map| finished_maps.push(map)).unwrap(); + let (map_sender, maps) = mpsc::channel(); + let (result_sender, receiver) = mpsc::channel(); + result_sender.send(Ok(output)).unwrap(); + let app = harness.state_mut(); + app.start_bake(vec![0]); + let mesh_id = app.session.mesh_id; + app.bake = Some(BakeJob { + queue: Vec::new(), + total: 1, + mesh_id, + current: Some(RunningBake { + set_index: 0, + progress: Arc::new(Progress::new()), + receiver, + maps, + maps_done: Arc::new(AtomicUsize::new(MAPS.len())), + maps_total: MAPS.len(), + }), + }); + + // A ready result cannot make an earlier empty map read conclusive + harness.run_steps(1); + + assert!(harness.state().bake.is_some(), "an open map stream can still deliver a map"); + assert_eq!(harness.state().session.doc.baked, before); + for map in finished_maps { + map_sender.send(map).unwrap(); + } + drop(map_sender); + + // Each queued map must reach a frame before the result ends the preview + for map in MAPS { + harness.run_steps(1); + + assert_eq!(harness.state().session.view, ViewMode::MeshMap(map)); + assert!(harness.state().session.bake_preview_baked(0).unwrap().maps.contains_key(&map)); + assert_eq!(harness.state().session.doc.baked, before); + } + harness.run_steps(1); + + assert!(harness.state().bake.is_none()); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(MAPS.iter().all(|map| harness.state().session.doc.baked[&0].maps.contains_key(map))); +} + +#[test] +fn an_invalid_set_does_not_start_a_partial_bake_or_change_the_view() { + let mut harness = harness(); + let app = harness.state_mut(); + let invalid_set = app.session.set_count(); + let expected_error = app.session.doc.project.texture_set(invalid_set).unwrap_err().to_string(); + let view = app.session.view; + let revision = app.session.revision; + let history_steps = app.session.history_labels().len(); + + app.start_bake(vec![0, invalid_set]); + + assert!(app.bake.is_none(), "validate every set before queuing any work"); + assert!(!app.session.bake_preview_active()); + assert_eq!(app.session.view, view); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.history_labels().len(), history_steps); + assert!(app.toasts.iter().any(|toast| toast.error && toast.text.contains(&expected_error))); +} diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs new file mode 100644 index 00000000..6c54d052 --- /dev/null +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -0,0 +1,158 @@ +//! The 2D view hides the system pointer and draws the brush outline under it while painting. + +use egui::{CursorIcon, Event, Pos2, Shape, TouchDeviceId, TouchId, TouchPhase}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +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(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +fn cursor(harness: &Harness<'_, TextureCraftApp>) -> CursorIcon { + harness.output().platform_output.cursor_icon +} + +#[test] +fn painting_in_the_2d_view_replaces_the_pointer_with_the_brush_outline() { + let mut harness = harness(); + let center = egui::pos2(800.0, 480.0); + harness.hover_at(center); + harness.run_steps(3); + assert_eq!(cursor(&harness), CursorIcon::None, "the brush outline replaces the pointer"); + harness.hover_at(egui::pos2(2.0, 2.0)); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is back"); +} + +#[test] +fn outside_painting_the_2d_view_keeps_the_normal_pointer() { + let mut harness = harness(); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + let center = egui::pos2(800.0, 480.0); + harness.hover_at(center); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None); +} + +#[test] +fn unavailable_paint_tool_keeps_the_pointer_and_hides_the_2d_brush_outline() { + let mut harness = harness(); + let fill = execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill, "target": "content"})).unwrap(); + + let pointer = egui::pos2(800.0, 480.0); + harness.hover_at(pointer); + harness.run_steps(3); + + assert_ne!(cursor(&harness), CursorIcon::None, "a fill layer cannot take the paint tool"); + assert!(rings_at(&harness, pointer).is_empty(), "an unavailable brush has no outline"); +} + +/// Radii of the white brush-outline rings (stroke 1.2) around `center` in the last frame. +fn rings_at(harness: &Harness<'_, TextureCraftApp>, center: Pos2) -> Vec { + fn walk(shape: &Shape, center: Pos2, out: &mut Vec) { + match shape { + Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, center, out)), + Shape::Circle(circle) if (circle.stroke.width - 1.2).abs() < 1e-3 && circle.center.distance(center) < 0.5 => out.push(circle.radius), + _ => {} + } + } + let mut out = Vec::new(); + harness.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, center, &mut out)); + out +} + +#[test] +fn the_view_header_keeps_the_normal_pointer_and_gets_no_brush_outline() { + let mut harness = harness(); + // The header starts 8 points below the view edge and is 22 points high + let view_top = (0..200).map(|y| y as f32).find(|&y| { + harness.hover_at(egui::pos2(300.0, y)); + harness.run_steps(2); + cursor(&harness) == CursorIcon::None + }); + let top = view_top.expect("the view has a top edge"); + let header = egui::pos2(800.0, top + 8.0 + 11.0); + harness.hover_at(header); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None, "over the pickers the pointer stays"); + assert!(rings_at(&harness, header).is_empty(), "no brush outline over the pickers"); + let below = egui::pos2(800.0, top + 120.0); + harness.hover_at(below); + harness.run_steps(3); + assert_eq!(cursor(&harness), CursorIcon::None, "below the header the brush outline is back"); + assert!(!rings_at(&harness, below).is_empty()); +} + +#[test] +fn a_light_pen_shows_the_smaller_footprint_it_paints() { + let mut harness = harness(); + harness.state_mut().session.tool.brush.size = 0.05; + harness.state_mut().session.tool.brush.min_size = 0.5; + let center = egui::pos2(800.0, 600.0); + harness.hover_at(center); + harness.run_steps(3); + let full = rings_at(&harness, center); + assert_eq!(full.len(), 1, "one outline at full pressure"); + // Half pressure gives 0.75 of the full radius with this minimum size + let events = &mut harness.input_mut().events; + events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: center, force: Some(0.5) }); + events.push(Event::PointerMoved(center)); + harness.step(); + let light = rings_at(&harness, center); + assert_eq!(light.len(), 1); + assert!((light[0] / full[0] - 0.75).abs() < 1e-3, "half pressure shows 0.75 of the radius: {} vs {}", light[0], full[0]); +} + +#[test] +fn dragging_out_of_the_2d_view_brings_the_system_pointer_back() { + let mut harness = harness(); + let center = egui::pos2(800.0, 480.0); + harness.hover_at(center); + harness.run_steps(3); + assert_eq!(cursor(&harness), CursorIcon::None, "inside the view the brush outline replaces the pointer"); + // Drag from the view to its upper-left outside corner + harness.event(Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + harness.run_steps(2); + assert_eq!(cursor(&harness), CursorIcon::None, "still inside while dragging"); + let outside = egui::pos2(2.0, 2.0); + harness.hover_at(outside); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible even during a drag"); + assert!(rings_at(&harness, outside).is_empty(), "no brush outline outside the view"); + harness.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + harness.run_steps(2); +} + +#[test] +fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { + let mut harness = harness(); + let center = egui::pos2(800.0, 480.0); + let ctrl = egui::Modifiers::COMMAND; + harness.hover_at(center); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(ctrl)); + harness.event(Event::PointerButton { pos: center, button: egui::PointerButton::Secondary, pressed: true, modifiers: ctrl }); + harness.run_steps(2); + // The outline stays anchored while the pointer is hidden inside the view + harness.hover_at(center + egui::vec2(10.0, 0.0)); + harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "anchored outline while the pointer is in the view"); + assert_eq!(cursor(&harness), CursorIcon::None); + // Outside the view, the outline stays anchored and the system pointer returns + harness.hover_at(egui::pos2(2.0, 2.0)); + harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "the outline stays at the press origin outside the view"); + assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible"); + harness.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl }); + harness.event(Event::ModifiersChanged(egui::Modifiers::NONE)); + harness.run_steps(2); +} diff --git a/crates/ui-egui/tests/display_panel.rs b/crates/ui-egui/tests/display_panel.rs new file mode 100644 index 00000000..9c72f884 --- /dev/null +++ b/crates/ui-egui/tests/display_panel.rs @@ -0,0 +1,30 @@ +//! Display Settings picks its tone mapping from a dropdown and leaves the AO intensity to Shader Settings + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.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; + +#[test] +fn display_picks_the_tone_mapping_from_a_dropdown() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).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.state_mut().ui.dock.focus(Panel::Display); + harness.run_steps(STARTUP_FRAMES); + + let tone_mapping = harness.get_all_by_role(Role::ComboBox).find(|combo| combo.accesskit_node().value().as_deref() == Some("ACES filmic")); + assert!(tone_mapping.is_some(), "the tone mapping is a dropdown showing ACES filmic"); + assert!(harness.query_by_label("Ambient occlusion intensity").is_none(), "the AO intensity is in Shader Settings"); +} diff --git a/crates/ui-egui/tests/effect_rows.rs b/crates/ui-egui/tests/effect_rows.rs deleted file mode 100644 index 218eb0cc..00000000 --- a/crates/ui-egui/tests/effect_rows.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Effect rows in the layer stack: dragging one reorders its stack. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::{Value, json}; -use texturecraft_engine::core::LayerId; -use texturecraft_engine::execute; -use texturecraft_ui_egui::TextureCraftApp; - -fn id(v: Value, key: &str) -> u64 { - v[key].as_u64().unwrap() -} - -/// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. -fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { - let start = h.get_by_label(from).rect().center(); - let r = h.get_by_label(to).rect(); - let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 }); - h.drag_at(start); - h.run_steps(2); - h.hover_at(end); - h.run_steps(2); - h.drop_at(end); - h.run_steps(3); -} - -#[test] -fn dragging_an_effect_row_reorders_its_stack() { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); - let mut add = - |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); - let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); - execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); - assert_eq!(order(&h), [a, b, c]); - // The rows list the top first: C, B, A. A dropped on C's upper half goes to the top. - drag(&mut h, "Effect A", "Effect C", false); - assert_eq!(order(&h), [b, c, a]); - // A dropped on B's lower half goes back to the bottom. - drag(&mut h, "Effect A", "Effect B", true); - assert_eq!(order(&h), [a, b, c]); - // C dropped on A's upper half lands between A and B. - drag(&mut h, "Effect C", "Effect A", false); - assert_eq!(order(&h), [a, c, b]); -} diff --git a/crates/ui-egui/tests/effect_sliders.rs b/crates/ui-egui/tests/effect_sliders.rs deleted file mode 100644 index c5374fb0..00000000 --- a/crates/ui-egui/tests/effect_sliders.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged -//! or clicked to. - -use egui::accesskit::Role; -use egui_kittest::Harness; -use egui_kittest::kittest::{Queryable, by}; -use serde_json::json; -use texturecraft_engine::core::{EffectKind, LayerId}; -use texturecraft_ui_egui::TextureCraftApp; - -/// The sample session with its first generator effect selected, and that effect's id. -fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let (layer, effect) = session - .doc - .project - .layers - .values() - .find_map(|l| { - let mask = l.mask.iter().flat_map(|m| m.effects.iter()); - l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id)) - }) - .unwrap(); - texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - (h, effect) -} - -fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { - h.state().session.doc.project.effect(effect).unwrap().1.opacity -} - -/// The track under the slider labelled `label` (the row below the label). -fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { - let l = h.get_by_label(label).rect(); - egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0)) -} - -#[test] -fn dragging_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - assert_eq!(opacity(&h, effect), 1.0); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect)); -} - -/// A generator slider applies while it is dragged (the texture follows the pointer), and the -/// whole drag is one undo step. -#[test] -fn dragging_a_generator_slider_applies_live_as_one_undo_step() { - let (mut h, effect) = harness(); - let level = |h: &Harness<'_, TextureCraftApp>| match &h.state().session.doc.project.effect(effect).unwrap().1.kind { - EffectKind::Generator(g) => g.level, - _ => panic!("a generator"), - }; - let steps = h.state().session.history_labels().len(); - let t = track(&h, "Level"); - let at = |x: f32| egui::pos2(t.left() + x, t.center().y); - h.drag_at(at(10.0)); - h.run_steps(2); - let mut last = 0.0; - for x in [60.0, 160.0] { - h.hover_at(at(x)); - h.run_steps(2); - assert!(level(&h) > last && level(&h) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&h)); - last = level(&h); - } - h.drop_at(at(160.0)); - h.run_steps(3); - assert_eq!(level(&h), last); - assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); -} - -/// The combo box in the row of the "Channel" label. -fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = h.get_by_label("Channel").rect().center().y; - h.get_all(by().role(Role::ComboBox)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() -} - -/// A content levels effect offers a channel for its histogram; picking one keeps it selected. -#[test] -fn content_levels_pick_the_histogram_channel() { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); - texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel"); - channel_picker(&h).click(); - h.run_steps(2); - h.get_by_label("Roughness").click(); - h.run_steps(3); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays"); -} - -#[test] -fn clicking_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - let t = track(&h, "Opacity"); - let at = egui::pos2(t.left() + 20.0, t.center().y); - h.drag_at(at); - h.drop_at(at); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect)); -} - -/// The number field in the row of the slider labelled `label`. -fn number_field<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = h.get_by_label(label).rect().center().y; - h.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() -} - -/// Focus the opacity field and press `keys`, then type `text`, one key per frame like a person. -fn type_opacity(h: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { - number_field(h, "Opacity").focus(); - h.run_steps(2); - for k in keys { - h.key_press(*k); - h.run_steps(1); - } - for c in text.chars() { - number_field(h, "Opacity").type_text(&c.to_string()); - h.run_steps(1); - } -} - -#[test] -fn a_value_typed_in_the_number_field_applies() { - let (mut h, effect) = harness(); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.25); - assert_eq!(h.state().session.history_labels().len(), steps + 1); -} - -/// Dragging the track while the number field has focus drops what was typed there: leaving the -/// field afterwards does not undo the drag. -#[test] -fn a_track_drag_drops_text_typed_in_the_number_field() { - let (mut h, effect) = harness(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "5"); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - let dragged = opacity(&h, effect); - assert!(dragged < 0.5, "the drag applies: {dragged}"); - // Leave whatever has focus: a click on empty space. - h.drag_at(egui::pos2(5.0, 1390.0)); - h.drop_at(egui::pos2(5.0, 1390.0)); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), dragged, "the text typed before the drag stays dropped"); -} - -/// Leaving the number field without typing, or with Escape, keeps the value (not the rounded -/// text the field shows) and makes no undo step. -#[test] -fn leaving_the_number_field_unchanged_keeps_the_value() { - let (mut h, effect) = harness(); - texturecraft_engine::execute(&mut h.state_mut().session, "effect.set", &json!({"effect": effect.0, "opacity": 0.333})).unwrap(); - h.run_steps(2); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[], ""); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333, "left without typing"); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "9"); - assert_eq!(number_field(&h, "Opacity").value().as_deref(), Some("0.39")); - assert!(number_field(&h, "Opacity").is_focused()); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333); - // Typing the value it already has is no edit either. - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(h.state().session.history_labels().len(), steps); -} 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/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 00000000..d7c447db --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.TextureCraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak", "--filesystem=xdg-data/ArtCraft/versions:ro"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/crates/ui-egui/tests/history_panel.rs b/crates/ui-egui/tests/history_panel.rs deleted file mode 100644 index b3f134f0..00000000 --- a/crates/ui-egui/tests/history_panel.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! A click on a step of the History panel goes back or forward to it. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::docking::Panel; - -#[test] -fn clicking_a_history_step_returns_to_it() { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let layer = session.selected_layer().unwrap(); - for name in ["Step A", "Step B", "Step C"] { - texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap(); - } - let done = session.history_labels().len(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.dock.focus(Panel::History); - h.run_steps(4); - let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone(); - // The first state: everything undone, and listed as undone. - h.get_by_label("Project opened").click(); - h.run_steps(3); - assert!(!h.state().session.can_undo()); - assert_eq!(h.state().session.redo_labels().len(), done); - // The first undone row is the next step: one redo. - h.get_all_by_label("Rename layer (undone)").next().unwrap().click(); - h.run_steps(3); - assert_eq!(h.state().session.history_labels().len(), 1); - assert_eq!(h.state().session.redo_labels().len(), done - 1); - // The last undone row: all the way forward again. - h.get_all_by_label("Rename layer (undone)").last().unwrap().click(); - h.run_steps(3); - assert_eq!(name(&h), "Step C"); - assert!(!h.state().session.can_redo()); -} diff --git a/crates/ui-egui/tests/i18n_build.rs b/crates/ui-egui/tests/i18n_build.rs new file mode 100644 index 00000000..c972cfc7 --- /dev/null +++ b/crates/ui-egui/tests/i18n_build.rs @@ -0,0 +1,100 @@ +//! Optional catalog embedding must work without network or application dependencies. +#[path = "../i18n_build.rs"] +#[allow(dead_code)] // The production build entry point is not invoked by these pure-input tests. +mod i18n_build; + +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; + +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let path = std::env::temp_dir().join(format!("texturecraft-i18n-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir_all(path.join("locales/es")).unwrap(); + Self(path) + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn no_input_is_english_but_required_input_errors() { + assert!(!i18n_build::generate(None, false).unwrap().contains("include_str!")); + assert!(i18n_build::generate(None, true).is_err()); +} + +#[test] +fn invalid_and_relative_checkouts_are_rejected() { + let fixture = Fixture::new(); + assert!(i18n_build::generate(Some(&fixture.0.join("missing")), false).is_err()); + assert!(i18n_build::generate(Some(std::path::Path::new("relative")), false).is_err()); +} + +#[test] +fn shared_only_locale_is_not_offered_and_required_needs_app_catalog() { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap(); + assert!(!i18n_build::generate(Some(&fixture.0), false).unwrap().contains("include_str!")); + assert!(i18n_build::generate(Some(&fixture.0), true).is_err()); +} + +#[test] +fn app_catalog_is_embedded_with_optional_shared_catalog() { + let fixture = Fixture::new(); + let app = fixture.0.join("locales/es/texturecraft.tsv"); + std::fs::write(&app, "\tLayers\tCapas\n").unwrap(); + let source = i18n_build::generate(Some(&fixture.0), true).unwrap(); + assert!(source.contains("texturecraft.tsv")); + assert!(source.contains("(\"es\", \"\",")); + let common = fixture.0.join("locales/es/common.tsv"); + std::fs::write(&common, "\tSave\tGuardar\n").unwrap(); + assert!(i18n_build::generate(Some(&fixture.0), true).unwrap().contains("common.tsv")); +} + +#[test] +fn unreadable_catalog_fails_before_generating_rust_source() { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), [0xff, 0xfe]).unwrap(); + assert!(i18n_build::generate(Some(&fixture.0), true).is_err()); +} + +#[test] +fn generated_paths_compile_and_embed_the_catalog_contents() { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); + let generated = i18n_build::generate(Some(&fixture.0), true).unwrap(); + let program = format!( + "extern crate self as craft_i18n;\npub type Embedded = [(&'static str, &'static str, &'static str)];\n{generated}\nfn main() {{ assert_eq!(CRAFT_I18N[0].2, \"\\tLayers\\tCapas\\n\"); }}" + ); + let source = fixture.0.join("check.rs"); + let binary = fixture.0.join(format!("check{}", std::env::consts::EXE_SUFFIX)); + std::fs::write(&source, program).unwrap(); + assert!(std::process::Command::new("rustc").arg(&source).arg("-o").arg(&binary).status().unwrap().success()); + assert!(std::process::Command::new(binary).status().unwrap().success()); +} + +#[test] +fn malformed_utf8_catalogs_and_invalid_rows_fail_during_generation() { + for file in ["texturecraft.tsv", "common.tsv"] { + for invalid in [ + "not a TSV row\n", + "\tLayers\t\n", + "\tSave {name}\tGuardar\n", + "\tOpen…\tAbrir\n", + "\tSave\tGuardar\n\tSave\tSalvar\n", + "@plural\t{n} layer|{n} layers\t{n} capa\n", + "@unknown\tSave\tGuardar\n", + ] { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); + std::fs::write(fixture.0.join("locales/es").join(file), invalid).unwrap(); + for required in [false, true] { + assert!(i18n_build::generate(Some(&fixture.0), required).is_err(), "accepted {file}: {invalid:?}"); + } + } + } +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs new file mode 100644 index 00000000..60f6f03e --- /dev/null +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -0,0 +1,43 @@ +//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps +//! the mesh meanwhile, the job is cancelled and its result is dropped. + +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use egui_kittest::Harness; +use texturecraft_engine::bake::Progress; +use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; + +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { + 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); + let progress = Arc::new(Progress::new()); + let (tx, receiver) = std::sync::mpsc::channel(); + let (maps_tx, maps) = std::sync::mpsc::channel(); + let id = mesh_id(h.state().session.mesh_id); + // Leak the sender so the channel stays empty instead of closed. + std::mem::forget(tx); + std::mem::forget(maps_tx); + let running = + RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; + h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); + (h, progress) +} + +#[test] +fn a_job_on_a_swapped_mesh_is_cancelled_and_dropped() { + let (mut h, progress) = harness_with_job(|current| current + 1); + h.step(); + assert!(h.state().bake.is_none(), "the job is dropped"); + assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop"); +} + +#[test] +fn a_job_on_the_current_mesh_keeps_running() { + let (mut h, progress) = harness_with_job(|current| current); + h.step(); + assert!(h.state().bake.is_some(), "the job stays"); + assert!(!progress.cancel.load(Ordering::Relaxed)); +} 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..787f8645 --- /dev/null +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -0,0 +1,643 @@ +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("256x256").nth(1).unwrap().click(); + harness.run_steps(3); + click(&mut harness, "128x128"); + 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("256x256").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("256x256").count(), 2); + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(3); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); + harness.get_by_label("UV tile 1002 resolution").click(); + harness.run_steps(3); + click(&mut harness, "128x128"); + harness.get_by_value("128x128*"); + 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("128x128*").click(); + harness.run_steps(3); + click(&mut harness, "Remove resolution override"); + assert_eq!(harness.state().session.doc.project, before); + assert!(harness.query_by_value("128x128*").is_none()); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + harness.get_by_value("128x128*"); + + 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("256x256"); + harness.get_by_label("1002"); + harness.get_by_value("128x128*"); + 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 (7)").accesskit_node().is_disabled(), "7 checked maps on the one tile left"); + click_checkbox(&mut harness, "1001"); + assert!(harness.get_by_label("Bake (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_grey_out_with_a_reason() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + + // Without a high poly everything that needs one shows greyed, as in the reference + for needs_high in ["Match", "Max Frontal Distance", "Edge Protection"] { + assert!(harness.get_by_label(needs_high).accesskit_node().is_disabled(), "{needs_high} is greyed"); + } + harness.get_by_label("The cage applies once a high poly mesh is loaded."); + harness.get_by_label("Skew Correction applies once a high poly mesh is loaded."); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "nothing selected to remove"); + + 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); + assert!(!harness.get_by_label("Max Frontal Distance").accesskit_node().is_disabled()); + assert!(harness.query_by_label("The cage applies once a high poly mesh is loaded.").is_none()); + harness.get_by_label("Skew Correction"); + harness.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; + harness.run_steps(3); + assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); + harness.get_by_label("Skew Correction needs Average Normals turned on in the cage settings."); + harness.state_mut().session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + harness.run_steps(3); + harness.get_by_label("Skew Correction is not available while the low poly mesh is used as the high poly mesh."); + harness.get_by_label("The cage is not used while the low poly mesh is used as the high poly mesh."); + assert!(harness.get_by_label("Paint Cage").accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + (settings.cage.average_normals, settings.high_poly.use_low_as_high) = (true, false); + harness.run_steps(3); + assert!(!harness.get_by_label("Edge Protection").accesskit_node().is_disabled()); + + 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.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); + harness.get_by_label("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself."); + + 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)); + } + } +} + +#[test] +fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + let session = &mut harness.state_mut().session; + 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(); + let mesh = session.mesh.clone(); + session.bake_meshes.cage = Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), bytes: Default::default(), mesh, base_color: Vec::new() }); + let settings = &mut session.doc.project.texture_sets[0].bake; + (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); + harness.run_steps(3); + + assert!(harness.get_by_label("Load Cage").accesskit_node().is_disabled(), "the cage does not apply"); + assert!(!harness.get_by_label("Remove Cage").accesskit_node().is_disabled()); + click(&mut harness, "Remove Cage"); + assert!(harness.state().session.bake_meshes.cage.is_none()); +} + +#[test] +fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() { + let mut harness = harness(None); + assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode starts on the neutral material"); + harness.get_by_value("Neutral Material").click(); + harness.run_steps(3); + assert!(harness.query_by_label("UV checker").is_none(), "bake mode lists lighting and mesh maps only"); + harness.get_by_label("Material").click(); + harness.run_steps(3); + assert!(!harness.state().ui.bake_visualization.neutral_shown); + harness.get_by_value("Material"); +} + +#[test] +fn the_baking_visualization_panel_opens_like_the_reference_at_first_launch() { + let harness = harness(None); + for shown in ["Show for Selected Texture Set Only", "Mesh", "Matching Error", "Cage Surface", "Cage Wireframe Opacity"] { + harness.get_by_label(shown); + } + for closed in ["Missing Seams on Hard Edges", "Project Mesh", "Roughness"] { + assert!(harness.query_by_label(closed).is_none(), "{closed} sits in a section that starts closed"); + } + assert!(harness.state().ui.bake_visualization.missing_seams.shown, "missing seams are ticked in every reference capture"); +} + +#[test] +fn texture_set_names_show_in_full_beside_their_resolution() { + let mut harness = harness(None); + harness.state_mut().session.doc.project.texture_sets[0].name = "LowerTorso".into(); + harness.state_mut().ui.dock.focus(Panel::TextureSetList); + harness.run_steps(3); + + // "LowerTorso" is about 75 points wide; cut short it collapses to an ellipsis of about 20 + const FULL_NAME_MIN_WIDTH: f32 = 60.0; + + // The breadcrumb names the set too; the list row is the top-most + let row = harness.get_all_by_label("LowerTorso").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap(); + let width = row.rect().width(); + assert!(width >= FULL_NAME_MIN_WIDTH, "the name is not cut short: {width}"); +} + +#[test] +fn the_high_poly_scene_is_a_list_with_add_and_remove() { + let mut harness = harness(None); + harness.state_mut().session.add_high_poly_bytes("Gunhigh.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_label("Add High-Poly Meshes"); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "− waits for a selection"); + + harness.get_by_label("Gunhigh.obj").click(); + harness.run_steps(3); + harness.get_by_label("Remove").click(); + harness.run_steps(3); + assert!(harness.state().session.bake_meshes.high.is_empty()); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled()); +} + +#[test] +fn the_eye_greys_the_baking_meshes_and_holds_the_project_mesh() { + let mut harness = harness(None); + assert!(!harness.get_by_label("Mesh").accesskit_node().is_disabled(), "the eye starts off"); + harness.get_by_label("Hide Baking Meshes").click(); + harness.run_steps(3); + + for greyed in ["Mesh", "Matching Error", "Cage Surface", "Cage Wireframe Opacity"] { + assert!(harness.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed} is greyed"); + } + assert!(harness.state().ui.bake_visualization.project_mesh.shown); + + // The header, not its "Reset Project Mesh (LP)" button further right + let header = harness.get_all_by_label_contains("Project Mesh (LP)").min_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap(); + header.click(); + harness.run_steps(3); + assert!(harness.get_by_label("Project Mesh").accesskit_node().is_disabled(), "the project mesh stays on"); + assert!(!harness.get_by_label("Roughness").accesskit_node().is_disabled(), "the neutral material stays editable"); +} + +#[test] +fn picking_material_while_painting_keeps_bake_modes_neutral_material() { + let mut harness = harness(None); + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(3); + + // Painting mode shows the 3D and 2D views, each with a view menu; the 3D view's comes first + harness.get_all_by_value("Material").next().unwrap().click(); + harness.run_steps(3); + + // The menu entry, not the dropdown that shows the same word + let entry = harness.get_all_by_label("Material").find(|node| node.accesskit_node().role() != Role::ComboBox).unwrap(); + entry.click(); + harness.run_steps(3); + + assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); +} 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/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs new file mode 100644 index 00000000..12e4f08b --- /dev/null +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -0,0 +1,295 @@ +//! Each brush section header has a reset icon that puts only that section's settings back to their defaults + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::paint::{Alignment, BrushAlpha, BrushSettings, Particles, Symmetry}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The default window; Properties shows only the top of the brush there, so lower headers are scrolled to +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click to reach the brush settings and the panel +const SETTLE_FRAMES: usize = 3; + +/// Puts one section's fields of the first brush back to the second's values +type SectionReset = fn(&mut BrushSettings, &BrushSettings); + +/// Each brush section's title, a label shown only while it is open, whether it starts open, and its reset +const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ + ("Size", "Minimum size (%)", true, |brush, defaults| { + (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) + }), + ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) + }), + ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitters", "Size jitter", false, |brush, defaults| { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = + (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) + }), + ("Alignment and culling", "Backface culling", false, |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + }), + ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), + ("Lazy mouse", "Lazy mouse distance", false, |brush, defaults| brush.lazy = defaults.lazy), +]; + +/// A valid brush with every section field changed and a custom alpha that resets must preserve +fn changed_brush() -> BrushSettings { + BrushSettings { + size: 0.1, + min_size: 0.5, + screen_space: true, + flow: 0.5, + opacity: 0.6, + spacing: 0.5, + hardness: 0.9, + angle: 45.0, + follow_path: true, + jitter_size: 0.5, + jitter_angle: 0.4, + jitter_flow: 0.3, + jitter_position: 1.0, + alignment: Alignment::Camera, + backface_culling: false, + angle_fade: (30.0, 60.0), + depth: 2.0, + particles: Particles { enabled: true, count: 8, lifetime: 12, gravity: 0.5 }, + lazy: 50.0, + symmetry: Symmetry { x: true, y: true, z: true, radial: 4, axis: 2, ..Symmetry::default() }, + alpha: BrushAlpha::Star, + ..BrushSettings::default() + } +} + +/// The app showing the brush in Properties, set to `brush` +fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).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.state_mut().session.tool.brush = brush; + harness.run_steps(STARTUP_FRAMES); + + harness +} + +/// The reset icon on the header row titled `title` +fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { + let label = format!("{title}: Reset to defaults"); + harness + .query_all_by_role(egui::Role::Button) + .find(|node| node.accesskit_node().label().as_deref() == Some(label.as_str())) + .unwrap_or_else(|| panic!("no reset icon on the {title} header")) +} + +/// Scrolls the header titled `title` into view and clicks its reset icon +fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + reset_icon(harness, title).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn each_reset_puts_back_only_its_own_section() { + let defaults = BrushSettings::default(); + + for (title, _, _, reset_section) in SECTIONS { + let mut harness = app_with_brush(changed_brush()); + assert!(!reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is enabled once its section changed"); + let history = harness.state().session.history_labels(); + + click_reset(&mut harness, title); + + let mut expected = changed_brush(); + reset_section(&mut expected, &defaults); + assert_eq!(harness.state().session.tool.brush, expected, "resetting {title}"); + assert_eq!(harness.state().session.history_labels(), history, "resetting {title} adds no undo step"); + } +} + +/// Scrolls the header titled `title` into view and clicks the header itself, folding or unfolding it +fn click_header(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + let icon = reset_icon(harness, title).rect(); + harness.query_all_by_label(title).find(|label| label.rect().y_range().intersects(icon.y_range())).unwrap_or_else(|| panic!("no {title} header")).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn clicking_the_reset_icon_does_not_fold_or_unfold_the_section() { + for flip_first in [false, true] { + let mut harness = app_with_brush(changed_brush()); + if flip_first { + for (title, _, _, _) in SECTIONS { + click_header(&mut harness, title); + } + } + + for (title, body_label, starts_open, _) in SECTIONS { + let open = starts_open != flip_first; + + click_reset(&mut harness, title); + + assert_eq!(harness.query_by_label(body_label).is_some(), open, "{title} stays {}", if open { "open" } else { "closed" }); + } + } +} + +#[test] +fn at_the_defaults_the_reset_icons_are_inert() { + let mut harness = app_with_brush(BrushSettings::default()); + + for (title, body_label, starts_open, _) in SECTIONS { + assert!(reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is disabled at the defaults"); + + click_reset(&mut harness, title); + + assert_eq!(harness.query_by_label(body_label).is_some(), starts_open, "the click doesn't reach the {title} header"); + assert_eq!(harness.state().session.tool.brush, BrushSettings::default(), "the {title} reset is inert"); + } +} + +#[test] +fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { + for key in [egui::Key::Enter, egui::Key::Space] { + let mut harness = app_with_brush(changed_brush()); + reset_icon(&harness, "Size").focus(); + harness.run_steps(SETTLE_FRAMES); + assert!(reset_icon(&harness, "Size").is_focused()); + + harness.key_press(key); + harness.run_steps(SETTLE_FRAMES); + + let defaults = BrushSettings::default(); + let mut expected = changed_brush(); + (expected.size, expected.min_size, expected.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space); + assert_eq!(harness.state().session.tool.brush, expected, "resetting Size with {key:?}"); + } +} + +#[test] +fn reset_icons_identify_their_sections() { + let harness = app_with_brush(changed_brush()); + + for (title, _, _, _) in SECTIONS { + let label = format!("{title}: Reset to defaults"); + assert!(harness.query_by_role_and_label(egui::Role::Button, &label).is_some(), "the reset button must name its {title} section"); + } +} + +#[test] +fn narrow_headers_keep_title_clicks_separate_from_reset() { + use texturecraft_ui_egui::widgets::section_with_reset; + + for right_to_left in [false, true] { + for width in [120.0, 180.0, 300.0] { + let title = "Lazy mouse"; + let mut harness = Harness::builder().with_size(egui::vec2(width, 180.0)).with_context_setup(texturecraft_ui_egui::theme::install).build_ui_state( + |ui, resets| { + let alignment = if right_to_left { egui::Align::RIGHT } else { egui::Align::LEFT }; + ui.with_layout(egui::Layout::top_down(alignment), |ui| { + ui.style_mut().right_to_left = right_to_left; + if section_with_reset(ui, "narrow_section", title, false, false, |ui| { + ui.label("Section contents"); + }) { + *resets += 1; + } + }); + }, + 0_u32, + ); + harness.run_steps(STARTUP_FRAMES); + + let title_rect = harness.get_by_label(title).rect(); + let reset_label = format!("{title}: Reset to defaults"); + let reset_rect = harness.get_by_role_and_label(egui::Role::Button, &reset_label).rect(); + assert!(!title_rect.intersects(reset_rect), "title and reset overlap at width {width}, right_to_left={right_to_left}"); + assert!(reset_rect.left() >= 0.0 && reset_rect.right() <= width, "reset must stay inside the panel"); + + harness.get_by_label(title).click(); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(*harness.state(), 0, "clicking the title must not reset settings"); + assert!(harness.query_by_label("Section contents").is_some(), "clicking the title unfolds the section"); + + harness.get_by_role_and_label(egui::Role::Button, &reset_label).click(); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(*harness.state(), 1, "the reset remains clickable in a narrow panel"); + assert!(harness.query_by_label("Section contents").is_some(), "resetting leaves the section open"); + } + } +} + +#[test] +fn tab_visits_changed_resets_and_skips_default_resets() { + use texturecraft_ui_egui::widgets::section_with_reset; + + for at_default in [false, true] { + let mut harness = Harness::builder().with_size(egui::vec2(300.0, 180.0)).with_context_setup(texturecraft_ui_egui::theme::install).build_ui(|ui| { + let _ = ui.button("Before section"); + section_with_reset(ui, "tab_section", "Size", false, at_default, |_| {}); + let _ = ui.button("After section"); + }); + harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(egui::Role::Button, "Before section").focus(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.get_by_role_and_label(egui::Role::Button, "Before section").is_focused()); + let mut reset_was_focused = false; + + // Screen-reader mode also puts the header's labels in the focus order + for _ in 0..8 { + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + reset_was_focused |= harness.get_by_role_and_label(egui::Role::Button, "Size: Reset to defaults").is_focused(); + if harness.get_by_role_and_label(egui::Role::Button, "After section").is_focused() { + break; + } + } + + assert!(harness.get_by_role_and_label(egui::Role::Button, "After section").is_focused(), "Tab reaches the next control"); + assert_eq!(reset_was_focused, !at_default, "only an enabled reset belongs in the Tab order"); + } +} + +#[test] +fn overflowing_contents_do_not_push_resets_outside_the_panel() { + use texturecraft_ui_egui::widgets::section_with_reset; + + for right_to_left in [false, true] { + let width = 120.0; + let mut harness = Harness::builder().with_size(egui::vec2(width, 180.0)).with_context_setup(texturecraft_ui_egui::theme::install).build_ui_state( + |ui, resets| { + let alignment = if right_to_left { egui::Align::RIGHT } else { egui::Align::LEFT }; + ui.with_layout(egui::Layout::top_down(alignment), |ui| { + ui.style_mut().right_to_left = right_to_left; + + // A slider in an earlier section can expand the scroll area's content width + ui.allocate_exact_size(egui::vec2(400.0, 1.0), egui::Sense::hover()); + if section_with_reset(ui, "overflow_section", "Size", false, false, |_| {}) { + *resets += 1; + } + }); + }, + 0_u32, + ); + harness.run_steps(STARTUP_FRAMES); + let reset_rect = harness.get_by_role_and_label(egui::Role::Button, "Size: Reset to defaults").rect(); + assert!(reset_rect.left() >= 0.0 && reset_rect.right() <= width, "reset must stay visible when content overflows, right_to_left={right_to_left}"); + + harness.get_by_role_and_label(egui::Role::Button, "Size: Reset to defaults").click(); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(*harness.state(), 1, "overflowing contents must not block the reset"); + } +} 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..360dca82 --- /dev/null +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -0,0 +1,301 @@ +//! 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 escape_cancels_id_picking_with_a_hidden_rail_popup() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.log"); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Close"); + harness.key_press(egui::Key::Tab); + harness.run_steps(3); + assert!(harness.state().ui.hide_ui); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Close").is_none()); + assert!(harness.state().picking_id_color.is_some()); + 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(), "one Escape cancels ID picking despite the hidden popup"); + 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", &json!({"enabled": true})).unwrap(); + 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/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs new file mode 100644 index 00000000..fdd04351 --- /dev/null +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -0,0 +1,119 @@ +//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { + let start = harness.get_by_label(from).rect().center(); + let row_rect = harness.get_by_label(to).rect(); + let end = egui::pos2(row_rect.center().x, if below { row_rect.bottom() - 4.0 } else { row_rect.top() + 4.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); +} + +#[test] +fn dragging_an_effect_row_reorders_its_stack() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(order(&harness), [a, b, c]); + + // Rows show C, B, A; dropping A above C moves it to the top + drag(&mut harness, "Effect A", "Effect C", false); + assert_eq!(order(&harness), [b, c, a]); + + // Dropping A below B returns it to the bottom + drag(&mut harness, "Effect A", "Effect B", true); + assert_eq!(order(&harness), [a, b, c]); + + // Dropping C above A places it between A and B + drag(&mut harness, "Effect C", "Effect A", false); + assert_eq!(order(&harness), [a, c, b]); +} + +/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows. +#[test] +fn an_effect_row_sets_its_blend_mode_and_opacity() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect, effect_of(&harness).id.0); + + // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field + let row = harness.get_by_label("Effect A").rect(); + let pair_right = row.right() - 4.0; + let pair_left = pair_right - 82.0; + let mode_at = egui::pos2(pair_left + 20.0, row.center().y); + harness.drag_at(mode_at); + harness.drop_at(mode_at); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply); + + let history = harness.state().session.history_labels().len(); + let opacity_at = egui::pos2(pair_right - 20.0, row.center().y); + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); +} + +/// A drag whose first frame leaves the opacity unchanged still starts its own undo step: undo keeps the blend mode set before it +#[test] +fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + + let history = harness.state().session.history_labels().len(); + let opacity_at = harness.get_by_label("Opacity of Effect A").rect().center(); + // Equal right and down movement adds nothing to the value: the drag starts without a change + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at + egui::vec2(8.0, 8.0)); + harness.run_steps(2); + assert_eq!(effect_of(&harness).opacity, 1.0, "the drag started without changing the opacity"); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "the drag lowered the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(effect_of(&harness).opacity, 1.0); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); +} diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs new file mode 100644 index 00000000..3a4a2e63 --- /dev/null +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -0,0 +1,193 @@ +//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all). + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::json; +use texturecraft_engine::core::{EffectKind, LayerId}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample session with its first generator effect selected, and that effect's id. +fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let (layer, effect) = session + .doc + .project + .layers + .values() + .find_map(|layer| { + let mask_effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()); + layer.content_effects.iter().chain(mask_effects).find(|effect| matches!(effect.kind, EffectKind::Generator(_))).map(|effect| (layer.id, effect.id)) + }) + .unwrap(); + texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + (harness, effect) +} + +fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.global.balance, + _ => panic!("a generator"), + } +} + +/// The track under the slider labelled `label` (the row below the label). +fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { + let label_rect = harness.get_by_label(label).rect(); + egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0)) +} + +#[test] +fn dragging_a_slider_applies_it() { + let (mut harness, effect) = selected_generator(); + assert_eq!(balance(&harness, effect), 0.5); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); +} + +/// A generator slider applies while it is dragged (the texture follows the pointer), and the +/// whole drag is one undo step. +#[test] +fn dragging_a_generator_slider_applies_live_as_one_undo_step() { + let (mut harness, effect) = selected_generator(); + let level = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.level, + _ => panic!("a generator"), + }; + let steps = harness.state().session.history_labels().len(); + let track_rect = track(&harness, "Level"); + let point_at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y); + harness.drag_at(point_at(10.0)); + harness.run_steps(2); + let mut last = 0.0; + for x in [60.0, 160.0] { + harness.hover_at(point_at(x)); + harness.run_steps(2); + assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); + last = level(&harness); + } + harness.drop_at(point_at(160.0)); + harness.run_steps(3); + assert_eq!(level(&harness), last); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); +} + +/// The combo box in the row of the levels editor's Reset button. +fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let row = harness.get_by_label("Reset").rect().center().y; + harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +} + +/// A content levels effect offers a channel for its histogram; picking one keeps it selected. +#[test] +fn content_levels_pick_the_histogram_channel() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); + texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); + channel_picker(&harness).click(); + harness.run_steps(2); + harness.get_by_label("Roughness").click(); + harness.run_steps(3); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays"); +} + +#[test] +fn clicking_a_slider_track_applies_it() { + let (mut harness, effect) = selected_generator(); + let track_rect = track(&harness, "Global balance"); + let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); +} + +/// The number field in the row of the slider labelled `label`. +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +} + +/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person. +fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { + number_field(harness, "Global balance").focus(); + harness.run_steps(2); + for key in keys { + harness.key_press(*key); + harness.run_steps(1); + } + for character in text.chars() { + number_field(harness, "Global balance").type_text(&character.to_string()); + harness.run_steps(1); + } +} + +#[test] +fn a_value_typed_in_the_number_field_applies() { + let (mut harness, effect) = selected_generator(); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.25); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); +} + +/// Dragging the track while the number field has focus drops what was typed there: leaving the +/// field afterwards does not undo the drag. +#[test] +fn a_track_drag_drops_text_typed_in_the_number_field() { + let (mut harness, effect) = selected_generator(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5"); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + let dragged = balance(&harness, effect); + assert!(dragged < 0.25, "the drag applies: {dragged}"); + // Leave whatever has focus: a click on empty space + harness.drag_at(egui::pos2(5.0, 1390.0)); + harness.drop_at(egui::pos2(5.0, 1390.0)); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); +} + +/// Leaving the number field without typing, or with Escape, keeps the value (not the rounded +/// text the field shows) and makes no undo step. +#[test] +fn leaving_the_number_field_unchanged_keeps_the_value() { + let (mut harness, effect) = selected_generator(); + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "balance": 0.333})).unwrap(); + harness.run_steps(2); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[], ""); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333, "left without typing"); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); + assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); + assert!(number_field(&harness, "Global balance").is_focused()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333); + // Typing the value it already has is no edit either + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(harness.state().session.history_labels().len(), steps); +} 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/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs new file mode 100644 index 00000000..d09cfc0c --- /dev/null +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -0,0 +1,141 @@ +//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, Source}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::theme::Brightness; + +/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties 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, 2400.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 generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generator { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + _ => panic!("expected a generator"), + } +} + +/// Drags the track under slider `label` to the right. +fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_label(label).rect(); + let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0); + let end = start + egui::vec2(120.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); +} + +#[test] +fn global_blur_applies_as_one_undo_step() { + let (mut harness, effect) = harness(false); + let history = harness.state().session.history_labels().len(); + drag_slider(&mut harness, "Global blur"); + assert!(generator(&harness, effect).global.blur > 0.0); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + harness.state_mut().session.undo().unwrap(); + assert_eq!(generator(&harness, effect).global.blur, 0.0); +} + +#[test] +fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { + let (mut harness, effect) = harness(false); + let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.run_steps(3); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); +} + +#[test] +fn changing_kind_in_the_panel_preserves_the_effect() { + let (mut harness, effect) = harness(false); + let history = harness.state().session.history_labels().len(); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Curvature")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Dirt").click(); + harness.run_steps(3); + + assert_eq!(generator(&harness, effect).kind, GeneratorKind::Dirt); + assert_eq!(harness.state().session.history_labels().len(), history + 1); +} + +#[test] +fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { + let (mut harness, effect) = harness(false); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Uniform value").click(); + harness.run_steps(3); + assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_)))); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Mesh map").click(); + harness.run_steps(3); + assert!(generator(&harness, effect).inputs.is_empty()); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn generator_panel_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, effect) = harness(true); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap(); + + for section in ["Attributes", "Resolution"] { + harness.get_by_label(section).click(); + harness.run_steps(3); + } + harness.run_steps(6); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-panel-sections-open-{name}.png"))).unwrap(); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + + let edits = json!({"effect": effect.0, "blur": 0.3, "balance": 0.6, "contrast": 0.4, "resolutionFactor": -2}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.state_mut().session.update(); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-adjusted.png")).unwrap(); + + // The effect row with its blend mode and opacity, in the layer stack + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs new file mode 100644 index 00000000..7103161b --- /dev/null +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -0,0 +1,189 @@ +//! A click on a step of the History panel goes back or forward to it. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// Show document history so row clicks exercise the same command dispatch as the application +fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.focus(Panel::History); + harness.run_steps(4); + harness +} + +/// Three document rows provide an intermediate target that detects both short and excessive jumps +fn renamed_session() -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + session +} + +/// Canceling a preview can be its own undo or part of undoing the first placed point +#[test] +fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { + for placed in [false, true] { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + if placed { + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + for point in [Vec3::new(0.2, 0.5, 0.0), Vec3::new(0.5, 0.3, 0.0), Vec3::new(0.8, 0.5, 0.0)] { + session.append_path_point(point, true); + session.path_live().unwrap(); + } + } else { + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + } + session.path_checkpoint(); + let mut harness = history_harness(session); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), 2); + assert!(harness.state().session.tool.path.points.is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); + } +} + +/// A row jump traverses point history, while the Undo and Redo buttons still take one point step +#[test] +fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + session.move_path_point(0, original[0], true); + session.path_live().unwrap(); + session.path_checkpoint(); + let done = session.history_labels().len(); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, moved); + assert_eq!(harness.state().session.history_labels().len(), done); + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_by_label("Edit path 1").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), done - 1); + assert!(harness.state().session.tool.path.points.is_empty()); +} + +/// Incomplete filled curves keep point redo separate from the document redo rows +#[test] +fn history_redo_jump_accounts_for_point_steps_without_changing_single_steps() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let report = + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.3], [0.8, 0.5]], "closed": true, "fill": true, "commit": true})).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + let done = session.history_labels().len(); + execute(&mut session, "edit.undo", &json!({"steps": 3})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + + // Partial filled shapes do not repaint; their undo/redo leaves document redo available + for points in [json!([[0.2, 0.5], [0.8, 0.5]]), json!([[0.2, 0.5]]), json!([[0.2, 0.5], [0.8, 0.5]])] { + session.path_checkpoint(); + execute(&mut session, "tool.path", &json!({"uvPoints": points})).unwrap(); + } + for _ in 0..3 { + session.undo().unwrap(); + } + assert_eq!(session.redo_labels().len(), 3); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points.len(), 2); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + + harness.get_all_by_label("Rename layer (undone)").last().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step C"); + assert_eq!(harness.state().session.history_labels().len(), done); + assert!(harness.state().session.redo_labels().is_empty()); + assert!(harness.state().session.tool.path.points.is_empty()); +} + +/// Returning to the current document row cancels a draft without undoing a document step +#[test] +fn clicking_the_current_history_row_cancels_a_draft() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + let mut harness = history_harness(session); + + harness.get_by_label("Project opened").click(); + harness.run_steps(3); + + assert!(harness.state().session.tool.path.points.is_empty()); + assert!(harness.state().session.history_labels().is_empty()); + assert!(harness.state().session.redo_labels().is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); +} + +#[test] +fn clicking_a_history_step_returns_to_it() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + for name in ["Step A", "Step B", "Step C"] { + texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap(); + } + let done = session.history_labels().len(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.dock.focus(Panel::History); + h.run_steps(4); + let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone(); + // The first state: everything undone, and listed as undone. + h.get_by_label("Project opened").click(); + h.run_steps(3); + assert!(!h.state().session.can_undo()); + assert_eq!(h.state().session.redo_labels().len(), done); + // The first undone row is the next step: one redo. + h.get_all_by_label("Rename layer (undone)").next().unwrap().click(); + h.run_steps(3); + assert_eq!(h.state().session.history_labels().len(), 1); + assert_eq!(h.state().session.redo_labels().len(), done - 1); + // The last undone row: all the way forward again. + h.get_all_by_label("Rename layer (undone)").last().unwrap().click(); + h.run_steps(3); + assert_eq!(name(&h), "Step C"); + assert!(!h.state().session.can_redo()); +} 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/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs new file mode 100644 index 00000000..50e4458e --- /dev/null +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -0,0 +1,122 @@ +//! The Layers panel rows: content and mask thumbnails select their own target, effect groups +//! fold without touching the document, and the thumbnails arrive from the worker. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// A session whose top layer, "Masked fill", has one content effect and a mask with one effect. +fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer")); + execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Masked fill"})).unwrap(); + execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + (h, layer) +} + +/// Centre of the content (`mask` false) or mask thumbnail of the top-level, non-folder row +/// labelled `name`: after the 7-point edge, the 20-point eye column, then 36-point squares 4 apart. +fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2 { + let row = h.get_by_label(name).rect(); + let x = row.left() + 7.0 + 20.0 + 18.0 + if mask { 40.0 } else { 0.0 }; + egui::pos2(x, row.center().y) +} + +/// The `label` header that follows the "Masked fill" row (other layers have groups too). +fn header(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + let top = h.get_by_label("Masked fill").rect().top(); + let at = h.get_all_by_label(label).map(|n| n.rect()).filter(|r| r.top() > top).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap().center(); + click(h, at); +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + h.drag_at(at); + h.drop_at(at); + h.run_steps(3); +} + +#[test] +fn mask_and_content_thumbnails_select_their_own_target() { + let (mut h, layer) = harness(); + let at = thumb(&h, "Masked fill", true); + click(&mut h, at); + assert_eq!(h.state().session.selected_layer(), Some(layer)); + assert_eq!(h.state().session.target, StackTarget::Mask, "the mask thumbnail routes to the mask"); + let at = thumb(&h, "Masked fill", false); + click(&mut h, at); + assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); + // Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity) + let row = h.get_by_label("Effect A").rect(); + click(&mut h, row.center()); + assert!(matches!(h.state().session.target, StackTarget::Effect(_))); +} + +#[test] +fn folding_an_effect_group_hides_its_rows_without_changing_the_document() { + let (mut h, _) = harness(); + let (project, undo) = (h.state().session.doc.project.clone(), h.state().session.revision); + assert!(h.query_by_label("Effect A").is_some() && h.query_by_label("Effect M").is_some()); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_none(), "folded content effects are hidden"); + assert!(h.query_by_label("Effect M").is_some(), "the mask group stays open"); + header(&mut h, "Mask effects"); + assert!(h.query_by_label("Effect M").is_none()); + assert_eq!(h.state().session.doc.project, project); + assert_eq!(h.state().session.revision, undo, "folding is not an edit"); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_some(), "unfolds again"); +} + +#[test] +fn visible_rows_get_their_thumbnails() { + let (mut h, layer) = harness(); + let content = ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let mask = ThumbTarget::Mask { layer }; + let t0 = std::time::Instant::now(); + while !(h.state().layer_panel.service().is_fresh(content) && h.state().layer_panel.service().is_fresh(mask)) { + assert!(t0.elapsed().as_secs() < 60, "thumbnails never arrived"); + h.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + // Rows, mask, and every effect stage on screen were asked for: well under the cache size. + assert!(h.state().layer_panel.service().cached() >= 4); +} + +#[test] +fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { + use craft_ui::docking::Node; + use craft_ui::layout::SplitSize; + use texturecraft_ui_egui::docking::Dock; + + let (mut h, layer) = harness(); + for _ in 0..6 { + execute(&mut h.state_mut().session, "layer.group", &Value::Null).unwrap(); + } + let mut workspace = h.state().ui.dock.workspace().clone(); + let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; + let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; + *size = SplitSize::Ratio(0.99); + h.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + h.run_steps(4); + + let row = h.get_by_label("Effect A").rect(); + assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); + let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0); + click(&mut h, egui::pos2(row.left() + 15.0 + indent, row.center().y)); + + let content = &h.state().session.doc.project.layers[&layer].content_effects; + assert!(!content.iter().find(|effect| effect.name == "Effect A").unwrap().visible, "the compact eye toggles the effect instead of missing the panel"); +} diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs new file mode 100644 index 00000000..3fef7357 --- /dev/null +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -0,0 +1,432 @@ +//! The levels editor in Properties: handles, typed values and Reset, Auto and Invert edit the effect + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable, by}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, Levels}; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Histogram buckets and Auto's share, as in levels_properties.rs +const HISTOGRAM_BUCKETS: usize = 64; +const AUTO_MIN_SHARE: f64 = 0.001; + +/// Labels of the five handles +const HANDLE_LABELS: [&str; 5] = ["Input low", "Input high", "Gamma", "Output low", "Output high"]; + +/// Corners of a handle's pentagon pointer +const HANDLE_POINTER_CORNERS: usize = 5; + +/// A clouds mask under a levels effect added by `command` with `params`, selected, and its id +fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for (id, params) in [ + ("layer.add.fill", json!({"color": [0.8, 0.3, 0.1]})), + ("mask.add.black", Value::Null), + ("effect.add.fill", json!({"target": "mask", "procedural": "clouds"})), + (command, params), + ] { + execute(&mut session, id, ¶ms).unwrap(); + } + let effect = levels_effect(&session); + open(session, effect) +} + +fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraftApp>, LayerId) { + let (layer, _) = session.doc.project.effect(effect).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + + // Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The newest levels effect in the project +fn levels_effect(session: &Session) -> LayerId { + let layers = session.doc.project.layers.values(); + let effects = layers.flat_map(|layer| layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| mask.effects.iter()))); + effects.filter(|effect| matches!(effect.kind, EffectKind::Levels(_))).map(|effect| effect.id).max_by_key(|id| id.0).unwrap() +} + +fn levels(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Levels { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Levels(levels) => *levels, + other => panic!("a levels effect, found {other:?}"), + } +} + +fn undo_steps(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} + +fn handle(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Pos2 { + harness.get_by_role_and_label(Role::Slider, label).rect().center() +} + +/// The button labelled `label` (an effect in the stack can share its name) +fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_by_role_and_label(Role::Button, label) +} + +/// Presses at `from`, moves in a few steps to `to` (one frame each, like a hand) and releases +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) { + harness.drag_at(from); + 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.drop_at(to); + harness.run_steps(3); +} + +fn set_levels(harness: &mut Harness<'_, TextureCraftApp>, effect: LayerId, mut params: Value) { + params["effect"] = json!(effect.0); + execute(&mut harness.state_mut().session, "effect.set", ¶ms).unwrap(); + harness.run_steps(3); +} + +#[test] +fn dragging_each_handle_edits_its_value_in_one_undo_step() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + for (label, offset_x) in [("Input low", 80.0), ("Input high", -80.0), ("Gamma", 30.0), ("Output low", 60.0), ("Output high", -60.0)] { + let before = levels(&harness, effect); + let steps = undo_steps(&harness); + let at = handle(&harness, label); + + drag(&mut harness, at, at + egui::vec2(offset_x, 0.0)); + + let after = levels(&harness, effect); + let changed: Vec<&str> = [ + ("Input low", before.in_low != after.in_low), + ("Input high", before.in_high != after.in_high), + ("Gamma", before.gamma != after.gamma), + ("Output low", before.out_low != after.out_low), + ("Output high", before.out_high != after.out_high), + ] + .into_iter() + .filter_map(|(name, changed)| changed.then_some(name)) + .collect(); + assert_eq!(changed, [label], "dragging {label} changes only it: {before:?} -> {after:?}"); + assert_eq!(undo_steps(&harness), steps + 1, "dragging {label} is one undo step"); + } + + let dragged = levels(&harness, effect); + assert!(dragged.in_low > 0.0 && dragged.in_high < 1.0 && dragged.out_low > 0.0 && dragged.out_high < 1.0, "{dragged:?}"); + assert!(dragged.gamma < 1.0, "gamma right of the middle darkens: {}", dragged.gamma); +} + +#[test] +fn handles_stop_at_their_neighbours() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inLow": 0.2, "inHigh": 0.6, "outLow": 0.3, "outHigh": 0.7})); + let far_right = egui::vec2(1000.0, 0.0); + for label in ["Input low", "Gamma", "Output low"] { + let at = handle(&harness, label); + + drag(&mut harness, at, at + far_right); + } + + let edited = levels(&harness, effect); + assert!((edited.in_low - 0.59).abs() < 1e-4, "input low stops below input high: {edited:?}"); + assert_eq!(edited.gamma, 0.01, "gamma stops at its lowest value"); + let gap = handle(&harness, "Input high").x - handle(&harness, "Gamma").x; + assert!((0.0..1.0).contains(&gap), "the gamma handle reaches input high over this narrow range: {gap} pt apart"); + assert!((edited.out_low - 0.69).abs() < 1e-4, "output low stops below output high: {edited:?}"); +} + +#[test] +fn output_handles_keep_their_side_once_inverted() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "outLow": 0.2, "outHigh": 0.8})); + button(&harness, "Invert").click(); + harness.run_steps(3); + let inverted = levels(&harness, effect); + assert_eq!((inverted.out_low, inverted.out_high), (0.8, 0.2)); + + let at = handle(&harness, "Output high"); + drag(&mut harness, at, at + egui::vec2(1000.0, 0.0)); + + let edited = levels(&harness, effect); + assert!((edited.out_high - 0.79).abs() < 1e-4, "output high stops below output low: {edited:?}"); +} + +#[test] +fn reset_and_invert_are_one_undo_step_each() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert!(button(&harness, "Reset").accesskit_node().is_disabled(), "nothing to reset at the defaults"); + set_levels(&mut harness, effect, json!({"inLow": 0.1, "inHigh": 0.9, "gamma": 2.0, "outLow": 0.2, "outHigh": 0.7})); + + let steps = undo_steps(&harness); + button(&harness, "Invert").click(); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2 }); + assert_eq!(undo_steps(&harness), steps + 1); + + button(&harness, "Reset").click(); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect), Levels::default()); + assert_eq!(undo_steps(&harness), steps + 2); +} + +#[test] +fn auto_fits_the_input_range_to_the_histogram() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "gamma": 1.5})); + let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap(); + let total: u32 = counts.iter().sum(); + let holds = |count: &u32| f64::from(*count) > f64::from(total) * AUTO_MIN_SHARE; + let low = counts.iter().position(holds).unwrap() as f32 / HISTOGRAM_BUCKETS as f32; + let high = (counts.iter().rposition(holds).unwrap() + 1) as f32 / HISTOGRAM_BUCKETS as f32; + assert!(low > 0.0 || high < 1.0, "the clouds don't fill the whole range: {low}..{high}"); + + button(&harness, "Auto").click(); + harness.run_steps(3); + + let edited = levels(&harness, effect); + assert_eq!((edited.in_low, edited.in_high), (low, high)); + assert_eq!(edited.gamma, 1.5, "Auto leaves gamma"); + + let steps = undo_steps(&harness); + button(&harness, "Auto").click(); + harness.run_steps(3); + + assert_eq!(undo_steps(&harness), steps, "Auto again changes nothing, so it adds no undo step"); +} + +/// Double-clicks `label`'s handle, then types `text` into its number field with the value selected +fn type_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { + let at = handle(harness, label); + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false, true, false] { + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + } + harness.run_steps(2); + for character in text.chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } +} + +#[test] +fn a_value_typed_after_double_clicking_a_handle_applies() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + + type_value(&mut harness, "Gamma", "2.5"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect).gamma, 2.5); + assert_eq!(undo_steps(&harness), steps + 1); +} + +#[test] +fn focusing_exact_entry_moves_nothing_in_the_panel() { + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let buttons = |harness: &Harness<'_, TextureCraftApp>| ["Reset", "Auto", "Invert"].map(|label| button(harness, label).rect()); + let before = buttons(&harness); + + type_value(&mut harness, "Output low", ""); + + assert!(harness.query_all(by().role(Role::TextInput)).any(|node| node.is_focused()), "the number field has focus"); + assert_eq!(buttons(&harness), before); +} + +#[test] +fn escape_drops_a_typed_value() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + + type_value(&mut harness, "Output low", "0.4"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect), Levels::default()); + assert_eq!(undo_steps(&harness), steps); + assert!(harness.query_by_value("0.4").is_none(), "the draft was discarded"); +} + +#[test] +fn a_typed_value_keeps_input_low_below_input_high() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inHigh": 0.5})); + type_value(&mut harness, "Input low", "0.9"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert!((levels(&harness, effect).in_low - 0.49).abs() < 1e-4, "{:?}", levels(&harness, effect)); +} + +#[test] +fn the_levels_filter_shows_the_same_editor() { + let (harness, _) = levels_harness("effect.add.filter", json!({"target": "mask", "filter": "levels"})); + for label in ["Input low", "Gamma", "Input high", "Output low", "Output high"] { + harness.get_by_role_and_label(Role::Slider, label); + } + for button in ["Reset", "Auto", "Invert"] { + harness.get_by_role_and_label(Role::Button, button); + } +} + +/// Bounds of the handle pointers in paint order, the last one drawn on top +fn painted_handles(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let centres = HANDLE_LABELS.map(|label| handle(harness, label)); + let pointers = harness.output().shapes.iter().filter_map(|clipped| match &clipped.shape { + egui::Shape::Path(path) if path.closed && path.points.len() == HANDLE_POINTER_CORNERS => Some(egui::Rect::from_points(&path.points)), + _ => None, + }); + pointers.filter(|bounds| centres.iter().any(|centre| bounds.expand(1.0).contains(*centre))).collect() +} + +#[test] +fn the_hovered_handle_is_painted_on_top() { + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert_eq!(painted_handles(&harness).len(), HANDLE_LABELS.len(), "every handle is painted once"); + + for label in HANDLE_LABELS { + let at = handle(&harness, label); + harness.hover_at(at); + harness.run_steps(2); + + let on_top = painted_handles(&harness).last().copied().unwrap(); + assert!(on_top.expand(1.0).contains(at), "{label} is painted last while hovered: {on_top:?} vs {at:?}"); + } +} + +#[test] +fn number_fields_are_labelled_and_stay_in_one_row() { + let (harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + + let fields = HANDLE_LABELS.map(|label| harness.get_by_role_and_label(Role::TextInput, label).rect()); + let row = fields[0].center().y; + assert!(fields.iter().all(|field| (field.center().y - row).abs() < 1.0), "number fields must share a row: {fields:?}"); +} + +#[test] +fn keyboard_and_accessibility_actions_edit_handles() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + + harness.get_by_role_and_label(Role::Slider, "Input low").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::ArrowRight); + harness.run_steps(3); + + assert!(levels(&harness, effect).in_low > 0.0); + assert_eq!(undo_steps(&harness), steps + 1); + + harness.get_by_role_and_label(Role::Slider, "Gamma").increment_accesskit(); + harness.run_steps(3); + + assert!(levels(&harness, effect).gamma > 1.0); + + harness.get_by_role_and_label(Role::Slider, "Output high").set_value_accesskit(0.75); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect).out_high, 0.75); + assert_eq!(undo_steps(&harness), steps + 3); +} + +#[test] +fn invalid_typed_values_stay_open_with_feedback() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + + for text in ["invalid", "NaN", "inf"] { + type_value(&mut harness, "Gamma", text); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + let fields: Vec<_> = harness.query_all(by().role(Role::TextInput)).map(|node| (node.is_focused(), node.value())).collect(); + assert!(fields.iter().any(|(focused, value)| *focused && value.as_deref() == Some(text)), "{text}: {fields:?}"); + harness.get_by_label("Enter a finite number"); + assert_eq!(levels(&harness, effect), Levels::default()); + assert_eq!(undo_steps(&harness), steps); + + harness.key_press(egui::Key::Escape); + // Keep the next double-click separate from this one + harness.run_steps(30); + } +} + +#[test] +fn opening_exact_entry_does_not_round_the_saved_value() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "gamma": 1.23456})); + let steps = undo_steps(&harness); + + type_value(&mut harness, "Gamma", ""); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect).gamma, 1.23456); + assert_eq!(undo_steps(&harness), steps); +} + +#[test] +fn keyboard_entry_can_correct_an_invalid_value() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + + harness.get_by_role_and_label(Role::Slider, "Gamma").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); + assert!(harness.get_by_role_and_label(Role::TextInput, "Gamma").is_focused()); + + harness.get_by_role_and_label(Role::TextInput, "Gamma").type_text("bad"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + harness.get_by_label("Enter a finite number"); + + harness.get_by_role_and_label(Role::TextInput, "Gamma").set_text_value_accesskit("2.5"); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect).gamma, 2.5); + assert_eq!(undo_steps(&harness), steps + 1); + assert!(harness.query_by_label("Enter a finite number").is_none()); +} + +#[test] +fn dragging_near_a_handle_uses_the_larger_target() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let at = handle(&harness, "Gamma") + egui::vec2(9.0, 9.0); + let steps = undo_steps(&harness); + + drag(&mut harness, at, at + egui::vec2(30.0, 0.0)); + + assert!(levels(&harness, effect).gamma < 1.0); + assert_eq!(undo_steps(&harness), steps + 1); +} + +#[test] +fn number_fields_commit_on_focus_loss() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inLow": 0.2, "inHigh": 0.8})); + let steps = undo_steps(&harness); + + harness.get_by_role_and_label(Role::TextInput, "Input low").focus(); + harness.run_steps(2); + harness.get_by_role_and_label(Role::TextInput, "Input low").set_text_value_accesskit("0.3"); + harness.run_steps(2); + harness.get_by_role_and_label(Role::TextInput, "Gamma").focus(); + harness.run_steps(3); + + assert_eq!(levels(&harness, effect), Levels { in_low: 0.3, in_high: 0.8, ..Levels::default() }); + assert_eq!(undo_steps(&harness), steps + 1); +} + +#[test] +fn replacing_effects_releases_old_histograms() { + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + + for _ in 0..20 { + execute(&mut harness.state_mut().session, "effect.remove", &Value::Null).unwrap(); + execute(&mut harness.state_mut().session, "effect.add.levels", &json!({"target": "mask"})).unwrap(); + harness.run_steps(3); + } + + let cached = harness.ctx.data(|data| data.count::<(u64, std::sync::Arc>)>()); + assert_eq!(cached, 1, "only the current effect's histogram remains cached"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs new file mode 100644 index 00000000..41b4c8cc --- /dev/null +++ b/crates/ui-egui/tests/it/main.rs @@ -0,0 +1,43 @@ +//! 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_job_mesh; +mod bake_mode; +mod brush_drag; +mod brush_section_reset; +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 generator_panel; +mod history_panel; +mod layer_clipboard; +mod layer_rename; +mod layers_panel; +mod levels_editor; +mod mask_value_swap; +mod new_project_baked_maps; +mod path_in_view; +mod path_list; +mod pen_pressure; +mod polygon_fill; +mod properties_popup; +mod rail; +mod shelf_drop; +mod shelf_hover_preview; +mod shelf_panel; +mod shift_lines_2d; +mod shortcut_keys; +mod skew_paint; +mod split_divider; +mod start_window; +mod tool_availability; +mod toolbar; + +mod symmetry; diff --git a/crates/ui-egui/tests/it/mask_value_swap.rs b/crates/ui-egui/tests/it/mask_value_swap.rs new file mode 100644 index 00000000..d5f22ebc --- /dev/null +++ b/crates/ui-egui/tests/it/mask_value_swap.rs @@ -0,0 +1,73 @@ +//! X inverts the mask value while a mask is the paint target; Ctrl+X still cuts the layer + +use egui_kittest::Harness; +use texturecraft_engine::StackTarget; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample session with a white mask on its selected layer, painting that mask +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + texturecraft_engine::execute(&mut session, "mask.add.white", &serde_json::Value::Null).unwrap(); + session.target = StackTarget::Mask; + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + + harness +} + +fn mask_value(harness: &Harness<'_, TextureCraftApp>) -> f32 { + harness.state().session.tool.mask_value +} + +#[test] +fn x_inverts_the_mask_value_and_back() { + let mut harness = harness(); + harness.state_mut().session.tool.mask_value = 0.25; + + harness.key_press(egui::Key::X); + harness.run_steps(3); + + assert_eq!(mask_value(&harness), 0.75); + + harness.key_press(egui::Key::X); + harness.run_steps(3); + + assert_eq!(mask_value(&harness), 0.25); +} + +#[test] +fn x_does_nothing_while_painting_layer_content() { + let mut harness = harness(); + harness.state_mut().session.target = StackTarget::Content; + harness.state_mut().session.tool.mask_value = 0.25; + + harness.key_press(egui::Key::X); + harness.run_steps(3); + + assert_eq!(mask_value(&harness), 0.25); +} + +#[test] +fn ctrl_x_still_cuts_the_layer_while_a_mask_is_the_target() { + let mut harness = harness(); + let layer = harness.state().session.selected_layer().unwrap(); + + harness.event(egui::Event::Cut); + harness.run_steps(3); + + assert!(!harness.state().session.doc.project.layers.contains_key(&layer), "Ctrl+X removes the layer"); +} + +#[test] +fn ctrl_x_is_not_x() { + let mut harness = harness(); + + // With cut unbound, nothing else may answer Ctrl+X + harness.state_mut().ui.keymap.insert("layer.cut".into(), String::new()); + harness.state_mut().session.tool.mask_value = 0.25; + + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::X); + harness.run_steps(3); + + assert_eq!(mask_value(&harness), 0.25); +} 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/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs new file mode 100644 index 00000000..819a5468 --- /dev/null +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -0,0 +1,204 @@ +//! The Path tool in the 2D view: placing previews the path, and points are edited where they are drawn + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +type AppHarness<'a> = Harness<'a, TextureCraftApp>; + +// Three points left to right across the middle of the 2D view's texture +const A: Pos2 = pos2(600.0, 500.0); +const B: Pos2 = pos2(700.0, 500.0); +const C: Pos2 = pos2(800.0, 500.0); + +/// A Path tool session whose texture fills the test pointer coordinates in the 2D view +fn harness() -> AppHarness<'static> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + // Tall enough that the 2D view's texture square takes A, B and C + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.layout = ViewLayout::Only2D; + h.run_steps(4); + h +} + +/// Advance one input frame, optionally changing the primary button's state +fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { + let events = &mut h.input_mut().events; + events.push(Event::PointerMoved(pos)); + if let Some(pressed) = pressed { + events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.step(); +} + +/// Send a complete pointer click and allow the resulting preview to update +fn click(h: &mut AppHarness<'_>, at: Pos2) { + pointer(h, at, Some(true)); + pointer(h, at, Some(false)); + h.run_steps(2); +} + +/// Move through several frames so the test exercises drag grouping as well as its final position +fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { + pointer(h, from, Some(true)); + for k in 1..=6 { + pointer(h, from + (to - from) * (k as f32 / 6.0), None); + } + pointer(h, to, Some(false)); + h.run_steps(2); +} + +/// Dispatch an unmodified tool key and settle the resulting UI state +fn key(h: &mut AppHarness<'_>, key: Key) { + h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// The path sublayers of the selected layer: (id, stored paths) +fn path_sublayers(h: &AppHarness<'_>) -> Vec<(LayerId, usize)> { + let s = &h.state().session; + let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap(); + layer.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id, p.len()))).collect() +} + +/// Channel images painted in path sublayer `eid` +fn painted_channels(h: &AppHarness<'_>, eid: LayerId) -> usize { + h.state().session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == eid).count() +} + +#[test] +fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() { + let mut h = harness(); + let steps = h.state().session.history_labels().len(); + for at in [A, B, C] { + click(&mut h, at); + } + assert_eq!(h.state().session.tool.path.points.len(), 3); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("the preview is a path in a path sublayer: {:?}", path_sublayers(&h)) }; + assert!(painted_channels(&h, eid) > 0, "the preview painted"); + assert_eq!(h.state().session.history_labels().len(), steps, "no undo step while placing"); + key(&mut h, Key::Enter); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert_eq!(h.state().session.undo_label(), Some("Path")); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), vec![(eid, 1)]); +} + +/// Applying with the pointer commits the preview without leaving the current texture set +#[test] +fn apply_button_commits_the_path_in_the_current_texture_set() { + let mut h = harness(); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + let steps = h.state().session.history_labels().len(); + let texture_set = h.state().session.ts(); + for at in [A, B, C] { + click(&mut h, at); + } + let paths = path_sublayers(&h); + let preview = h.state().session.doc.pixels.layers.clone(); + + // Path controls share the horizontally scrolling brush toolbar + h.get_all_by_label("Apply").next().unwrap().scroll_to_me(); + h.run_steps(30); + assert!(!h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + h.get_all_by_label("Apply").next().unwrap().click(); + h.run_steps(2); + + assert_eq!(h.state().session.ts(), texture_set); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), paths); + assert_eq!(h.state().session.doc.pixels.layers, preview); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); +} + +#[test] +fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + key(&mut h, Key::Enter); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("one path") }; + let stored = |h: &AppHarness<'_>| h.state().session.paths(eid).unwrap()[0].points.clone(); + let before = stored(&h); + let steps = h.state().session.history_labels().len(); + + // A click on the path's curve opens it for editing without repainting it + click(&mut h, A.lerp(B, 0.5)); + assert_eq!(h.state().session.tool.path.editing, Some((eid, 0))); + assert_eq!(h.state().session.history_labels().len(), steps, "opening a path repaints nothing"); + + drag(&mut h, B, B + egui::vec2(0.0, 60.0)); + let after = stored(&h); + assert_eq!(after.len(), 3); + assert_eq!((after[0], after[2]), (before[0], before[2])); + assert!(after[1][1] > before[1][1], "the dragged point moved down: {:?} -> {:?}", before[1], after[1]); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "the edit is one step"); +} + +#[test] +fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { + let mut session = + texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [260, 210]], "viewport": [400, 400], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(4); + let view_3d = harness.state().viewport_rect; + let view_2d_center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + + click(&mut harness, view_2d_center); + + assert_eq!(harness.state().session.tool.path, path); + assert_eq!(harness.state().session.doc.project, before.project); + assert_eq!(harness.state().session.doc.pixels.layers, before.pixels.layers); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + let path = |h: &AppHarness<'_>| h.state().session.tool.path.clone(); + let before = path(&h).points; + click(&mut h, B.lerp(C, 0.5)); + let after = path(&h); + assert_eq!(after.points.len(), 4, "inserted, not appended"); + assert_eq!(after.selected, Some(2)); + assert_eq!((after.points[1], after.points[3]), (before[1], before[2])); + assert!(after.points[2].x > before[1].x && after.points[2].x < before[2].x); + + // B, not A: clicking the first point closes the path + click(&mut h, B); + assert_eq!(path(&h).selected, Some(1)); + key(&mut h, Key::Backspace); + assert_eq!(path(&h).points, vec![after.points[0], after.points[2], after.points[3]]); + + // Undo brings the point back and keeps the path; again, the inserted point goes + let undo = |h: &mut AppHarness<'_>| { + h.input_mut().events.push(Event::Key { key: Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }); + h.run_steps(2); + }; + undo(&mut h); + assert_eq!(path(&h).points, after.points); + undo(&mut h); + assert_eq!(path(&h).points, before); + assert!(!path_sublayers(&h).is_empty(), "the path is still there"); +} 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/rail.rs b/crates/ui-egui/tests/it/rail.rs new file mode 100644 index 00000000..db4046f6 --- /dev/null +++ b/crates/ui-egui/tests/it/rail.rs @@ -0,0 +1,444 @@ +//! The rail opens its panels in a popup beside their icons, one at a time; dragging the popup's title docks or floats the panel + +use egui::{Event, Modifiers, PointerButton, Pos2, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable, by}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::ViewLayout; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// The rail is the last 38 points of the window; the popup's own buttons sit left of it +const RAIL_LEFT_EDGE: f32 = WINDOW_SIZE.x - 38.0; + +// Small texture and bake sizes keep the sample session fast; the rail 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; + +/// Where a drag out of the popup ends: in the viewport, clear of every panel +const INTO_THE_VIEWPORT: egui::Vec2 = egui::vec2(-500.0, 100.0); + +/// Moves a drag takes, so the dock sees it pass its threshold and move +const DRAG_STEPS: usize = 6; + +/// Frames between a drag's events: the press must land before the moves, and each move be seen +const FRAMES_PER_DRAG_EVENT: usize = 2; + +/// Frames for a click to reach the rail, the popup and the dock +const SETTLE_FRAMES: usize = 3; + +// A setting only Shader Settings shows, and one only Display Settings shows +const SHADER_SETTING: &str = "Index of refraction"; +const DISPLAY_SETTING: &str = "Environment opacity"; + +fn app() -> Harness<'static, TextureCraftApp> { + app_of_size(WINDOW_SIZE) +} + +fn app_of_size(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(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 +} + +/// The rail icon of the panel named `name`, if the rail shows one +fn rail_icon<'h>(harness: &'h Harness<'_, TextureCraftApp>, name: &str) -> Option> { + // A rail icon's label is its tooltip, which adds the shortcut when the panel has one + let is_panel = |label: &str| label == name || label.starts_with(&format!("{name} (")); + harness + .get_all_by_role(Role::Button) + .find(|button| button.rect().min.x >= RAIL_LEFT_EDGE && button.accesskit_node().label().is_some_and(|label| is_panel(&label))) +} + +fn click_rail(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + rail_icon(harness, name).expect("the panel's icon on the rail").click(); + harness.run_steps(SETTLE_FRAMES); +} + +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + harness.hover_at(position); + 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(SETTLE_FRAMES); +} + +/// Drag with 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(FRAMES_PER_DRAG_EVENT); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + + for step in 1..=DRAG_STEPS { + harness.hover_at(from + (to - from) * (step as f32 / DRAG_STEPS as f32)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + } + + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(SETTLE_FRAMES); +} + +/// The popup's Close button, left of the rail (the window's own Close sits above the rail) +fn popup_close_button(harness: &Harness<'_, TextureCraftApp>) -> Option { + harness + .query_all(by().role(Role::Button)) + .find(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some("Close")) + .map(|button| button.rect()) +} + +/// The title of the popup open on the panel named `name`: that name, level with the popup's Close button +fn open_popup_title(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Option { + let close = popup_close_button(harness)?; + harness + .get_all_by_label(name) + .map(|node| node.rect()) + .find(|title| title.right() < close.left() && (close.top()..=close.bottom()).contains(&title.center().y)) +} + +fn popup_title(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Rect { + open_popup_title(harness, name).expect("the popup's title") +} + +fn popup_shows(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + open_popup_title(harness, name).is_some() +} + +fn popup_closed(harness: &Harness<'_, TextureCraftApp>) -> bool { + popup_close_button(harness).is_none() +} + +#[test] +fn the_rail_shows_one_panel_at_a_time() { + let mut harness = app(); + + click_rail(&mut harness, "Shader Settings"); + + assert!(popup_shows(&harness, "Shader Settings")); + assert!(harness.query_by_label(SHADER_SETTING).is_some()); + + click_rail(&mut harness, "Display Settings"); + + assert!(popup_shows(&harness, "Display Settings")); + assert!(harness.query_by_label(SHADER_SETTING).is_none(), "opening Display Settings closed Shader Settings"); + assert!(harness.query_by_label(DISPLAY_SETTING).is_some()); + assert!(!harness.state().ui.dock.is_open(Panel::Shader), "the rail's panels are not dock windows"); + + click_rail(&mut harness, "Display Settings"); + + assert!(popup_closed(&harness), "its own icon closes it"); +} + +#[test] +fn the_popup_lines_up_with_its_icon() { + let mut harness = app(); + + click_rail(&mut harness, "History"); + let icon = rail_icon(&harness, "History").expect("the History icon").rect(); + let title = popup_title(&harness, "History"); + + assert!(title.top() >= icon.top() && title.top() <= icon.bottom(), "the title {title:?} is not level with the icon {icon:?}"); +} + +#[test] +fn the_close_button_a_press_outside_and_escape_close_it() { + let mut harness = app(); + + click_rail(&mut harness, "Display Settings"); + harness.get_by_role_and_label(Role::Button, "Close").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness), "Close"); + + click_rail(&mut harness, "Log"); + harness.get_by_label("Assets").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness), "a press outside"); + + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness), "Escape"); +} + +#[test] +fn dragging_the_title_out_floats_the_panel_and_frees_the_rail() { + let mut harness = app(); + + click_rail(&mut harness, "History"); + let title = popup_title(&harness, "History").center(); + drag(&mut harness, title, title + INTO_THE_VIEWPORT); + + assert!(popup_closed(&harness)); + assert!(harness.state().ui.dock.is_visible(Panel::History), "History floats on its own"); + assert!(rail_icon(&harness, "History").is_none(), "a panel in the dock has no rail icon"); + + click_rail(&mut harness, "Shader Settings"); + + assert!(popup_shows(&harness, "Shader Settings")); + assert!(harness.state().ui.dock.is_visible(Panel::History), "History stays open beside the rail's panel"); +} + +#[test] +fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { + let mut harness = app(); + + click_rail(&mut harness, "Log"); + let title = popup_title(&harness, "Log").center(); + let properties_tab = harness.get_by_label("Properties - Paint").rect().center(); + drag(&mut harness, title, properties_tab); + + let layout = &harness.state().ui.dock.workspace().layout; + assert!(layout.contains(&Panel::Log) && !layout.floating.iter().any(|window| window.contains(&Panel::Log)), "the Log is docked"); +} + +#[test] +fn a_panel_closed_in_the_dock_returns_to_the_rail() { + let mut harness = app(); + assert!(rail_icon(&harness, "Texture Set Settings").is_none(), "Texture Set Settings starts in the dock, beside Layers"); + + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Texture Set Settings"); + + assert!(popup_shows(&harness, "Texture Set Settings")); +} + +#[test] +fn window_views_open_the_rail_panels_popup() { + let mut harness = app(); + + let ctx = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.view.shader"); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Shader Settings")); + assert!(!harness.state().ui.dock.is_open(Panel::Shader)); + + // Project configuration opens Display Settings, in its popup too + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.projectConfig"); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Display Settings")); +} + +#[test] +fn a_popup_that_would_run_past_the_bottom_moves_up() { + // Too short for Display Settings below its icon + const SHORT_WINDOW: egui::Vec2 = egui::vec2(1600.0, 600.0); + let mut harness = app_of_size(SHORT_WINDOW); + + click_rail(&mut harness, "Display Settings"); + let icon = rail_icon(&harness, "Display Settings").expect("the Display Settings icon").rect(); + let title = popup_title(&harness, "Display Settings"); + + assert!(title.top() < icon.top(), "the popup at {title:?} did not move up from the icon at {icon:?}"); +} + +#[test] +fn display_settings_remain_reachable_in_a_short_window() { + let mut harness = app_of_size(egui::vec2(1600.0, 600.0)); + click_rail(&mut harness, "Display Settings"); + + let last_setting = "Temporal anti-aliasing (refines the 3D view while it is still)"; + harness.get_by_label(last_setting).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + let setting = harness.get_by_label(last_setting).rect(); + assert!(harness.ctx.content_rect().contains_rect(setting), "the last setting must be reachable: {setting:?}"); +} + +#[test] +fn history_actions_remain_reachable_in_a_short_window() { + let mut harness = app_of_size(egui::vec2(1600.0, 400.0)); + click_rail(&mut harness, "History"); + + for label in ["Undo", "Redo"] { + let button = harness + .get_all_by_role(Role::Button) + .find(|button| button.accesskit_node().label().is_some_and(|text| text.ends_with(label))) + .expect("the History action") + .rect(); + assert!(harness.ctx.content_rect().contains_rect(button), "{label} must be reachable: {button:?}"); + } +} + +#[test] +fn opening_the_window_menu_closes_the_rail_popup() { + let mut harness = app(); + click_rail(&mut harness, "Shader Settings"); + + harness.get_by_role_and_label(Role::Button, "Window").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness)); +} + +#[test] +fn escape_closes_a_dropdown_before_its_rail_popup() { + let mut harness = app(); + click_rail(&mut harness, "Display Settings"); + let environment_row = harness.get_by_label("Environment map").rect(); + harness + .get_all_by_role(Role::ComboBox) + .find(|combo| (combo.rect().center().y - environment_row.center().y).abs() < 1.0) + .expect("the environment dropdown") + .click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(egui::Popup::is_any_open(&harness.ctx)); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(popup_shows(&harness, "Display Settings")); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness)); +} + +#[test] +fn dismissing_a_rail_popup_does_not_paint_the_viewport() { + for layout in [ViewLayout::Only3D, ViewLayout::Only2D] { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + harness.state_mut().ui.layout = layout; + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + let center = if layout == ViewLayout::Only2D { egui::pos2(700.0, 420.0) } else { harness.state().viewport_rect.center() }; + let history = harness.state().session.history_labels().len(); + + click_at(&mut harness, center); + + assert!(popup_closed(&harness)); + assert_eq!(harness.state().session.history_labels().len(), history, "dismissing the popup must not paint in {layout:?}"); + + click_at(&mut harness, center); + + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the next click paints in {layout:?}"); + + click_rail(&mut harness, "Log"); + drag(&mut harness, center, center + egui::vec2(40.0, 0.0)); + + assert!(popup_closed(&harness)); + assert!(!harness.state().session.stroke_active()); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "a dismissing drag must not paint in {layout:?}"); + } +} + +#[test] +fn opening_a_rail_popup_during_a_stroke_still_finishes_the_stroke() { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(SETTLE_FRAMES); + let center = harness.state().viewport_rect.center(); + let history = harness.state().session.history_labels().len(); + harness.drag_at(center); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + harness.hover_at(center + egui::vec2(20.0, 0.0)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(harness.state().session.stroke_active()); + + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.log"); + harness.run_steps(SETTLE_FRAMES); + harness.drop_at(center + egui::vec2(30.0, 0.0)); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Log")); + assert!(!harness.state().session.stroke_active()); + assert_eq!(harness.state().session.history_labels().len(), history + 1); +} + +#[test] +fn escape_cancels_a_stroke_with_a_hidden_rail_popup() { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.hide_ui); + assert!(popup_closed(&harness)); + let center = harness.state().viewport_rect.center(); + let history = harness.state().session.history_labels(); + harness.drag_at(center); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + harness.hover_at(center + egui::vec2(20.0, 0.0)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(harness.state().session.stroke_active()); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(!harness.state().session.stroke_active(), "one Escape cancels the stroke despite the hidden popup"); + harness.drop_at(center + egui::vec2(30.0, 0.0)); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.history_labels(), history, "the canceled stroke must not be committed on release"); +} + +#[test] +fn escape_cancels_a_path_with_a_hidden_rail_popup() { + for stored_path in [false, true] { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + let path = texturecraft_engine::execute( + &mut harness.state_mut().session, + "tool.path", + &serde_json::json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": stored_path}), + ) + .unwrap(); + if stored_path { + texturecraft_engine::execute( + &mut harness.state_mut().session, + "path.edit", + &serde_json::json!({"effect": path["committed"]["effect"], "index": 0}), + ) + .unwrap(); + } + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.hide_ui); + assert!(popup_closed(&harness)); + assert_eq!(harness.state().session.tool.path.points.len(), 2); + + // Drafts and committed paths both have a live preview target while edited + let (effect, index) = harness.state().session.tool.path.editing.unwrap(); + let history = harness.state().session.history_labels(); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.state().session.tool.path.points.is_empty(), "one Escape clears the path despite the hidden popup"); + assert!(harness.state().session.tool.path.editing.is_none()); + assert_eq!(harness.state().session.history_labels(), history); + assert_eq!( + harness.state().session.paths(effect).and_then(|paths| paths.get(index)).is_some(), + stored_path, + "Escape removes a draft but keeps a committed path" + ); + + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Log"), "showing the UI restores its remembered popup"); + } +} 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..db784edf --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -0,0 +1,312 @@ +//! A shelf material or image dropped on the 3D view goes to the texture set under the pointer; an image first asks what it becomes + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::Tool; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; +use texturecraft_ui_egui::state::ViewLayout; + +/// Distance between the view points searched for a set or the background +const SEARCH_STEP: f32 = 8.0; + +/// How far from the drop point the drop menu's items can be +const MENU_REACH: f32 = 60.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) { + drop_asset(harness, Asset::Material("iron_rusted"), position); +} + +/// Drop shelf `asset` at `position`, as a drag from the shelf ends there +fn drop_asset(harness: &mut Harness<'_, TextureCraftApp>, asset: Asset, position: Pos2) { + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".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); +} + +/// Import a small white image and return its resource name +fn import_white_image(harness: &mut Harness<'_, TextureCraftApp>) -> String { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("logo.png", png).unwrap(); + harness.run_steps(2); + name +} + +/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) +fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { + let mut harness = sample_app(); + harness.state_mut().ui.prefs.language = "en".into(); + let name = import_white_image(&mut harness); + + let position = point_over(&harness, position_over); + drop_asset(&mut harness, Asset::Texture(name), position); + // The menu's first frame only measures it + harness.run_steps(2); + (harness, position) +} + +#[test] +fn an_image_dropped_on_another_set_asks_for_a_channel_then_goes_to_that_set() { + let (mut harness, position) = drop_image(Some(1)); + let before = stack_sizes(&harness); + + // The menu item nearest the drop point (Properties may show the same name) + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + + let app = harness.state(); + assert_eq!(app.session.ts(), 1, "the set under the drop point is selected"); + assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1]); + let layer = app.session.selected_layer().and_then(|id| app.session.doc.project.layer(id).ok()).unwrap(); + assert_eq!(layer.channels.keys().copied().collect::>(), [Channel::Roughness], "the image fills the picked channel"); +} + +/// Whether the drop menu is open at `position` (its Mask item near there) +fn menu_open(harness: &Harness<'_, TextureCraftApp>, position: Pos2) -> bool { + harness.query_all_by_label("Mask").any(|node| node.rect().center().distance(position) < MENU_REACH) +} + +/// Press and release the primary button at `position` +fn click(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + harness.hover_at(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(2); +} + +#[test] +fn dismissing_an_image_drop_in_the_2d_view_does_not_paint() { + let (mut harness, position) = drop_image(Some(1)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let view_3d = harness.state().viewport_rect; + let uv_center = egui::pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + let history = harness.state().session.history_labels(); + assert!(menu_open(&harness, position)); + + click(&mut harness, uv_center); + + assert!(!menu_open(&harness, position)); + assert_eq!(harness.state().session.history_labels(), history, "dismissing the menu must not fill the UV view"); + + click(&mut harness, uv_center); + + assert_eq!(harness.state().session.history_labels().len(), history.len() + 1, "the next click paints normally"); + assert_eq!(harness.state().session.undo_label(), Some("Polygon fill")); +} + +#[test] +fn a_pending_image_drop_does_not_drag_the_selected_decal() { + let mut harness = sample_app(); + let image = import_white_image(&mut harness); + let rect = harness.state().viewport_rect; + let center = rect.center(); + let local = center - rect.min; + harness.state_mut().run("layer.add.decal", serde_json::json!({"image": image, "x": local.x, "y": local.y})).unwrap(); + harness.run_steps(2); + let drop_position = point_over(&harness, Some(1)); + drop_asset(&mut harness, Asset::Texture(image), drop_position); + harness.run_steps(2); + assert!(menu_open(&harness, drop_position)); + let layer = harness.state().session.selected_layer().unwrap(); + let before = harness.state().session.doc.project.layer(layer).unwrap().kind.clone(); + let history = harness.state().session.history_labels(); + + harness.hover_at(center); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: center, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + let moved = center + egui::vec2(30.0, 0.0); + harness.hover_at(moved); + harness.run_steps(2); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().kind, before, "a pending drop owns the decal-drag input"); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { + let (mut harness, position) = drop_image(Some(1)); + let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); + assert!(menu_open(&harness, position)); + + // A click elsewhere on the mesh closes the menu and fills nothing there (a polygon fill click records a step in this harness) + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let elsewhere = point_over(&harness, Some(0)); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!menu_open(&harness, position)); + assert_eq!(stack_sizes(&harness), stacks); + assert_eq!(harness.state().session.history_labels().len(), history); + + let (harness, position) = drop_image(None); + assert!(!menu_open(&harness, position), "the background opens no menu"); +} + +#[test] +fn hiding_the_3d_view_lets_go_of_a_waiting_image_drop() { + let (mut harness, position) = drop_image(Some(1)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let history = harness.state().session.history_labels().len(); + assert!(menu_open(&harness, position)); + + // Only the 3D view shows the menu, so a 2D-only layout would otherwise leave the views blocked + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(3); + click(&mut harness, egui::pos2(700.0, 420.0)); + + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the hidden menu no longer blocks UV painting"); + assert_eq!(harness.state().session.undo_label(), Some("Polygon fill")); + + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(3); + + assert!(!menu_open(&harness, position), "the drop lapsed while its menu was hidden"); +} + +#[test] +fn changing_the_camera_cancels_a_drop_with_stale_view_coordinates() { + let (mut harness, position) = drop_image(Some(1)); + let history = harness.state().session.history_labels(); + let stacks = stack_sizes(&harness); + assert!(menu_open(&harness, position)); + + harness.state_mut().session.camera.distance *= 2.0; + harness.run_steps(3); + + let app = harness.state(); + let local = position - app.viewport_rect.min; + assert_ne!(app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport), Some(1), "the saved pixel no longer hits the dropped-on set"); + assert!(!menu_open(&harness, position), "a stale drop must not offer placement on a different surface"); + assert_eq!(harness.state().session.history_labels(), history); + assert_eq!(stack_sizes(&harness), stacks); +} + +#[test] +fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { + let (mut harness, position) = drop_image(Some(1)); + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + let decal_layer = harness.state().session.selected_layer().unwrap(); + harness.state_mut().placing_decal = Some(decal_layer); + + let image = import_white_image(&mut harness); + drop_asset(&mut harness, Asset::Texture(image), position); + harness.run_steps(2); + assert!(menu_open(&harness, position)); + let history = harness.state().session.history_labels().len(); + + // A point on the same set, away from the menu + let rect = harness.state().viewport_rect; + let elsewhere = (1..(rect.width() / SEARCH_STEP) as usize) + .map(|step| Pos2::new(rect.max.x - step as f32 * SEARCH_STEP, position.y)) + .find(|point| { + let app = harness.state(); + let local = *point - rect.min; + point.distance(position) > MENU_REACH * 2.0 && app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport) == Some(1) + }) + .unwrap(); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + assert!(!menu_open(&harness, position)); + assert_eq!(harness.state().session.history_labels().len(), history, "the decal wasn't moved"); +} + +#[test] +#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] +fn image_drop_menu_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().ui.prefs.language = "en".into(); + harness.run_steps(6); + let image = import_white_image(&mut harness); + let position = point_over(&harness, Some(1)); + drop_asset(&mut harness, Asset::Texture(image), position); + harness.run_steps(6); + + assert!(menu_open(&harness, position)); + harness.render().unwrap().save(directory.join("image-drop-menu.png")).unwrap(); + + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Mask").min_by(|left, right| distance(left).total_cmp(&distance(right))).unwrap().click(); + harness.run_steps(6); + + assert_eq!(harness.state().session.ts(), 1); + assert!(matches!(harness.state().session.target, texturecraft_engine::StackTarget::Effect(_))); + harness.render().unwrap().save(directory.join("image-drop-mask.png")).unwrap(); +} 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..237de107 --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -0,0 +1,185 @@ +//! 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 the first two labels (the grid is sorted by name) 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 harness = 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)); + harness.state_mut().ui.shelf_tab = MATERIALS_TAB; + harness.run_steps(4); + + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + let unique: Vec<_> = plain.into_iter().filter(|material| harness.query_all_by_label(material.label).count() == 1).take(2).collect(); + assert_eq!(unique.len(), 2, "two materials with unique names"); + (harness, 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"); +} + +// Coverage instrumentation makes the 512px software-rendered preview substantially slower. +fn high_dpi_worker_timeout() -> Duration { + if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + WORKER_TIMEOUT + } +} + +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() < high_dpi_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/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs new file mode 100644 index 00000000..a33068b7 --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -0,0 +1,316 @@ +//! The Assets panel's layout: columns at the reference width, type row, size menu, breadcrumb, side panes and toolbar + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::saved_search::SavedSearch; +use texturecraft_ui_egui::shelf_view::ShelfView; + +/// The reference's capture window: its Assets panel shows four columns there +const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0); +/// A window whose default Assets panel is too narrow for the full type row +const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0); +/// The types' positions in the shelf's type row (its table is crate-private) +const MATERIALS_TYPE: usize = 0; +const SMART_MASKS_TYPE: usize = 2; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; +const ENVIRONMENTS_TYPE: usize = 7; +/// How far the saved brush's spacing differs from the current brush's, so loading it shows +const SAVED_SPACING_CHANGE: f32 = 0.25; +/// Tile columns the reference shows at its panel width +const REFERENCE_COLUMNS: usize = 4; + +/// The sample project with the shelf on the Materials type +fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; + harness.run_steps(4); + harness +} + +/// The plain materials in the grid's order (by name) +fn plain_materials() -> Vec<&'static SmartMaterial> { + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + plain +} + +/// A clickable node labelled `label` (its tooltip, once shown, has the same label) +fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")) +} + +#[test] +fn the_default_panel_shows_the_reference_column_count() { + let harness = shelf(REFERENCE_WINDOW); + let tops: Vec = plain_materials().iter().take(REFERENCE_COLUMNS + 1).map(|material| harness.get_by_label(material.label).rect().top()).collect(); + + assert!(tops[..REFERENCE_COLUMNS].iter().all(|top| *top == tops[0]), "the first {REFERENCE_COLUMNS} tiles share a row: {tops:?}"); + assert!(tops[REFERENCE_COLUMNS] > tops[0], "the next tile starts a row: {tops:?}"); +} + +#[test] +fn a_click_on_the_picked_type_shows_every_type() { + let mut harness = shelf(REFERENCE_WINDOW); + let mask = SMART_MASKS[0].label; + assert!(harness.query_by_label(mask).is_none(), "the Materials type hides smart masks"); + + button(&harness, "Materials").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(mask).is_some(), "no type picked shows smart masks too"); +} + +#[test] +fn the_search_narrows_the_picked_type_and_greys_types_without_matches() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials().into_iter().find(|material| material.label.to_lowercase().contains("rust")).unwrap(); + let mask = SMART_MASKS.iter().find(|mask| mask.label.to_lowercase().contains("rust")).unwrap(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(mask.label).is_some(), "the matching mask shows"); + assert!(harness.query_by_label(material.label).is_none(), "a matching material of another type does not"); + assert!(button(&harness, "Environments").accesskit_node().is_disabled(), "no environment matches"); + assert!(!button(&harness, "Materials").accesskit_node().is_disabled()); + + button(&harness, "Materials").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.shelf_filter, "rust", "picking a type keeps the search"); + assert!(harness.query_by_label(material.label).is_some()); +} + +#[test] +fn unavailable_project_images_do_not_make_textures_match() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().session.doc.resources.insert("unavailable-preview.png".into(), vec![0].into()); + harness.state_mut().ui.shelf_filter = "unavailable-preview.png".into(); + harness.run_steps(3); + + assert!(button(&harness, "Textures").accesskit_node().is_disabled()); + assert!(harness.query_by_label("unavailable-preview.png").is_none()); +} + +#[test] +fn the_breadcrumb_arrow_picks_a_library() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + + button(&harness, "Browse folders").click(); + harness.run_steps(2); + for library in ["Project", "Starter assets", "Your assets"] { + assert!(harness.query_by_label(library).is_some(), "the list offers {library}"); + } + harness.get_by_label("Project").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_path, ["project"]); + assert!(harness.query_by_label(material).is_none(), "built-in materials are not in the project"); +} + +#[test] +fn the_thumbnail_size_menu_switches_to_the_list() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + let tile_width = harness.get_by_label(material).rect().width(); + + button(&harness, "Thumbnail size").click(); + harness.run_steps(2); + harness.get_by_label_contains("List").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_view, ShelfView::List); + assert!(harness.get_by_label(material).rect().width() > tile_width * 2.0, "a list row spans the panel"); +} + +#[test] +fn reset_query_shows_every_asset_again() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_path = vec!["starter".into()]; + harness.run_steps(2); + + button(&harness, "Reset query").click(); + harness.run_steps(3); + + let ui = &harness.state().ui; + assert!(ui.shelf_filter.is_empty() && ui.shelf_path.is_empty()); + assert!(harness.query_by_label(SMART_MASKS[0].label).is_some(), "every type shows"); +} + +#[test] +fn refresh_reads_the_saved_brushes_again() { + let mut harness = shelf(REFERENCE_WINDOW); + let stale = vec![std::path::PathBuf::from("gone.tcbrush")]; + harness.state_mut().brushes = Some(stale.clone()); + harness.run_steps(1); + + button(&harness, "Refresh").click(); + harness.run_steps(3); + + assert_ne!(harness.state().brushes, Some(stale), "the brushes folder was read again"); + assert!(harness.query_by_label("Import resources...").is_some(), "the toolbar has the import button"); +} + +#[test] +fn a_saved_search_restores_its_query() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Saved searches").click(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.run_steps(3); + + button(&harness, "Save the current search").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1); + harness.state_mut().ui.shelf_filter.clear(); + harness.run_steps(2); + + harness.get_by_label("rust").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_filter, "rust"); + + harness.get_by_label("rust").click_secondary(); + harness.run_steps(2); + // The context menu opens last, so its Delete is the newest node with that label + harness.get_all_by_label("Delete").last().unwrap().click(); + harness.run_steps(2); + assert!(harness.state().ui.shelf_saved_searches.is_empty()); +} + +#[test] +fn filter_by_path_picks_a_folder() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Filter by path").click(); + harness.run_steps(3); + + harness.get_by_label("Starter assets").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_path, ["starter"]); +} + +#[test] +fn many_saved_searches_keep_the_path_filter_reachable() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.state_mut().ui.shelf_saved_searches = (0..100) + .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .collect(); + harness.run_steps(3); + + let heading = harness.get_by_label("FILTER BY PATH").rect(); + assert!(heading.bottom() < NARROW_WINDOW.y, "the path pane heading stays on screen: {heading:?}"); + assert!(harness.query_by_label("Starter assets").is_some(), "the folder tree remains reachable"); +} + +#[test] +fn a_long_saved_search_list_can_select_the_last_query() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_saved_searches = (0..1000) + .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .collect(); + harness.run_steps(3); + assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); + + harness.get_by_label("search 0").hover(); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -50_000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(3); + harness.get_by_label("search 999").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_filter, "filter 999"); +} + +#[test] +fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.run_steps(3); + + for label in ["Refresh", "Reset query", "Import resources...", "Saved searches", "Filter by path"] { + let rect = button(&harness, label).rect(); + assert!(rect.bottom() <= NARROW_WINDOW.y, "{label} is inside the window: {rect:?}"); + } + assert!(harness.query_by_label("Filter by type").is_some(), "the type row folds into one dropdown"); + assert!(harness.query_by_label("Environments").is_none()); +} + +#[test] +fn an_environment_tile_switches_the_lighting() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = ENVIRONMENTS_TYPE; + harness.run_steps(3); + let shown = harness.state().session.doc.project.display.environment.clone(); + let other = ENVIRONMENTS.iter().find(|name| **name != shown).unwrap(); + + harness.get_by_label(other).click(); + harness.run_steps(2); + + assert_eq!(harness.state().session.doc.project.display.environment, *other); +} + +#[test] +fn a_saved_brush_is_a_tile_that_loads_the_preset() { + let mut harness = shelf(REFERENCE_WINDOW); + let mut saved = harness.state().session.tool.brush.clone(); + saved.spacing += SAVED_SPACING_CHANGE; + let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id())); + std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); + harness.state_mut().brushes = Some(vec![path.clone()]); + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + harness.get_by_label(path.file_stem().unwrap().to_str().unwrap()).click(); + harness.run_steps(2); + std::fs::remove_file(&path).unwrap(); + + assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke"); +} + +#[test] +fn saved_smart_materials_keep_their_type_pickable_in_your_assets() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().library = Some(vec![std::path::PathBuf::from("Mine.tcmat")]); + harness.state_mut().ui.shelf_path = vec!["user".into()]; + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + assert!(!button(&harness, "Smart materials").accesskit_node().is_disabled(), "a saved smart material is in Your assets"); + assert!(button(&harness, "Materials").accesskit_node().is_disabled(), "no plain material is"); +} + +#[test] +fn saved_smart_materials_are_read_whatever_the_type_and_after_a_refresh() { + let mut harness = shelf(REFERENCE_WINDOW); + assert!(harness.state().library.is_some(), "read on the Materials type"); + + button(&harness, "Refresh").click(); + harness.run_steps(2); + + assert!(harness.state().library.is_some(), "read again after a refresh"); +} + +#[test] +fn procedurals_are_in_the_textures_type() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some()); +} 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..08537f4f --- /dev/null +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -0,0 +1,284 @@ +//! 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_engine::{StackTarget, core::LayerId}; +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_forced_2d_completion_moves_the_next_line_start() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.hover_at(CANCELLED_DRAG_FROM); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: CANCELLED_DRAG_FROM, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(CANCELLED_DRAG_TO); + harness.run_steps(2); + assert!(harness.state().session.stroke_active(), "the 2D drag is still active"); + + harness.state_mut().session.target = StackTarget::Effect(LayerId(u64::MAX)); + harness.run_steps(1); + assert!(!harness.state().session.stroke_active(), "the unavailable tool finishes the drag"); + harness.state_mut().session.target = StackTarget::Content; + harness.event(Event::PointerButton { pos: CANCELLED_DRAG_TO, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + let (before_line, width) = alpha(&harness); + click(&mut harness, SECOND_CLICK, true); + let (after_line, _) = alpha(&harness); + let line = added(&before_line, &after_line); + + let dab_centre = |point| { + let mut reference = uv_view_app(); + let (blank, width) = alpha(&reference); + click(&mut reference, point, false); + let (painted, _) = alpha(&reference); + centre(&added(&blank, &painted), width) + }; + let expected_middle = (dab_centre(CANCELLED_DRAG_TO) + dab_centre(SECOND_CLICK)) * 0.5; + assert!(painted_at(&line, width, expected_middle), "Shift+click starts at the forced completion endpoint"); +} + +#[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/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs new file mode 100644 index 00000000..dd3b5d02 --- /dev/null +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -0,0 +1,74 @@ +//! Bake mode: with the skew brush on, dragging in the 2D view paints the skew map, and the +//! 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 stroke inside the 2D view, right of bake mode's two settings columns +const STROKE_START: egui::Pos2 = egui::pos2(700.0, 500.0); +const STROKE_END: egui::Pos2 = egui::pos2(900.0, 500.0); + +/// 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(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + 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::CommonSettings); + h.run_steps(3); + h +} + +#[test] +fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { + let mut h = harness(); + h.get_by_label("Skew Correction"); + assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on); + + // Off: a drag in the view paints nothing + h.drag_at(STROKE_START); + h.hover_at(STROKE_END); + h.drop_at(STROKE_END); + h.run_steps(3); + assert!(h.state().session.doc.bake_paint.is_empty(), "the brush is off"); + + // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke + h.get_by_label("Paint Skew Correction").scroll_to_me(); + h.run_steps(3); + h.get_by_label("Paint Skew Correction").click(); + h.run_steps(3); + assert!(h.state().ui.bake_paint_brush.on); + h.get_by_label("Radius"); + h.drag_at(STROKE_START); + h.run_steps(2); + h.hover_at(STROKE_END); + h.run_steps(2); + h.drop_at(STROKE_END); + h.run_steps(3); + let map = h.state().session.doc.bake_paint.get(&(0, texturecraft_engine::core::BakePaintTarget::Skew)).cloned().expect("the stroke made a skew map"); + let painted = map.values.iter().filter(|v| **v > 0.5).count(); + assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); + + // Removing it from the panel clears the map + h.get_by_label("Remove Skew Correction").scroll_to_me(); + h.run_steps(3); + h.get_by_label("Remove Skew Correction").click(); + h.run_steps(3); + assert!(h.state().session.doc.bake_paint.is_empty()); +} + +#[test] +fn turning_average_normals_off_stops_the_skew_brush() { + let mut h = harness(); + h.state_mut().ui.bake_paint_brush.on = true; + h.run_steps(2); + assert!(h.state().ui.bake_paint_brush.on, "skew correction applies with the default cage"); + + h.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; + h.run_steps(2); + assert!(!h.state().ui.bake_paint_brush.on, "the bake would leave the skew map out"); +} 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..4e8c0364 --- /dev/null +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -0,0 +1,229 @@ +//! 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 old_textures_tab_index_migrates_without_changing_new_all_types() { + let mut storage = MemoryStorage::default(); + let mut state = UiState::default(); + state.shelf_tab = 8; + UiStateStore::default().save(&state, &mut storage); + + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(8)); + + let mut legacy: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + legacy.as_object_mut().unwrap().remove("shelf_path"); + legacy.as_object_mut().unwrap().insert("shelf_filter".into(), "shelf_path".into()); + storage.0.insert("ui.json".into(), legacy.to_string()); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(6)); + + state.shelf_tab = 0; + UiStateStore::default().save(&state, &mut storage); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(0)); +} + +#[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/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs new file mode 100644 index 00000000..2d6181be --- /dev/null +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -0,0 +1,319 @@ +//! Symmetry: the toolbar toggle, the settings popup and the 3D view's manipulator + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::{Value, json}; +use texturecraft_engine::Tool; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_ui_egui::TextureCraftApp; + +/// The settings popup's width and its color square's (points) +const POPUP_WIDTH: f32 = 340.0; +const COLOR_SWATCH_WIDTH: f32 = 48.0; + +/// How far along Y (world units) the test measures the arrow's direction on screen +const AXIS_PROBE: f32 = 0.05; + +/// Points from the manipulator's center to grab the arrow (inside its length at the default size) and how far to drag it +const ON_THE_SHAFT: f32 = 40.0; +const DRAG_DISTANCE: f32 = 60.0; + +/// A point inside the 3D view near its lower left corner, clear of the mesh and the popup (points from the corner) +const VIEW_CORNER_INSET: f32 = 40.0; + +fn app_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(1024, 256).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().session.tool.tool = Tool::Paint; + harness.run_steps(4); + harness +} + +/// Hold a primary-button drag from `from` to `to` without releasing it +fn hold_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); + } +} + +fn click_at(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.run_steps(1); + release(harness, at); +} + +fn release(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +/// The brush settings as agents read them +fn brush(harness: &mut Harness<'_, TextureCraftApp>) -> Value { + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({})).unwrap() +} + +/// The number field beside a uniquely labelled slider +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(egui::accesskit::Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +} + +/// Type a complete value in the number field beside a uniquely labelled slider +fn set_number(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { + let length = number_field(harness, label).value().unwrap().len(); + number_field(harness, label).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::End); + harness.run_steps(1); + for _ in 0..length { + harness.key_press(egui::Key::Backspace); + harness.run_steps(1); + } + number_field(harness, label).type_text(value); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); +} + +/// Where world `point` is in the 3D view +fn on_screen(harness: &Harness<'_, TextureCraftApp>, point: Vec3) -> Pos2 { + let rect = harness.state().viewport_rect; + let ndc = harness.state().session.camera.project(point, rect.width() / rect.height()).unwrap(); + egui::pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height()) +} + +#[test] +fn the_toolbar_popup_and_manipulator_change_the_brush_symmetry() { + let mut harness = app_harness(); + let revision = harness.state().session.revision; + let history = harness.state().session.history_labels(); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert!(harness.state().session.revision > revision, "the toggle runs the brush command"); + assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false]), "the toggle mirrors on X"); + + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "X").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Y").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["symmetry"], json!([false, true, false]), "mirror axes can be toggled independently"); + + harness.get_by_label("Symmetry settings").click(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + + // Drag the arrow along Y, starting on its shaft + let (lo, hi) = harness.state().session.mesh.bounds(); + let origin = (lo + hi) * 0.5; + let center = on_screen(&harness, origin); + let along = (on_screen(&harness, origin + Vec3::Y * AXIS_PROBE) - center).normalized(); + let from = center + along * ON_THE_SHAFT; + let to = from + along * DRAG_DISTANCE; + let revision = harness.state().session.revision; + + hold_drag(&mut harness, from, to); + release(&mut harness, to); + + assert!(harness.state().session.revision > revision, "the manipulator runs the brush command"); + assert_eq!(harness.state().session.history_labels(), history, "symmetry settings do not add undo steps"); + let offset = brush(&mut harness)["symmetryOffset"].clone(); + assert!(offset[1].as_f64().unwrap() > 0.05, "the plane moved up: {offset}"); + assert_eq!((offset[0].as_f64(), offset[2].as_f64()), (Some(0.0), Some(0.0)), "only along Y: {offset}"); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + let settings = brush(&mut harness); + assert_eq!(settings["symmetryOn"], json!(false), "the toggle turns it off"); + assert_eq!(settings["symmetry"], json!([false, true, false]), "and keeps the settings"); +} + +#[test] +fn the_color_picker_opens_inside_the_combined_symmetry_popup() { + let mut harness = app_harness(); + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["radialSymmetry"], json!({"copies": 6, "axis": "y"})); + assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false])); + assert!(harness.query_by_label("Angle span").is_some(), "the popup stays open after enabling radial symmetry"); + + // The color square sits at the right end of its row + let row = harness.get_by_label("Symmetry color display").rect(); + let left = harness.get_by_label("Radial symmetry").rect().left(); + click_at(&mut harness, egui::pos2(left + POPUP_WIDTH - COLOR_SWATCH_WIDTH / 2.0, row.center().y)); + harness.run_steps(2); + assert!(harness.query_by_label("Copy RGB values").is_some(), "the color picker opened"); + assert!(harness.query_by_label("Show cursor").is_some(), "the popup stays open with the color picker"); + + // A click on the view closes it + let view_corner = harness.state().viewport_rect.left_bottom() + egui::vec2(VIEW_CORNER_INSET, -VIEW_CORNER_INSET); + click_at(&mut harness, view_corner); + harness.run_steps(2); + assert!(harness.query_by_label("Show cursor").is_none(), "a click elsewhere closes the popup"); +} + +#[test] +fn radial_axis_edits_preserve_combined_symmetry() { + let mut harness = app_harness(); + harness + .state_mut() + .run("tool.brush", json!({"symmetryX": true, "symmetryZ": true, "symmetryRadial": 5, "symmetryAxis": "y", "symmetryAngleSpan": 215})) + .unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let revision = harness.state().session.revision; + let history = harness.state().session.history_labels(); + + harness.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Z").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true]), "editing radial symmetry must preserve every mirror axis"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 5, "axis": "z"})); + assert_eq!(settings["symmetryAngleSpan"], json!(215.0)); + assert!(harness.state().session.revision > revision, "the edit runs the brush command"); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn the_popup_creates_and_edits_mirror_and_radial_copies_independently() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryOn": false})).unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let history = harness.state().session.history_labels(); + + for axis in ["X", "Z"] { + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, axis).click(); + harness.run_steps(2); + } + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true])); + assert_eq!(settings["radialSymmetry"], json!({"copies": 6, "axis": "y"})); + assert_eq!(settings["symmetryOn"], json!(false), "editing settings preserves the master toggle"); + assert!(harness.query_by_label("Show plane").is_some()); + assert!(harness.query_by_label("Show axis").is_some()); + + set_number(&mut harness, "Count", "9"); + set_number(&mut harness, "Angle span", "180"); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true]), "radial edits keep both mirror axes"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 9, "axis": "y"})); + assert_eq!(settings["symmetryAngleSpan"], json!(180.0)); + + for axis in ["X", "Y", "Z"] { + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, axis).click(); + harness.run_steps(2); + } + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([false, true, false])); + assert_eq!(settings["radialSymmetry"], json!({"copies": 9, "axis": "y"}), "mirror edits keep the radial settings"); + assert_eq!(settings["symmetryAngleSpan"], json!(180.0)); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + let combined = harness.state().session.tool.brush.symmetry; + assert!(combined.enabled); + assert_eq!(combined.transforms().len(), 18, "the engine receives both symmetry settings"); + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert_eq!(harness.state().session.tool.brush.symmetry, texturecraft_engine::paint::Symmetry { enabled: false, ..combined }); + + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([false, true, false]), "disabling radial symmetry keeps the mirror"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 0, "axis": "y"})); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn clicking_a_symmetry_handle_does_not_paint() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryY": true})).unwrap(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + let (lo, hi) = harness.state().session.mesh.bounds(); + let center = on_screen(&harness, (lo + hi) * 0.5); + let history = harness.state().session.history_labels(); + + click_at(&mut harness, center); + + assert_eq!(harness.state().session.history_labels(), history, "clicking a handle must not add a paint dab"); + assert!(!harness.state().session.stroke_active()); +} + +#[test] +fn a_paint_stroke_can_cross_and_end_on_a_symmetry_handle() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryY": true})).unwrap(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + let (lo, hi) = harness.state().session.mesh.bounds(); + let center = on_screen(&harness, (lo + hi) * 0.5); + let from = center + egui::vec2(80.0, 0.0); + let history = harness.state().session.history_labels().len(); + + hold_drag(&mut harness, from, center); + release(&mut harness, center); + + assert!(!harness.state().session.stroke_active(), "releasing over the handle must finish painting"); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + assert_eq!(harness.state().session.tool.brush.symmetry.offset, [0.0; 3]); +} + +#[test] +fn ctrl_drag_on_a_symmetry_handle_only_adjusts_the_brush() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryY": true})).unwrap(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + let (lo, hi) = harness.state().session.mesh.bounds(); + let from = on_screen(&harness, (lo + hi) * 0.5); + let to = from + egui::vec2(-60.0, -40.0); + let before = harness.state().session.tool.brush.clone(); + let history = harness.state().session.history_labels(); + + harness.event(Event::ModifiersChanged(Modifiers::COMMAND)); + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::COMMAND }); + 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: PointerButton::Primary, pressed: false, modifiers: Modifiers::COMMAND }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + + let after = &harness.state().session.tool.brush; + assert!(after.flow < before.flow); + assert_ne!(after.angle, before.angle); + assert_eq!(after.symmetry, before.symmetry, "adjusting the brush must not also move symmetry"); + assert_eq!(harness.state().session.history_labels(), history); +} diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs new file mode 100644 index 00000000..77fd888f --- /dev/null +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -0,0 +1,270 @@ +//! The shelf greys tools that can't act on the selection; the top bar and Properties follow it + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; +use texturecraft_engine::{Session, StackTarget, Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::theme::Brightness; + +fn add_layer(session: &mut Session, command: &str) -> u64 { + execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn select(session: &mut Session, layer: u64, target: Value) { + execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap(); +} + +fn select_nothing(session: &mut Session) { + let set = session.ts(); + session.selected.remove(&set); + session.target = StackTarget::Content; +} + +fn app_harness() -> 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(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness +} + +/// Selects a new fill layer's content with `tool` equipped +fn select_fill_content(harness: &mut Harness<'_, TextureCraftApp>, tool: Tool) { + let session = &mut harness.state_mut().session; + let fill = add_layer(session, "layer.add.fill"); + select(session, fill, json!("content")); + session.tool.tool = tool; + harness.run_steps(4); +} + +fn shelf_button_disabled(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.get_by_label(label).accesskit_node().is_disabled() +} + +fn shelf_button_selected(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +fn shows_text(harness: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + harness.output().shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(found) if found.galley.text() == text)) +} + +#[test] +fn a_fill_layer_greys_the_paint_tools_and_shows_its_own_properties() { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + harness.run_steps(4); + + assert!(!shelf_button_disabled(&harness, "Paint (1)")); + assert!(shelf_button_selected(&harness, "Paint (1)")); + assert!(shows_text(&harness, "Size"), "the brush controls are in the top bar"); + + select_fill_content(&mut harness, Tool::PolygonFill); + + assert!(shelf_button_disabled(&harness, "Paint (1)")); + assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); + assert!(!shelf_button_selected(&harness, "Polygon fill (4)"), "the equipped tool doesn't show as selected while greyed"); + assert!(!shelf_button_disabled(&harness, "Geometry mask (8)")); + assert!(shows_text(&harness, "Properties - Fill"), "a fill layer shows its fill whatever the tool"); + assert!(!shows_text(&harness, "Size"), "a tool that can't act leaves the top bar"); +} + +#[test] +fn shortcuts_skip_the_tools_the_shelf_greys() { + let mut harness = app_harness(); + select_fill_content(&mut harness, Tool::Paint); + + harness.key_press(egui::Key::Num2); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.tool, Tool::Paint, "Eraser can't act on a fill layer"); + + harness.key_press(egui::Key::P); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.tool, Tool::ColorPicker); +} + +/// Drag with the left button across the middle of the 3D view, as a stroke would +fn drag_across_the_view(harness: &mut Harness<'_, TextureCraftApp>) { + const STEPS: usize = 4; + const STEP_POINTS: f32 = 15.0; + + let center = harness.state().viewport_rect.center(); + let modifiers = egui::Modifiers::NONE; + harness.hover_at(center); + harness.event(egui::Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(2); + + for step in 1..=STEPS { + harness.hover_at(center + egui::vec2(STEP_POINTS * step as f32, 0.0)); + harness.run_steps(1); + } + + let end = center + egui::vec2(STEP_POINTS * STEPS as f32, 0.0); + harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(3); +} + +#[test] +fn a_tool_that_cant_act_ignores_the_view() { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + harness.run_steps(4); + + let steps_before = harness.state().session.history_labels().len(); + drag_across_the_view(&mut harness); + + assert!(harness.state().session.history_labels().len() > steps_before, "the drag reaches the mesh and paints a paint layer"); + + for tool in [Tool::Paint, Tool::PolygonFill, Tool::Path] { + select_fill_content(&mut harness, tool); + let steps_before = harness.state().session.history_labels().len(); + drag_across_the_view(&mut harness); + + let state = harness.state(); + assert!(state.toasts.is_empty(), "{tool:?} on a fill layer: no error toast, got {:?}", state.toasts.first().map(|toast| &toast.text)); + assert_eq!(state.session.history_labels().len(), steps_before, "{tool:?} on a fill layer changes nothing"); + assert!(state.session.tool.path.points.is_empty(), "{tool:?} places no path points"); + } +} + +#[test] +fn bake_painting_turns_on_the_shelf_paint_tool() { + 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(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + assert!(shelf_button_disabled(&harness, "Paint (1)"), "nothing is being painted yet"); + + harness.state_mut().ui.bake_paint_brush.on = true; + harness.run_steps(4); + + assert!(harness.state().ui.bake_paint_brush.on, "the high poly allows bake painting"); + assert!(!shelf_button_disabled(&harness, "Paint (1)"), "Paint is the bake brush while it paints"); + assert!(shelf_button_disabled(&harness, "Eraser (2)")); + assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); +} + +#[test] +fn nothing_selected_asks_for_a_layer() { + let mut harness = app_harness(); + select_nothing(&mut harness.state_mut().session); + harness.run_steps(4); + + assert!(shows_text(&harness, "Select a layer to paint on")); + assert!(shelf_button_disabled(&harness, "Geometry mask (8)")); +} + +#[test] +fn baking_keeps_three_greyed_tools_and_rendering_none() { + let mut harness = app_harness(); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + for label in ["Paint (1)", "Eraser (2)", "Polygon fill (4)"] { + assert!(shelf_button_disabled(&harness, label), "{label}"); + } + assert!(harness.query_by_label("Path (7)").is_none()); + + harness.state_mut().ui.mode = Mode::Rendering; + harness.run_steps(4); + + assert!(harness.query_by_label("Paint (1)").is_none()); +} + +#[test] +#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] +fn tool_availability_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)); + let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + for (brightness, suffix) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(8); + harness.render().unwrap().save(directory.join(format!("{name}-{suffix}.png"))).unwrap(); + } + }; + + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + session.tool.tool = Tool::Paint; + save(&mut harness, "paint-layer"); + + let session = &mut harness.state_mut().session; + let fill = add_layer(session, "layer.add.fill"); + select(session, fill, json!("content")); + session.tool.tool = Tool::PolygonFill; + save(&mut harness, "fill-content-polygon-fill"); + + let session = &mut harness.state_mut().session; + execute(session, "effect.add.filter", &json!({"layer": paint, "target": "content", "filter": "blur"})).unwrap(); + let filter = session.doc.project.layer(texturecraft_engine::core::LayerId(paint)).unwrap().content_effects.last().unwrap().id.0; + select(session, paint, json!(filter)); + session.tool.tool = Tool::Paint; + save(&mut harness, "filter"); + + let session = &mut harness.state_mut().session; + execute(session, "mask.add.black", &json!({"layer": paint})).unwrap(); + select(session, paint, json!("mask")); + session.tool.tool = Tool::Smudge; + save(&mut harness, "mask-smudge"); + + let session = &mut harness.state_mut().session; + let folder = add_layer(session, "layer.add.group"); + select(session, folder, json!("content")); + session.tool.tool = Tool::Paint; + save(&mut harness, "folder"); + + select_nothing(&mut harness.state_mut().session); + save(&mut harness, "nothing-selected"); + + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, "baking"); + + harness.state_mut().ui.mode = Mode::Rendering; + save(&mut harness, "rendering"); +} + +#[test] +fn unavailable_effect_tools_hide_their_properties() { + for path in [false, true] { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let layer = add_layer(session, "layer.add.paint"); + select(session, layer, json!("content")); + let (effect, usable, blocked) = if path { + let result = execute(session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + (result["committed"]["effect"].as_u64().unwrap(), Tool::Path, Tool::Paint) + } else { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + let result = execute(session, "effect.add.paint", &json!({"layer": layer, "target": "mask"})).unwrap(); + (result["effect"].as_u64().unwrap(), Tool::Paint, Tool::Smudge) + }; + select(session, layer, json!(effect)); + session.tool.tool = usable; + harness.run_steps(4); + assert!(shows_text(&harness, "Size")); + harness.state_mut().session.tool.tool = blocked; + harness.run_steps(4); + assert!(!shows_text(&harness, "Size"), "unavailable effect tools hide brush controls"); + if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { + let directory = std::path::PathBuf::from(directory); + std::fs::create_dir_all(&directory).unwrap(); + let name = if path { "unavailable-path-effect.png" } else { "unavailable-mask-paint-effect.png" }; + harness.render().unwrap().save(directory.join(name)).unwrap(); + } + } +} 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/list_panels.rs b/crates/ui-egui/tests/list_panels.rs new file mode 100644 index 00000000..7b6ace60 --- /dev/null +++ b/crates/ui-egui/tests/list_panels.rs @@ -0,0 +1,73 @@ +//! The History and Log lists fill their panel instead of stopping at a fixed height + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, Panel}; + +/// The list heights the panels used to stop at +const OLD_HISTORY_HEIGHT: f32 = 320.0; +const OLD_LOG_HEIGHT: f32 = 300.0; + +/// Leaves the left column (where the panel is docked) between 700 and 800 points tall +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 860.0); + +/// Right of the left column (11.5% of the window, about 184 points) and left of every other panel's scroll bar +const LEFT_COLUMN_MAX_X: f32 = 300.0; + +/// Enough rows to overflow the tallest panel +const ROWS: usize = 80; + +/// Small texture and bake sizes keep the sample session fast; the panels don'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; + +/// Dock `panel` in the full-height left column, where the Assets panel is by default +fn dock_in_left_column(harness: &mut Harness<'_, TextureCraftApp>, panel: &str) { + // Each panel name appears once in the saved dock: in the layout or in the hidden list + let saved = serde_json::to_string(&harness.state().ui.dock).unwrap(); + let placeholder = "\"swapped-out\""; + let swapped = saved.replace("\"Assets\"", placeholder).replace(&format!("\"{panel}\""), "\"Assets\"").replace(placeholder, &format!("\"{panel}\"")); + harness.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); +} + +/// The height of the list's scroll bar, which runs the visible height of the list +fn list_height(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let bar = harness.get_all_by_role(Role::ScrollBar).find(|bar| bar.rect().max.x < LEFT_COLUMN_MAX_X).expect("a scroll bar in the left column"); + bar.rect().height() +} + +#[test] +fn the_history_list_fills_a_tall_panel() { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let layer = session.selected_layer().unwrap(); + for step in 0..ROWS { + texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": format!("Step {step}")})).unwrap(); + } + + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + dock_in_left_column(&mut harness, "History"); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.state().ui.dock.is_visible(Panel::History)); + let height = list_height(&harness); + assert!(height > OLD_HISTORY_HEIGHT, "the history list is {height} points tall"); +} + +#[test] +fn the_log_list_fills_a_tall_panel() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.log.extend((0..ROWS).map(|line| format!("Log line {line}"))); + dock_in_left_column(&mut harness, "Log"); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.state().ui.dock.is_visible(Panel::Log)); + let height = list_height(&harness); + assert!(height > OLD_LOG_HEIGHT, "the log list is {height} points tall"); +} diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs new file mode 100644 index 00000000..7363a5dd --- /dev/null +++ b/crates/ui-egui/tests/project_limits.rs @@ -0,0 +1,55 @@ +use eframe::App as _; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::{Session, formats, geom}; +use texturecraft_ui_egui::{TextureCraftApp, UiState, control, state::Prefs}; + +#[path = "../src/ui_state_store/memory_storage.rs"] +mod memory_storage; +use memory_storage::MemoryStorage; + +#[test] +fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() { + let legacy: Prefs = serde_json::from_str("{}").unwrap(); + assert_eq!(legacy.project_open_limit_gib, 8); + let mut state = UiState::default(); + state.prefs.language = "en".into(); + state.prefs.project_open_limit_gib = 16; + state.prefs.reserved_cores = u32::MAX; + state.windows.settings = true; + let mut storage = MemoryStorage::default(); + storage.values.insert("ui.json".into(), serde_json::to_string(&state).unwrap()); + let session = Session::new_project("Limits", geom::primitives::plane(2.0, 1), "builtin:plane", None, 128).unwrap(); + let available_cores = u32::try_from(std::thread::available_parallelism().unwrap().get()).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).with_accessibility_check(false).build_eframe(|context| { + context.egui_ctx.data_mut(|data| data.insert_temp(egui::Id::unique("settings_resources"), (0.0_f64, available_cores, 16_u64 << 30))); + let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); + creation.storage = Some(&storage); + TextureCraftApp::new(&creation, session) + }); + + assert_eq!(formats::project_open_limit_gib(), 16, "saved preferences apply during startup"); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "preferences from a larger machine are clamped"); + harness.get_by_role_and_label(egui::Role::SpinButton, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX)); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "editing cannot exceed this machine's CPU count"); + assert!(harness.query_by_label("≈ 8.00 GiB").is_some(), "50% of 16 GiB is shown beside the percentage"); + harness.get_by_role_and_label(egui::Role::SpinButton, "Max RAM while saving").set_value_accesskit(25.0); + harness.run_steps(3); + assert!(harness.query_by_label("≈ 4.00 GiB").is_some(), "the byte estimate follows the edited percentage"); + + harness.get_by_role_and_label(egui::Role::SpinButton, "Max project size on open").set_value_accesskit(24.0); + harness.run_steps(3); + assert_eq!(formats::project_open_limit_gib(), 24, "the input field applies the edited value"); + + let context = egui::Context::default(); + let reply = control::handle(harness.state_mut(), &context, "ui.set", &serde_json::json!({"prefs": {"project_open_limit_gib": 32}})); + + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(formats::project_open_limit_gib(), 32, "no frame is needed before the next command"); + harness.state_mut().save(&mut storage); + let restored: UiState = serde_json::from_str(&storage.values["ui.json"]).unwrap(); + assert_eq!(restored.prefs.project_open_limit_gib, 32); +} diff --git a/crates/ui-egui/tests/shader_panel.rs b/crates/ui-egui/tests/shader_panel.rs new file mode 100644 index 00000000..805420cb --- /dev/null +++ b/crates/ui-egui/tests/shader_panel.rs @@ -0,0 +1,30 @@ +//! Shader Settings shows each of its settings once: the height strength lives in the texture set settings + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.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; + +#[test] +fn shader_settings_leave_the_height_strength_to_the_texture_set_settings() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).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.state_mut().ui.dock.focus(Panel::Shader); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.query_by_label("AO intensity").is_some(), "the Shader Settings panel is shown"); + // Texture Set Settings, the slider's other home, sits behind Layers in the default layout, so any match is in Shader Settings + assert!(!harness.state().ui.dock.is_visible(Panel::TextureSetSettings), "Texture Set Settings is behind Layers"); + assert!(harness.query_by_label("Height to normal strength").is_none()); +} diff --git a/crates/ui-egui/tests/skew_paint.rs b/crates/ui-egui/tests/skew_paint.rs deleted file mode 100644 index 891c1f25..00000000 --- a/crates/ui-egui/tests/skew_paint.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! 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. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::{Mode, 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, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.mode = Mode::Baking; - h.state_mut().ui.layout = ViewLayout::Only2D; - h.run_steps(4); - h -} - -#[test] -fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() { - let mut h = harness(); - h.get_by_label("Skew correction"); - assert!(h.state().session.bake_meshes.skew.is_none() && !h.state().ui.skew_brush.on); - // Off: a drag in the view paints nothing. - h.drag_at(egui::pos2(600.0, 500.0)); - h.hover_at(egui::pos2(800.0, 500.0)); - h.drop_at(egui::pos2(800.0, 500.0)); - h.run_steps(3); - assert!(h.state().session.bake_meshes.skew.is_none(), "the brush is off"); - - // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke. - h.get_by_label("Paint skew in the 2D view").click(); - h.run_steps(3); - assert!(h.state().ui.skew_brush.on); - h.get_by_label("Radius"); - h.drag_at(egui::pos2(600.0, 500.0)); - h.run_steps(2); - h.hover_at(egui::pos2(800.0, 500.0)); - h.run_steps(2); - h.drop_at(egui::pos2(800.0, 500.0)); - h.run_steps(3); - let map = h.state().session.bake_meshes.skew.clone().expect("the stroke made a skew map"); - let painted = map.values.iter().filter(|v| **v > 0.5).count(); - assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); - - // Removing it from the panel clears the map. - h.get_by_label("Remove skew correction").click(); - h.run_steps(3); - assert!(h.state().session.bake_meshes.skew.is_none()); -} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2f716340..d4374926 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -1,23 +1,25 @@ -//! Offscreen pictures of the whole window, for checking layout and design without a visible -//! screen (locked machines, CI, agents): +//! Offscreen UI snapshots at 1600x960, except the taller mesh-map panel +//! Requires a GPU adapter //! -//! ```sh -//! TC_UI_SNAPSHOTS= cargo test -p texturecraft-ui-egui --release --test ui_snapshots -- --ignored -//! ``` -//! -//! Writes `/.png` at 1600x960: the default layout in each brightness, the strip as the -//! app-drawn title bar (Windows) and with the macOS traffic lights' inset, a floating panel and the -//! main windows. Ignored by default: it needs a GPU adapter and takes a few -//! seconds. +//! Run with TC_UI_SNAPSHOTS= cargo test -p texturecraft-ui-egui --release --test ui_snapshots -- --ignored use std::path::{Path, PathBuf}; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakedMap, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; +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}")); @@ -26,83 +28,490 @@ fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { eprintln!("wrote {}", path.display()); } +/// Capture the moving preview and settled render after submitting real GPU callbacks. +#[test] +#[ignore] +fn rendering_mode_snapshots() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + 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(1280.0, 800.0)) + .with_pixels_per_point(1.0) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Rendering; + harness.state_mut().ui.render.max_samples = 16; + eprintln!("Rendering-mode adapter: {}", harness.state().gpu.as_ref().unwrap().adapter); + + // Submit each frame so the snapshots exercise the tracer callback, including size switches + for _ in 0..6 { + harness.state_mut().session.camera.yaw += 0.08; + harness.run_steps(1); + harness.render().unwrap(); + } + let moving_path = output_dir.join("rendering-moving.png"); + harness.render().unwrap().save(&moving_path).unwrap(); + eprintln!("wrote {}", moving_path.display()); + + for _ in 0..45 { + harness.run_steps(1); + harness.render().unwrap(); + } + save(&mut harness, &output_dir, "rendering-settled"); +} + +#[test] +#[ignore] +fn symmetry_snapshots() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(1024, 256).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.prefs.language = "en".into(); + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryY": true, "symmetryOffset": [0, 0.1, 0]})).unwrap(); + harness.state_mut().ui.symmetry.show_plane = true; + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(4); + harness.get_by_label("Symmetry settings").click(); + + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("symmetry-mirror-{name}")); + } + + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryY": false, "symmetryRadial": 6, "symmetryAxis": "y", "symmetryAngleSpan": 240})).unwrap(); + harness.state_mut().ui.symmetry.show_axis = true; + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + save(&mut harness, &output_dir, "symmetry-radial"); + + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryX": true, "symmetryY": true})).unwrap(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("symmetry-combined-{name}")); + } +} + #[test] #[ignore] fn window_snapshots() { - let Some(dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + 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(&dir).unwrap(); + + std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(1024, 256).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); - for (b, name) in [(Brightness::MediumDark, "main"), (Brightness::Dark, "brightness-dark"), (Brightness::Light, "brightness-light")] { - h.state_mut().ui.prefs.brightness = b; - save(&mut h, &dir, name); + 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)); + for (brightness, name) in [(Brightness::MediumDark, "main"), (Brightness::Dark, "brightness-dark"), (Brightness::Light, "brightness-light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, name); } - h.state_mut().ui.prefs.brightness = Brightness::MediumDark; - h.state_mut().title_bar = TitleBar::Integrated; - save(&mut h, &dir, "titlebar-macos"); - h.state_mut().title_bar = TitleBar::App(craft_window::Layout::default()); - save(&mut h, &dir, "titlebar-app"); - // The close button under the pointer, and the glyphs at a fractional scale. - h.hover_at(egui::pos2(1600.0 - 23.0, 14.0)); - save(&mut h, &dir, "titlebar-app-close-hover"); - h.hover_at(egui::pos2(800.0, 500.0)); - h.set_pixels_per_point(1.5); - save(&mut h, &dir, "titlebar-app-150"); - h.set_pixels_per_point(1.0); - h.state_mut().title_bar = TitleBar::System; - h.state_mut().ui.dock.focus(Panel::Display); - save(&mut h, &dir, "panel-display"); - h.state_mut().ui.dock.close(Panel::Display); - h.state_mut().ui.windows.export = true; - save(&mut h, &dir, "window-export"); - h.state_mut().ui.windows.export = false; - h.state_mut().ui.windows.settings = true; - save(&mut h, &dir, "window-settings"); - h.state_mut().ui.windows.settings = false; - // The mesh map slots, each with its menu of images (a tall window shows them all). - h.state_mut().ui.dock.focus(Panel::TextureSetSettings); - h.set_size(egui::vec2(1600.0, 1800.0)); - save(&mut h, &dir, "panel-texture-set-settings"); - h.set_size(egui::vec2(1600.0, 960.0)); - // A mask's levels effect over clouds: the histogram in Properties. - let s = &mut h.state_mut().session; - for (id, p) in [ + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.state_mut().title_bar = TitleBar::Integrated; + save(&mut harness, &output_dir, "titlebar-macos"); + harness.state_mut().title_bar = TitleBar::App(craft_window::Layout::default()); + save(&mut harness, &output_dir, "titlebar-app"); + + // Check hover feedback and fractional scaling + harness.hover_at(egui::pos2(1600.0 - 23.0, 14.0)); + save(&mut harness, &output_dir, "titlebar-app-close-hover"); + harness.hover_at(egui::pos2(800.0, 500.0)); + harness.set_pixels_per_point(1.5); + save(&mut harness, &output_dir, "titlebar-app-150"); + harness.set_pixels_per_point(1.0); + harness.state_mut().title_bar = TitleBar::System; + + for texture_set in &mut harness.state_mut().session.doc.project.texture_sets { + texture_set.bake = Default::default(); + } + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, &output_dir, "mode-bake"); + 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; + 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::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_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"); + harness.get_by_label("Output Size").scroll_to_me(); + harness.state_mut().session.doc.project.texture_sets[0].bake.common.resolution_height = Some(BakeResolution::R1024); + save(&mut harness, &output_dir, "bake-settings-unlocked"); + harness.set_pixels_per_point(1.5); + save(&mut harness, &output_dir, "bake-settings-150"); + harness.set_pixels_per_point(1.0); + { + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + settings.maps.select([BakedMap::Curvature, BakedMap::Height]); + settings.maps.curvature.parameters.method = CurvatureMethod::Mesh; + settings.maps.height.parameters.normalization = HeightNormalization::Manual; + settings.maps.height.parameters.scaling_divisor = 100.0; + } + select_map(&mut harness, "Curvature"); + save(&mut harness, &output_dir, "bake-curvature-mesh"); + 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; + save(&mut harness, &output_dir, "painting-restored"); + + harness.state_mut().ui.dock.focus(Panel::Display); + save(&mut harness, &output_dir, "panel-display"); + harness.state_mut().ui.dock.close(Panel::Display); + harness.state_mut().ui.windows.export = true; + save(&mut harness, &output_dir, "window-export"); + harness.state_mut().ui.windows.export = false; + harness.state_mut().ui.windows.settings = true; + save(&mut harness, &output_dir, "window-settings"); + harness.state_mut().ui.windows.settings = false; + + // A taller window exposes every mesh-map slot + harness.state_mut().ui.dock.focus(Panel::TextureSetSettings); + harness.set_size(egui::vec2(1600.0, 1800.0)); + save(&mut harness, &output_dir, "panel-texture-set-settings"); + harness.set_size(egui::vec2(1600.0, 960.0)); + + // Show the mask histogram in Properties + let session = &mut harness.state_mut().session; + for (id, params) in [ ("layer.add.fill", serde_json::json!({"color": [0.8, 0.3, 0.1]})), ("mask.add.black", serde_json::Value::Null), ("effect.add.fill", serde_json::json!({"target": "mask", "procedural": "clouds"})), ("effect.add.levels", serde_json::json!({"target": "mask", "inLow": 0.3, "inHigh": 0.8})), ] { - texturecraft_engine::execute(s, id, &p).unwrap(); + texturecraft_engine::execute(session, id, ¶ms).unwrap(); } - save(&mut h, &dir, "properties-levels"); - // A path sublayer: its paths listed in Properties, the second one being edited. - let s = &mut h.state_mut().session; - for (id, p) in [ + save(&mut harness, &output_dir, "properties-levels"); + // Show the Layers panel thumbnails with a hidden content effect, a folder and a mask + let session = &mut harness.state_mut().session; + for (id, params) in [ + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "hsl"})), + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "invert"})), + ("layer.add.paint", serde_json::Value::Null), + ("layer.group", serde_json::Value::Null), + ] { + texturecraft_engine::execute(session, id, ¶ms).unwrap(); + } + let hidden = harness + .state() + .session + .doc + .project + .layers + .values() + .flat_map(|layer| layer.content_effects.iter()) + .find(|effect| effect.name == "Invert") + .map(|effect| effect.id.0); + if let Some(effect) = hidden { + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &serde_json::json!({"effect": effect, "visible": false})).unwrap(); + } + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.set_size(egui::vec2(1600.0, 1400.0)); + for _ in 0..400 { + harness.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + if !harness.state().layer_panel.service().busy() { + break; + } + } + save(&mut harness, &output_dir, "panel-layers"); + harness.set_size(egui::vec2(1600.0, 960.0)); + // Show the second path selected in Properties + let session = &mut harness.state_mut().session; + for (id, params) in [ ("layer.add.paint", serde_json::Value::Null), ("tool.path", serde_json::json!({"uvPoints": [[0.2, 0.5], [0.5, 0.4], [0.8, 0.5]], "commit": true})), ("tool.path", serde_json::json!({"uvPoints": [[0.3, 0.7], [0.7, 0.7], [0.7, 0.9]], "closed": true, "fill": true, "commit": true})), ] { - texturecraft_engine::execute(s, id, &p).unwrap(); + texturecraft_engine::execute(session, id, ¶ms).unwrap(); } - let effect = match s.target { + + let effect = match session.target { texturecraft_engine::StackTarget::Effect(e) => e.0, _ => 0, }; - texturecraft_engine::execute(s, "path.edit", &serde_json::json!({"effect": effect, "index": 1})).unwrap(); - save(&mut h, &dir, "properties-paths"); - // Ctrl+right drag in the 3D view: the brush cursor where it began and the readout. - let c = h.state().viewport_rect.center(); - let (m, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary); - h.event(egui::Event::ModifiersChanged(m)); - h.event(egui::Event::PointerButton { pos: c, button, pressed: true, modifiers: m }); - for k in 1..=4 { - h.hover_at(c + egui::vec2(15.0 * k as f32, -8.0 * k as f32)); - h.run_steps(1); + texturecraft_engine::execute(session, "path.edit", &serde_json::json!({"effect": effect, "index": 1})).unwrap(); + save(&mut harness, &output_dir, "properties-paths"); + + // Show the brush cursor and readout during Ctrl+right drag + let cursor_position = harness.state().viewport_rect.center(); + let (modifiers, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary); + harness.event(egui::Event::ModifiersChanged(modifiers)); + harness.event(egui::Event::PointerButton { pos: cursor_position, button, pressed: true, modifiers }); + for step in 1..=4 { + harness.hover_at(cursor_position + egui::vec2(15.0 * step as f32, -8.0 * step as f32)); + harness.run_steps(1); } - save(&mut h, &dir, "brush-ctrl-drag"); - h.event(egui::Event::PointerButton { pos: c, button, pressed: false, modifiers: m }); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + save(&mut harness, &output_dir, "brush-ctrl-drag"); + 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("128x128*").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("128x128*").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("256x256").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"); +} + +/// Compact nested rows must keep their content, mask and effect controls in the panel. +#[test] +#[ignore] +fn nested_layers_snapshot() { + use craft_ui::docking::Node; + use craft_ui::layout::SplitSize; + use serde_json::{Value, json}; + use texturecraft_engine::execute; + use texturecraft_ui_egui::docking::Dock; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(); + execute(&mut session, "mask.add.white", &Value::Null).unwrap(); + execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + for _ in 0..6 { + execute(&mut session, "layer.group", &Value::Null).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1600.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + let mut workspace = harness.state().ui.dock.workspace().clone(); + let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; + let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; + *size = SplitSize::Ratio(0.99); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + for _ in 0..100 { + harness.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + if !harness.state().layer_panel.service().busy() { + break; + } + } + save(&mut harness, &output_dir, "panel-layers-narrow-nested"); +} + +#[test] +#[ignore] +fn path_tool_snapshots() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + texturecraft_engine::execute(&mut session, "tool.path", &serde_json::json!({"uvPoints": [[0.25, 0.5], [0.5, 0.3], [0.75, 0.5]]})).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.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; + harness.state_mut().session.select_path_point(1); + harness.hover_at(egui::pos2(800.0, 600.0)); + save(&mut harness, &output_dir, "path-preview-2d"); + + harness.state_mut().session.commit_path(texturecraft_engine::geom::glam::Vec2::splat(400.0)).unwrap(); + save(&mut harness, &output_dir, "path-stored-2d"); +} + +#[test] +#[ignore] +fn rail_window_snapshots() { + 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::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(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + let context = harness.ctx.clone(); + + for (command, name) in [ + ("ui.view.textureSetSettings", "rail-texture-set-settings"), + ("ui.view.display", "rail-display"), + ("ui.view.shader", "rail-shader"), + ("ui.view.history", "rail-history"), + ("ui.view.log", "rail-log"), + ] { + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, command); + save(&mut harness, &output_dir, name); + } + + harness.set_size(egui::vec2(1600.0, 600.0)); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.display"); + harness.run_steps(6); + harness.get_by_label("Temporal anti-aliasing (refines the 3D view while it is still)").scroll_to_me(); + save(&mut harness, &output_dir, "rail-display-short"); + + harness.set_size(egui::vec2(1600.0, 400.0)); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.history"); + save(&mut harness, &output_dir, "rail-history-short"); +} + +/// Visual check of the migrated catalogs and the live language selector. +#[test] +#[ignore] +fn i18n_snapshots() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + for code in ["en", "es", "ar"] { + assert!(texturecraft_ui_egui::i18n::available(code), "build with migrated catalogs for {code}"); + let session = texturecraft_engine::sample_session(128, 32).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.prefs.language = code.into(); + harness.state_mut().ui.windows.settings = true; + save(&mut harness, &output_dir, &format!("i18n-{code}")); + } + texturecraft_ui_egui::i18n::set_language("en"); } 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/architecture.md b/docs/architecture.md index d53763a3..9b0bd08c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,6 +69,30 @@ The CPU compositor is the reference for everything users see and export. Export (`formats::export`) reads the same composite, adds height-to-normal (Sobel) combined with the normal channel and baked normals by reoriented normal mapping, and packs channels per preset. +### Layer-panel thumbnails + +The Layers panel shows each layer's content (in the displayed channel), its mask and every effect +stage as small pictures. `compose::thumb::render` runs the same compositor on a *cut* copy of the +project: the requested layer is forced visible at Normal / 100 %, without its mask for content, +and with its effect list truncated after the previewed effect (a hidden effect shows the result +it bypasses). Lower layers remain available when the preview reads anchor points; only the requested +layer is drawn. Instances use their source's channels. Paint and fill layers are flattened to +(value, coverage), so empty texels are transparent; folders composite their children. Colors are +encoded linear to sRGB, data channels raw. Everything is evaluated on a 64 px G-buffer of the mesh +(painted tiles are resampled), never at the set's resolution, and the main composite is never touched. + +`engine::thumbs::ThumbService` runs it off the UI thread: an immutable `ThumbSnapshot` (the +project, copy-on-write pixel tiles, baked maps, images and the cached 64 px G-buffer) is rebuilt +only when the document really differs (compared at most every 120 ms while it keeps changing), a +worker thread renders one job at a time (inline, one per frame, on wasm32), results of an older +snapshot are dropped. At most two jobs, including stale generations, retain snapshots in the worker. +Collecting a result requests another frame to display it. An LRU of 96 pictures keeps the out-of-date +picture on screen until its replacement arrives. Only rows on screen ask for pictures; queued rows +that scrolled away are dropped. Baked-map changes are checked by shared buffer identity, without +scanning full-resolution float arrays on the UI thread. Run `perf::bench_layer_thumbs_4k` in release mode to measure snapshot +construction and content, mask and stage rendering on a ten-layer 4096 set. Run +`thumbs::tests::benchmark_unchanged_4k_baked_snapshot` to measure comparisons with 256 MiB of baked maps. + ## Undo `Session::edit` snapshots the `Document` (project + pixels + baked maps + resources) before a @@ -98,10 +122,10 @@ on the CPU by `render::displace` from the composited height. A fill can carry a `MaterialLink` (`core::layer`): a MaterialCraft graph whose cooked maps are the fill's image sources. `engine::link_cmds` imports `.mcmat` files (`formats::mcmat`), keeps the -`.mcraft` package as a resource, and re-cooks by running `materialcraft-cli` with the link's +`.mcraft` or `.sbs` source as a resource, and re-cooks its named graph by running `materialcraft-cli` with the link's values, the texture set's resolution and its baked mesh maps (`LinkJob::run`, on a worker thread in the UI). Every cook stores its maps under fresh resource names, so undo, redo and the decoded -image cache never disagree. The apps share the file format and the command line, never code. +image cache never disagree. The apps share the `craft-mcmat` format library and the command line; neither depends on the other app. ## Commands and automation diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..0ead3445 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 @@ -62,9 +104,11 @@ keeps its state in a throwaway file. | `command.run` | `{id, params?}` | the command's JSON result | | `command.list` | `{filter?}` | `[{id, label, menu, shortcut, params, enabled}]` | | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | -| `ui.inspect` | | UI state, viewport rect, fps, bake progress, toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | +| `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled}` | | `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window) | +| `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | +| `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back | | `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History` and `Log`; `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | @@ -85,6 +129,41 @@ Example session: < {"id":3,"ok":true,"result":{"width":1210,"height":788,"png":"iVBORw0KGgo…"}} ``` +### Live bake preview + +A bake started in the app (`ui.bake.start`, or the Bake button) makes the mesh maps one after +another, in the `BakedMap` order of the set's enabled maps, and shows each one on the model as +soon as it is finished and padded: the 3D view displays the newest finished map raw (normals as +RGB, scalar maps as gray, ID maps as their colors), maps and texture sets not baked yet show their +neutral value, and the bake bar names the stage (`Baking Ambient Occlusion (2/4)`). Each map is a +bake of its own, so with a high poly the transfer rays are cast once per map; the pixels are the +same as a single bake's. `bake.run` and the CLI bake all maps at once and never show a preview. + +The streamed maps are held by the session, not the document: nothing enters the undo history +until a texture set's bake is applied (one undo step); a cancelled bake leaves the set it was baking +as it was, while sets that finished before the cancel stay applied. When +the bake ends, is cancelled or Bake mode is left, the view mode that was in use comes back. +Bake setup overlays are hidden during the preview so they cannot cover the maps; their visibility +settings take effect again when the preview ends. +**Painting is paused while a bake is shown**: strokes and polygon fills fail with "Painting is paused while a bake +is shown. Cancel the bake or wait for it to finish." + +`bake.preview` `{show?: "follow" \| "material" \| "map:"}` reads and sets what the view shows +(also the control in the bake bar): `follow` (default) the newest finished map, `material` the lit +material, `map:` one map pinned (neutral until it is baked). Picking a mesh map with +`viewport.view` during a bake pins it; any other view mode is kept for when the bake ends. Result, +also `session.inspect`'s `bakePreview`: + +```json +{"active": true, "show": "follow", "shown": "ambientOcclusion", "newest": "ambientOcclusion", + "restore": "Material", "stage": {"set": 0, "map": "curvature", "n": 3, "total": 4}, + "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} +``` + +`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with +`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) +until `baking` is `null`. + A minimal client (Python, for illustration): ```python @@ -103,6 +182,15 @@ call("auth", {"token": token}) print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1, 0.1]}})) ``` +The UI's `prefs.project_open_limit_gib` sets the maximum decompressed project data accepted on open +(default 8 GiB, minimum 1 GiB). Set it with `ui.set {"prefs":{"project_open_limit_gib":16}}`; +it takes effect before the next control request, without waiting for a frame, and persists with +the UI preferences. Individual entry limits still apply. This controls opening only, independently +of `prefs.reserved_cores` and `prefs.save_ram_percent` for saving. +Settings bounds the reserved-core input to the available logical CPU count and shows the estimated +save budget in GiB beside the RAM percentage. The readout refreshes once a second from currently +available RAM; a save calculates its budget when it starts. + ## MCP server `texturecraft-cli mcp` speaks MCP on stdin/stdout (stdout carries only protocol messages). @@ -120,8 +208,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 +225,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,13 +311,23 @@ 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 documented in MaterialCraft's `docs/control-protocol.md` § Portable materials) becomes a fill layer whose channel sources are its cooked maps and whose `link` (shown by `project.inspect`) holds the -graph's exposed inputs, presets and image inputs. The apps share the format and the command line, -not code. +graph's exposed inputs, presets and image inputs. Both apps use the shared `craft-mcmat` container. +Versions 1 and 2 are accepted; version 1 contains a legacy JSON `.mcraft` source that current +MaterialCraft cannot reopen, so its cooked maps remain usable but re-cooking needs a compatible older version. | Command | Params | |---|---| @@ -237,9 +335,9 @@ not code. | `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` | | `material.link.preset` | `{layer?, name, cook?: true}` | | `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) | -| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` package, to open in MaterialCraft | +| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` or `.sbs` source, to open in MaterialCraft | -Re-cooks run `materialcraft-cli run file.exportMaterial {path, size, values, inputs}`: +Re-cooks use `materialcraft-cli batch` to open the saved graph by name and run `file.exportMaterial` with its size, values and inputs: `$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`, diff --git a/docs/features.md b/docs/features.md index fcbaca5f..6c68cf6e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -16,7 +16,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA stroke and keep the size; save your own brushes there too. - **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the stencil), polygon fill (triangle, UV island or the whole mesh), **path** and **lasso fill**, a - **particle brush**, **smudge**, **clone** (V + click sets the source), color picker, Shift+click + **particle brush**, **smudge**, **clone** (V + click sets the source), material picker, Shift+click straight lines, and painting directly in the **2D UV view**. - **Geometry decals:** drop an image on the surface, then move, scale and turn its frame; it stays an editable fill layer. @@ -80,7 +80,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. - Reimport a changed mesh and your painted strokes stay on the surface. + Reimport a changed mesh and your painted strokes stay on the surface. The + `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). @@ -103,6 +104,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA edited): drop one from the Assets panel on a slot of the Texture Set Settings, or pick it from the slot's menu. A UV-tiled set takes one image per tile, named with its tile number (`ao.1001.png`, `ao.1002.png`…): drop or pick any one of them. +- **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is + finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md new file mode 100644 index 00000000..fbe4f69d --- /dev/null +++ b/docs/helpful-pr-review-guidelines.md @@ -0,0 +1,69 @@ +# 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 +- Read and apply [CODE_STYLE.md](../CODE_STYLE.md) throughout that scope +- 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 +- Keep control flow direct and share repeated logic when it makes the code simpler +- Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access +- For loops, batches, and streaming operations, trace allocations and buffer lifetimes across multiple iterations, including outputs retained from earlier iterations. Identify work that belongs once per operation rather than once per item, using the full selection when making retention decisions +- 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 + +## 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 +- For memory-related changes, verify allocation/resampling counts or peak live memory in representative multi-item cases. Final pixel equality and shared output buffers do not prove that temporary allocations are avoided +- 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/internationalization.md b/docs/internationalization.md new file mode 100644 index 00000000..c75b7e44 --- /dev/null +++ b/docs/internationalization.md @@ -0,0 +1,29 @@ +# Interface translations + +TextureCraft uses the `craft-i18n` runtime from craft-libs and optional catalogs from +[craft-i18n](https://github.com/storytold/craft-i18n). + +Set `CRAFT_I18N_DIR` to the absolute path of a craft-i18n checkout before building. +The build embeds `locales//common.tsv` and `texturecraft.tsv`. Without catalog input, +the application uses English. `CRAFT_I18N_REQUIRED=1` makes missing/invalid input a build error. +The same catalogs are embedded for native and WebAssembly builds; no runtime files are needed. + +Feature changes add English strings through `tr`, `n_` or `trf`. Translations belong in +craft-i18n PRs. A missing translation displays English and does not block a feature or release. +Run `cargo test -p texturecraft-ui-egui translation_coverage_report -- --nocapture` with +catalog input to inspect untranslated and unused/shared keys. Shared catalogs contain other +apps' strings, so unused shared keys are informational, not candidates for automatic deletion. + +The initial migration is tracked in storytold/texturecraft#419. Catalog changes must merge +before the application cutover, and translations landing meanwhile need a final sync. +Saved `pt-BR` and `zh-Hans` preferences retain their original spelling and meaning. + +## CI and release catalog revision + +`craft-i18n.rev` pins the catalog commit. The shared craft-common-actions gate and release +workflows read this file, check out storytold/craft-i18n and set CRAFT_I18N_DIR together with +CRAFT_I18N_REQUIRED=1. No application workflow changes are needed. + +The catalog commit must be available in storytold/craft-i18n before merging the app cutover. +After a squash or rebase merge of the companion catalog PR, update the pin to the resulting +upstream commit and rerun validation before merging TextureCraft. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index e664b605..fb6a8a49 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -2,20 +2,23 @@ TextureCraft's interface text goes through one lookup, `tr("English text")` in `crates/ui-egui/src/i18n.rs`: the English string is the key, so English needs no table and a -missing translation falls back to English. Each language is a static `(English, translation)` -table in `crates/ui-egui/src/i18n/.rs`, indexed into a hash map the first time the -language is used. Text with values uses `trf("Saved {path}", &[("path", &p)])`; static labels -that are translated where they are shown are marked with `n_("…")`. +missing translation falls back to English. Translations are embedded from the optional shared +craft-i18n catalogs; see [integration and contribution instructions](internationalization.md). +Text with values uses `trf("Saved {path}", &[("path", &p)])`; static labels translated where +they are shown are marked with `n_("…")`. Pick the language in **Edit ▸ Settings ▸ Language** (it switches live). The first run follows the operating system's language (the browser's in the web build). ## Status +The table records coverage before the initial catalog migration. Actual coverage depends on +the craft-i18n catalogs embedded in a build. Without catalogs, only English is offered. + UI strings: every `tr`/`trf`/`n_` literal in `crates/ui-egui/src` plus the menu catalog, panel names, shortcut editor rows and the engine's channel, blend mode, mesh map, tool, procedural, generator, filter and brush alpha names (**KEYS** strings, counted by the -`every_key_is_translated_in_every_language` test, which fails when one is missing). +`translation_coverage_report` test, which reports missing and unused keys without failing). | Language | Code | UI strings | Dialogs, tooltips, help | Script support | Native review | Status | To `full` | |---|---|---|---|---|---|---|---| 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..4fb8d5fd --- /dev/null +++ b/docs/testing-ci.md @@ -0,0 +1,49 @@ +# 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:: +``` + +For faster optimized local verification, run the same workspace tests and doctests +with the `verify` profile: + +```sh +cargo test --workspace --profile verify +``` + +`verify` inherits the release profile's optimization level and runtime checks, but +uses 16 codegen units and `lto = false`. Cargo retains thin LTO within each crate +without repeating cross-crate LTO for every test executable. The existing test +selection and ignore attributes still apply. Keep the target directory between +runs so Cargo can reuse unchanged build artifacts. + +To compile the normal application binaries alongside the test binaries before +running them: + +```sh +cargo build --workspace --bins --tests --profile verify +cargo test --workspace --profile verify +``` + +This profile is for local verification. Use `--release` for release validation and +performance measurements; its compiler settings remain unchanged. The regular +debug test profile and CI gates also remain unchanged. + +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. diff --git a/packaging/env.sh b/packaging/env.sh index 4fe93776..9ca7ca2c 100644 --- a/packaging/env.sh +++ b/packaging/env.sh @@ -21,7 +21,7 @@ workspace_version() { ' "$ROOT/Cargo.toml" } -VERSION="${TEXTURECRAFT_VERSION:-$(workspace_version)}" +VERSION="${TEXTURECRAFT_VERSION:-${RELEASE_VERSION:-$(workspace_version)}}" if [ -z "$VERSION" ]; then echo "error: could not read [workspace.package] version from $ROOT/Cargo.toml" >&2 exit 1 diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index c9929b40..bf2b46ca 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -20,7 +20,7 @@ APP_ID=ai.storyteller.texturecraft SKIP_BUILD=0 DRY_RUN=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --dry-run) DRY_RUN=1; SKIP_BUILD=1; shift ;; @@ -37,14 +37,14 @@ case "$MACHINE" in *) echo "unsupported architecture $MACHINE" >&2; exit 2 ;; esac ARCH="$HOST_ARCH" -if [ -n "${CARGO_BUILD_TARGET:-}" ]; then +if [[ -n "${CARGO_BUILD_TARGET:-}" ]]; then case "$CARGO_BUILD_TARGET" in aarch64-unknown-freebsd) ARCH=aarch64 ;; x86_64-unknown-freebsd) ARCH=x86_64 ;; *) echo "error: unsupported FreeBSD target $CARGO_BUILD_TARGET" >&2; exit 2 ;; esac fi -if [ "$DRY_RUN" = 0 ] && [ "$(uname -s)" != FreeBSD ]; then +if [[ "$DRY_RUN" = 0 ]] && [[ "$(uname -s)" != FreeBSD ]]; then echo "error: build on FreeBSD (or pass --dry-run to check the tree layout)" >&2 exit 2 fi @@ -54,7 +54,7 @@ echo "==> TextureCraft $VERSION for FreeBSD $ARCH" # The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli) fi WORK="$CARGO_TARGET_DIR/freebsd-package" @@ -64,7 +64,7 @@ mkdir -p "$WORK" BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release" OUT_DIR="$DIST" -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then # Stub binaries, and the tarball stays in the work dir so dist/ only ever holds real builds. BIN="$WORK/stub-bin" OUT_DIR="$WORK" @@ -92,7 +92,7 @@ copy_docs "$STAGE/share/doc/texturecraft" for f in bin/texturecraft bin/texturecraft-cli "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ share/doc/texturecraft/LICENSE-MIT share/doc/texturecraft/LICENSE-APACHE; do - if [ ! -e "$STAGE/$f" ]; then echo "error: $f is missing from the package" >&2; exit 1; fi + if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done # ---- .tar.gz ------------------------------------------------------------------------------------ @@ -100,10 +100,10 @@ mkdir -p "$OUT_DIR" tar -C "$WORK" -czf "$OUT_DIR/$BASENAME.tar.gz" "$BASENAME" echo "wrote $OUT_DIR/$BASENAME.tar.gz" -if [ -z "${CARGO_BUILD_TARGET:-}" ] || [ "$DRY_RUN" = 1 ]; then +if [[ -z "${CARGO_BUILD_TARGET:-}" ]] || [[ "$DRY_RUN" = 1 ]]; then "$STAGE/bin/texturecraft-cli" --version fi -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then echo "==> dry run: tarball contents" tar -tzvf "$OUT_DIR/$BASENAME.tar.gz" fi diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 0668cc80..cfb9548e 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -37,10 +37,10 @@ fail() { # 1. Launch works and passes arguments through. out="$("$APPDIR/AppRun" open model.glb)" || fail "AppRun exited non-zero" -[ "$out" = "stub: open model.glb" ] || fail "arguments not forwarded: $out" +[[ "$out" = "stub: open model.glb" ]] || fail "arguments not forwarded: $out" DESKTOP="$XDG_DATA_HOME/applications/$APP_ID.desktop" -[ -f "$DESKTOP" ] || fail "desktop entry not installed" +[[ -f "$DESKTOP" ]] || fail "desktop entry not installed" # 2. Exec rewritten to the AppImage (quoted, spaces intact), TryExec dropped, # everything else preserved from the packaged entry. @@ -55,15 +55,15 @@ fi # 3. Icons landed under the name the .desktop entry references. for f in "16x16/apps/$APP_ID.png" "256x256/apps/$APP_ID.png" "scalable/apps/$APP_ID.svg"; do - [ -f "$XDG_DATA_HOME/icons/hicolor/$f" ] || fail "icon missing: $f" + [[ -f "$XDG_DATA_HOME/icons/hicolor/$f" ]] || fail "icon missing: $f" done # 4. Idempotent: a second launch must not rewrite anything (inode unchanged). before="$(stat -c %i "$DESKTOP")" out="$("$APPDIR/AppRun")" || fail "second launch exited non-zero" -[ "$out" = "stub: " ] || fail "second launch output: $out" +[[ "$out" = "stub: " ]] || fail "second launch output: $out" after="$(stat -c %i "$DESKTOP")" -[ "$before" = "$after" ] || fail "desktop entry rewritten although unchanged" +[[ "$before" = "$after" ]] || fail "desktop entry rewritten although unchanged" # 5. Moving the AppImage refreshes Exec. mv "$APPIMAGE" "$TMP/moved.AppImage" @@ -74,25 +74,25 @@ grep -Fxq "Exec=\"$(readlink -f "$APPIMAGE")\" %F" "$DESKTOP" || fail "Exec not # 6. Opt-out installs nothing. rm -rf "$XDG_DATA_HOME" TEXTURECRAFT_NO_DESKTOP_INTEGRATION=1 "$APPDIR/AppRun" >/dev/null || fail "opt-out launch exited non-zero" -[ ! -e "$XDG_DATA_HOME" ] || fail "opt-out still integrated" +[[ ! -e "$XDG_DATA_HOME" ]] || fail "opt-out still integrated" # 7. An unwritable data dir never blocks the launch. mkdir -p "$TMP/ro" && chmod a-w "$TMP/ro" out="$(XDG_DATA_HOME="$TMP/ro/data" "$APPDIR/AppRun" out.txt)" || fail "launch blocked by unwritable data dir" -[ "$out" = "stub: out.txt" ] || fail "stub not run against unwritable data dir: $out" +[[ "$out" = "stub: out.txt" ]] || fail "stub not run against unwritable data dir: $out" chmod u+w "$TMP/ro" # 8. No $APPIMAGE (extracted AppDir): launch only, nothing installed. rm -rf "$XDG_DATA_HOME" env -u APPIMAGE "$APPDIR/AppRun" >/dev/null || fail "extracted-AppDir launch exited non-zero" -[ ! -e "$XDG_DATA_HOME" ] || fail "integrated without $APPIMAGE" +[[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated without $APPIMAGE" # 9. A path that would need Exec escaping (here a `$`): launch only, nothing installed. rm -rf "$XDG_DATA_HOME" odd="$TMP/odd\$(id).AppImage" : >"$odd" out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exited non-zero" -[ "$out" = "stub: x" ] || fail "odd path: $out" -[ ! -e "$XDG_DATA_HOME" ] || fail "integrated an AppImage path that needs escaping" +[[ "$out" = "stub: x" ]] || fail "odd path: $out" +[[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated an AppImage path that needs escaping" echo "AppRun desktop integration ok" diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 3f9e4e07..4e884d84 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -18,12 +18,18 @@ set -euo pipefail HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.texturecraft FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo +# The OCI repository serves only the latest stable release, so a prerelease bundle gets no update +# source: Flatpak would otherwise replace it with that older stable build. +OCI_REPO=oci+https://getartcraft.com +if [[ "$VERSION" == *-* ]]; then OCI_REPO=""; fi TEST=1 +OCI=0 TARBALL="" -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --no-test) TEST=0; shift ;; + --oci) OCI=1; shift ;; -h | --help) sed -n '2,14p' "$0"; exit 0 ;; -*) echo "unknown argument: $1" >&2; exit 2 ;; *) TARBALL="$1"; shift ;; @@ -38,7 +44,7 @@ case "$ARCH" in esac BASENAME="texturecraft-$VERSION-linux-$ARCH" TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}" -[ -f "$TARBALL" ] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } +[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } for tool in flatpak flatpak-builder; do command -v "$tool" >/dev/null || { echo "error: $tool not found (apt install flatpak flatpak-builder librsvg2-common)" >&2; exit 1; } done @@ -49,7 +55,7 @@ WORK="$CARGO_TARGET_DIR/flatpak-bundle" rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 -[ -x "$WORK/stage/bin/texturecraft" ] || { echo "error: $TARBALL has no bin/texturecraft" >&2; exit 1; } +[[ -x "$WORK/stage/bin/texturecraft" ]] || { echo "error: $TARBALL has no bin/texturecraft" >&2; exit 1; } cp "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" "$WORK/$APP_ID.yml" flatpak remote-add --user --if-not-exists flathub "$FLATHUB" @@ -58,11 +64,26 @@ flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --forc --default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml" OUT="$DIST/$BASENAME.flatpak" +# A release build (the shared release workflow sets SIGNING_FPR, SIGNING_PUBKEY and GNUPGHOME) +# signs the commit and embeds the public key, so Flatpak verifies the bundle when installing it. +GPG_KEYS=() +if [[ -n "${SIGNING_FPR:-}" ]]; then + flatpak build-sign "$WORK/repo" "$APP_ID" stable --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}" + GPG_KEYS=(--gpg-keys="${SIGNING_PUBKEY:?}") + if [[ "${OCI_SIGNATURES_READY:-}" != 1 ]]; then OCI_REPO=""; fi +fi # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. -flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable +# --repo-url makes the installed origin update from the ArtCraft OCI repository. +flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" +if [[ "$OCI" = 1 ]]; then + OUT_OCI="$DIST/$BASENAME-oci" + rm -rf "$OUT_OCI" + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + echo "wrote OCI layout to $OUT_OCI" +fi -if [ "$TEST" = 1 ]; then +if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" flatpak info --user "$APP_ID" flatpak run --command=texturecraft-cli "$APP_ID" --version diff --git a/packaging/linux/flatpak-oci.sh b/packaging/linux/flatpak-oci.sh new file mode 100755 index 00000000..d905eda4 --- /dev/null +++ b/packaging/linux/flatpak-oci.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Build texturecraft as an OCI container layout and push it to GitHub Container Registry (GHCR) +# for consumption by Flatpak OCI clients (flatpak-oci-specs). +# +# Usage: +# packaging/linux/flatpak-oci.sh [--push] [TARBALL] +# +# Environment variables: +# REGISTRY Target registry image (default: ghcr.io/storytold/texturecraft) +# TAG Target image tag (default: $VERSION-$ARCH, also tags stable-$ARCH) +# GITHUB_TOKEN Token for GHCR authentication when --push is used +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" + +PUSH=0 +TARBALL="" +while [[ $# -gt 0 ]]; do + case "$1" in + --push) PUSH=1; shift ;; + -h | --help) sed -n '2,12p' "$0"; exit 0 ;; + -*) echo "unknown argument: $1" >&2; exit 2 ;; + *) TARBALL="$1"; shift ;; + esac +done + +ARCH="$(uname -m)" +case "$ARCH" in + x86_64) ;; + aarch64 | arm64) ARCH=aarch64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac + +BASENAME="texturecraft-$VERSION-linux-$ARCH" +OUT_OCI="$DIST/$BASENAME-oci" + +echo "==> Building Flatpak OCI layout for $BASENAME" +"$HERE/flatpak-bundle.sh" --oci --no-test "${TARBALL:-}" + +[[ -d "$OUT_OCI" ]] || { echo "error: $OUT_OCI layout not generated" >&2; exit 1; } + +REGISTRY="${REGISTRY:-ghcr.io/storytold/texturecraft}" +TAG="${TAG:-$VERSION-$ARCH}" + +echo "==> OCI layout ready at $OUT_OCI (Target: $REGISTRY:$TAG)" + +if [[ "$PUSH" = 1 ]]; then + command -v skopeo >/dev/null || { echo "error: skopeo is required to push OCI images (apt install skopeo)" >&2; exit 1; } + + AUTH_ARGS=() + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + AUTH_ARGS=(--dest-creds "${GITHUB_ACTOR:-storytold}:$GITHUB_TOKEN") + fi + + echo "==> Pushing to $REGISTRY:$TAG" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:$TAG" + + # Only a stable release-branch build may move the stable tag. + if [[ "$VERSION" != *-* && "${GITHUB_REF:-}" == refs/heads/release ]]; then + echo "==> Pushing to $REGISTRY:stable-$ARCH" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:stable-$ARCH" + fi + + echo "==> Push complete" +fi diff --git a/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml index 259e2396..56d29581 100644 --- a/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml @@ -17,6 +17,12 @@ runtime-version: '26.08' sdk: org.freedesktop.Sdk command: texturecraft finish-args: + # Honor the launcher's pinned and nightly version choices before offering updates. + - --filesystem=xdg-data/ArtCraft/versions:ro + # Release checks and downloads use HTTPS. + - --share=network + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 @@ -30,9 +36,6 @@ finish-args: # line, Open Recent, "Save" next to the original) work in the usual places. - --filesystem=xdg-pictures - --filesystem=xdg-documents - # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in - # the sandbox; `flatpak override --user --share=network ai.storyteller.texturecraft` exposes it to - # host agents) and home/host filesystem access. modules: - name: texturecraft buildsystem: simple diff --git a/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml b/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml index 3b680178..8529d8bc 100644 --- a/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml @@ -18,6 +18,12 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: texturecraft finish-args: + # Honor the launcher's pinned and nightly version choices before offering updates. + - --filesystem=xdg-data/ArtCraft/versions:ro + # Release checks and downloads use HTTPS. + - --share=network + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 @@ -31,9 +37,6 @@ finish-args: # line, Open Recent, "Save" next to the original) work in the usual places. - --filesystem=xdg-pictures - --filesystem=xdg-documents - # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in - # the sandbox; `flatpak override --user --share=network ai.storyteller.texturecraft` exposes it to - # host agents) and home/host filesystem access. build-options: append-path: /usr/lib/sdk/rust-stable/bin modules: diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 51021aab..a5a3ffd1 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -21,7 +21,7 @@ APP_ID=ai.storyteller.texturecraft SKIP_BUILD=0 FORMATS="appimage deb rpm tar" -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; @@ -42,7 +42,7 @@ BASENAME="texturecraft-$VERSION-linux-$ARCH" echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS)" -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" @@ -89,7 +89,7 @@ if has deb || has rpm; then # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39. - if [ "$ARCH" = riscv64 ]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi + if [[ "$ARCH" = riscv64 ]]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done @@ -110,10 +110,10 @@ if has appimage; then ln -s "$APP_ID.png" "$APPDIR/.DirIcon" TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" - if [ -z "$TOOL" ]; then + if [[ -z "$TOOL" ]]; then TOOL="$CARGO_TARGET_DIR/appimagetool-$ARCH.AppImage" - if [ ! -x "$TOOL" ]; then - curl -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" + if [[ ! -x "$TOOL" ]]; then + curl --proto '=https' -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" chmod +x "$TOOL" fi fi @@ -135,15 +135,15 @@ if has appimage; then # package) appimagetool also writes the .zsync, into its working directory, hence the cd. (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT") echo "wrote $OUT" - if [ -s "$OUT.zsync" ]; then + if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" else warn "zsyncmake not found, so $OUT.zsync was not written; AppImage delta updates need it" fi fi -if [ -n "${CROSS_TARGET:-}" ]; then - if [ -n "${EMULATOR:-}" ]; then "$EMULATOR" "$STAGE/usr/bin/texturecraft-cli" --version; fi +if [[ -n "${CROSS_TARGET:-}" ]]; then + if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$STAGE/usr/bin/texturecraft-cli" --version; fi else "$STAGE/usr/bin/texturecraft-cli" --version fi diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh index 249dfed1..9a414085 100755 --- a/packaging/macos/import-cert.sh +++ b/packaging/macos/import-cert.sh @@ -12,7 +12,7 @@ umask 077 # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" -if [ -z "${APPLE_CERTIFICATE:-}" ]; then +if [[ -z "${APPLE_CERTIFICATE:-}" ]]; then warn "APPLE_CERTIFICATE is not set: macOS builds will be ad-hoc signed and not notarized" exit 0 fi @@ -36,13 +36,13 @@ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KC_PASS" security list-keychains -d user -s "$KEYCHAIN" $(security list-keychains -d user | tr -d '"') IDENTITY="$(security find-identity -v -p codesigning "$KEYCHAIN" | awk '/Developer ID Application/ { print $2; exit }')" -if [ -z "$IDENTITY" ]; then +if [[ -z "$IDENTITY" ]]; then security find-identity -v -p codesigning "$KEYCHAIN" >&2 echo "error: no 'Developer ID Application' identity in APPLE_CERTIFICATE" >&2 exit 1 fi echo "Imported signing identity $IDENTITY" -if [ -n "${GITHUB_ENV:-}" ]; then +if [[ -n "${GITHUB_ENV:-}" ]]; then { echo "MACOS_SIGN_IDENTITY=$IDENTITY"; echo "MACOS_KEYCHAIN=$KEYCHAIN"; } >>"$GITHUB_ENV" else echo "MACOS_SIGN_IDENTITY=$IDENTITY" diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index c39774e3..36298423 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -19,7 +19,7 @@ HERE="$ROOT/packaging/macos" ARCH=universal SKIP_BUILD=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --arch) ARCH="$2"; shift 2 ;; --skip-build) SKIP_BUILD=1; shift ;; @@ -44,9 +44,9 @@ DMG="$DIST/texturecraft-$VERSION-macos-$ARCH.dmg" CLI_ZIP="$DIST/texturecraft-cli-$VERSION-macos-$ARCH.zip" NOTARIZE=0 -if [ "$IDENTITY" = "-" ]; then +if [[ "$IDENTITY" = "-" ]]; then warn "macOS: ad-hoc signing (no MACOS_SIGN_IDENTITY); artifacts are not notarized" -elif [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then +elif [[ -n "${APPLE_ID:-}" ]] && [[ -n "${APPLE_PASSWORD:-}" ]] && [[ -n "${APPLE_TEAM_ID:-}" ]]; then NOTARIZE=1 else warn "macOS: APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID incomplete; signed but not notarized" @@ -55,7 +55,7 @@ fi echo "==> TextureCraft $VERSION for macOS ($ARCH), identity: $IDENTITY, notarize: $NOTARIZE" # ---- build ------------------------------------------------------------------------------------- -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then args=() for t in "${TARGETS[@]}"; do args+=(--target "$t"); done (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli "${args[@]}") @@ -74,9 +74,9 @@ done sign() { # Hardened runtime + secure timestamp for a real identity; ad-hoc can't be timestamped. local ts=(--timestamp) - [ "$IDENTITY" = "-" ] && ts=(--timestamp=none) + [[ "$IDENTITY" = "-" ]] && ts=(--timestamp=none) local kc=() - [ -n "${MACOS_KEYCHAIN:-}" ] && kc=(--keychain "$MACOS_KEYCHAIN") + [[ -n "${MACOS_KEYCHAIN:-}" ]] && kc=(--keychain "$MACOS_KEYCHAIN") codesign --force --sign "$IDENTITY" ${kc[@]+"${kc[@]}"} "${ts[@]}" "$@" } @@ -88,8 +88,8 @@ notarize() { echo "$out" id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" - if [ "$status" != "Accepted" ]; then - if [ -n "$id" ]; then + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" || true fi echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 @@ -103,7 +103,7 @@ stapler_retry() { local action="$1" target="$2" try for try in 1 2 3 4; do xcrun stapler "$action" "$target" && return 0 - [ "$try" = 4 ] && break + [[ "$try" = 4 ]] && break echo "stapler $action failed (try $try of 4); retrying in $((try * 20)) s" >&2 sleep $((try * 20)) done @@ -131,7 +131,7 @@ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" codesign --verify --strict --deep --verbose=2 "$APP" -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then ditto -c -k --keepParent "$APP" "$WORK/TextureCraft-notarize.zip" notarize "$WORK/TextureCraft-notarize.zip" stapler_retry staple "$APP" @@ -153,7 +153,7 @@ hdiutil convert "$WORK/raw.dmg" -format UDZO -imagekey zlib-level=9 -o "$DMG" rm -f "$WORK/raw.dmg" sign "$DMG" codesign --verify --strict --verbose=2 "$DMG" -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then notarize "$DMG" stapler_retry staple "$DMG" stapler_retry validate "$DMG" @@ -174,7 +174,7 @@ rm -f "$CLI_ZIP" ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP" # notarytool accepts a zip of the bare binary. A bare Mach-O can't carry a stapled ticket, so # Gatekeeper looks the notarization up online when a quarantined copy first runs. -if [ "$NOTARIZE" = 1 ]; then notarize "$CLI_ZIP"; fi +if [[ "$NOTARIZE" = 1 ]]; then notarize "$CLI_ZIP"; fi "$WORK/bin/texturecraft-cli" --version echo "==> done (check the artifacts as shipped with packaging/macos/verify.sh --arch $ARCH)" diff --git a/packaging/macos/verify.sh b/packaging/macos/verify.sh index 948107f0..110622db 100755 --- a/packaging/macos/verify.sh +++ b/packaging/macos/verify.sh @@ -23,7 +23,7 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" ARCH=universal -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --arch) ARCH="$2"; shift 2 ;; -h | --help) sed -n '2,20p' "$0"; exit 0 ;; @@ -41,13 +41,13 @@ DMG="$DIST/texturecraft-$VERSION-macos-$ARCH.dmg" CLI_ZIP="$DIST/texturecraft-cli-$VERSION-macos-$ARCH.zip" IDENTITY="${MACOS_SIGN_IDENTITY:--}" STRICT=0 -if [ "$IDENTITY" != "-" ] && [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then +if [[ "$IDENTITY" != "-" ]] && [[ -n "${APPLE_ID:-}" ]] && [[ -n "${APPLE_PASSWORD:-}" ]] && [[ -n "${APPLE_TEAM_ID:-}" ]]; then STRICT=1 fi FAILED=0 fail() { - if [ "$STRICT" = 1 ]; then + if [[ "$STRICT" = 1 ]]; then echo "error: $*" >&2 FAILED=1 else @@ -58,13 +58,13 @@ fail() { # spctl's online ticket lookup can lag a few seconds behind notarytool's "Accepted". assess() { local out attempt tries=1 - [ "$STRICT" = 1 ] && tries=5 + [[ "$STRICT" = 1 ]] && tries=5 for attempt in $(seq "$tries"); do if out="$(spctl "$@" 2>&1)"; then printf '%s\n' "$out" return 0 fi - [ "$attempt" = "$tries" ] || sleep 10 + [[ "$attempt" = "$tries" ]] || sleep 10 done printf '%s\n' "$out" return 1 @@ -75,7 +75,7 @@ stapler_validate() { local target="$1" try for try in 1 2 3 4; do xcrun stapler validate "$target" && return 0 - [ "$try" = 4 ] && break + [[ "$try" = 4 ]] && break echo "stapler validate failed (try $try of 4); retrying in $((try * 20)) s" >&2 sleep $((try * 20)) done @@ -83,7 +83,7 @@ stapler_validate() { } for f in "$DMG" "$CLI_ZIP"; do - if [ ! -f "$f" ]; then + if [[ ! -f "$f" ]]; then echo "error: missing $f" >&2 exit 1 fi @@ -96,7 +96,7 @@ trap 'rm -rf "$WORK"' EXIT echo "==> $(basename "$CLI_ZIP")" ditto -x -k "$CLI_ZIP" "$WORK/cli" CLI="$WORK/cli/texturecraft-cli-$VERSION-macos-$ARCH/texturecraft-cli" -if [ ! -x "$CLI" ]; then +if [[ ! -x "$CLI" ]]; then echo "error: $(basename "$CLI_ZIP") has no executable texturecraft-cli-$VERSION-macos-$ARCH/texturecraft-cli" >&2 exit 1 fi @@ -120,7 +120,7 @@ printf '%s\n' "$details" | grep -q '^Authority=Developer ID Application:' \ || fail "texturecraft-cli is not signed with a Developer ID Application identity" printf '%s\n' "$details" | grep -q '^Timestamp=' \ || fail "texturecraft-cli signature has no secure timestamp" -if [ -n "${APPLE_TEAM_ID:-}" ]; then +if [[ -n "${APPLE_TEAM_ID:-}" ]]; then printf '%s\n' "$details" | grep -qx "TeamIdentifier=$APPLE_TEAM_ID" \ || fail "texturecraft-cli is signed by a different team" fi @@ -137,24 +137,24 @@ fi # ---- DMG --------------------------------------------------------------------------------------- echo "==> $(basename "$DMG")" codesign --verify --strict --verbose=2 "$DMG" -if [ "$STRICT" = 1 ]; then +if [[ "$STRICT" = 1 ]]; then stapler_validate "$DMG" || fail "no notarization ticket stapled to the DMG" assess --assess --type open --context context:primary-signature -vv "$DMG" \ || fail "Gatekeeper rejects the DMG" fi -if [ "$FAILED" != 0 ]; then +if [[ "$FAILED" != 0 ]]; then echo "error: macOS artifacts failed verification" >&2 exit 1 fi -if [ "$STRICT" = 1 ]; then +if [[ "$STRICT" = 1 ]]; then result="signed (Developer ID, hardened runtime), notarized; DMG stapled" else result="signature intact; Developer ID and notarization not required (no signing secrets)" fi echo "==> verified: $result" -if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then +if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then { echo "- macOS \`$(basename "$DMG")\`, \`$(basename "$CLI_ZIP")\`: $result" } >>"$GITHUB_STEP_SUMMARY" diff --git a/packaging/web/package.sh b/packaging/web/package.sh index baecbc0d..7b5a4915 100755 --- a/packaging/web/package.sh +++ b/packaging/web/package.sh @@ -11,13 +11,13 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/web" -if [ "${1:-}" != "--skip-build" ]; then +if [[ "${1:-}" != "--skip-build" ]]; then command -v trunk >/dev/null || { echo "error: trunk not found (cargo install trunk --locked)" >&2; exit 1; } (cd "$ROOT/apps/texturecraft-web" && trunk build --release) fi SITE="$ROOT/dist/web" -[ -f "$SITE/index.html" ] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } +[[ -f "$SITE/index.html" ]] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } # Paths must be relative so the site works under any prefix (public_url = "./" in Trunk.toml). if grep -Eq '(src|href)="/[^/]' "$SITE/index.html"; then echo "error: $SITE/index.html has root-absolute URLs; it would break when served from a sub-path" >&2 @@ -27,19 +27,19 @@ fi # Size gate: Cloudflare Pages/Workers reject any single file over 25 MiB, and other # hosts and CDNs have similar caps. Fail well before that so a regression shows up here, not at # upload time. Override with TEXTURECRAFT_WASM_MAX_BYTES only to investigate. -MAX_WASM_BYTES="${TEXTURECRAFT_WASM_MAX_BYTES:-25165824}" # 24 MiB +MAX_WASM_BYTES=$((10#${TEXTURECRAFT_WASM_MAX_BYTES:-25165824})) # 24 MiB WASM_COUNT=0 for wasm in "$SITE"/*.wasm; do - [ -f "$wasm" ] || continue + [[ -f "$wasm" ]] || continue WASM_COUNT=$((WASM_COUNT + 1)) size=$(wc -c <"$wasm" | tr -d ' ') echo "$(basename "$wasm"): $size bytes ($((size / 1048576)) MiB; limit $MAX_WASM_BYTES)" - if [ "$size" -gt "$MAX_WASM_BYTES" ]; then + if [[ "$size" -gt "$MAX_WASM_BYTES" ]]; then echo "error: $(basename "$wasm") is $size bytes, over the $MAX_WASM_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2 exit 1 fi done -[ "$WASM_COUNT" -gt 0 ] || { echo "error: no .wasm in $SITE" >&2; exit 1; } +[[ "$WASM_COUNT" -gt 0 ]] || { echo "error: no .wasm in $SITE" >&2; exit 1; } NAME="texturecraft-web-$VERSION" WORK="$CARGO_TARGET_DIR/web-package" diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ccbdc2c7..2ff6178a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -15,7 +15,7 @@ usage: cargo xtask commands: layers enforce the crate dependency layering (xtask/src/layers.rs) wasm cargo check --target wasm32-unknown-unknown for the wasm crates and the web app - ci fmt --check, clippy -D warnings, test, layers, wasm (stops at the first failure) + ci fmt --check, layers, clippy -D warnings, test, wasm (stops at the first failure) version [set X.Y.Z[-pre]] print the workspace version, or set it (Cargo.toml + Cargo.lock) ico ... @@ -154,11 +154,12 @@ fn cmd_ci() -> Result<(), String> { } }; type Step = (&'static str, Box Result<(), String>>); + // Reject invalid dependency layering before spending time compiling and running the workspace. let steps: Vec = vec![ ("fmt", Box::new(cargo_step(&["fmt", "--all", "--", "--check"]))), + ("layers", Box::new(cmd_layers)), ("clippy", Box::new(cargo_step(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]))), ("test", Box::new(cargo_step(&["test", "--workspace"]))), - ("layers", Box::new(cmd_layers)), ("wasm", Box::new(cmd_wasm)), ]; for (i, (name, step)) in steps.iter().enumerate() {