diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 35cb9eeb..ab63e5a3 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1419654881, "producer_workflow_id": 429738073, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index 75134544..1c49c360 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -36,7 +36,7 @@ jobs: RUST_BACKTRACE: 1 steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -44,12 +44,12 @@ jobs: persist-credentials: false # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. - name: Check out craft-fonts - uses: storytold/craft-common-actions/actions/checkout-craft-fonts@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: ref: aced4137c022f1f587624d48e81ec77e1914a9cc - - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/actions/rust-channel@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: targets: aarch64-apple-darwin - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 998acbae..65767940 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,9 +34,9 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a app-name: texturecraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 1600b2e0..a0933e12 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a app-name: texturecraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc diff --git a/.github/workflows/notify-services.yml b/.github/workflows/notify-services.yml new file mode 100644 index 00000000..3dc8eaf4 --- /dev/null +++ b/.github/workflows/notify-services.yml @@ -0,0 +1,20 @@ +name: Notify Services on Release Change + +on: + release: + types: + - published + - unpublished + - created + - edited + - deleted + - prereleased + - released + +permissions: {} + +jobs: + notify: + uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main + secrets: + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index feb8675d..75332dd7 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -25,3 +25,21 @@ jobs: # Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks # that need no compiler are part of CI rather than a local step. extra-checks-script: packaging/nightly-checks.sh + + freebsd-layout: + # The FreeBSD package layout, with stub binaries standing in for the build: RFC-0018 rule 1.9 + # puts texturecraft-cli's man pages and its bash, zsh and fish completions in it. + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: FreeBSD package layout (dry run) + run: | + CARGO_TARGET_DIR="$RUNNER_TEMP/texturecraft-target" bash packaging/freebsd/package.sh --dry-run + listing="$(tar -tzf "$RUNNER_TEMP"/texturecraft-target/freebsd-package/texturecraft-*-freebsd-x86_64.tar.gz)" + for f in man/man1/texturecraft-cli.1 share/bash-completion/completions/texturecraft-cli \ + share/zsh/site-functions/_texturecraft-cli share/fish/vendor_completions.d/texturecraft-cli.fish; do + grep -q "/$f$" <<<"$listing" || { echo "::error::$f is missing from the FreeBSD package"; exit 1; } + done diff --git a/AGENTS.md b/AGENTS.md index e42b5d53..63517554 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,7 +63,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119 ## This repository -TextureCraft is an open-source, native 3D texture painter in Rust: a native egui/eframe app on wgpu, a headless CLI and MCP server, and the same app in the browser (trunk, wasm-bindgen). The project extension is `.tcraft`. Crates are `texturecraft-*`; the product name is written TextureCraft. MaterialCraft's `.mcmat` portable materials are read here through the shared `craft-mcmat` format crate (craft-libs), with the app's own checks in `formats::mcmat`; each app keeps its own models and policy. Start with `docs/architecture.md`, `docs/control-protocol.md`, `ROADMAP.md` and `docs/parity.md`. +TextureCraft is an open-source, native 3D texture painter in Rust: a native egui/eframe app on wgpu, a headless CLI and MCP server, and the same app in the browser (trunk, wasm-bindgen). The project extension is `.tcraft`. Crates are `texturecraft-*`; the product name is written TextureCraft. MaterialCraft's `.mcmat` portable materials are read here through the shared `craft-mcmat` format crate (craft-libs), with the app's own checks in `formats::mcmat`; each app keeps its own models and policy. Start with `docs/architecture.md`, `docs/control-protocol.md`, `ROADMAP.md` and `docs/parity.md`. `docs/parity.md` carries the [RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md) Headless column: `yes` only when the id is an engine command (`texturecraft_engine::find`), which `texturecraft-cli` and the MCP server reach. A `ui.*` id is live in the desktop app only and gets a `no`/`partial` mark with a `window`, `os` or `engine-gap` reach in `HEADLESS` (`crates/ui-egui/src/parity.rs`). Never write `yes` there. Regenerate with `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. ### Layout ```text diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 5bfb7129..c2eab178 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -28,6 +28,7 @@ licensed and keep their license file next to them. | `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | +| `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 | ## Third-party assets compiled into the binary @@ -52,6 +53,8 @@ time (nothing is bundled); see [docs/localization-parity.md](docs/localization-p | `xcap` | Windows screen pixel capture | https://github.com/nashaofu/xcap | Apache-2.0 | | `widestring` | Windows string handling through `xcap` | https://github.com/VoidStarKat/widestring-rs | MIT OR Apache-2.0 | | `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 | +| `x11rb-protocol` | X11 setup and Xauthority for the Linux pen startup probe | https://github.com/psychon/x11rb | MIT OR Apache-2.0 | +| `rustix` | Linux socket and hostname APIs for the X11 setup probe | https://github.com/bytecodealliance/rustix | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | | `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT | ## Procedural content (no asset files) diff --git a/Cargo.lock b/Cargo.lock index acafef1d..2ccaed92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -212,12 +212,56 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "arboard" version = "3.6.1" @@ -672,7 +716,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.6", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -776,6 +820,65 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "clap_mangen" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78" +dependencies = [ + "clap", + "roff", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -820,6 +923,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.8" @@ -1740,7 +1849,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2141,7 +2250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2339,7 +2448,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3237,6 +3346,12 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.13.0" @@ -3674,7 +3789,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png", "thiserror 2.0.21", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4343,6 +4458,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "openssl-probe" version = "0.2.2" @@ -4391,7 +4512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5138,6 +5259,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "roff" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" + [[package]] name = "ron" version = "0.12.2" @@ -5192,7 +5319,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5205,7 +5332,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5272,7 +5399,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5650,7 +5777,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5800,10 +5927,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.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5819,6 +5946,7 @@ dependencies = [ name = "texturecraft" version = "0.6.1" dependencies = [ + "craft-host", "craft-image-codecs", "craft-menu", "craft-update", @@ -5829,6 +5957,7 @@ dependencies = [ "log", "rfd", "ron", + "rustix 1.1.6", "serde_json", "texturecraft-automation", "texturecraft-engine", @@ -5836,6 +5965,7 @@ dependencies = [ "winit", "winresource", "winsafe", + "x11rb-protocol", ] [[package]] @@ -5852,6 +5982,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "tempfile", "texturecraft-engine", "texturecraft-formats", "texturecraft-render", @@ -5875,10 +6006,14 @@ dependencies = [ name = "texturecraft-cli" version = "0.6.1" dependencies = [ + "clap", + "clap_complete", + "clap_mangen", "image", "serde_json", "texturecraft-automation", "texturecraft-engine", + "thiserror 2.0.21", "tokio", "winresource", ] @@ -5952,7 +6087,6 @@ dependencies = [ "half", "image", "png", - "quick-xml 0.41.0", "rayon", "serde", "serde_json", @@ -6005,6 +6139,7 @@ dependencies = [ "texturecraft-bake", "texturecraft-compose", "texturecraft-core", + "texturecraft-formats", "texturecraft-geom", "texturecraft-texel", "wasm-bindgen-futures", @@ -6381,7 +6516,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6516,6 +6651,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" @@ -7071,7 +7212,7 @@ 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.61.2", ] [[package]] @@ -7458,7 +7599,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" dependencies = [ "bitflags 2.13.2", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -7865,7 +8006,7 @@ dependencies = [ "memchr", "nix", "typed-path", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index 2b52c050..1f07aa7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,10 @@ texturecraft-ui-egui = { path = "crates/ui-egui" } # external thiserror = "2" +# The command line of texturecraft-cli (RFC-0018); the generators are dev-dependencies, for the man pages and completions. +clap = { version = "4", features = ["derive", "string", "env"] } +clap_complete = "4" +clap_mangen = "0.2" chrono = { version = "0.4", default-features = false, features = ["now", "wasmbind"] } serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -51,7 +55,6 @@ 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"] } flate2 = "1" -quick-xml = "0.41" mikktspace = { version = "0.3", default-features = false, features = ["glam"] } rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } diff --git a/LICENSE-MIT b/LICENSE-MIT index efc19869..222c8d9f 100644 --- a/LICENSE-MIT +++ b/LICENSE-MIT @@ -1,6 +1,7 @@ MIT License Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors +Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors (adapted Linux pen and display probing code) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/NOTICE b/NOTICE index 25d962ff..c3f3e481 100644 --- a/NOTICE +++ b/NOTICE @@ -12,6 +12,16 @@ Third-party material This product bundles third-party material under its own licenses, listed below. The per-file list (author, source, license) is in ATTRIBUTION.md. +PhotoCraft Linux pen and display probing code, adapted in apps/texturecraft/src/xwayland_pen.rs +from storytold/photocraft at 830316b775f1f6734498ac6e39fd1298955ff93f. +Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. +Licensed under the MIT License or the Apache License, Version 2.0, at your option +(LICENSE-MIT, LICENSE-APACHE). + +Linux X11 setup probe components: +- rustix — Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT. +- x11rb-protocol — MIT OR Apache-2.0. Copyright 2019 x11rb contributors. + Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr), by Sergej Majboroda (Poly Haven) — CC0-1.0. Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256). diff --git a/ROADMAP.md b/ROADMAP.md index 7dbebfbb..ad234ca3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -82,7 +82,7 @@ The evidence column includes the November 16 scores for comparison. | UI/UX fidelity | ~75% | 20 | TBD | Layer targeting, the workspace, Bake Mode and export dialogs changed. Live task, layout, shortcut and accessibility checks remain. November 16 estimate ~65% | | File formats / interchange | ~70% | 10 | TBD | Shared import/export codecs, rebuilt UV persistence and linked `.mcmat` v3 have landed. Project/output contracts, `.spp` and destination-tool coverage remain open. November 16 estimate ~60% | | Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete. November 16 estimate ~50% | -| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% | +| Localization | ~35% | 4 | TBD | Eleven picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% | | Performance | ~45% | 10 | TBD | Main added dirty-region uploads, cheaper undo snapshots and faster glTF lookups. Establish response-time and memory budgets with representative large projects. November 16 estimate ~40% | | Stability | ~60% | 10 | TBD | The live baseline covered small save/reopen and undo/redo. Rebuilt UV layouts gained persistence checks. Recovery, large projects and long sessions remain open. November 16 estimate ~55% | | Platforms | ~70% | 3 | TBD | Desktop and web build paths exist. Nightly packaging and supervised signing workflows landed for Windows, Linux and macOS. Install, update and hardware checks remain. November 16 estimate ~65% | @@ -151,7 +151,7 @@ signed release installation remain outside the November 25 test evidence. ## Languages -The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at +The [picker](crates/ui-egui/src/i18n.rs) contains eleven languages. Shared catalogs are optional at build time; missing entries fall back to English, and builds without catalogs offer English only. The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%” rows are not a current measurement. The November 16 live audit ran an English build without external catalogs. diff --git a/apps/texturecraft-cli/Cargo.toml b/apps/texturecraft-cli/Cargo.toml index d458a8d0..61f4c61a 100644 --- a/apps/texturecraft-cli/Cargo.toml +++ b/apps/texturecraft-cli/Cargo.toml @@ -6,6 +6,14 @@ edition.workspace = true license.workspace = true build = "build.rs" +[lib] +name = "texturecraft_cli" +path = "src/lib.rs" + +[[bin]] +name = "texturecraft-cli" +path = "src/main.rs" + [lints] workspace = true @@ -14,9 +22,13 @@ texturecraft-automation = { workspace = true } texturecraft-engine = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true } +thiserror = { workspace = true } +clap = { workspace = true } [dev-dependencies] image = { workspace = true } +clap_complete = { workspace = true } +clap_mangen = { workspace = true } [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft-cli/examples/man-and-completions.rs b/apps/texturecraft-cli/examples/man-and-completions.rs new file mode 100644 index 00000000..55885101 --- /dev/null +++ b/apps/texturecraft-cli/examples/man-and-completions.rs @@ -0,0 +1,42 @@ +//! Writes texturecraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish, +//! PowerShell) and man pages ([`clap_mangen`]: `texturecraft-cli.1` and one per subcommand, such as +//! `texturecraft-cli-info.1`) into a directory. The Linux and FreeBSD packages ship them +//! (`packaging/linux/package.sh`, `packaging/freebsd/package.sh`): +//! +//! ```sh +//! cargo run -p texturecraft-cli --example man-and-completions -- +//! ``` + +use std::path::Path; +use std::process::ExitCode; + +use clap::ValueEnum; +use clap_complete::Shell; + +fn main() -> ExitCode { + let mut args = std::env::args_os().skip(1); + let (Some(dir), None) = (args.next(), args.next()) else { + eprintln!("usage: man-and-completions "); + return ExitCode::from(2); + }; + let dir = Path::new(&dir); + match generate(dir) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {}: {e}", dir.display()); + ExitCode::FAILURE + } + } +} + +/// Also run by `tests/it/man_and_completions.rs`. +pub(crate) fn generate(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let mut cmd = texturecraft_cli::command(); + for &shell in Shell::value_variants() { + clap_complete::generate_to(shell, &mut cmd, "texturecraft-cli", dir)?; + } + // A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand, + // which `clap_mangen` would otherwise give pages of its own (`texturecraft-cli-help-convert.1`). + clap_mangen::generate_to(texturecraft_cli::command(), dir) +} diff --git a/apps/texturecraft-cli/src/args.rs b/apps/texturecraft-cli/src/args.rs new file mode 100644 index 00000000..64373804 --- /dev/null +++ b/apps/texturecraft-cli/src/args.rs @@ -0,0 +1,422 @@ +//! The command line as clap derive types. Values arrive typed, so the commands never validate a +//! string; what clap can't say alone is a [`UsageError`], printed and exited like clap's own. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use clap::error::ErrorKind; +use clap::{Args, FromArgMatches, Parser, Subcommand}; +use serde_json::Value; + +/// The end of `--help` of every command. +const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 a command failed\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell."; + +const INPUTS: &str = "An is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl) or builtin: (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane). See docs/control-protocol.md."; + +/// Headless TextureCraft +#[derive(Parser, Debug)] +#[command(name = "texturecraft-cli", propagate_version = true, arg_required_else_help = true, after_help = EXIT_STATUS)] +pub(crate) struct Cli { + #[command(subcommand)] + pub(crate) command: Command, +} + +#[derive(Subcommand, Debug)] +pub(crate) enum Command { + /// Texture sets, layers, triangles, materials and the UV report, as JSON + #[command(after_help = INPUTS)] + Info(InfoArgs), + /// List the engine commands (id, label, params) + Commands(CommandsArgs), + /// Run one command and print its JSON result; -o saves the project + #[command(after_help = INPUTS)] + Run(RunArgs), + /// Run a script of commands + /// + /// The script is JSON: [{"id", "params"}, ...] or {"open": , "steps": [...], "save": }. + Batch(BatchArgs), + /// Bake mesh maps for every texture set + /// + /// A project is saved in place without -o, which needs --in-place; a mesh needs -o. + #[command(after_help = INPUTS)] + Bake(BakeArgs), + /// Export textures (default preset: Document channels + Normal + AO (No Alpha)) + #[command(after_help = INPUTS)] + Export(ExportArgs), + /// Render the viewport to PNG (needs a GPU or software adapter) + /// + /// --camera looks through a camera saved in the project (camera.add); --samples path traces it + /// instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on + /// the CPU. + #[command(after_help = INPUTS)] + Render(RenderArgs), + /// A new project from a mesh or a built-in mesh + /// + /// --sample bakes and applies a smart material to every texture set. The sample's mesh maps are + /// baked at the resolution up to 1024 px (most of the file's size), so a 2048 sample project is + /// as large as a 1024 one. + #[command(after_help = INPUTS)] + New(NewArgs), + /// MCP server on stdio: headless, or bridged to `texturecraft --control ` + /// + /// Headless, file access is only below the roots. + Mcp(McpArgs), + /// JSON lines ({"id","method","params"}) on stdio, or on 127.0.0.1: with a token + Serve(ServeArgs), +} + +#[derive(Args, Debug)] +pub(crate) struct InfoArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, +} + +#[derive(Args, Debug)] +pub(crate) struct CommandsArgs { + /// Only the commands whose id or label contains this text + #[arg(long, value_name = "TEXT")] + pub(crate) filter: Option, + /// Print the list as JSON instead of a table + #[arg(long)] + pub(crate) json: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct RunArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "COMMAND-ID")] + pub(crate) id: String, + /// The command's parameters, as JSON + #[arg(value_name = "PARAMS-JSON", value_parser = json_value)] + pub(crate) params: Option, + /// Save the project here + #[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")] + pub(crate) output: Option, + /// Allow -o to replace the project it opened + #[arg(long, requires = "output")] + pub(crate) in_place: bool, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("params are not JSON: {0}")] +pub(crate) struct NotJson(String); + +fn json_value(s: &str) -> Result { + serde_json::from_str(s).map_err(|e| NotJson(e.to_string())) +} + +#[derive(Args, Debug)] +pub(crate) struct BatchArgs { + #[arg(value_name = "SCRIPT.JSON")] + pub(crate) script: PathBuf, + /// Allow `save` to replace the project `open` named + #[arg(long)] + pub(crate) in_place: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct BakeArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + /// Save the baked project here + #[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")] + pub(crate) output: Option, + /// Bake at this size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) resolution: Option, + /// Only these maps (ids, comma separated) + #[arg(long, value_name = "ID,ID,...", value_delimiter = ',')] + pub(crate) maps: Vec, + /// Save over the project it opened (without -o), or allow -o to replace it + #[arg(long)] + pub(crate) in_place: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct ExportArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "DIR")] + pub(crate) dir: PathBuf, + /// An export preset by name + #[arg(long, value_name = "NAME")] + pub(crate) preset: Option, + /// File format (an extension) + #[arg(long, value_name = "EXT")] + pub(crate) format: Option, + /// Padding mode + #[arg(long, value_name = "MODE")] + pub(crate) padding: Option, + /// Texture size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) size: Option, +} + +#[derive(Args, Debug)] +pub(crate) struct RenderArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT.PNG")] + pub(crate) output: PathBuf, + /// Image size + #[arg(long, value_name = "WxH")] + pub(crate) size: Option, + /// The viewport: 3D, or the UV view of the active texture set + #[arg(long, value_name = "VIEW", value_parser = ["3d", "2d", "uv"])] + pub(crate) view: Option, + /// Look through a camera saved in the project + #[arg(long, value_name = "NAME")] + pub(crate) camera: Option, + /// Camera yaw in degrees + #[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)] + pub(crate) yaw: Option, + /// Camera pitch in degrees + #[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)] + pub(crate) pitch: Option, + /// Path trace with this many samples per pixel + #[arg(long, value_name = "N", value_parser = positive)] + pub(crate) samples: Option, + /// Light bounces of the path tracer + #[arg(long, value_name = "N", requires = "samples")] + pub(crate) bounces: Option, + /// Path trace on the CPU + #[arg(long, requires = "samples")] + pub(crate) cpu: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct NewArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT.TCRAFT")] + pub(crate) output: PathBuf, + /// Texture size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) resolution: Option, + /// Bake and apply a smart material to every texture set + #[arg(long)] + pub(crate) sample: bool, +} + +/// The folders a server may read from and write to; with neither, it has no file access. +#[derive(Args, Debug, Default)] +pub(crate) struct RootArgs { + /// Serve file access below this folder (alias --automation-read-root) + #[arg(long, alias = "automation-read-root", value_name = "DIR")] + pub(crate) read_root: Option, + /// Allow writes below this folder (alias --automation-write-root) + #[arg(long, alias = "automation-write-root", value_name = "DIR")] + pub(crate) write_root: Option, +} + +#[derive(Args, Debug)] +pub(crate) struct McpArgs { + /// Bridge to a running app's control port instead of a headless session + #[arg(long, value_name = "PORT", value_parser = port)] + pub(crate) bridge: Option, + /// The app's control token (TEXTURECRAFT_CONTROL_TOKEN; else the file the app wrote) + #[arg(long, value_name = "TOKEN", env = "TEXTURECRAFT_CONTROL_TOKEN", hide_env_values = true)] + pub(crate) token: Option, + #[command(flatten)] + pub(crate) roots: RootArgs, +} + +#[derive(Args, Debug)] +pub(crate) struct ServeArgs { + /// Listen on 127.0.0.1: with a token, instead of stdio + #[arg(long, value_name = "PORT", value_parser = port)] + pub(crate) port: Option, + #[command(flatten)] + pub(crate) roots: RootArgs, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a number of pixels above zero")] +pub(crate) struct NotPositive(String); + +fn positive(s: &str) -> Result { + s.parse::().ok().filter(|n| *n > 0).ok_or_else(|| NotPositive(s.to_string())) +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a finite number")] +pub(crate) struct NotFinite(String); + +fn finite(s: &str) -> Result { + s.parse::().ok().filter(|n| n.is_finite()).ok_or_else(|| NotFinite(s.to_string())) +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a loopback port (1-65535)")] +pub(crate) struct BadPort(String); + +/// A port, as `7878`, `127.0.0.1:7878` or `localhost:7878`. +fn port(s: &str) -> Result { + let digits = s.strip_prefix("127.0.0.1:").or_else(|| s.strip_prefix("localhost:")).unwrap_or(s); + digits.parse::().ok().filter(|p| *p != 0).ok_or_else(|| BadPort(s.to_string())) +} + +/// `--size` of `render`: WIDTHxHEIGHT. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Dimensions { + pub(crate) width: u32, + pub(crate) height: u32, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not x, e.g. 1280x800")] +pub(crate) struct BadDimensions(String); + +impl FromStr for Dimensions { + type Err = BadDimensions; + + fn from_str(s: &str) -> Result { + let (width, height) = s.split_once(['x', 'X']).ok_or_else(|| BadDimensions(s.to_string()))?; + match (positive(width), positive(height)) { + (Ok(width), Ok(height)) => Ok(Dimensions { width, height }), + _ => Err(BadDimensions(s.to_string())), + } + } +} + +/// A mistake in the command line that clap can't see by itself. +#[derive(Debug, PartialEq, thiserror::Error)] +pub(crate) enum UsageError { + #[error("{output} {} is the {input}, which it would replace: choose another file{}", path.display(), if *in_place_helps { ", or pass --in-place" } else { "" })] + WouldReplace { output: &'static str, input: &'static str, path: PathBuf, in_place_helps: bool }, + #[error("--in-place is for an output that is the INPUT, and this is another file")] + InPlaceNotUsed, + #[error("a mesh is not saved in place: give -o to save the baked project")] + BakeNeedsOutput, + #[error("saving over {} needs --in-place (or give -o )", path.display())] + BakeInPlace { path: PathBuf }, + #[error("{flag} is for a headless server, and --bridge connects to an app")] + RootsWithBridge { flag: &'static str }, + #[error("--token is for --bridge, and this is a headless server")] + TokenNeedsBridge, + #[error("mcp needs --read-root and --write-root (or their --automation-*-root aliases)")] + McpNeedsRoots, +} + +impl UsageError { + /// The clap error, printed with the usage and exited with 2 like clap's own. + pub(crate) fn into_clap(self, subcommand: &str) -> clap::Error { + let mut command = crate::command(); + // Built, so a subcommand's usage names the program: `texturecraft-cli run`. + command.build(); + let mut command = command.find_subcommand_mut(subcommand).map_or_else(crate::command, std::mem::take); + command.error(ErrorKind::ArgumentConflict, self.to_string()) + } +} + +/// Whether two paths name the same existing file, through links and `.` and `..`. +fn same_file(a: &Path, b: &Path) -> bool { + matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b) +} + +/// Whether `path` is a .tcraft project. +pub(crate) fn is_project(path: &Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case(texturecraft_engine::core::PROJECT_EXT)) +} + +/// The path `Headless::save` writes: it appends `.tcraft` when the extension is missing. +fn project_save_path(path: &Path) -> PathBuf { + if is_project(path) { + path.to_owned() + } else { + let mut raw = path.as_os_str().to_os_string(); + raw.push("."); + raw.push(texturecraft_engine::core::PROJECT_EXT); + PathBuf::from(raw) + } +} + +fn would_replace(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> { + if same_file(to, from) { Err(UsageError::WouldReplace { output, input, path: to.to_owned(), in_place_helps }) } else { Ok(()) } +} + +fn would_replace_project(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> { + would_replace(output, input, &project_save_path(to), from, in_place_helps) +} + +fn same_project(output: &Path, input: &Path) -> bool { + same_file(&project_save_path(output), input) +} + +/// If a batch script's `save` would replace `open`, it needs `--in-place`. An unreadable or +/// malformed script is left to the command, which reports that as a failure (exit 1). +fn batch_would_replace(a: &BatchArgs) -> Result<(), UsageError> { + let Ok(text) = std::fs::read_to_string(&a.script) else { + return Ok(()); + }; + let Ok(script) = serde_json::from_str::(&text) else { + return Ok(()); + }; + let field = |name: &str| script.get(name).and_then(Value::as_str); + let Some(output) = field("save") else { + return Ok(()); + }; + let input = field("open").unwrap_or("builtin:material_ball"); + if input.starts_with("builtin:") { + return if a.in_place { Err(UsageError::InPlaceNotUsed) } else { Ok(()) }; + } + let input = Path::new(input); + let output = Path::new(output); + match (same_project(output, input), a.in_place) { + (true, false) => Err(UsageError::WouldReplace { output: "save", input: "open", path: project_save_path(output), in_place_helps: true }), + (false, true) => Err(UsageError::InPlaceNotUsed), + _ => Ok(()), + } +} + +impl Command { + /// What clap can't check: the files a command would replace, and flags for another mode. + fn check(&self) -> Result<(), (&'static str, UsageError)> { + match self { + Command::Run(a) => match (&a.output, a.in_place) { + (Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("run", e)), + (Some(out), true) if !same_project(out, &a.input) => Err(("run", UsageError::InPlaceNotUsed)), + _ => Ok(()), + }, + Command::Bake(a) => match (&a.output, a.in_place) { + (None, false) if is_project(&a.input) => Err(("bake", UsageError::BakeInPlace { path: a.input.clone() })), + (None, _) if !is_project(&a.input) => Err(("bake", UsageError::BakeNeedsOutput)), + (Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("bake", e)), + (Some(out), true) if !same_project(out, &a.input) => Err(("bake", UsageError::InPlaceNotUsed)), + _ => Ok(()), + }, + Command::Render(a) => would_replace("OUT.PNG", "INPUT", &a.output, &a.input, false).map_err(|e| ("render", e)), + Command::New(a) => would_replace_project("OUT.TCRAFT", "INPUT", &a.output, &a.input, false).map_err(|e| ("new", e)), + Command::Batch(a) => batch_would_replace(a).map_err(|e| ("batch", e)), + Command::Mcp(a) if a.bridge.is_some() => match (&a.roots.read_root, &a.roots.write_root) { + (Some(_), _) => Err(("mcp", UsageError::RootsWithBridge { flag: "--read-root" })), + (_, Some(_)) => Err(("mcp", UsageError::RootsWithBridge { flag: "--write-root" })), + _ => Ok(()), + }, + Command::Mcp(a) if a.bridge.is_none() => match (&a.roots.read_root, &a.roots.write_root) { + (Some(_), Some(_)) => Ok(()), + _ => Err(("mcp", UsageError::McpNeedsRoots)), + }, + _ => Ok(()), + } + } +} + +/// Parses the arguments (without the program name). Help and the version come back as errors too, +/// which print to stdout and exit 0. +pub(crate) fn parse(args: &[OsString]) -> Result { + let matches = crate::command().try_get_matches_from(std::iter::once(OsString::from("texturecraft-cli")).chain(args.iter().cloned()))?; + let cli = Cli::from_arg_matches(&matches)?; + // An inherited TEXTURECRAFT_CONTROL_TOKEN must not force --bridge: the variable is how a + // client authenticates when --bridge is already set. Only an explicit --token flag requires it. + let token_flag_without_bridge = matches + .subcommand_matches("mcp") + .is_some_and(|mcp| mcp.value_source("token") == Some(clap::parser::ValueSource::CommandLine) && mcp.get_one::("bridge").is_none()); + if token_flag_without_bridge { + return Err(UsageError::TokenNeedsBridge.into_clap("mcp")); + } + cli.command.check().map_err(|(sub, e)| e.into_clap(sub))?; + Ok(cli) +} diff --git a/apps/texturecraft-cli/src/error.rs b/apps/texturecraft-cli/src/error.rs new file mode 100644 index 00000000..30687f1c --- /dev/null +++ b/apps/texturecraft-cli/src/error.rs @@ -0,0 +1,36 @@ +use std::path::{Path, PathBuf}; + +use texturecraft_automation::AutomationError; + +/// Why a subcommand failed: printed as `error: {e}`, exit 1. +#[derive(Debug, thiserror::Error)] +pub(crate) enum CliError { + #[error(transparent)] + Automation(#[from] AutomationError), + /// The engine's commands take paths as JSON text, which holds only Unicode. + #[error("{}: the path is not valid Unicode", .0.display())] + NotUnicode(PathBuf), + #[error("unknown built-in mesh `{0}`")] + UnknownBuiltin(String), + #[error("cannot read {}: {message}", path.display())] + Read { path: PathBuf, message: String }, + #[error("cannot write {}: {source}", path.display())] + Write { path: PathBuf, source: std::io::Error }, + #[error("{} is not JSON: {source}", path.display())] + Script { path: PathBuf, source: serde_json::Error }, + #[error("the script must be a list of steps or {{\"steps\": [...]}}")] + ScriptShape, + #[error("the script's `{0}` field must be a string")] + ScriptField(&'static str), + #[error("step {index} (`{id}`) failed: {message}")] + BatchStopped { index: String, id: String, message: String }, + #[error("{} is already a project", .0.display())] + AlreadyProject(PathBuf), + #[error("{0}")] + Serve(std::io::Error), +} + +/// A path as the text the engine's commands take. +pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> { + path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned())) +} diff --git a/apps/texturecraft-cli/src/lib.rs b/apps/texturecraft-cli/src/lib.rs new file mode 100644 index 00000000..872765af --- /dev/null +++ b/apps/texturecraft-cli/src/lib.rs @@ -0,0 +1,342 @@ +//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and +//! serve agents over MCP or JSON lines. Never opens a window. `run` is the whole program, so it can +//! be tested in-process as well as through the binary; `texturecraft-cli --help` lists the +//! subcommands. The conventions are RFC-0018's: exit 0, 1 (a command failed) or 2 (a usage error), +//! results on stdout, `error: ` on stderr. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod args; +mod error; + +use std::ffi::OsString; +use std::io::Write; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use clap::CommandFactory; +use serde_json::{Value, json}; +use texturecraft_automation::security::{client_token, server_token}; +use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc}; +use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report}; + +use args::{ + BakeArgs, BatchArgs, Cli, Command, CommandsArgs, ExportArgs, InfoArgs, McpArgs, NewArgs, RenderArgs, RootArgs, RunArgs, ServeArgs, is_project, parse, +}; +use error::{CliError, unicode}; + +/// Writes a line. A closed pipe (`texturecraft-cli info x | head`) is not worth an error: the rest +/// of the output is dropped. +macro_rules! outln { + ($to:expr, $($arg:tt)*) => { + drop(writeln!($to, $($arg)*)) + }; +} + +/// The version `--version` prints after the program's name: ` ( )`. +fn version() -> String { + let sha = env!("TEXTURECRAFT_BUILD_SHA"); + let short = sha.get(..7).unwrap_or(sha); + let date = env!("TEXTURECRAFT_BUILD_DATE"); + match (short.is_empty(), date.is_empty()) { + (true, true) => texturecraft_engine::VERSION.to_string(), + (true, false) => format!("{} ({date})", texturecraft_engine::VERSION), + _ => format!("{} ({short} {date})", texturecraft_engine::VERSION), + } +} + +/// The command line's clap definition. +pub fn command() -> clap::Command { + Cli::command().version(version()) +} + +/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the +/// GUI only, and a script that passes them to the CLI has the wrong program. +fn launch_profile_argument(args: &[OsString]) -> Option { + args.iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .find(|arg| ["--launch-profile", "--profile-root"].iter().any(|flag| arg == flag || arg.starts_with(&format!("{flag}=")))) +} + +/// Run the CLI on its arguments (without the program name), writing results to `out` and +/// diagnostics to `err`. Returns the process exit code: 0 on success, 1 on failure, 2 for a usage +/// error. Help and the version go to `out`, exit 0. `mcp` and `serve` speak on the process's own +/// stdin and stdout. +pub fn run(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32 +where + I: IntoIterator, + T: Into, +{ + let args: Vec = args.into_iter().map(Into::into).collect(); + if let Some(flag) = launch_profile_argument(&args) { + outln!(err, "error: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); + return 2; + } + // Help and the version (`help`, `-h`, ` --help`, `-V`) come back as errors too. + let cli = match parse(&args) { + Ok(cli) => cli, + Err(e) => { + let to: &mut dyn Write = if e.use_stderr() { err } else { out }; + let _ = write!(to, "{}", e.render()); + return e.exit_code(); + } + }; + match dispatch(cli.command, out, err) { + Ok(()) => 0, + Err(e) => { + outln!(err, "error: {e}"); + 1 + } + } +} + +fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + match command { + Command::Info(a) => info(&a, out), + Command::Commands(a) => commands(&a, out), + Command::Run(a) => run_command(&a, out, err), + Command::Batch(a) => batch(&a, out, err), + Command::Bake(a) => bake(&a, out, err), + Command::Export(a) => export(&a, out, err), + Command::Render(a) => render(&a, err), + Command::New(a) => new(&a, err), + Command::Mcp(a) => mcp(&a), + Command::Serve(a) => serve(&a, err), + } +} + +fn print(out: &mut dyn Write, v: &Value) { + outln!(out, "{}", serde_json::to_string_pretty(v).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}"))); +} + +/// A trusted local session on `input`: a project, a mesh file or `builtin:`. +fn open(input: &Path, resolution: Option) -> Result { + let mut h = Headless::new(Headless::default_session()?, Filesystem::TrustedLocal); + match input.to_str().and_then(|text| text.strip_prefix("builtin:")) { + Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ())?, + None if is_project(input) => h.open(unicode(input)?).map(|_| ())?, + None => h.import_mesh(unicode(input)?, resolution, None).map(|_| ())?, + } + Ok(h) +} + +fn save(h: &mut Headless, out: &Path, err: &mut dyn Write) -> Result<(), CliError> { + let r = h.save(Some(unicode(out)?))?; + outln!(err, "saved {}", r["path"].as_str().unwrap_or_default()); + Ok(()) +} + +fn report_json(r: &MeshReport) -> Value { + json!({ + "triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated, + "uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings, + }) +} + +fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> { + let file = unicode(&a.input)?; + if let Some(id) = file.strip_prefix("builtin:") { + let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| CliError::UnknownBuiltin(id.to_string()))?; + let report = mesh_report(&m); + print( + out, + &json!({ + "file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(), + "materials": m.materials, "textureSets": m.materials, "uv": report_json(&report), + }), + ); + return Ok(()); + } + if !is_project(&a.input) { + let m = import_mesh(&a.input).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; + print( + out, + &json!({ + "file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(), + "materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report), + }), + ); + return Ok(()); + } + let h = open(&a.input, None)?; + let mut v = h.inspect(); + v["file"] = json!(file); + v["kind"] = json!("project"); + // The embedded mesh is re-imported for its UV report (built-in meshes have none). + v["uv"] = match &h.session.mesh_source { + Some((ext, bytes)) => { + let m = import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; + report_json(&m.report) + } + None => Value::Null, + }; + print(out, &v); + Ok(()) +} + +fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result<(), CliError> { + let h = open(Path::new("builtin:cube"), Some(128))?; + let list = h.command_list(a.filter.as_deref()); + if a.json { + print(out, &list); + return Ok(()); + } + for c in list.as_array().into_iter().flatten() { + let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + outln!(out, "{:<28} {:<36} {}", f("id"), f("label"), f("params")); + } + Ok(()) +} + +fn run_command(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let mut h = open(&a.input, None)?; + print(out, &h.command_run(&a.id, a.params.clone().unwrap_or_else(|| json!({})))?); + match &a.output { + Some(path) => save(&mut h, path, err), + None => Ok(()), + } +} + +fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let text = std::fs::read_to_string(&a.script).map_err(|e| CliError::Read { path: a.script.clone(), message: e.to_string() })?; + let script: Value = serde_json::from_str(&text).map_err(|source| CliError::Script { path: a.script.clone(), source })?; + let steps = script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or(CliError::ScriptShape)?; + let path_field = |field: &'static str| -> Result, CliError> { + match script.get(field) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) => Ok(Some(path.as_str())), + Some(_) => Err(CliError::ScriptField(field)), + } + }; + let input = path_field("open")?.unwrap_or("builtin:material_ball"); + let output = path_field("save")?; + + let mut h = open(Path::new(input), None)?; + let reply = h.batch(steps); + print(out, &reply); + if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) { + return Err(CliError::BatchStopped { + index: failure["index"].to_string(), + id: failure["id"].as_str().unwrap_or_default().to_string(), + message: failure["error"].as_str().unwrap_or_default().to_string(), + }); + } + match output { + Some(path) => save(&mut h, Path::new(path), err), + None => Ok(()), + } +} + +fn bake(a: &BakeArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + // `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o. + let target = a.output.as_deref().unwrap_or(&a.input); + let mut p = json!({"ts": "all"}); + if let Some(r) = a.resolution { + p["resolution"] = json!(r); + } + if !a.maps.is_empty() { + p["maps"] = json!(a.maps.iter().map(|m| m.trim()).filter(|m| !m.is_empty()).collect::>()); + } + let mut h = open(&a.input, None)?; + h.command_run("bake.run", p)?; + save(&mut h, target, err)?; + print(out, &h.inspect()["textureSets"]); + Ok(()) +} + +fn export(a: &ExportArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let mut p = json!({"dir": unicode(&a.dir)?}); + for (key, value) in [("preset", &a.preset), ("format", &a.format), ("padding", &a.padding)] { + if let Some(v) = value { + p[key] = json!(v); + } + } + if let Some(v) = a.size { + p["size"] = json!(v); + } + let mut h = open(&a.input, None)?; + let r = h.export(&p)?; + for w in r["warnings"].as_array().into_iter().flatten() { + outln!(err, "warning: {}", w.as_str().unwrap_or_default()); + } + for f in r["files"].as_array().into_iter().flatten() { + outln!(out, "{}", f.as_str().unwrap_or_default()); + } + Ok(()) +} + +fn render(a: &RenderArgs, err: &mut dyn Write) -> Result<(), CliError> { + let options = RenderOptions { + view: a.view.clone(), + width: a.size.map(|s| s.width), + height: a.size.map(|s| s.height), + yaw: a.yaw, + pitch: a.pitch, + samples: a.samples, + bounces: a.bounces, + cpu: a.cpu, + }; + let mut h = open(&a.input, None)?; + if let Some(name) = &a.camera { + h.command_run("camera.select", json!({ "name": name }))?; + } + let t0 = std::time::Instant::now(); + let r = h.render_png(&options)?; + let secs = t0.elapsed().as_secs_f64(); + std::fs::write(&a.output, &r.png).map_err(|source| CliError::Write { path: a.output.clone(), source })?; + outln!(err, "wrote {} ({}x{}, {}, {secs:.2} s)", a.output.display(), r.width, r.height, r.by); + Ok(()) +} + +fn new(a: &NewArgs, err: &mut dyn Write) -> Result<(), CliError> { + if is_project(&a.input) { + return Err(CliError::AlreadyProject(a.input.clone())); + } + let mut h = open(&a.input, a.resolution)?; + if a.sample { + let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024)); + h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res}))?; + for ts in 0..h.session.set_count() { + h.command_run("textureSet.select", json!({"ts": ts}))?; + h.command_run("material.apply", json!({"material": "steel_painted_worn"}))?; + } + h.command_run("textureSet.select", json!({"ts": 0}))?; + } + save(&mut h, &a.output, err) +} + +/// File access for servers: none without roots, else only below them +fn workspace(roots: &RootArgs) -> Result { + if roots.read_root.is_none() && roots.write_root.is_none() { + return Ok(Filesystem::Denied); + } + Ok(Filesystem::Workspace(AuthorizedWorkspace::new(roots.read_root.as_deref(), roots.write_root.as_deref())?)) +} + +fn mcp(a: &McpArgs) -> Result<(), CliError> { + let server = match a.bridge { + Some(port) => TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.token.clone())?)), + None => TexturecraftMcp::headless(Headless::new(Headless::default_session()?, workspace(&a.roots)?)), + }; + let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(CliError::Serve)?; + rt.block_on(server.serve_stdio()).map_err(|e| CliError::Automation(texturecraft_automation::AutomationError::Other(e.to_string()))) +} + +fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result<(), CliError> { + let h = Arc::new(Mutex::new(Headless::new(Headless::default_session()?, workspace(&a.roots)?))); + match a.port { + None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(CliError::Serve)?, + Some(port) => { + // Bind first: a port in use must not replace its server's token file. + let listener = rpc::bind_tcp(port)?; + let addr = listener.local_addr().map_err(CliError::Serve)?; + let (token, file) = server_token(addr.port())?; + match file { + Some(f) => outln!(err, "texturecraft-cli: serving on {addr}; token in {}", f.display()), + None => outln!(err, "texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"), + } + rpc::serve_listener(listener, h, token)?; + } + } + Ok(()) +} diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index 80069d9d..357cf17e 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -1,452 +1,8 @@ -//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and -//! serve agents over MCP or JSON lines. Never opens a window. +//! Headless TextureCraft command line. Never opens a window. See the library crate for the commands. #![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -use std::path::Path; -use std::sync::{Arc, Mutex}; - -use serde_json::{Value, json}; -use texturecraft_automation::security::{client_token, server_token}; -use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc}; -use texturecraft_engine::core::PROJECT_EXT; -use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report}; - -const USAGE: &str = "\ -texturecraft-cli: headless TextureCraft - -USAGE: - texturecraft-cli --version - texturecraft-cli info > - Texture sets, layers, triangles, materials and the UV report, as JSON. - texturecraft-cli commands [--filter ] - List the engine commands (id, label, params). - texturecraft-cli run [params-json] [-o ] - Run one command and print its JSON result; -o saves the project. - texturecraft-cli batch - Run [{\"id\", \"params\"}, ...] or {\"open\": , \"steps\": [...], \"save\": }. - texturecraft-cli bake [-o ] [--resolution ] [--maps ] - Bake mesh maps for every texture set (a project is saved in place without -o). - texturecraft-cli export [--preset ] [--format ] [--padding ] [--size ] - Export textures (default preset: Document channels + Normal + AO (No Alpha)). - texturecraft-cli render [--size x] [--view 3d|2d] [--camera ] [--yaw ] - [--pitch ] [--samples ] [--bounces ] [--cpu] - Render the viewport to PNG (needs a GPU or software adapter); --camera looks through a - camera saved in the project (camera.add); --samples path traces it instead (Rendering - mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU. - texturecraft-cli new > [--resolution ] [--sample] - New project; --sample bakes and applies a smart material to every texture set. The - sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size), - so a 2048 sample project is as large as a 1024 one. - texturecraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] - MCP server on stdio: headless (file access only below the roots), or bridged to - `texturecraft --control `. --automation-read-root / --automation-write-root are - the same as --read-root / --write-root (mcp and serve). - texturecraft-cli serve [--port ] [--read-root ] [--write-root ] - JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. - - is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl) -or builtin: (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane). -See docs/control-protocol.md. -"; - -/// (name, flags taking a value, bare flags) -const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ - ("info", &[], &[]), - ("commands", &["--filter"], &[]), - ("run", &["-o"], &[]), - ("batch", &[], &[]), - ("bake", &["-o", "--resolution", "--maps"], &[]), - ("export", &["--preset", "--format", "--padding", "--size"], &[]), - ("render", &["--size", "--view", "--camera", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]), - ("new", &["--resolution"], &["--sample"]), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), - ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), -]; - -struct Args { - pos: Vec, - flags: Vec<(String, Option)>, -} - -impl Args { - fn get(&self, k: &str) -> Option<&str> { - self.flags.iter().rev().find(|(f, _)| f == k).and_then(|(_, v)| v.as_deref()) - } - fn has(&self, k: &str) -> bool { - self.flags.iter().any(|(f, _)| f == k) - } - fn num(&self, k: &str) -> Result, String> { - self.get(k).map(|v| v.parse().map_err(|_| format!("{k}: `{v}` is not a valid number"))).transpose() - } - fn pos(&self, n: usize, what: &str) -> Result<&str, String> { - self.pos.get(n).map(String::as_str).ok_or_else(|| format!("missing {what}")) - } -} - -fn parse(values: &[&str], bare: &[&str], args: &[String]) -> Result { - let mut a = Args { pos: Vec::new(), flags: Vec::new() }; - let mut it = args.iter(); - while let Some(s) = it.next() { - let (k, inline) = match s.split_once('=') { - Some((k, v)) if k.starts_with("--") => (k, Some(v.to_string())), - _ => (s.as_str(), None), - }; - if values.contains(&k) { - let v = match inline { - Some(v) => v, - None => it.next().ok_or_else(|| format!("{k} needs a value"))?.clone(), - }; - a.flags.push((k.to_string(), Some(v))); - } else if bare.contains(&k) && inline.is_none() { - a.flags.push((k.to_string(), None)); - } else if k.starts_with('-') && k.len() > 1 && k.parse::().is_err() { - return Err(format!("unknown option `{s}`")); - } else { - a.pos.push(s.clone()); - } - } - Ok(a) -} - -fn version() -> String { - let sha = env!("TEXTURECRAFT_BUILD_SHA"); - let short = sha.get(..7).unwrap_or(sha); - let date = env!("TEXTURECRAFT_BUILD_DATE"); - match (short.is_empty(), date.is_empty()) { - (true, true) => format!("TextureCraft {}", texturecraft_engine::VERSION), - (true, false) => format!("TextureCraft {} ({date})", texturecraft_engine::VERSION), - _ => format!("TextureCraft {} ({short} {date})", texturecraft_engine::VERSION), - } -} - -/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the -/// GUI only, and a script that passes them to the CLI has the wrong program. -fn is_launch_profile_flag(arg: &str) -> bool { - arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") -} fn main() { - let args: Vec = std::env::args().skip(1).collect(); - if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) { - eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); - std::process::exit(2); - } - let code = match args.first().map(String::as_str) { - None => { - eprint!("{USAGE}"); - 2 - } - Some("--version" | "-V" | "version") => { - println!("{}", version()); - 0 - } - Some("--help" | "-h" | "help") => { - print!("{USAGE}"); - 0 - } - Some(cmd) => match SUBCOMMANDS.iter().find(|(n, _, _)| *n == cmd) { - None => { - eprintln!("texturecraft-cli: unknown command `{cmd}`\n\n{USAGE}"); - 2 - } - Some(_) if args.iter().any(|a| a == "--help" || a == "-h") => { - print!("{USAGE}"); - 0 - } - Some((name, values, bare)) => match parse(values, bare, args.get(1..).unwrap_or_default()) { - Err(e) => { - eprintln!("texturecraft-cli {name}: {e}\n\n{USAGE}"); - 2 - } - Ok(a) => match dispatch(name, &a) { - Ok(()) => 0, - Err(e) => { - eprintln!("texturecraft-cli {name}: error: {e}"); - 1 - } - }, - }, - }, - }; + // `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed. + let code = texturecraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); std::process::exit(code); } - -type R = Result<(), String>; - -fn dispatch(name: &str, a: &Args) -> R { - match name { - "info" => info(a), - "commands" => commands(a), - "run" => run(a), - "batch" => batch(a), - "bake" => bake(a), - "export" => export(a), - "render" => render(a), - "new" => new(a), - "mcp" => mcp(a), - "serve" => serve(a), - other => Err(format!("unknown command `{other}`")), - } -} - -fn s(e: impl std::fmt::Display) -> String { - e.to_string() -} - -fn print_json(v: &Value) -> R { - println!("{}", serde_json::to_string_pretty(v).map_err(s)?); - Ok(()) -} - -fn is_project(path: &str) -> bool { - Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case(PROJECT_EXT)) -} - -/// A trusted local session on `input`: a project, a mesh file or `builtin:`. -fn open(input: &str, resolution: Option) -> Result { - let mut h = Headless::new(Headless::default_session().map_err(s)?, Filesystem::TrustedLocal); - match input.strip_prefix("builtin:") { - Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ()), - None if is_project(input) => h.open(input).map(|_| ()), - None => h.import_mesh(input, resolution, None).map(|_| ()), - } - .map_err(s)?; - Ok(h) -} - -fn save(h: &mut Headless, out: &str) -> R { - let r = h.save(Some(out)).map_err(s)?; - eprintln!("saved {}", r["path"].as_str().unwrap_or_default()); - Ok(()) -} - -fn report_json(r: &MeshReport) -> Value { - json!({ - "triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated, - "uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings, - }) -} - -fn info(a: &Args) -> R { - let file = a.pos(0, "")?; - if let Some(id) = file.strip_prefix("builtin:") { - let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| format!("unknown built-in mesh `{id}`"))?; - let report = mesh_report(&m); - return print_json(&json!({ - "file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(), - "materials": m.materials, "textureSets": m.materials, "uv": report_json(&report), - })); - } - if !is_project(file) { - let m = import_mesh(Path::new(file)).map_err(|e| format!("cannot read {file}: {e}"))?; - return print_json(&json!({ - "file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(), - "materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report), - })); - } - let h = open(file, None)?; - let mut v = h.inspect(); - v["file"] = json!(file); - v["kind"] = json!("project"); - // The embedded mesh is re-imported for its UV report (built-in meshes have none). - v["uv"] = match &h.session.mesh_source { - Some((ext, bytes)) => import_mesh_bytes(&format!("mesh.{ext}"), bytes).map(|m| report_json(&m.report)).map_err(s)?, - None => Value::Null, - }; - print_json(&v) -} - -fn commands(a: &Args) -> R { - let h = open("builtin:cube", Some(128))?; - for c in h.command_list(a.get("--filter")).as_array().into_iter().flatten() { - let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); - println!("{:<28} {:<36} {}", f("id"), f("label"), f("params")); - } - Ok(()) -} - -fn run(a: &Args) -> R { - let (input, id) = (a.pos(0, "")?, a.pos(1, "")?); - let params: Value = match a.pos.get(2) { - Some(j) => serde_json::from_str(j).map_err(|e| format!("params are not JSON: {e}"))?, - None => json!({}), - }; - let mut h = open(input, None)?; - print_json(&h.command_run(id, params).map_err(s)?)?; - match a.get("-o") { - Some(out) => save(&mut h, out), - None => Ok(()), - } -} - -fn batch(args: &Args) -> R { - let path = args.pos(0, "")?; - let script: Value = { - let script_text = std::fs::read_to_string(path).map_err(|err| format!("cannot read {path}: {err}"))?; - serde_json::from_str(&script_text).map_err(|err| format!("{path} is not JSON: {err}"))? - }; - - let steps = - script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or("the script must be a list of steps or {\"steps\": [...]}")?; - let path_field = |field: &str| -> Result, String> { - match script.get(field) { - None | Some(Value::Null) => Ok(None), - Some(Value::String(path)) => Ok(Some(path.as_str())), - Some(_) => Err(format!("the script's `{field}` field must be a string")), - } - }; - let input = path_field("open")?.unwrap_or("builtin:material_ball"); - let output = path_field("save")?; - - let mut headless = open(input, None)?; - let reply = headless.batch(steps); - print_json(&reply)?; - if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) { - return Err(format!( - "step {} (`{}`) failed: {}", - failure["index"], - failure["id"].as_str().unwrap_or_default(), - failure["error"].as_str().unwrap_or_default() - )); - } - - match output { - Some(output_path) => save(&mut headless, output_path), - None => Ok(()), - } -} - -fn bake(a: &Args) -> R { - let input = a.pos(0, "")?; - let out = a.get("-o").or(is_project(input).then_some(input)).ok_or("give -o to save the baked project")?; - let mut p = json!({"ts": "all"}); - if let Some(r) = a.num::("--resolution")? { - p["resolution"] = json!(r); - } - if let Some(m) = a.get("--maps") { - p["maps"] = json!(m.split(',').map(str::trim).filter(|m| !m.is_empty()).collect::>()); - } - let mut h = open(input, None)?; - h.command_run("bake.run", p).map_err(s)?; - save(&mut h, out)?; - print_json(&h.inspect()["textureSets"]) -} - -fn export(a: &Args) -> R { - let (input, dir) = (a.pos(0, "")?, a.pos(1, "")?); - let mut p = json!({"dir": dir}); - for k in ["preset", "format", "padding"] { - if let Some(v) = a.get(&format!("--{k}")) { - p[k] = json!(v); - } - } - if let Some(v) = a.num::("--size")? { - p["size"] = json!(v); - } - let mut h = open(input, None)?; - let r = h.export(&p).map_err(s)?; - for w in r["warnings"].as_array().into_iter().flatten() { - eprintln!("warning: {}", w.as_str().unwrap_or_default()); - } - for f in r["files"].as_array().into_iter().flatten() { - println!("{}", f.as_str().unwrap_or_default()); - } - Ok(()) -} - -fn render(a: &Args) -> R { - let (input, out) = (a.pos(0, "")?, a.pos(1, "")?); - let (width, height) = match a.get("--size") { - Some(sz) => { - let (w, h) = sz.split_once(['x', 'X']).ok_or("--size must be x, e.g. 1280x800")?; - (Some(w.parse().map_err(|_| "bad --size width")?), Some(h.parse().map_err(|_| "bad --size height")?)) - } - None => (None, None), - }; - let o = RenderOptions { - view: a.get("--view").map(str::to_string), - width, - height, - yaw: a.num("--yaw")?, - pitch: a.num("--pitch")?, - samples: a.num("--samples")?, - bounces: a.num("--bounces")?, - cpu: a.has("--cpu"), - }; - let mut h = open(input, None)?; - if let Some(name) = a.get("--camera") { - h.command_run("camera.select", json!({ "name": name })).map_err(s)?; - } - let t0 = std::time::Instant::now(); - let r = h.render_png(&o).map_err(s)?; - let secs = t0.elapsed().as_secs_f64(); - std::fs::write(out, &r.png).map_err(|e| format!("cannot write {out}: {e}"))?; - eprintln!("wrote {out} ({}x{}, {}, {secs:.2} s)", r.width, r.height, r.by); - Ok(()) -} - -fn new(a: &Args) -> R { - let (input, out) = (a.pos(0, "")?, a.pos(1, "")?); - if is_project(input) { - return Err(format!("{input} is already a project")); - } - let res = a.num::("--resolution")?; - let mut h = open(input, res)?; - if a.has("--sample") { - let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024)); - h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res})).map_err(s)?; - for ts in 0..h.session.set_count() { - h.command_run("textureSet.select", json!({"ts": ts})).map_err(s)?; - h.command_run("material.apply", json!({"material": "steel_painted_worn"})).map_err(s)?; - } - h.command_run("textureSet.select", json!({"ts": 0})).map_err(s)?; - } - save(&mut h, out) -} - -fn workspace(a: &Args) -> Result { - // `--automation-*-root` is the spelling the other crafting apps use. - let root = |k: &str| a.get(&format!("--automation-{k}")).or_else(|| a.get(&format!("--{k}"))).map(Path::new); - let (r, w) = (root("read-root"), root("write-root")); - if r.is_none() && w.is_none() { - return Ok(Filesystem::Denied); - } - Ok(Filesystem::Workspace(AuthorizedWorkspace::new(r, w).map_err(s)?)) -} - -fn port_of(v: &str) -> Result { - let p = v.strip_prefix("127.0.0.1:").or_else(|| v.strip_prefix("localhost:")).unwrap_or(v); - p.parse::().ok().filter(|p| *p != 0).ok_or_else(|| format!("`{v}` is not a loopback port (1-65535)")) -} - -fn mcp(a: &Args) -> R { - let server = match a.get("--bridge") { - Some(b) => { - let port = port_of(b)?; - TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.get("--token").map(str::to_string)).map_err(s)?)) - } - None => TexturecraftMcp::headless(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?)), - }; - let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(s)?; - rt.block_on(server.serve_stdio()).map_err(s) -} - -fn serve(a: &Args) -> R { - let h = Arc::new(Mutex::new(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?))); - match a.get("--port") { - None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(s), - Some(p) => { - // Bind first: a port in use must not replace its server's token file, and port 0's - // token file is named after the port actually picked. - let listener = rpc::bind_tcp(port_of(p)?).map_err(s)?; - let addr = listener.local_addr().map_err(s)?; - let (token, file) = server_token(addr.port()).map_err(s)?; - match file { - Some(f) => eprintln!("texturecraft-cli: serving on {addr}; token in {}", f.display()), - None => eprintln!("texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"), - } - rpc::serve_listener(listener, h, token).map_err(s) - } - } -} diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 6bef0017..a5089e96 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -44,9 +44,9 @@ fn p(path: &Path) -> &str { #[test] fn version_and_usage_errors() { let v = ok(&["--version"]); - assert!(v.starts_with("TextureCraft "), "{v}"); + assert!(v.starts_with("texturecraft-cli "), "{v}"); assert_eq!(v.lines().count(), 1); - assert!(ok(&["--help"]).contains("texturecraft-cli mcp")); + assert!(ok(&["--help"]).contains("Usage: texturecraft-cli ")); assert_eq!(cli(&[]).status.code(), Some(2)); assert_eq!(cli(&["frobnicate"]).status.code(), Some(2)); assert_eq!(cli(&["info", "--bogus"]).status.code(), Some(2)); @@ -54,8 +54,8 @@ fn version_and_usage_errors() { assert_eq!(o.status.code(), Some(1)); assert!(String::from_utf8_lossy(&o.stderr).contains("error")); assert_eq!(cli(&["run", "builtin:nope", "layer.add.fill"]).status.code(), Some(1)); - assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(1)); - assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(1)); + assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(2)); + assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(2)); } #[test] @@ -73,7 +73,7 @@ fn new_info_run_bake_export_batch() { assert!(r["layer"].is_u64(), "{r}"); assert_eq!(json(&["info", p(&b)])["layers"][0]["kind"], "fill"); - ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature"]); + ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature", "--in-place"]); let maps = json(&["info", p(&b)])["textureSets"][0]["baked"]["maps"].clone(); assert_eq!(maps.as_array().unwrap().len(), 2, "{maps}"); @@ -202,10 +202,10 @@ fn path_traced_render_needs_no_gpu() { // --camera looks through a camera saved in the project; an unknown name is an error. let proj = d.join("cams.tcraft"); ok(&["run", "builtin:cube", "camera.set", r#"{"yaw": 80, "distance": 9}"#, "-o", p(&proj)]); - ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj)]); + ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj), "--in-place"]); ok(&["render", p(&proj), p(&out), "--size", "48x32", "--camera", "Side", "--samples", "2", "--cpu"]); assert_eq!(cli(&["render", p(&proj), p(&out), "--camera", "Nope", "--samples", "2", "--cpu"]).status.code(), Some(1)); - assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1)); + assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(2)); assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1)); let _ = std::fs::remove_dir_all(&d); } diff --git a/apps/texturecraft-cli/tests/it/cli.rs b/apps/texturecraft-cli/tests/it/cli.rs new file mode 100644 index 00000000..332da939 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/cli.rs @@ -0,0 +1,331 @@ +//! RFC-0018 rule 2.7: help, versions, usage errors with exit 2 on stderr, and nothing written +//! before the arguments are checked. + +use std::ffi::OsString; + +use crate::{argv, invoke, project, workdir}; + +const SUBCOMMANDS: [&str; 10] = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"]; + +/// The shortest valid command line of each subcommand. +fn minimal(sub: &str) -> Vec<&str> { + match sub { + "info" => vec!["info", "builtin:cube"], + "run" => vec!["run", "builtin:cube", "layer.add.fill"], + "batch" => vec!["batch", "s.json"], + "bake" => vec!["bake", "builtin:cube", "-o", "o.tcraft"], + "export" => vec!["export", "builtin:cube", "dir"], + "render" => vec!["render", "builtin:cube", "o.png"], + "new" => vec!["new", "builtin:cube", "o.tcraft"], + other => vec![other], + } +} + +fn usage_error(args: &[&str]) -> String { + let got = invoke(args.iter().copied()); + assert_eq!(got.code, 2, "{args:?}: {}", got.err); + assert_eq!(got.out, "", "{args:?} wrote to stdout"); + assert!(got.err.starts_with("error: "), "{args:?}: {}", got.err); + got.err +} + +#[test] +fn help_and_the_version_go_to_stdout_with_exit_0() { + for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"]] { + let got = invoke(args.iter().copied()); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{args:?}"); + assert!(got.out.contains("texturecraft-cli"), "{args:?}: {}", got.out); + } + let help = invoke(["--help"]).out; + assert!(help.contains("Exit status:") && help.contains("128 + the signal number"), "{help}"); + for sub in SUBCOMMANDS { + for flag in ["--help", "-h"] { + let got = invoke([sub, flag]); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{sub} {flag}"); + assert!(got.out.contains(&format!("Usage: texturecraft-cli {sub}")), "{sub}: {}", got.out); + } + assert_eq!(invoke(["help", sub]).out, invoke([sub, "--help"]).out, "{sub}"); + } +} + +#[test] +fn every_subcommand_takes_the_version_and_there_is_no_version_subcommand() { + let top = invoke(["--version"]).out; + let want = top.strip_prefix("texturecraft-cli ").unwrap().trim_end().to_string(); + assert!(want.starts_with(texturecraft_engine::VERSION), "{want}"); + for sub in SUBCOMMANDS { + for flag in ["--version", "-V"] { + let got = invoke([sub, flag]); + assert_eq!((got.code, got.out.as_str(), got.err.as_str()), (0, format!("texturecraft-cli-{sub} {want}\n").as_str(), ""), "{sub} {flag}"); + } + } + usage_error(&["version"]); +} + +#[test] +fn no_arguments_is_a_usage_error_that_prints_the_help_on_stderr() { + let got = invoke(Vec::::new()); + assert_eq!((got.code, got.out.as_str()), (2, "")); + assert!(got.err.contains("Usage: texturecraft-cli "), "{}", got.err); +} + +#[test] +fn an_unknown_flag_or_subcommand_is_refused_by_every_subcommand() { + for sub in SUBCOMMANDS { + let mut args = minimal(sub); + args.push("--fromat"); + let message = usage_error(&args); + assert!(message.contains("--fromat"), "{sub}: {message}"); + } + usage_error(&["rendre"]); + usage_error(&["--fromat"]); +} + +#[test] +fn a_flag_given_twice_is_refused() { + usage_error(&["new", "builtin:cube", "o.tcraft", "--resolution", "8", "--resolution", "9"]); + usage_error(&["bake", "builtin:cube", "-o", "a.tcraft", "-o", "b.tcraft"]); + usage_error(&["render", "builtin:cube", "o.png", "--samples", "2", "--cpu", "--cpu"]); + usage_error(&["mcp", "--read-root", "a", "--automation-read-root", "b"]); +} + +#[test] +fn bad_values_conflicts_and_missing_arguments_are_refused_before_any_file_is_written() { + let dir = workdir("refused"); + let out = dir.join("never"); + let o = out.to_str().unwrap(); + let project_file = dir.join("p.tcraft"); + let p = project_file.to_str().unwrap(); + for (args, expect) in [ + (vec!["new", "builtin:cube", o, "--resolution", "0"], "--resolution"), + (vec!["new", "builtin:cube", o, "--resolution", "big"], "--resolution"), + (vec!["bake", "builtin:cube", "-o", o, "--resolution", "-1"], "-1"), + (vec!["bake", "builtin:cube"], "give -o"), + (vec!["bake", p], "--in-place"), + (vec!["bake", "builtin:cube", "--in-place"], "-o"), + (vec!["export", "builtin:cube", o, "--size", "0"], "--size"), + (vec!["export", "builtin:cube"], "required"), + (vec!["run", "builtin:cube", "layer.add.fill", "{not json"], "not JSON"), + (vec!["run", "builtin:cube", "layer.add.fill", "{}", "--in-place"], "--output"), + (vec!["render", "builtin:cube", o, "--size", "big"], "x"), + (vec!["render", "builtin:cube", o, "--size", "0x5"], "x"), + (vec!["render", "builtin:cube", o, "--view", "4d"], "--view"), + (vec!["render", "builtin:cube", o, "--yaw", "NaN"], "--yaw"), + (vec!["render", "builtin:cube", o, "--samples", "0"], "--samples"), + (vec!["render", "builtin:cube", o, "--cpu"], "--samples"), + (vec!["render", "builtin:cube", o, "--bounces", "3"], "--samples"), + (vec!["mcp", "--token", "abcdefghijklmnop"], "--bridge"), + (vec!["mcp", "--bridge", "9878", "--read-root", o], "headless server"), + (vec!["mcp", "--bridge", "99999"], "--bridge"), + (vec!["mcp", "--bridge", "0"], "--bridge"), + (vec!["serve", "--port", "http"], "--port"), + ] { + let message = usage_error(&args); + assert!(message.contains(expect), "{args:?}: {message}"); + } + assert!(!out.exists()); + assert!(std::fs::read_dir(&dir).unwrap().next().is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn loopback_ports_take_the_host_prefix_and_a_dashed_name_follows_a_double_dash() { + // `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token. + for bridge in ["127.0.0.1:9", "localhost:9"] { + let got = invoke(["mcp", "--bridge", bridge, "--token", "short"]); + assert_eq!(got.code, 1, "{bridge}: {}", got.err); + } + let got = invoke(["info", "--", "-odd.tcraft"]); + assert_eq!(got.code, 1); + assert!(got.err.contains("-odd.tcraft"), "{}", got.err); + usage_error(&["render", "builtin:cube", "o.png", "--camera", "--cpu"]); +} + +#[test] +fn info_and_commands_print_what_a_program_reads() { + let got = invoke(["info", "builtin:cube"]); + assert_eq!((got.code, got.err.as_str()), (0, "")); + assert_eq!(serde_json::from_str::(&got.out).unwrap()["kind"], "mesh"); + let table = invoke(["commands", "--filter", "layer.add"]); + assert_eq!((table.code, table.err.as_str()), (0, "")); + assert!(table.out.lines().all(|l| l.starts_with("layer.add") || l.trim().is_empty()) && !table.out.is_empty(), "{}", table.out); + let json = invoke(["commands", "--filter", "layer.add", "--json"]); + assert_eq!(json.code, 0); + let list: serde_json::Value = serde_json::from_str(&json.out).unwrap(); + assert!(list.as_array().is_some_and(|l| !l.is_empty()), "{}", json.out); + let got = invoke(["info", "builtin:bogus"]); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.starts_with("error: unknown built-in mesh `bogus`"), "{}", got.err); +} + +#[test] +fn new_run_bake_and_export_through_files() { + let dir = workdir("files"); + let a = project(&dir, "a.tcraft"); + let b = dir.join("b.tcraft"); + let got = invoke(argv(&[&"run", &a, &"layer.add.fill", &r#"{"color":[1,0,0]}"#, &"-o", &b])); + assert_eq!(got.code, 0, "{}", got.err); + assert!(got.err.starts_with("saved "), "{}", got.err); + assert!(b.is_file()); + let got = invoke(argv(&[&"bake", &b, &"--resolution", &"128", &"--maps", &"ambientOcclusion", &"--in-place"])); + assert_eq!(got.code, 0, "{}", got.err); + let textures = dir.join("tex"); + let got = invoke(argv(&[&"export", &b, &textures, &"--preset", &"glTF PBR Metal Roughness", &"--size", &"128"])); + assert_eq!(got.code, 0, "{}", got.err); + assert!(got.out.lines().count() >= 3, "{}", got.out); + let got = invoke(argv(&[&"new", &"builtin:cube", &a])); + assert_eq!(got.code, 0, "{}", got.err); + let got = invoke(argv(&[&"new", &a, &dir.join("again.tcraft")])); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.contains("is already a project"), "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn an_output_that_would_replace_an_input_is_refused_without_in_place() { + let dir = workdir("replace"); + let source = project(&dir, "a.tcraft"); + let a = source.to_str().unwrap(); + let before = std::fs::read(&source).unwrap(); + let again = dir.join(".").join("a.tcraft"); + let again = again.to_str().unwrap(); + for args in [ + vec!["run", a, "layer.add.fill", "{}", "-o", a], + vec!["run", a, "layer.add.fill", "{}", "-o", again], + vec!["bake", a, "-o", a], + vec!["bake", a], + vec!["render", a, again], + vec!["new", a, a], + ] { + let message = usage_error(&args); + assert!(message.contains("--in-place") || message.contains("would replace"), "{args:?}: {message}"); + } + assert_eq!(std::fs::read(&source).unwrap(), before, "a refused command changes nothing"); + // `--in-place` lets only a project be replaced, and only by itself. + let got = invoke(["run", a, "layer.add.fill", "{}", "-o", a, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + let got = invoke(["bake", a, "--in-place", "--resolution", "128", "--maps", "ambientOcclusion"]); + assert_eq!(got.code, 0, "{}", got.err); + let elsewhere = dir.join("b.tcraft"); + assert!(usage_error(&["run", a, "layer.add.fill", "{}", "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); + assert!(usage_error(&["bake", a, "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); + assert!(!elsewhere.exists()); + // Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft. + let unsuffixed = dir.join("a"); + let unsuffixed = unsuffixed.to_str().unwrap(); + let after_in_place = std::fs::read(&source).unwrap(); + let message = usage_error(&["run", a, "layer.add.fill", "{}", "-o", unsuffixed]); + assert!(message.contains("would replace") || message.contains("--in-place"), "{message}"); + assert_eq!(std::fs::read(&source).unwrap(), after_in_place, "an unsuffixed -o changes nothing"); + let got = invoke(["run", a, "layer.add.fill", "{}", "-o", unsuffixed, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn batch_runs_a_script_and_a_failing_step_fails_the_command() { + let dir = workdir("batch"); + let good = dir.join("good.json"); + std::fs::write(&good, r#"[{"id": "layer.add.paint", "params": {"name": "Scripted"}}]"#).unwrap(); + let got = invoke(argv(&[&"batch", &good])); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{}", got.out); + let bad = dir.join("bad.json"); + std::fs::write(&bad, r#"[{"id": "layer.add.paint"}, {"id": "no.such.command"}]"#).unwrap(); + let got = invoke(argv(&[&"batch", &bad])); + assert_eq!(got.code, 1); + assert!(got.err.starts_with("error: step 1 (`no.such.command`) failed: "), "{}", got.err); + for (body, expect) in [("[", "is not JSON"), ("{}", "list of steps"), (r#"{"steps": [], "open": false}"#, "`open` field must be a string")] { + let script = dir.join("odd.json"); + std::fs::write(&script, body).unwrap(); + let got = invoke(argv(&[&"batch", &script])); + assert_eq!(got.code, 1, "{body}"); + assert!(got.err.contains(expect), "{body}: {}", got.err); + } + let got = invoke(argv(&[&"batch", &dir.join("missing.json")])); + assert_eq!(got.code, 1); + assert!(got.err.contains("missing.json"), "{}", got.err); + // A script that saves over the project it opened needs --in-place, and must not have run. + let opened = project(&dir, "opened.tcraft"); + let before = std::fs::read(&opened).unwrap(); + let overwrite = dir.join("overwrite.json"); + std::fs::write( + &overwrite, + serde_json::json!({ + "open": opened, + "save": opened, + "steps": [{"id": "layer.add.paint", "params": {"name": "Batch"}}] + }) + .to_string(), + ) + .unwrap(); + let message = usage_error(&["batch", overwrite.to_str().unwrap()]); + assert!(message.contains("--in-place") || message.contains("would replace"), "{message}"); + assert_eq!(std::fs::read(&opened).unwrap(), before); + let got = invoke(argv(&[&"batch", &overwrite, &"--in-place"])); + assert_eq!(got.code, 0, "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_failed_command_exits_1_with_the_message_on_stderr() { + let got = invoke(["run", "builtin:cube", "no.such.command"]); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.starts_with("error: "), "{}", got.err); + let got = invoke(["info", "missing.tcraft"]); + assert_eq!(got.code, 1); + assert!(got.err.starts_with("error: ") && got.err.contains("missing.tcraft"), "{}", got.err); +} + +#[test] +fn the_desktop_launch_options_are_refused_before_any_subcommand() { + for args in + [vec!["--launch-profile", "nightly-v1", "--version"], vec!["--profile-root=/tmp/p", "--version"], vec!["info", "builtin:cube", "--launch-profile=x"]] + { + let message = usage_error(&args); + assert!(message.contains("desktop launch option"), "{args:?}: {message}"); + } +} + +#[cfg(unix)] +#[test] +fn a_path_that_is_not_valid_unicode_is_named_in_the_error() { + use std::os::unix::ffi::OsStringExt; + let dir = workdir("non-unicode"); + // The engine's commands take their paths as JSON text: the command says so and names the file. + let input = dir.join(OsString::from_vec(b"in-\xff.tcraft".to_vec())); + let got = invoke(argv(&[&"info", &input])); + assert_eq!(got.code, 1); + assert!(got.err.contains("the path is not valid Unicode") && got.err.contains("in-"), "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_closed_stdout_is_not_an_error() { + struct Closed; + impl std::io::Write for Closed { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut err = Vec::new(); + assert_eq!(texturecraft_cli::run(["commands"], &mut Closed, &mut err), 0); + assert_eq!(texturecraft_cli::run(["--help"], &mut Closed, &mut err), 0); + assert!(err.is_empty()); +} + +#[test] +fn headless_mcp_requires_both_roots() { + for args in [ + vec!["mcp"], + vec!["mcp", "--read-root", "."], + vec!["mcp", "--write-root", "."], + vec!["mcp", "--automation-read-root", "."], + vec!["mcp", "--automation-write-root", "."], + ] { + let message = usage_error(&args); + assert!(message.contains("--read-root") && message.contains("--write-root"), "{args:?}: {message}"); + } +} diff --git a/apps/texturecraft-cli/tests/it/main.rs b/apps/texturecraft-cli/tests/it/main.rs new file mode 100644 index 00000000..ea1db565 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/main.rs @@ -0,0 +1,48 @@ +//! Integration tests, built as one test binary: each file is a module. They call `run` in-process, +//! except where a test needs the real binary (a protocol on stdio, the environment). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod cli; +mod man_and_completions; +mod protocol; + +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; + +/// What `run` returned and wrote. +pub struct Outcome { + pub code: i32, + pub out: String, + pub err: String, +} + +pub fn invoke(args: I) -> Outcome +where + I: IntoIterator, + T: Into, +{ + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = texturecraft_cli::run(args, &mut out, &mut err); + Outcome { code, out: String::from_utf8_lossy(&out).into_owned(), err: String::from_utf8_lossy(&err).into_owned() } +} + +/// A new, empty folder for one test. +pub fn workdir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-cli-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A small project made by `new`. +pub fn project(dir: &Path, name: &str) -> PathBuf { + let path = dir.join(name); + let made = invoke(argv(&[&"new", &"builtin:cube", &path, &"--resolution", &"128"])); + assert_eq!(made.code, 0, "{}", made.err); + path +} + +/// An argument vector from parts of different types (strings, paths). +pub fn argv(parts: &[&dyn AsRef]) -> Vec { + parts.iter().map(|p| p.as_ref().to_os_string()).collect() +} diff --git a/apps/texturecraft-cli/tests/it/man_and_completions.rs b/apps/texturecraft-cli/tests/it/man_and_completions.rs new file mode 100644 index 00000000..47607b5a --- /dev/null +++ b/apps/texturecraft-cli/tests/it/man_and_completions.rs @@ -0,0 +1,55 @@ +//! The clap definition is consistent, and every shell's completions and every man page +//! (`examples/man-and-completions.rs`) can be generated from it. + +use clap::ValueEnum; +use clap_complete::Shell; + +// The example itself, so the test writes the files exactly as the packages get them. +#[allow(dead_code)] +#[path = "../../examples/man-and-completions.rs"] +mod example; + +#[test] +fn command_is_consistent() { + texturecraft_cli::command().debug_assert(); +} + +#[test] +fn completions_generate_for_every_shell() { + for &shell in Shell::value_variants() { + let mut out = Vec::new(); + clap_complete::generate(shell, &mut texturecraft_cli::command(), "texturecraft-cli", &mut out); + assert!(!out.is_empty(), "{shell}"); + } +} + +#[test] +fn man_pages_render_for_the_command_and_every_subcommand() { + let cmd = texturecraft_cli::command(); + for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) { + let mut out = Vec::new(); + clap_mangen::Man::new(page.clone()).render(&mut out).unwrap(); + assert!(!out.is_empty(), "{}", page.get_name()); + } +} + +/// The example writes the five completion files under the names `packaging/linux/package.sh` and +/// `packaging/freebsd/package.sh` install, `texturecraft-cli.1` and a page per subcommand, and no +/// pages for the `help` subcommand. +#[test] +fn the_example_writes_the_files_the_packages_install() { + let dir = std::env::temp_dir().join(format!("mc-cli-{}-man-and-completions", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + example::generate(&dir).unwrap(); + + let mut written: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect(); + written.sort(); + let completions = ["texturecraft-cli.bash", "_texturecraft-cli", "texturecraft-cli.fish", "texturecraft-cli.elv", "_texturecraft-cli.ps1"]; + let subcommands = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"]; + let mut expected: Vec = completions.map(String::from).into(); + expected.push("texturecraft-cli.1".into()); + expected.extend(subcommands.iter().map(|s| format!("texturecraft-cli-{s}.1"))); + expected.sort(); + assert_eq!(written, expected); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/apps/texturecraft-cli/tests/it/protocol.rs b/apps/texturecraft-cli/tests/it/protocol.rs new file mode 100644 index 00000000..db504b54 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/protocol.rs @@ -0,0 +1,118 @@ +//! The subcommands that talk over a stream (`mcp` and `serve` on stdio, through the real binary, +//! which owns stdin and stdout) and the environment variable of the control token. + +use std::io::Write; +use std::net::TcpListener; +use std::process::{Command, Output, Stdio}; + +fn binary() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")); + command.env("TEXTURECRAFT_NO_PREFS", "1").env_remove("TEXTURECRAFT_CONTROL_TOKEN"); + command +} + +/// A port nothing listens on, with no token file. +fn free_port() -> String { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port().to_string() +} + +#[test] +fn serve_writes_nothing_but_json_lines_to_stdout() { + let mut child = binary().arg("serve").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + writeln!(stdin, r#"{{"id":1,"method":"ping","params":{{}}}}"#).unwrap(); + writeln!(stdin, "not json").unwrap(); + drop(stdin); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr)); + let lines: Vec<_> = String::from_utf8(output.stdout).unwrap().lines().map(str::to_string).collect(); + assert_eq!(lines.len(), 2, "{lines:?}"); + for line in &lines { + assert!(serde_json::from_str::(line).unwrap().get("ok").is_some(), "{line}"); + } +} + +#[test] +fn serve_ends_quietly_and_mcp_reports_it_when_stdin_is_closed() { + let output = binary().arg("serve").stdin(Stdio::null()).output().unwrap(); + assert_eq!((output.status.code(), output.stdout.is_empty(), output.stderr.is_empty()), (Some(0), true, true)); + // An MCP client must open with `initialize`; end of input before it is a failed start. + let dir = std::env::temp_dir().join(format!("tc-mcp-stdio-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let output = binary().args(["mcp", "--read-root", dir.to_str().unwrap(), "--write-root", dir.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!((output.status.code(), output.stdout.is_empty()), (Some(1), true)); + assert!(String::from_utf8_lossy(&output.stderr).starts_with("error: MCP start: "), "{}", String::from_utf8_lossy(&output.stderr)); +} + +fn bridge(token_flag: Option<&str>, env: Option<&str>) -> Output { + let port = free_port(); + let mut command = binary(); + command.args(["mcp", "--bridge", &port]); + if let Some(token) = token_flag { + command.args(["--token", token]); + } + if let Some(token) = env { + command.env("TEXTURECRAFT_CONTROL_TOKEN", token); + } + command.stdin(Stdio::null()).output().unwrap() +} + +#[test] +fn the_control_token_variable_is_a_fallback_the_flag_wins_and_an_empty_one_is_unset() { + let secret = "env-token-0123456789-secret"; + // Empty or blank counts as unset: the error says to set one, as when there is none. + for blank in ["", " "] { + let output = bridge(None, Some(blank)); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{err}"); + assert!(err.contains("no control token: set TEXTURECRAFT_CONTROL_TOKEN"), "{err}"); + } + // The variable is used when there is no flag: a good token gets as far as connecting. + let err = String::from_utf8_lossy(&bridge(None, Some(secret)).stderr).into_owned(); + assert!(!err.contains("16 to 1024") && !err.contains(secret), "{err}"); + // The flag wins over a good variable: its bad value is what is reported, without echoing either. + let err = String::from_utf8_lossy(&bridge(Some("short"), Some(secret)).stderr).into_owned(); + assert!(err.contains("control token must be 16 to 1024"), "{err}"); + assert!(!err.contains(secret) && !err.contains("short\n"), "{err}"); + // A bad value in the variable is refused too, and its value stays out of the message. + let err = String::from_utf8_lossy(&bridge(None, Some("bad token")).stderr).into_owned(); + assert!(err.contains("control token must be 16 to 1024") && !err.contains("bad token"), "{err}"); +} + +#[test] +fn help_lists_the_variable_but_never_its_value() { + let output = binary().args(["mcp", "--help"]).env("TEXTURECRAFT_CONTROL_TOKEN", "do-not-print-this-0123456789").output().unwrap(); + let help = String::from_utf8_lossy(&output.stdout); + assert!(help.contains("TEXTURECRAFT_CONTROL_TOKEN") && !help.contains("do-not-print-this"), "{help}"); +} + +#[test] +fn a_variable_alone_grants_no_file_access() { + // The token variable is for authentication only: a headless server with no roots still refuses files. + let mut child = + binary().arg("serve").env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + writeln!(stdin, r#"{{"id":1,"method":"project.save","params":{{"path":"never.tcraft"}}}}"#).unwrap(); + drop(stdin); + let output = child.wait_with_output().unwrap(); + let reply: serde_json::Value = serde_json::from_str(String::from_utf8(output.stdout).unwrap().lines().next().unwrap()).unwrap(); + assert_eq!(reply["ok"], false, "{reply}"); +} + +#[test] +fn a_token_in_the_environment_does_not_require_bridge() { + // Headless MCP must parse even when TEXTURECRAFT_CONTROL_TOKEN is set; only --token on the + // command line requires --bridge. + let output = binary().args(["mcp", "--fromat"]).env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").output().unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{err}"); + assert!(err.contains("--fromat"), "{err}"); + assert!(!err.contains("--bridge") && !err.contains("--token is for"), "{err}"); + + let output = binary().args(["mcp", "--token", "flag-token-0123456789"]).output().unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{err}"); + assert!(err.contains("--token") && err.contains("--bridge"), "{err}"); +} diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 7f5ee538..ab29d036 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -23,6 +23,8 @@ serde_json = { workspace = true } log = { workspace = true } # The message box for errors that end the app (a Windows release build has no console). rfd = { workspace = true } +# Pass the selected window backend to the title bar and UI runtime +craft-host = { workspace = true } # Reads the saved System title bar setting before the window opens (eframe's settings format). ron = "0.12" @@ -35,6 +37,12 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s # The update helper is a copy of this program (`main`). craft-update = { workspace = true } +# X11 setup probing and event loop selection for Wayland pen support +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { workspace = true, features = ["net", "system"] } +winit = { version = "0.30", default-features = false, features = ["x11"] } +x11rb-protocol = "0.13" + # 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 } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 664b791a..678c0a8c 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -15,6 +15,8 @@ mod nightly_session; mod process_identity; mod profile_root; mod window_frame; +#[cfg(target_os = "linux")] +mod xwayland_pen; use std::ffi::OsString; @@ -259,13 +261,22 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1)) } -/// A refused Nightly start explains itself in a dialog where there is a desktop to show one. +/// Whether a refusal may also open a native message box. Standard error always carries the reason; +/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert +/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in +/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26). +fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool { + build_flavor::needs_native_error(flavor, desktop_session) && !macos +} + +/// A refused Nightly start explains itself in a dialog where the desktop shows one without the +/// app's run loop (Windows, X11/Wayland); macOS gets the standard-error line only. fn report_launch_profile_error(error: &str) { eprintln!("texturecraft: {error}"); let desktop_session = cfg!(windows) || cfg!(target_os = "macos") || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); - if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) { if let Err(error) = initialize_nightly_process_identity() { eprintln!("texturecraft: {error}"); return; @@ -325,8 +336,7 @@ fn launch_arguments(arguments: Vec) -> Result, String> { } fn main() { - // Windows: the update helper is a copy of this program started with `--finish-update`. A - // Nightly install is updated by ArtCraft Launcher, so it never installs an update itself. + // Stable handles --finish-update on Windows while the launcher updates Nightly #[cfg(windows)] if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable && let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) @@ -334,15 +344,16 @@ fn main() { std::process::exit(i32::from(result.is_err())); } - // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with - // its own argument. It reads no user state and is started without the profile tokens, so it - // runs before the launch protocol would refuse it. + // Dispatch the Windows pointer keeper before launch validation because it has no profile tokens #[cfg(windows)] if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) { std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer()); } - let Some(arguments) = prepare_launch() else { return }; + let Some(arguments) = prepare_launch() else { + return; + }; + let nightly = launch_profile::current().is_nightly(); let args = match launch_arguments(arguments).and_then(parse_args_from) { Ok(Some(a)) => a, @@ -352,8 +363,8 @@ fn main() { std::process::exit(2); } }; - // The control server is a stable-install service: a Nightly window is driven by the Launcher, - // and its token file would sit in the shared temp folder rather than its private profile. + + // Keep the control token out of the shared temp folder for a private Nightly profile if nightly && args.control.is_some() { eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli"); std::process::exit(2); @@ -368,9 +379,8 @@ fn main() { previous_hook(info); })); - // Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe - // is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the - // folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`). + // Scripted runs use temporary files to protect saved settings + // An explicit eframe path keeps app.ron with ui.json and errors.log despite the app ID let no_prefs_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron"))); @@ -384,8 +394,16 @@ fn main() { prefs.apply_work_threads(); prefs.apply_resource_limits(); let session = initial_session(&args); - let frame_decision = TitleBar::decide(prefs.system_title_bar); + + // Xwayland can forward pen input as pointer events on Wayland desktops + #[cfg(target_os = "linux")] + let use_xwayland_for_pen = xwayland_pen::opens_through_xwayland(); + #[cfg(not(target_os = "linux"))] + let use_xwayland_for_pen = false; + let backend = if use_xwayland_for_pen { craft_host::target::Backend::X11 } else { craft_host::target::Backend::from_env() }; + let frame_decision = TitleBar::decide(prefs.system_title_bar, backend); let title_bar = TitleBar::of(&frame_decision.frame); + let mut viewport = egui::ViewportBuilder::default() .with_app_id(os_window::app_id()) .with_title(os_window::name()) @@ -394,15 +412,32 @@ fn main() { if let Some(i) = icon() { viewport = viewport.with_icon(i); } + let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport); let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; + #[cfg(target_os = "linux")] + if use_xwayland_for_pen { + use winit::platform::x11::EventLoopBuilderExtX11 as _; + + options.event_loop_builder = Some(Box::new(|builder| { + builder.with_x11(); + })); + let notice = texturecraft_ui_egui::i18n::trf( + "Opening the window through Xwayland for pen input. Set {variable}=1 to keep Wayland.", + &[("variable", &xwayland_pen::NATIVE_WAYLAND_VARIABLE)], + ); + eprintln!("texturecraft: {notice}"); + } + if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) { fatal(&e.to_string(), true); std::process::exit(2); } + let control = args.control; - // The Nightly session record: one owner per profile, an unclean exit reported by the next - // start, and no document name, path or diagnostic payload collected. + + // Nightly records one owner per profile so the next launch can report an unclean exit + // The record carries no document name, path or diagnostics let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health( launch_profile::current().root(), build_flavor::BUILT_VERSION, @@ -415,12 +450,13 @@ fn main() { } }; let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean); - // Set once a window has posted the interruption notice; until then the record must survive. + + // Keep the record until a window has posted the interruption notice let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let notice_shown_in_window = unclean_notice_shown.clone(); let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session)); - // The exit hook is the controlled return on macOS, where every quit ends the process inside - // AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes. + + // AppKit terminates the process without returning from run_native, so macOS needs the exit hook let finish_at_exit = { let shared = nightly_session.clone(); let shown = unclean_notice_shown.clone(); @@ -441,7 +477,8 @@ fn main() { if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) { log::warn!("the app menu could not be installed: {e}"); } - texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?; + + texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision, backend)?; let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; @@ -461,8 +498,8 @@ fn main() { Ok(Box::new(Shell { app, window_frame: frame_guard, exit_hook: Some(Box::new(finish_at_exit)) })) }), ); - // A controlled return, including a handled startup error. On macOS a window already finished in - // its exit hook, so this is then a no-op. + + // Close the session record on controlled return, including handled startup errors nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed)); if let Err(e) = result { fatal(&e.to_string(), true); @@ -667,3 +704,17 @@ mod tests { assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}"); } } + +#[cfg(test)] +mod refusal_dialog_tests { + use super::refusal_dialog; + use crate::build_flavor::BuildFlavor; + + #[test] + fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() { + assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box"); + assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box"); + } +} diff --git a/apps/texturecraft/src/xwayland_pen.rs b/apps/texturecraft/src/xwayland_pen.rs new file mode 100644 index 00000000..47e3f3f0 --- /dev/null +++ b/apps/texturecraft/src/xwayland_pen.rs @@ -0,0 +1,264 @@ +//! A pen on a Wayland desktop opens the window through Xwayland (#816). +//! +//! Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors for the adapted code. +//! Licensed under the MIT License or the Apache License, Version 2.0, at your option. +//! +//! Wayland compositors give a pen only to clients that bind the tablet protocol (`zwp_tablet_v2`), +//! which winit 0.30 doesn't (and binding it on winit's connection needs `unsafe`, which this app +//! forbids). Some compositors (KWin) then send the window nothing from the pen: no cursor, no +//! painting. Xwayland binds the protocol and serves the pen as an X11 pointer, so with a pen +//! attached the window opens there. `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland. +//! +//! Adapted from PhotoCraft (storytold/photocraft `830316b7`, MIT OR Apache-2.0): +//! `apps/photocraft/src/tablet.rs` (`display_session`, `pen_needs_xwayland`, `has_pen`, `bit_set`) +//! and `apps/photocraft/src/linux_libs.rs` (`session_from_env`, `ldconfig_has`, the library +//! search), reduced to the pen decision. See the repository's NOTICE for the port. + +use std::io::{Read as _, Write as _}; +use std::os::unix::net::UnixStream; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use x11rb_protocol::connect::Connect; +use x11rb_protocol::xauth::{Family, get_auth}; + +/// Set (and not `0`) to keep native Wayland with a pen attached +pub(super) const NATIVE_WAYLAND_VARIABLE: &str = "TEXTURECRAFT_NATIVE_WAYLAND"; + +/// `BTN_TOOL_PEN` (linux/input-event-codes.h): the key a tablet's stylus, a pen display's or a +/// pen-enabled touchscreen's pen reports +const BTN_TOOL_PEN: u32 = 0x140; + +/// `ABS_X` and `ABS_Y` (linux/input-event-codes.h): the absolute axes every pen reports +const ABS_X: u32 = 0x00; +const ABS_Y: u32 = 0x01; + +/// What winit 0.30 loads at run time for an X11 window: Xlib, Xlib-xcb, xcb, Xcursor, XInput2 and +/// xkbcommon with its X11 part +const X11_LIBRARIES: &[&str] = + &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; + +// Give local Xwayland time to answer while bounding the wait before falling back to Wayland +const X11_SETUP_TIMEOUT: Duration = Duration::from_secs(1); + +/// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland +/// has the required libraries and accepts an X11 client setup. +pub fn opens_through_xwayland() -> bool { + let var = |name: &str| std::env::var(name).ok(); + let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)); + pen_needs_xwayland(var, pen, |display| x11_libraries_available() && x_server_accepts_setup(display)) +} + +/// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or +/// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland. +fn pen_needs_xwayland(var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool, xwayland_ready: impl FnOnce(&str) -> bool) -> bool { + let set = |name: &str| var(name).is_some_and(|value| !value.is_empty()); + let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET"); + let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0"); + wayland && !keeps_wayland && var("DISPLAY").filter(|display| !display.is_empty()).is_some_and(|display| pen() && xwayland_ready(&display)) +} + +/// winit commits to its forced backend, so require an accepted X11 setup before forcing X11. +fn x_server_accepts_setup(display: &str) -> bool { + let Some((display_number, screen)) = local_display(display) else { + return false; + }; + + let Some(socket) = connect_local_x_server(display_number) else { + return false; + }; + + let hostname = rustix::system::uname(); + let auth_hostname = std::env::var_os("XAUTHLOCALHOSTNAME"); + let auth_address = auth_hostname.as_ref().map_or(hostname.nodename().to_bytes(), |name| name.as_encoded_bytes()); + let (auth_name, auth_data) = get_auth(Family::LOCAL, auth_address, display_number).ok().flatten().unwrap_or_default(); + let (setup, request) = Connect::with_authorization(auth_name, auth_data); + exchange_x11_setup(socket, setup, &request, screen) +} + +/// Parse the display and screen of a local X server such as `:0`, `:0.0` or `unix:0`. +fn local_display(display: &str) -> Option<(u16, usize)> { + let local = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?; + let (display_number, screen) = local.split_once('.').unwrap_or((local, "0")); + Some((display_number.parse().ok()?, screen.parse().ok()?)) +} + +fn connect_local_x_server(display_number: u16) -> Option { + use rustix::net::{AddressFamily, SocketAddrUnix, SocketFlags, SocketType, connect, socket_with}; + + let path = format!("/tmp/.X11-unix/X{display_number}"); + + // Try the abstract socket first, as Xlib does on Linux + [SocketAddrUnix::new_abstract_name(path.as_bytes()), SocketAddrUnix::new(&path)].into_iter().find_map(|address| { + let address = address.ok()?; + + // A full Unix socket backlog must not block app startup + let socket = UnixStream::from(socket_with(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::NONBLOCK | SocketFlags::CLOEXEC, None).ok()?); + connect(&socket, &address).ok()?; + socket.set_nonblocking(false).ok()?; + Some(socket) + }) +} + +fn exchange_x11_setup(mut socket: UnixStream, mut setup: Connect, request: &[u8], screen: usize) -> bool { + let start = Instant::now(); + if socket.set_write_timeout(Some(X11_SETUP_TIMEOUT)).is_err() || socket.write_all(request).is_err() { + return false; + } + + while !setup.buffer().is_empty() { + let remaining = X11_SETUP_TIMEOUT.saturating_sub(start.elapsed()); + if remaining.is_zero() || socket.set_read_timeout(Some(remaining)).is_err() { + return false; + } + + let Ok(received) = socket.read(setup.buffer()) else { + return false; + }; + + if received == 0 { + return false; + } + + if setup.advance(received) { + break; + } + } + + setup.into_setup().is_ok_and(|reply| screen < reply.roots.len()) +} + +/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has +/// `BTN_TOOL_PEN` and its `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as libinput asks of a tablet +/// tool. The key alone isn't enough: a virtual keyboard made with uinput claims every key code. +fn has_pen(devices: &str) -> bool { + devices.split("\n\n").any(|device| { + let bitmap = |name: &str| device.lines().find_map(|line| line.strip_prefix(name)); + bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)) + }) +} + +/// Bit `bit` of a `/proc/bus/input/devices` bitmap: hex words of the kernel's `long`, most +/// significant first. Short or malformed bitmaps have no bits set. +fn bit_set(bitmap: &str, bit: u32) -> bool { + let word_bits = usize::BITS; + let word = usize::try_from(bit / word_bits).unwrap_or(usize::MAX); + bitmap.split_whitespace().rev().nth(word).and_then(|hex| u64::from_str_radix(hex, 16).ok()).is_some_and(|value| (value >> (bit % word_bits)) & 1 == 1) +} + +/// Are the libraries an X11 window needs installed? The linker cache (`ldconfig -p`) or the usual +/// library directories must list each; one that can't be found counts as missing. +fn x11_libraries_available() -> bool { + let cache = linker_cache(); + let dirs = library_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref()); + X11_LIBRARIES.iter().all(|soname| cache.as_deref().is_some_and(|cache| ldconfig_has(cache, soname)) || dirs.iter().any(|dir| dir.join(soname).exists())) +} + +/// `ldconfig -p` in English (it is parsed), from where distributions put it +fn linker_cache() -> Option { + ["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"].into_iter().find_map(|command| { + let output = std::process::Command::new(command).arg("-p").env("LC_ALL", "C").output().ok()?; + output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned()) + }) +} + +/// Does an `ldconfig -p` listing have `soname` for this build's architecture? Lines look like +/// `\tlibXi.so.6 (libc6,x86-64) => /lib/x86_64-linux-gnu/libXi.so.6`. +fn ldconfig_has(cache: &str, soname: &str) -> bool { + let architecture = if cfg!(target_arch = "x86_64") { + Some("x86-64") + } else if cfg!(target_arch = "aarch64") { + Some("AArch64") + } else { + None + }; + + cache.lines().any(|line| { + let Some((name, rest)) = line.trim_start().split_once(' ') else { + return false; + }; + + let flags = rest.split_once('(').and_then(|(_, after)| after.split_once(')')).map_or("", |(flags, _)| flags); + name == soname && architecture.is_none_or(|tag| flags.split(',').any(|flag| flag.trim() == tag)) + }) +} + +/// `LD_LIBRARY_PATH`, then the usual system and Flatpak library directories +fn library_dirs(ld_library_path: Option<&str>) -> Vec { + let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else { "x86_64-linux-gnu" }; + let mut dirs: Vec = ld_library_path.into_iter().flat_map(|value| value.split(':')).filter(|dir| !dir.is_empty()).map(PathBuf::from).collect(); + dirs.extend(["/app/lib", "/usr/local/lib", "/usr/lib64", "/lib64", "/usr/lib", "/lib"].map(PathBuf::from)); + dirs.extend([Path::new("/usr/lib").join(triplet), Path::new("/lib").join(triplet)]); + dirs +} + +#[cfg(test)] +mod tests { + use super::*; + + // Capabilities from /proc/bus/input/devices for a touchpad and a Wacom pen + const TOUCHPAD: &str = "N: Name=\"SYNA2B33:00 06CB:CE26 Touchpad\"\nB: KEY=e520 10000 0 0 0 0\nB: ABS=2e0800000000003\n"; + const PEN: &str = "N: Name=\"Wacom Intuos Pro M Pen\"\nB: KEY=1c03 0 0 0 0 0\nB: ABS=1000f000003\n"; + + // The uinput keyboard claims the pen key but reports no axes + const VIRTUAL_KEYBOARD: &str = "N: Name=\"RustDesk UInput Keyboard\"\nB: EV=20013\nB: KEY=ffffffffff 0 7ffffff000301ff 1000f7fffffff 7fe001fffff000f 7ffffffffffffff ffffffff0003fdff 7fff8fff00ff03ff 1ffffffffffff07 ffffffffffffffff ffffffffffefffff fffffffffffffffe\n"; + + #[test] + fn a_pen_is_a_device_with_the_pen_key_and_absolute_axes() { + assert!(has_pen(&format!("{TOUCHPAD}\n{PEN}"))); + assert!(!has_pen(TOUCHPAD), "a touchpad is no pen"); + assert!(!has_pen(&format!("{VIRTUAL_KEYBOARD}\n{TOUCHPAD}")), "a keyboard claiming the pen key has no pen axes"); + assert!(!has_pen("B: KEY=zz 0 0 0 0 0\nB: ABS=3\n"), "a malformed bitmap is no pen"); + } + + #[test] + fn a_pen_on_wayland_opens_the_window_through_xwayland() { + fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string()) + } + const WAYLAND: &[(&str, &str)] = &[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]; + + assert!(pen_needs_xwayland(env(WAYLAND), || true, |display| display == ":0")); + assert!(!pen_needs_xwayland(env(WAYLAND), || false, |_| true), "no pen"); + assert!(!pen_needs_xwayland(env(WAYLAND), || true, |_| false), "Xwayland can't run the window"); + assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, |_| true), "no Xwayland"); + assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, |_| true), "kept"); + assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, |_| true)); + assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), |_| panic!("probed off Wayland")), "X11 already has the pen"); + assert_eq!([":1.2", "unix:0", "remote:0", ":0.bad"].map(local_display), [Some((1, 2)), Some((0, 0)), None, None]); + } + + #[test] + fn a_pen_keeps_wayland_when_the_x_server_rejects_setup() -> std::io::Result<()> { + use x11rb_protocol::protocol::xproto::{Screen, Setup, SetupFailed}; + use x11rb_protocol::x11_utils::Serialize as _; + + const REPLY_HEADER_BYTES: usize = 8; + const BYTES_PER_X11_WORD: usize = 4; + let reason = b"Setup denied".to_vec(); + let rejected = SetupFailed { protocol_major_version: 11, length: (reason.len() / BYTES_PER_X11_WORD) as u16, reason, ..Default::default() }; + let mut accepted = Setup { status: 1, protocol_major_version: 11, roots: vec![Screen::default()], ..Default::default() }; + accepted.length = ((accepted.serialize().len() - REPLY_HEADER_BYTES) / BYTES_PER_X11_WORD) as u16; + + for (reply, screen, selects_xwayland) in [(rejected.serialize(), 0, false), (accepted.serialize(), 1, false), (accepted.serialize(), 0, true)] { + let (client, mut server) = UnixStream::pair()?; + server.write_all(&reply)?; + let (setup, request) = Connect::with_authorization(Vec::new(), Vec::new()); + let var = |name: &str| match name { + "WAYLAND_DISPLAY" => Some("wayland-0".into()), + "DISPLAY" => Some(format!(":0.{screen}")), + _ => None, + }; + + let xwayland = pen_needs_xwayland( + var, + || true, + |display| local_display(display).is_some_and(|(_, screen)| exchange_x11_setup(client, setup, &request, screen)), + ); + + assert_eq!(xwayland, selects_xwayland); + } + + Ok(()) + } +} diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index a0c3c0ad..eb28b995 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -28,4 +28,5 @@ getrandom = { workspace = true } rustix = { workspace = true } [dev-dependencies] +tempfile = "3" rmcp = { workspace = true, features = ["client"] } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 6f86119e..7eaed255 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -225,9 +225,9 @@ impl Headless { /// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the /// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it. - pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result { + pub fn export_mesh(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { self.require_project()?; - let out = self.session.mesh_export(path, format)?; + let out = self.session.mesh_export_with_normals(path, format, recompute_normals)?; let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or("."); self.create_dir_all(dir)?; let mut textures = Vec::new(); @@ -289,25 +289,50 @@ impl Headless { } /// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…). - pub fn export(&mut self, p: &Value) -> Result { + pub fn export(&mut self, params: &Value) -> Result { + use texturecraft_engine::shader_parameters::{shader_parameters_param, shader_parameters_sidecar}; + self.require_project()?; - let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?; - let opts = file_cmds::export_options(&self.session, p, "textures.export")?; - let n = self.session.set_count(); - let sets: Vec = match p.get("ts") { - None | Some(Value::Null) => (0..n).collect(), - Some(Value::String(a)) if a == "all" => (0..n).collect(), - Some(v) => vec![v.as_u64().and_then(|t| usize::try_from(t).ok()).filter(|t| *t < n).ok_or_else(|| bad(format!("invalid `ts` {v}")))?], + let dir = params.get("dir").and_then(Value::as_str).filter(|dir| !dir.is_empty()).ok_or_else(|| bad("`dir` is required"))?; + let options = file_cmds::export_options(&self.session, params, "textures.export")?; + let set_count = self.session.set_count(); + let sets: Vec = match params.get("ts") { + None | Some(Value::Null) => (0..set_count).collect(), + Some(Value::String(selection)) if selection == "all" => (0..set_count).collect(), + Some(value) => vec![ + value + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < set_count) + .ok_or_else(|| bad(format!("invalid `ts` {value}")))?, + ], }; - let files = self.session.export_files(&sets, &opts)?; + let shader_sets = shader_parameters_param(&self.session.doc.project, params, &sets, "textures.export")?; + + let files = self.session.export_files(&sets, &options)?; + let sidecar = shader_sets.map(|sets| shader_parameters_sidecar(&self.session.doc.project, &sets, &files)); self.create_dir_all(dir)?; let mut written = Vec::new(); - for f in &files { - let path = join(dir, &f.name); - self.write(&path, &f.bytes)?; + let mut warnings = Vec::new(); + for file in files { + let path = join(dir, &file.name); + self.write(&path, &file.bytes)?; written.push(path); + warnings.extend(file.warnings); } - let warnings: Vec<&String> = files.iter().flat_map(|f| &f.warnings).collect(); + + if let Some(sidecar) = sidecar { + let result = sidecar.and_then(|file| { + let path = join(dir, &file.name); + self.write(&path, &file.bytes).map_err(|error| error.to_string())?; + Ok(path) + }); + match result { + Ok(path) => written.push(path), + Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), + } + } + Ok(json!({ "files": written, "warnings": warnings })) } diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index d159bc80..5fbff34d 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -4,8 +4,9 @@ //! //! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`, //! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`, -//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?, -//! preserveStrokes?}`, `mesh.export {path, format?}`, `bake.mesh.add {path, cage?}`, +//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, +//! `mesh.reimport {path?, preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`, +//! `bake.mesh.add {path, cage?}`, //! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}` //! (workspace-scoped versions of the engine commands), //! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the @@ -88,13 +89,14 @@ impl Headless { if steps.len() > MAX_BATCH_STEPS { return Err(bad(format!("at most {MAX_BATCH_STEPS} steps per batch"))); } + Ok(self.batch(steps)) } "project.open" => self.open(required(p, "path")?), "project.save" => self.save(str_of(p, "path")), "mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")), "mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?), - "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")), + "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format"), bool_of(p, "recomputeNormals")?), "bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?), "resource.import" => self.import_resource(required(p, "path")?), "material.save" => self.material_save(p), diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 63c12b0e..6d4bca71 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -45,9 +45,16 @@ pub fn generate_token() -> Result { Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) } +/// `TEXTURECRAFT_CONTROL_TOKEN`; an empty (or blank) variable counts as unset, as for every other +/// variable of the command line (RFC-0018 rule 1.7). +fn env_token() -> Option { + std::env::var(TOKEN_ENV).ok().filter(|t| !t.trim().is_empty()) +} + /// Token for a client of `port`: explicit, else `TEXTURECRAFT_CONTROL_TOKEN`, else the token file. +/// A blank value counts as not given. pub fn client_token(port: u16, supplied: Option) -> Result { - let token = match supplied.or_else(|| std::env::var(TOKEN_ENV).ok()) { + let token = match supplied.filter(|t| !t.trim().is_empty()).or_else(env_token) { Some(t) => t, None => { let path = token_file(port); @@ -64,7 +71,7 @@ pub fn client_token(port: u16, supplied: Option) -> Result Result<(String, Option), AutomationError> { - if let Ok(t) = std::env::var(TOKEN_ENV) { + if let Some(t) = env_token() { validate_token(t.trim())?; return Ok((t.trim().to_string(), None)); } @@ -228,6 +235,25 @@ mod tests { assert!(client_token(1, Some(format!(" {a}\n"))).is_ok()); } + #[test] + fn a_blank_token_counts_as_not_given() { + // No token anywhere (the port has no token file): the error says what to set, not that a + // blank token is invalid. A non-blank inherited TOKEN_ENV can still satisfy the client + // after a blank supplied value, so do not unwrap_err() first. + match client_token(1, Some(" ".into())) { + Err(error) => { + if std::env::var_os(TOKEN_ENV).is_none() { + let message = error.to_string(); + assert!(message.contains("no control token"), "{message}"); + } + } + Ok(_) => { + let inherited = std::env::var(TOKEN_ENV).unwrap_or_default(); + assert!(!inherited.trim().is_empty(), "a blank token was accepted with no inherited value"); + } + } + } + fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("tc-token-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0ce54f55..f2ebfee6 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -141,6 +141,9 @@ pub struct MeshExportParams { /// written next to it) or usdz (textures packaged); default: from the extension, else obj. #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, + /// Replace stored normals with smooth area-weighted normals on the exported copy (default false). + #[serde(default, rename = "recomputeNormals", skip_serializing_if = "Option::is_none")] + pub recompute_normals: Option, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] @@ -174,6 +177,9 @@ pub struct ExportParams { /// Settings for individual maps in the selected template. #[serde(default, skip_serializing_if = "Option::is_none")] pub maps: Option>, + /// Write shader settings for the exported sets (true) or the specified texture set indexes. + #[serde(default, rename = "shaderParameters", skip_serializing_if = "Option::is_none")] + pub shader_parameters: Option, } #[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] diff --git a/crates/automation/src/server/export_map_params.rs b/crates/automation/src/server/export_map_params.rs index b19aa8dd..7acffc96 100644 --- a/crates/automation/src/server/export_map_params.rs +++ b/crates/automation/src/server/export_map_params.rs @@ -19,4 +19,7 @@ pub struct ExportMapParams { /// Override dithering for this map's 8-bit outputs. #[serde(default, skip_serializing_if = "Option::is_none")] pub dithering: Option, + /// Side length in pixels for this map, overriding the export size. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, } diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index a1f18ab9..64897380 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -132,6 +132,13 @@ 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> { + // The Resources Updater reads the files a project names, which may lie outside the read root + if matches!(id, "resource.status" | "resource.update" | "resource.relink") { + return Err(bad(format!( + "`{id}` reads the image files the project names on this machine, so it is disabled for automation; re-import changed files with resource_import" + ))); + } + 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 @@ -245,6 +252,10 @@ mod tests { assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err()); assert!(authorize_command("file.reimportMesh", &json!({})).is_ok()); assert!(authorize_command("file.close", &json!({})).is_ok()); + for id in ["resource.status", "resource.update", "resource.relink"] { + let error = authorize_command(id, &json!({})).unwrap_err().to_string(); + assert!(error.contains("reads the image files"), "{id}: {error}"); + } assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rs index 93e59d23..4058e1c1 100644 --- a/crates/automation/tests/agent_tasks.rs +++ b/crates/automation/tests/agent_tasks.rs @@ -88,14 +88,15 @@ async fn inspect(c: &Conn) -> Value { #[tokio::test(flavor = "multi_thread")] async fn textures_export_accepts_per_map_settings() { - let dir = tmp("map-options"); - let (client, server) = connect(workspace(&dir)).await; + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let (client, server) = connect(workspace(dir)).await; let result = tool( &client, "textures_export", json!({"dir": "textures", "preset": "glTF PBR Metal Roughness", "maps": [ - {"map": 0, "format": "pgm", "bitDepth": 16}, + {"map": 0, "format": "pgm", "bitDepth": 16, "size": 256}, {"map": 1, "enabled": false} ]}), ) @@ -104,9 +105,42 @@ async fn textures_export_accepts_per_map_settings() { let files = result["files"].as_array().unwrap(); assert_eq!(files.len(), 2, "{result}"); let graymap = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".pgm")).unwrap(); - assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n128 128\n65535\n")); + assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n256 256\n65535\n")); + let inherited = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".png")).unwrap(); + assert_eq!(image::image_dimensions(dir.join(inherited)).unwrap(), (128, 128)); + + shutdown(client, server).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn textures_export_reports_the_shader_sidecar_and_write_failures() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let (client, server) = connect(workspace(dir)).await; + let params = json!({"dir": "textures", "shaderParameters": [0]}); + + let result = tool(&client, "textures_export", params.clone()).await; + + let files = result["files"].as_array().unwrap(); + let sidecar = files.iter().filter_map(Value::as_str).find(|name| name.ends_with("_shaders.json")).expect("shader settings file"); + let path = dir.join(sidecar); + let settings: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(settings["shaders"][0]["textureSets"].as_array().unwrap().len(), 1); + assert!(settings["shaders"][0]["model"].is_string()); + + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + let result = tool(&client, "textures_export", params).await; + + assert!(result["warnings"].as_array().unwrap().iter().any(|warning| warning.as_str().is_some_and(|text| text.contains("shader settings file")))); + assert!(result["files"].as_array().unwrap().iter().any(|file| file.as_str().is_some_and(|name| name.ends_with(".png")))); + + let error = tool_err(&client, "textures_export", json!({"dir": "invalid", "shaderParameters": [99]})).await; + + assert!(error.contains("shaderParameters")); + assert!(!dir.join("invalid").exists()); + shutdown(client, server).await; - std::fs::remove_dir_all(dir).unwrap(); } fn top(s: &Value) -> &Value { diff --git a/crates/bake/src/bake_passes.rs b/crates/bake/src/bake_passes.rs index eb7d5846..503bd45d 100644 --- a/crates/bake/src/bake_passes.rs +++ b/crates/bake/src/bake_passes.rs @@ -1,7 +1,7 @@ use crate::cage::RayFrame; use crate::map::BakeContext; use crate::tracing::{CpuTracer, Tracer}; -use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake}; use std::sync::atomic::Ordering::Relaxed; use texturecraft_core::{BakeSettings, BakedMap}; @@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> { progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>, + ) -> Result { + self.bake_map_in(map, progress, excluded_tiles, None, tracer) + } + + /// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does + pub fn bake_map_in( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, ) -> Result { let mut settings = self.request.settings.clone(); settings.maps.select([map]); - self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS) } pub(super) fn run( @@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> { settings: &BakeSettings, progress: &Progress, excluded_tiles: &[(u32, u32)], + region: Option, tracer: Option<&dyn Tracer>, strip_texels: usize, ) -> Result { @@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> { } }; let context = BakeContext::with_frame(&request, *extent, frame); - let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region); match tracer { Some(tracer) => match bake(tracer) { Err(BakeError::Tracer(error)) => { diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 5c8c3ba8..d67c684c 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -12,6 +12,8 @@ mod high_poly; mod mesh_extent; mod name_pair; mod progress; +mod region_bake; +mod texel_box; pub use bake_error::BakeError; pub use bake_output::BakeOutput; @@ -22,6 +24,8 @@ pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; pub use name_pair::NamePair; pub use progress::Progress; +pub use region_bake::{RegionBake, region_keeps_pixels}; +pub use texel_box::TexelBox; mod map; mod skew; @@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24; const BATCH: usize = 1 << 18; // Curvature batches stay small so progress and cancellation remain responsive const CURVATURE_BATCH: usize = 1 << 15; +/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero +const MIN_MESH_EXTENT: f32 = 1e-6; fn validate(request: &BakeRequest) -> Result<(), BakeError> { let settings = request.settings; @@ -161,7 +167,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn 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 { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) + bake_tiles_in(request, progress, excluded_tiles, None, tracer) +} + +/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps +pub fn bake_tiles_in( + request: &BakeRequest, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, +) -> Result { + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; @@ -173,8 +190,9 @@ fn bake_in_strips( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels) } fn bake_prepared( @@ -184,6 +202,7 @@ fn bake_prepared( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); @@ -211,7 +230,7 @@ fn bake_prepared( 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 strip_error = || BakeError::Invalid("strip output out 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); @@ -250,6 +269,16 @@ fn bake_prepared( } }); + // Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled + if let Some(region) = region { + for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() { + let y = (sample_start_y + row_index) / samples_per_axis; + for outside in region.texels.outside_row(y, samples_per_axis, row.len()) { + row.get_mut(outside).unwrap_or_default().fill(NO_TRI); + } + } + } + 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(); @@ -258,6 +287,7 @@ fn bake_prepared( row.push(chunk); } } + let mut bake_strip = || { for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() { if progress.cancel.load(Relaxed) { @@ -276,10 +306,11 @@ fn bake_prepared( (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_rows).min(10_000) as u32, Relaxed); + progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed); } Ok(()) }; + if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) { bake_strip()?; } else { @@ -291,6 +322,22 @@ fn bake_prepared( } } + if let Some(region) = region { + for (map, pixels) in maps.iter().zip(buffers.iter_mut()) { + let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len()); + let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?; + let components = map.components(); + let row_len = (width * components).max(1); + for (y, (row, kept)) in pixels.chunks_exact_mut(row_len).zip(previous.chunks_exact(row_len)).enumerate() { + for outside in region.texels.outside_row(y, components, row_len) { + if let (Some(row), Some(kept)) = (row.get_mut(outside.clone()), kept.get(outside)) { + row.copy_from_slice(kept); + } + } + } + } + } + let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { let world_normal = @@ -306,7 +353,8 @@ fn bake_prepared( } 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)); + map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT)); + if let Some(padding_map) = padding_map { for (map, data) in output.iter_mut() { padding_map.apply(data, map.components()); @@ -315,11 +363,12 @@ fn bake_prepared( } } } + if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } - progress.done.store(10_000, Relaxed); + progress.done.store(Progress::DONE, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } diff --git a/crates/bake/src/progress.rs b/crates/bake/src/progress.rs index 5bb924ec..4f0a740c 100644 --- a/crates/bake/src/progress.rs +++ b/crates/bake/src/progress.rs @@ -8,12 +8,15 @@ pub struct Progress { } impl Progress { + /// The basis points of a finished bake + pub const DONE: u32 = 10_000; + pub fn new() -> Self { Self::default() } pub fn fraction(&self) -> f32 { - self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 + self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32 } pub fn cancel(&self) { diff --git a/crates/bake/src/region_bake.rs b/crates/bake/src/region_bake.rs new file mode 100644 index 00000000..224202f3 --- /dev/null +++ b/crates/bake/src/region_bake.rs @@ -0,0 +1,17 @@ +use std::collections::BTreeMap; +use std::sync::Arc; +use texturecraft_core::BakedMap; + +use crate::TexelBox; + +/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size +#[derive(Clone, Copy, Debug)] +pub struct RegionBake<'a> { + pub texels: TexelBox, + pub previous: &'a BTreeMap>>, +} + +/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours +pub fn region_keeps_pixels(map: BakedMap) -> bool { + !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) +} diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs index 18f13968..40b8216f 100644 --- a/crates/bake/src/test/tile_selection.rs +++ b/crates/bake/src/test/tile_selection.rs @@ -28,11 +28,13 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() { 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 strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).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")); diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 7d94031e..f34d834e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -365,9 +365,9 @@ fn two_runs_are_identical_and_sized() { #[test] fn strips_match_a_single_pass() { - let m = primitives::material_ball(); - let bvh = Bvh::new(&m); - let s = with_rays( + let mesh = primitives::material_ball(); + let bvh = Bvh::new(&mesh); + let bake_settings = with_rays( { let mut base = settings(64, &[]); base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, ..base.common }; @@ -377,24 +377,26 @@ fn strips_match_a_single_pass() { 4, 0.25, ); - let req = BakeRequest { + let request = BakeRequest { low_base_color: &[], - mesh: &m, + mesh: &mesh, bvh: &bvh, material: 0, - settings: &s, + settings: &bake_settings, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1), }; - let whole = bake(&req, &Progress::new()).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(); - assert!(off * 200 < a.len(), "{map:?}: {off} of {} differ", a.len()); + + let whole = bake(&request, &Progress::new()).unwrap(); + let strips = bake_in_strips(&request, &Progress::new(), 128 * 2, &CpuTracer, &[], None).unwrap(); + + for (map, whole_pixels) in &whole.maps { + let strip_pixels = &strips.maps[map]; + let differences = whole_pixels.iter().zip(strip_pixels).filter(|(whole, strip)| (*whole - *strip).abs() > 1e-3).count(); + assert!(differences * 200 < whole_pixels.len(), "{map:?}: {differences} of {} differ", whole_pixels.len()); } } diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs new file mode 100644 index 00000000..306dd04b --- /dev/null +++ b/crates/bake/src/texel_box.rs @@ -0,0 +1,57 @@ +use std::ops::Range; + +/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TexelBox { + pub min: (u32, u32), + pub max: (u32, u32), +} + +impl TexelBox { + /// Whether texel (`x`, `y`) lies inside the box + pub fn contains(&self, x: usize, y: usize) -> bool { + (self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y) + } + + /// The items of texel row `y` outside the box, in a row of `len` items with `scale` items per texel: those before the box and those after it + pub fn outside_row(&self, y: usize, scale: usize, len: usize) -> [Range; 2] { + let (start, end) = match (self.min.1 as usize..self.max.1 as usize).contains(&y) { + true => ((self.min.0 as usize * scale).min(len), (self.max.0 as usize * scale).min(len)), + false => (len, len), + }; + [0..start, end.max(start)..len] + } + + /// The box grown by `texels` on every side, kept inside a `width` x `height` image + pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox { + TexelBox { + min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)), + max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_items_outside_a_row_are_the_ones_contains_leaves_out() { + let (width, scale) = (6, 2); + let boxes = [ + TexelBox { min: (1, 1), max: (4, 3) }, + TexelBox { min: (0, 0), max: (6, 4) }, + TexelBox { min: (3, 1), max: (9, 2) }, + TexelBox { min: (4, 1), max: (2, 3) }, + ]; + for texels in boxes { + for y in 0..4 { + let outside = texels.outside_row(y, scale, width * scale); + for item in 0..width * scale { + let is_outside = outside.iter().any(|range| range.contains(&item)); + assert_eq!(is_outside, !texels.contains(item / scale, y), "{texels:?} row {y} item {item}"); + } + } + } + } +} diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index a40f5ab0..8289ef42 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation; mod ambient_occlusion_settings; mod backface_mode; mod bake_antialiasing; +mod bake_change; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_source; mod bake_sync; mod bake_sync_group; mod mesh_match_mode; @@ -45,8 +47,10 @@ 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_change::BakeChange; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_source::{BakeSource, fingerprint, fingerprint_words}; pub use bake_sync::BakeSync; pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; diff --git a/crates/core/src/bake/bake_change.rs b/crates/core/src/bake/bake_change.rs new file mode 100644 index 00000000..bb73b1f2 --- /dev/null +++ b/crates/core/src/bake/bake_change.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// What changed since a mesh map was baked, which makes it out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BakeChange { + LowPoly, + HighPoly, + Cage, + Settings, + MapSettings, +} + +impl BakeChange { + /// Identifier in automation replies + pub fn id(self) -> &'static str { + match self { + BakeChange::LowPoly => "lowPoly", + BakeChange::HighPoly => "highPoly", + BakeChange::Cage => "cage", + BakeChange::Settings => "settings", + BakeChange::MapSettings => "mapSettings", + } + } +} diff --git a/crates/core/src/bake/bake_source.rs b/crates/core/src/bake/bake_source.rs new file mode 100644 index 00000000..21fe07e9 --- /dev/null +++ b/crates/core/src/bake/bake_source.rs @@ -0,0 +1,79 @@ +use super::BakeChange; +use serde::{Deserialize, Serialize}; + +/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeSource { + /// The low poly's geometry + pub low_poly: u64, + /// The embedded mesh file when this map reads its material colors. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub low_material_file: Option, + /// The high poly files, in list order (0: none, the set bakes from the low poly) + pub high_poly: u64, + /// The cage file (0: none) + pub cage: u64, + /// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles + pub settings: u64, + /// The map's own settings + pub map_settings: u64, +} + +impl BakeSource { + /// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date) + pub fn changes(&self, current: &BakeSource) -> Vec { + // Switching color source is already reported under high poly or map settings + let material_changed = match (self.low_material_file, current.low_material_file) { + (Some(previous), Some(now)) => previous != now, + (None, None) => false, + _ => self.high_poly == current.high_poly && self.map_settings == current.map_settings, + }; + + [ + (self.low_poly != current.low_poly || material_changed, BakeChange::LowPoly), + (self.high_poly != current.high_poly, BakeChange::HighPoly), + (self.cage != current.cage, BakeChange::Cage), + (self.settings != current.settings, BakeChange::Settings), + (self.map_settings != current.map_settings, BakeChange::MapSettings), + ] + .into_iter() + .filter_map(|(changed, change)| changed.then_some(change)) + .collect() + } +} + +/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`) +pub fn fingerprint(bytes: &[u8]) -> u64 { + let words = bytes.chunks(8).map(|chunk| { + let mut word_bytes = [0; 8]; + word_bytes[..chunk.len()].copy_from_slice(chunk); + u64::from_le_bytes(word_bytes) + }); + fingerprint_words(words.chain([bytes.len() as u64])) +} + +/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step +pub fn fingerprint_words(words: impl IntoIterator) -> u64 { + // FNV-1a 64-bit offset basis and prime + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + + words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_fingerprint_changes_with_any_byte_and_with_the_length() { + let bytes: Vec = (0..=20).collect(); + let mut changed = bytes.clone(); + changed[17] ^= 1; + + assert_ne!(fingerprint(&bytes), fingerprint(&changed)); + assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20])); + assert_ne!(fingerprint(&[]), fingerprint(&[0])); + } +} diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index 281d5c98..b9b43271 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -37,6 +37,11 @@ impl Default for MeshMapSettings { } impl MeshMapSettings { + /// Whether this map reads the source mesh's material colors, independently of its enabled flag. + pub fn reads_material_colors(&self, map: BakedMap) -> bool { + map == BakedMap::Opacity || (map == BakedMap::Id && self.id.parameters.source == super::IdColorSource::MaterialColor) + } + pub fn is_enabled(&self, map: BakedMap) -> bool { match map { BakedMap::Normal => self.normal.is_enabled, @@ -84,6 +89,22 @@ impl MeshMapSettings { } } + /// `map`'s typed parameters as JSON + pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value { + let parameters = match map { + // These maps have no parameters of their own + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null, + BakedMap::Id => serde_json::to_value(self.id.parameters), + BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters), + BakedMap::Curvature => serde_json::to_value(self.curvature.parameters), + BakedMap::Position => serde_json::to_value(self.position.parameters), + BakedMap::Thickness => serde_json::to_value(self.thickness.parameters), + BakedMap::Height => serde_json::to_value(self.height.parameters), + BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters), + }; + parameters.unwrap_or_default() + } + pub fn enabled(&self) -> impl Iterator { BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 158a1b6a..f0265ed2 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -739,6 +739,15 @@ impl Source { } } + /// [`Source::images`], to rename them + pub fn images_mut(&mut self) -> Vec<&mut String> { + match self { + Source::Image { name, .. } => vec![name], + Source::Procedural { pattern, .. } => pattern.tile.iter_mut().flat_map(|tile| tile.images_mut()).collect(), + Source::Uniform(_) | Source::Anchor { .. } => Vec::new(), + } + } + /// The gradient map stops of a procedural or anchor source (empty: none). pub fn ramp(&self) -> &[[f32; 3]] { match self { @@ -844,6 +853,12 @@ pub struct LinkPreset { } impl Fill { + /// The image resource names the fill holds, to rename them: its sources' and, when linked, its package and cooked outputs + pub fn images_mut(&mut self) -> impl Iterator { + let link = self.link.iter_mut().map(|link| &mut **link).flat_map(|link| std::iter::once(&mut link.package).chain(link.outputs.values_mut())); + self.sources.values_mut().flat_map(Source::images_mut).chain(link) + } + /// Value used for `c` when the fill has no source for it: the channel default. pub fn source(&self, c: Channel) -> Source { self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c)) @@ -1268,6 +1283,14 @@ impl Generator { if reads_geometry { &[] } else { self.kind.inputs() } } + /// The mesh maps the generator reads that a bake makes: its inputs in use, and the occlusion Dripping Rust reads whole, which no input replaces + pub fn baked_maps_read(&self) -> &'static [BakedMap] { + match self.kind { + GeneratorKind::DrippingRust => &[BakedMap::AmbientOcclusion], + _ => self.inputs_in_use(), + } + } + /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity pub fn texture_in_use(&self) -> Option<&TextureLayer> { self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) @@ -1279,6 +1302,17 @@ impl Generator { self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } + /// [`Generator::sources`], to rename the images they read + pub fn sources_mut(&mut self) -> impl Iterator { + let grayscale = match self.controls.as_deref_mut() { + Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => grayscale.source.as_mut(), + _ => None, + }; + let micro = self.micro.iter_mut().flat_map(|micro| micro.sources_mut()).chain(grayscale); + let texture = self.texture.as_mut().and_then(|texture| texture.source.as_mut()); + self.inputs.values_mut().chain(texture).chain(self.grunge.as_mut()).chain(micro) + } + /// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted) pub fn micro_in_use(&self) -> Option<&MicroDetails> { self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model())) @@ -2340,6 +2374,17 @@ impl EffectKind { sources.into_iter().flat_map(Source::images).chain(id_map) } + /// [`EffectKind::images_read`], to rename them + pub fn images_mut(&mut self) -> Vec<&mut String> { + match self { + EffectKind::Fill { source, .. } => source.images_mut(), + EffectKind::Material(fill) => fill.images_mut().collect(), + EffectKind::Generator(generator) => generator.sources_mut().flat_map(Source::images_mut).collect(), + EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(), + _ => Vec::new(), + } + } + /// Reads a channel of the layer or of the stack below it (a compare mask's layer sides) pub fn reads_stack(&self) -> bool { matches!(self, EffectKind::Compare { left, right, .. } if left.reads_stack() || right.reads_stack()) @@ -2402,6 +2447,11 @@ impl Effect { self.kind.images_read().chain(self.inputs.values().flat_map(Source::images)) } + /// [`Effect::images_read`], to rename them + pub fn images_mut(&mut self) -> impl Iterator { + self.kind.images_mut().into_iter().chain(self.inputs.values_mut().flat_map(Source::images_mut)) + } + /// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None) pub fn reads(&self, anchor: Option) -> bool { self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor)) diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 36248e27..4ccb0373 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -119,6 +119,11 @@ impl MicroDetails { self.height_source.iter().chain(self.normal_source.as_ref()) } + /// [`MicroDetails::sources`], to rename the images they read + pub fn sources_mut(&mut self) -> impl Iterator { + self.height_source.iter_mut().chain(self.normal_source.as_mut()) + } + /// Every value brought into its range, non-finite ones to the defaults of `kind` pub fn clamped(self, kind: GeneratorKind) -> MicroDetails { let Some(defaults) = MicroDetails::defaults(kind) else { return self }; diff --git a/crates/core/src/layer/tile_generator.rs b/crates/core/src/layer/tile_generator.rs index 6836fcd9..94e25752 100644 --- a/crates/core/src/layer/tile_generator.rs +++ b/crates/core/src/layer/tile_generator.rs @@ -202,6 +202,11 @@ impl TileGenerator { pub fn images(&self) -> impl Iterator { self.inputs.iter().chain(&self.background_image).map(String::as_str) } + + /// [`TileGenerator::images`], to rename them + pub fn images_mut(&mut self) -> impl Iterator { + self.inputs.iter_mut().chain(&mut self.background_image) + } } impl Default for TileGenerator { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eedf93ec..868d0283 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -39,6 +39,7 @@ pub mod image_input; pub mod layer; pub mod lighting_output; pub mod mask_outline; +pub mod mesh_map_slot; pub mod mirror; pub mod mirror_corner; pub mod mirror_mode; @@ -51,6 +52,7 @@ pub mod project; pub mod projector; pub mod ramp_curve; pub mod randomized_seed; +pub mod resource_source; mod saved_decal; mod saved_projection; pub mod selection_background; @@ -80,11 +82,12 @@ pub const FULL_TURN_DEGREES: f32 = 360.0; pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ - AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync, - BakeSyncGroup, 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, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings, + BakeSource, BakeSync, BakeSyncGroup, 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, fingerprint, + fingerprint_words, }; pub use bevel::Bevel; pub use bevel_blur::BevelBlur; @@ -121,6 +124,7 @@ pub use layer::{ }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; +pub use mesh_map_slot::MeshMapSlot; pub use mirror::Mirror; pub use mirror_corner::MirrorCorner; pub use mirror_mode::MirrorMode; @@ -135,6 +139,7 @@ pub use project::{ pub use projector::Projector; pub use ramp_curve::RampCurve; pub use randomized_seed::RandomizedSeed; +pub use resource_source::ResourceSource; pub use selection_background::SelectionBackground; pub use shape_crop::ShapeCrop; pub use slope_blending::SlopeBlending; diff --git a/crates/core/src/mesh_map_slot.rs b/crates/core/src/mesh_map_slot.rs new file mode 100644 index 00000000..7cade977 --- /dev/null +++ b/crates/core/src/mesh_map_slot.rs @@ -0,0 +1,15 @@ +//! The mesh map an imported image file was resampled into + +use serde::{Deserialize, Serialize}; + +use crate::BakedMap; + +/// A mesh map of a texture set, and the UV tile one image of it covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct MeshMapSlot { + /// Index of the texture set. + pub texture_set: usize, + pub map: BakedMap, + /// The UV tile the image covers (1001 on a set without UV tiles). + pub tile: u32, +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 4212d787..f8b8e6c0 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -69,6 +69,12 @@ pub struct TextureSet { /// Mesh maps that have been baked (pixels live with the engine / project file). #[serde(default)] pub baked: BTreeSet, + /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub bake_sources: BTreeMap, + /// The one mesh map the app rebakes by itself when what it is baked from changes + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_rebake: Option, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -171,6 +177,8 @@ impl TextureSet { height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), + bake_sources: BTreeMap::new(), + auto_rebake: None, visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), @@ -187,6 +195,19 @@ impl TextureSet { self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) } + /// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions) + pub fn bake_settings_fingerprint(&self) -> u64 { + let mut common = self.bake.common; + common.is_enabled = true; + let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles); + crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes()) + } + + /// Fingerprint of `map`'s own bake settings (not whether it is checked) + pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 { + crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes()) + } + /// 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 { @@ -316,8 +337,10 @@ pub struct DisplaySettings { pub scatter_color: [f32; 3], /// Subsurface scattering mean free path as a fraction of the mesh's bounding radius. pub scatter_radius: f32, - /// Index of refraction of transmissive surfaces (where the Transmission channel is painted). + /// Index of refraction for transmission and, when enabled, dielectric reflectance. pub ior: f32, + /// Use IOR to determine dielectric reflectance at normal incidence in Metallic/Roughness. + pub ior_specular: bool, /// Depth of field of the viewport and the path tracer (thin lens). pub dof: DepthOfField, /// The selected fill's projection gizmos show in the 3D view (the Projection row's eye) @@ -381,11 +404,35 @@ pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast /// Prefix of [`DisplaySettings::environment`] naming an image resource. pub const ENV_RESOURCE_PREFIX: &str = "resource:"; +/// Original dielectric F0 multiplier for the Specular Level channel. +pub const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; + +/// Project limits for the index of refraction. +pub const MIN_INDEX_OF_REFRACTION: f32 = 1.0; +pub const MAX_INDEX_OF_REFRACTION: f32 = 3.0; + impl DisplaySettings { /// The image resource used as the environment, if any. pub fn environment_resource(&self) -> Option<&str> { self.environment.strip_prefix(ENV_RESOURCE_PREFIX) } + + /// Multiplier for Specular Level in the Metallic/Roughness model. + pub fn dielectric_f0_scale(&self) -> f32 { + if !self.ior_specular || self.spec_gloss || !self.ior.is_finite() { + return LEGACY_DIELECTRIC_F0_SCALE; + } + + const AIR_INDEX_OF_REFRACTION: f32 = 1.0; + // Specular Level 0.5 corresponds to OpenPBR specular weight 1 + const SPECULAR_LEVEL_TO_WEIGHT_SCALE: f32 = 2.0; + let ior = self.ior.clamp(MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION); + let contrast = ior - AIR_INDEX_OF_REFRACTION; + let index_sum = ior + AIR_INDEX_OF_REFRACTION; + + // Square before dividing so IOR 1.5 rounds to the legacy multiplier + SPECULAR_LEVEL_TO_WEIGHT_SCALE * contrast.powi(2) / index_sum.powi(2) + } } impl Default for DisplaySettings { @@ -416,6 +463,7 @@ impl Default for DisplaySettings { scatter_color: [1.0, 0.4, 0.25], scatter_radius: 0.1, ior: 1.5, + ior_specular: false, dof: DepthOfField::default(), projection_gizmos: true, } @@ -452,6 +500,10 @@ pub struct Project { /// The project's colour swatches (linear RGB), in the order they were added; projects without any save none #[serde(default, skip_serializing_if = "Vec::is_empty")] pub swatches: Vec<[f32; 3]>, + /// The files image resources were imported from, by resource name (the Resources Updater + /// reads them again). Resources made in the app or imported without a file path have none. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub resource_sources: BTreeMap, } impl Project { @@ -470,6 +522,7 @@ impl Project { display: DisplaySettings::default(), cameras: Vec::new(), swatches: Vec::new(), + resource_sources: BTreeMap::new(), } } @@ -817,6 +870,28 @@ mod tests { p } + #[test] + fn enabling_ior_at_the_default_preserves_legacy_reflectance() { + let mut display = DisplaySettings::default(); + let legacy = display.dielectric_f0_scale(); + + display.ior_specular = true; + + assert_eq!(display.dielectric_f0_scale(), legacy); + } + + #[test] + fn dielectric_reflectance_clamps_ior_and_falls_back_for_non_finite_values() { + let scale_at = |ior| DisplaySettings { ior, ior_specular: true, ..DisplaySettings::default() }.dielectric_f0_scale(); + + assert_eq!(scale_at(0.5), scale_at(1.0)); + assert_eq!(scale_at(1.0), 0.0); + assert!(scale_at(1.5) < scale_at(3.0)); + assert_eq!(scale_at(4.0), scale_at(3.0)); + assert_eq!(scale_at(f32::NAN), LEGACY_DIELECTRIC_F0_SCALE); + assert_eq!(scale_at(f32::INFINITY), LEGACY_DIELECTRIC_F0_SCALE); + } + #[test] fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() { let group = BakeSyncGroup::Common; diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs new file mode 100644 index 00000000..6a8627ed --- /dev/null +++ b/crates/core/src/resource_source.rs @@ -0,0 +1,21 @@ +//! Where an image resource was imported from, so the Resources Updater can read it again + +use serde::{Deserialize, Serialize}; + +/// The file an image resource was read from and its modification time then. +/// +/// The resource's stored bytes are the file's bytes at that time, so a file whose size or +/// contents differ from them has changed on disk. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResourceSource { + /// Path of the file on the machine that imported it. + pub path: String, + /// The file's modification time when it was read, in milliseconds since the Unix epoch + /// (0 when unknown). An unchanged time and size skip reading the file again. + #[serde(default)] + pub modified_ms: u64, + /// The mesh map the file was imported as (`textureSet.meshMap.import`): an update resamples it + /// again while the map still holds what this file gave it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mesh_map: Option, +} diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs new file mode 100644 index 00000000..d6c39ebc --- /dev/null +++ b/crates/engine/src/bake/auto_rebake.rs @@ -0,0 +1,73 @@ +//! Auto-rebake: the one mesh map per texture set that is baked again whenever what it is baked from changes + +use serde_json::{Value, json}; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::commands::{CommandSpec, always, bad, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "bake.autoRebake", + "Auto-rebake", + [], + None, + "{ts?: index (default: the active set), map: id | null} → {ts, autoRebake: id | null}. Turn on Auto-rebake for one mesh map of the set (it replaces the set's previous one), or turn it off with null. The app then rebakes that map in the background once what it is baked from changes", + always, + set_auto_rebake + )] +} + +fn set_auto_rebake(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.autoRebake"; + let texture_set = match params.get("ts") { + None => session.ts(), + Some(_) => u64p(params, "ts") + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < session.set_count()) + .ok_or_else(|| bad(COMMAND, "invalid `ts`"))?, + }; + let map = match params.get("map") { + Some(Value::Null) => None, + Some(_) => Some(strp(params, "map").and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, "`map` must be a mesh map id or null"))?), + None => return Err(bad(COMMAND, "`map` is required (a mesh map id or null)")), + }; + + if session.doc.project.texture_set(texture_set)?.auto_rebake != map { + session.edit("Auto-rebake", |session| { + session.doc.project.texture_set_mut(texture_set)?.auto_rebake = map; + Ok(()) + })?; + } + + Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) })) +} + +impl Session { + /// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now) + pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> { + let sets = self.doc.project.texture_sets.iter().enumerate(); + sets.filter_map(|(index, set)| { + let map = set.auto_rebake?; + let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?; + let current = self.bake_source(index, map).ok()?; + (*record != current).then_some((index, map, current)) + }) + .collect() + } + + /// Bake the selected map alone, or include every checked map if the atlas changed size + pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] }; + + let (tile_width, tile_height) = set.bake.common.output_size(); + let (columns, rows) = set.tile_grid().map_or((1, 1), |grid| (grid.cols, grid.rows)); + let (width, height) = (tile_width * columns, tile_height * rows); + let stored = self.doc.baked.get(&texture_set); + let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height)); + match resized { + true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(), + false => vec![map], + } + } +} diff --git a/crates/engine/src/bake/bake_high_state.rs b/crates/engine/src/bake/bake_high_state.rs new file mode 100644 index 00000000..8ecbd0a5 --- /dev/null +++ b/crates/engine/src/bake/bake_high_state.rs @@ -0,0 +1,27 @@ +use serde::Serialize; + +/// Where one high poly file of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeHighState { + /// Its texture set has not started baking + Waiting, + Loading, + Loaded, + /// Its texture set's bake failed while getting the high polys ready; the reason is the error + Failed(String), + /// The bake stopped before the file was loaded + Canceled, +} + +impl BakeHighState { + /// Whether the file can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Loading) + } + + /// Whether the file counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs new file mode 100644 index 00000000..e48a3ffa --- /dev/null +++ b/crates/engine/src/bake/bake_log.rs @@ -0,0 +1,188 @@ +use std::collections::HashSet; + +use texturecraft_bake::NamePair; +use texturecraft_core::{BakedMap, MeshMatchMode, Project}; + +use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh}; +use crate::Session; + +/// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BakeLog { + pub maps: Vec, + /// Each high poly file of each texture set that bakes from the high polys, in bake order + pub highs: Vec, + /// How the parts paired by name; `None` when no set of the bake matches "By Mesh Name" + pub matching: Option, +} + +impl BakeLog { + /// Start over for a bake of `sets`: every checked map of each set and the `high_polys` of each set that bakes from them, waiting, in bake order + pub fn begin(&mut self, project: &Project, high_polys: &[BakeMesh], sets: &[usize]) { + self.maps = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .flat_map(|(index, set)| { + set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting }) + }) + .collect(); + self.highs = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .filter(|(_, set)| !set.bake.high_poly.use_low_as_high) + .flat_map(|(index, set)| { + high_polys.iter().map(move |high| BakeLogHigh { + texture_set: index, + set_name: set.name.clone(), + file: high.name.clone(), + state: BakeHighState::Waiting, + }) + }) + .collect(); + self.matching = None; + } + + /// `set` starts baking: its high polys load and its first map is the one in progress + pub fn set_started(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Waiting) { + row.state = BakeHighState::Loading; + } + self.start_next(set); + } + + /// `set`'s bake has its high polys ready + pub fn high_polys_loaded(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Loading) { + row.state = BakeHighState::Loaded; + } + } + + /// `map` of `set` is baked; the set's next map starts + pub fn map_baked(&mut self, set: usize, map: BakedMap) { + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) { + row.state = BakeMapState::Baked; + } + self.start_next(set); + } + + /// `set`'s bake was kept: a map it did not hand over is not baked + pub fn set_finished(&mut self, set: usize) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) { + row.state = BakeMapState::Canceled; + } + } + + /// Nothing of `set` was kept: every one of its maps failed for `reason` + pub fn set_failed(&mut self, set: usize, reason: &str) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set) { + row.state = BakeMapState::Failed(reason.to_owned()); + } + + // A file that loaded is not what failed + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) { + row.state = BakeHighState::Failed(reason.to_owned()); + } + } + + /// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept) + pub fn cancel(&mut self, discarded: Option) { + for row in &mut self.maps { + if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) { + row.state = BakeMapState::Canceled; + } + } + self.cancel_pending_highs(); + } + + /// The whole bake was rolled back: every map that did not fail is canceled + pub fn discard(&mut self) { + for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) { + row.state = BakeMapState::Canceled; + } + self.cancel_pending_highs(); + } + + /// Whether a map is still waiting or baking + pub fn is_running(&self) -> bool { + self.maps.iter().any(|row| row.state.is_pending()) + } + + /// Whether a high poly file is still waiting or loading + pub fn is_loading_high_polys(&self) -> bool { + self.highs.iter().any(|row| row.state.is_pending()) + } + + fn cancel_pending_highs(&mut self) { + for row in self.highs.iter_mut().filter(|row| row.state.is_pending()) { + row.state = BakeHighState::Canceled; + } + } + + fn start_next(&mut self, set: usize) { + if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) { + return; + } + + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.state == BakeMapState::Waiting) { + row.state = BakeMapState::Baking; + } + } +} + +impl Session { + /// Start the Baking Log over for a bake of `sets` ([`BakeLog::begin`]), with how their parts pair by name + pub fn begin_bake_log(&mut self, sets: &[usize]) { + let matching = self.bake_log_matching(sets); + self.bake_log.begin(&self.doc.project, &self.doc.bake_meshes.high, sets); + self.bake_log.matching = matching; + } + + /// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not + pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) { + self.begin_bake_log(sets); + let project = &self.doc.project; + self.bake_log.maps = sets + .iter() + .filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone()))) + .flat_map(|(texture_set, set_name)| { + maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting }) + }) + .collect(); + } + + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it and no set matching "Always" bakes from every part + fn bake_log_matching(&self, sets: &[usize]) -> Option { + let mut matching: Option = None; + let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new()); + let mut every_high_used = false; + for &set in sets { + let Ok(texture_set) = self.doc.project.texture_set(set) else { continue }; + + let settings = &texture_set.bake.high_poly; + every_high_used |= !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always; + let Ok(Some(pairs)) = self.bake_name_pairs(set) else { continue }; + + let matching = matching.get_or_insert_with(|| BakeLogMatching { + low_suffix: settings.low_suffix.clone(), + high_suffix: settings.high_suffix.clone(), + pairs: Vec::new(), + }); + for pair in pairs { + match (&pair.low, &pair.high) { + (None, Some(high)) if !unpaired_highs.contains(high) => unpaired_highs.push(high.clone()), + (None, _) => {} + (Some(_), high) => { + paired_highs.extend(high.clone()); + matching.pairs.push(pair); + } + } + } + } + + if let Some(matching) = matching.as_mut().filter(|_| !every_high_used) { + let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high)); + matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) })); + } + matching + } +} diff --git a/crates/engine/src/bake/bake_log_high.rs b/crates/engine/src/bake/bake_log_high.rs new file mode 100644 index 00000000..7c6de83d --- /dev/null +++ b/crates/engine/src/bake/bake_log_high.rs @@ -0,0 +1,11 @@ +use super::BakeHighState; + +/// One row of the Baking Log's high poly list: a high poly file a texture set bakes from in the latest bake +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogHigh { + pub texture_set: usize, + pub set_name: String, + /// The file's name as the project keeps it (the project carries the file itself, not where it came from) + pub file: String, + pub state: BakeHighState, +} diff --git a/crates/engine/src/bake/bake_log_map.rs b/crates/engine/src/bake/bake_log_map.rs new file mode 100644 index 00000000..6f5d714a --- /dev/null +++ b/crates/engine/src/bake/bake_log_map.rs @@ -0,0 +1,12 @@ +use texturecraft_core::BakedMap; + +use super::BakeMapState; + +/// One row of the Baking Log's process list: a map of a texture set in the latest bake +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogMap { + pub texture_set: usize, + pub set_name: String, + pub map: BakedMap, + pub state: BakeMapState, +} diff --git a/crates/engine/src/bake/bake_log_matching.rs b/crates/engine/src/bake/bake_log_matching.rs new file mode 100644 index 00000000..9e0ef379 --- /dev/null +++ b/crates/engine/src/bake/bake_log_matching.rs @@ -0,0 +1,18 @@ +use texturecraft_bake::NamePair; + +/// The Baking Log's matching list: how the latest bake paired low poly parts with high poly parts by name +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogMatching { + /// The suffixes the first set matching by name strips, for the column captions + pub low_suffix: String, + pub high_suffix: String, + /// Each low poly part with the high poly part it bakes from, then the high poly parts no set of the bake pairs with + pub pairs: Vec, +} + +impl BakeLogMatching { + /// How many parts found no partner + pub fn issue_count(&self) -> usize { + self.pairs.iter().filter(|pair| pair.unpaired()).count() + } +} diff --git a/crates/engine/src/bake/bake_map_state.rs b/crates/engine/src/bake/bake_map_state.rs new file mode 100644 index 00000000..fec7583b --- /dev/null +++ b/crates/engine/src/bake/bake_map_state.rs @@ -0,0 +1,26 @@ +use serde::Serialize; + +/// Where one map of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeMapState { + Waiting, + Baking, + Baked, + /// The bake of its texture set failed; the reason is the error + Failed(String), + /// The bake stopped before this map was kept + Canceled, +} + +impl BakeMapState { + /// Whether the map can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Baking) + } + + /// Whether the map counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index bcdb2bcc..d4dbfeeb 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -11,4 +11,6 @@ pub struct BakeMesh { pub bytes: Arc>, pub mesh: Arc, pub base_color: Vec>>, + /// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record + pub fingerprint: u64, } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs new file mode 100644 index 00000000..b66a64fe --- /dev/null +++ b/crates/engine/src/bake/bake_sources.rs @@ -0,0 +1,115 @@ +//! What each baked map was baked from, and which maps are out of date since + +use std::collections::BTreeMap; + +use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, TextureSet, fingerprint, fingerprint_words}; + +use crate::{Result, Session}; + +impl Session { + /// What a bake of `map` on texture set `texture_set` would read now + pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + Ok(self.map_bake_source(set, map, self.set_bake_source(set))) + } + + /// The inputs of the maps selected for one task. + pub(super) fn task_bake_sources(&self, set: &TextureSet, maps: impl Iterator) -> BTreeMap { + let shared = std::cell::LazyCell::new(|| self.set_bake_source(set)); + maps.map(|map| (map, self.map_bake_source(set, map, *shared))).collect() + } + + /// The inputs shared by every map in a texture set. + fn set_bake_source(&self, set: &TextureSet) -> BakeSource { + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + let high_poly = match from_high { + true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)), + false => 0, + }; + let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile; + let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint); + + BakeSource { + low_poly: self.low_poly_fingerprint(), + low_material_file: None, + high_poly, + cage, + settings: set.bake_settings_fingerprint(), + map_settings: 0, + } + } + + fn map_bake_source(&self, set: &TextureSet, map: BakedMap, shared: BakeSource) -> BakeSource { + let reads_low_colors = shared.high_poly == 0 && set.bake.maps.reads_material_colors(map); + let low_material_file = + self.mesh_source.as_ref().filter(|_| reads_low_colors).map(|(_, bytes)| *self.low_material_file_fingerprint.get_or_init(|| fingerprint(bytes))); + + BakeSource { low_material_file, map_settings: set.map_settings_fingerprint(map), ..shared } + } + + /// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record + pub fn bake_changes(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return Vec::new() }; + + let Some(record) = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map)) else { return Vec::new() }; + + self.bake_source(texture_set, map).map(|current| record.changes(¤t)).unwrap_or_default() + } + + /// The out-of-date maps of texture set `texture_set`, each with what changed + pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap> { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return BTreeMap::new() }; + + let mut records = set.bake_sources.iter().filter(|(map, _)| set.baked.contains(map)).peekable(); + + if records.peek().is_none() { + return BTreeMap::new(); + } + + let shared = self.set_bake_source(set); + let changes = records.map(|(map, record)| (*map, record.changes(&self.map_bake_source(set, *map, shared)))); + changes.filter(|(_, changes)| !changes.is_empty()).collect() + } + + /// Fingerprint of the low poly's geometry, tangent frame, vertex colors and part assignments (computed once per loaded mesh) + fn low_poly_fingerprint(&self) -> u64 { + *self.low_poly_fingerprint.get_or_init(|| { + let source = &self.source; + let floats = source + .positions + .iter() + .chain(&source.normals) + .flat_map(|vector| vector.to_array()) + .chain(source.tangents.iter().flat_map(|tangent| tangent.to_array())) + .chain(source.uvs.iter().flat_map(|uv| uv.to_array())) + .chain(source.colors.iter().flat_map(|color| color.to_array())); + let indices = source.indices.iter().copied().map(u64::from); + let parts = + source.submeshes.iter().flat_map(|part| [fingerprint(part.name.as_bytes()), part.material as u64, part.start.into(), part.count.into()]); + + fingerprint_words(floats.map(|float| u64::from(float.to_bits())).chain(indices).chain(parts)) + }) + } + + /// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record + pub(super) fn record_bake_sources( + &mut self, + texture_set: usize, + recorded: Option<(&BTreeMap, u64)>, + stored: &[BakedMap], + ) -> Result<()> { + let set = self.doc.project.texture_set_mut(texture_set)?; + match recorded { + Some((sources, _)) => set.bake_sources.extend(sources), + None => set.bake_sources.retain(|map, _| !stored.contains(map)), + } + + let baked = &set.baked; + set.bake_sources.retain(|map, _| baked.contains(map)); + if let Some((_, painted_stroke)) = recorded { + self.forget_painted_region(texture_set, stored, painted_stroke); + } + + Ok(()) + } +} diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index a617d97b..77639b4d 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,12 +1,12 @@ use super::{MergedHigh, StreamedBake, StreamedMap}; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, 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. +/// A self-contained bake task that can run on another thread pub struct BakeTask { pub low_base_color: super::MaterialColors, pub ts: usize, @@ -14,18 +14,24 @@ pub struct BakeTask { pub bvh: Arc, pub material: usize, pub settings: BakeSettings, - /// The merged high polys, unless the set bakes from the low poly. + /// 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. + /// 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}`). + /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`) pub tracer: Option>, + /// What each map this task makes is baked from, taken when the task was made + pub sources: std::collections::BTreeMap, + /// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake + pub painted_stroke: u64, + /// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel + pub region: Option, } impl BakeTask { @@ -34,13 +40,7 @@ impl BakeTask { 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. + /// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result { let maps = self.maps(); let total = maps.len(); @@ -48,7 +48,7 @@ impl BakeTask { let mut passes = BakePasses::new(self.request()); for (index, map) in maps.iter().copied().enumerate() { - let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; let Some(data) = output.maps.remove(&map) else { continue }; if combined.is_none() { @@ -66,7 +66,14 @@ impl BakeTask { // 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 }); + combined = Some(StreamedBake { + resolution: output.resolution, + height: output.height, + maps: retained, + tracer: output.tracer, + sources: self.sources.clone(), + painted_stroke: self.painted_stroke, + }); } } } @@ -80,18 +87,25 @@ impl BakeTask { height: output.height, maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, + sources: self.sources.clone(), + painted_stroke: self.painted_stroke, }) } } } pub fn run(&self, progress: &Progress) -> Result { - let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?; Ok(output) } + /// The texels to sample, with the stored maps to take the rest from; `None` samples every texel + fn region(&self) -> Option> { + self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps }) + } + fn request(&self) -> BakeRequest<'_> { 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 }); @@ -111,7 +125,10 @@ impl BakeTask { } fn bake_error(error: texturecraft_bake::BakeError) -> EngineError { - EngineError::Other(format!("bake failed: {error}")) + match error { + texturecraft_bake::BakeError::Cancelled => EngineError::BakeCancelled, + error => EngineError::Other(format!("bake failed: {error}")), + } } #[cfg(test)] diff --git a/crates/engine/src/bake/canceled_bake.rs b/crates/engine/src/bake/canceled_bake.rs new file mode 100644 index 00000000..ad5dcc7f --- /dev/null +++ b/crates/engine/src/bake/canceled_bake.rs @@ -0,0 +1,41 @@ +//! A canceled bake keeps the maps it finished: the Baking Log ticked them and the 3D view may have shown them + +use std::collections::BTreeMap; + +use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::{Result, Session}; + +impl Session { + /// Store the maps the canceled bake of `texture_set` `finished` as one undo step and return them; none at a new output size, which would drop the set's other maps + pub fn keep_canceled_bake( + &mut self, + texture_set: usize, + finished: BakedMaps, + sources: &BTreeMap, + painted_stroke: u64, + ) -> Result> { + let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) }; + + let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| { + !stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height)) + }); + if resized { + return Ok(Vec::new()); + } + + // A map the bake did not finish keeps the record of what its stored pixels were baked from + let kept_sources: BTreeMap = + sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect(); + let kept: Vec = finished.maps.keys().copied().collect(); + self.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke))) + })?; + + // Named like the Texture Set List and the progress footer, which count sets from 1 + let name = self.doc.project.texture_sets.get(texture_set).map_or_else(|| format!("{}", texture_set + 1), |set| set.name.clone()); + self.log.info("Baker", format!("Kept {} baked maps of texture set {name} from the canceled bake", kept.len())); + Ok(kept) + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index f253e1e6..4a5162e8 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -15,8 +15,8 @@ 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, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, - SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, + RaySettings, SelfOcclusion, }; use texturecraft_geom::Mesh; @@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty()); - Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color }) + let fingerprint = texturecraft_core::fingerprint(&bytes); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint }) } impl Session { @@ -130,9 +131,14 @@ impl Session { self.bake_task_of(texture_set, None) } + /// A task that bakes only `maps` of texture set `texture_set`, checked or not; its other baked maps stay as they are + pub fn bake_task_for(&self, texture_set: usize, maps: &[BakedMap]) -> Result { + self.bake_task_of(texture_set, Some(maps)) + } + /// The bake of texture set `texture_set`'s map `map` alone, checked or not pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result { - self.bake_task_of(texture_set, Some(map)) + self.bake_task_of(texture_set, Some(&[map])) } /// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles @@ -142,20 +148,19 @@ impl Session { Ok(task) } - fn bake_task_of(&self, texture_set: usize, only: Option) -> Result { + fn bake_task_of(&self, texture_set: usize, only: Option<&[BakedMap]>) -> 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 mut settings = set.bake.clone(); - if let Some(map) = only { - settings.maps.select([map]); + if let Some(maps) = only { + settings.maps.select(maps.iter().copied()); } // Read from the maps that bake, so a map baked alone while unchecked still gets the colours - let needs_low_color = settings.maps.opacity.is_enabled - || (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); + let needs_low_color = settings.maps.enabled().any(|map| settings.maps.reads_material_colors(map)); let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) { self.doc .bake_meshes @@ -183,6 +188,8 @@ impl Session { let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed)); + let sources = self.task_bake_sources(set, settings.maps.enabled()); + Ok(BakeTask { low_base_color, ts: texture_set, @@ -198,6 +205,9 @@ impl Session { excluded_tiles, previous_maps, tracer, + sources, + painted_stroke: self.painted_strokes, + region: None, }) } @@ -260,46 +270,60 @@ impl Session { /// 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.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?; self.log.info("Baker", 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) + /// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares 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.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke))) + })?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + /// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`]) + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap, u64)>) -> 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) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded) } - fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap>>) -> Result<()> { + pub(super) fn store_bake_maps( + &mut self, + texture_set: usize, + resolution: u32, + height: u32, + maps: BTreeMap>>, + recorded: Option<(&BTreeMap, u64)>, + ) -> Result<()> { + let stored: Vec = maps.keys().copied().collect(); let entry = self.doc.baked.entry(texture_set).or_default(); - if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) { + let size_changed = entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height); + crate::meshmap_cmds::detach_imported_sources(&mut self.doc.project, texture_set, |map| size_changed || maps.contains_key(&map)); + if size_changed { 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(()) + self.record_bake_sources(texture_set, recorded, &stored) } - /// 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)?; + /// Bake texture set `texture_set` now (blocking), on the CPU when `cpu`; returns where the rays ran + pub fn bake_now(&mut self, texture_set: usize, cpu: bool) -> Result { + let mut task = self.bake_task(texture_set)?; if cpu { task.tracer = None; } - let out = task.run(&Progress::new())?; - let tracer = out.tracer.clone(); - self.apply_bake(ts, out)?; + + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, Some((&task.sources, task.painted_stroke))))?; + self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(tracer) } @@ -395,20 +419,6 @@ impl Session { } } } - - 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 = |mesh: &BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone()); - (self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry)) - } } /// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`). @@ -857,16 +867,21 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } + session.begin_bake_log(&sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { - let mut task = session.bake_task(index)?; - if cpu { - task.tracer = None; + session.bake_log.set_started(index); + let baked = bake_one_set(session, index, cpu); + match baked { + Ok(tracer) => tracers.push(tracer), + Err(error) => { + session.bake_log.set_failed(index, &error.to_string()); + // The edit rolls back the sets baked before this one too + session.bake_log.discard(); + return Err(error); + } } - let output = task.run(&Progress::new())?; - tracers.push(output.tracer.clone()); - session.store_bake(index, output)?; } Ok(tracers) })?; @@ -877,6 +892,24 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { Ok(json!({ "baked": sets, "tracer": tracers })) } +/// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log +fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result { + let mut task = session.bake_task(index)?; + session.bake_log.high_polys_loaded(index); + if cpu { + task.tracer = None; + } + + let maps = task.maps(); + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + session.store_bake(index, output, Some((&task.sources, task.painted_stroke)))?; + for map in maps { + session.bake_log.map_baked(index, map); + } + Ok(tracer) +} + #[cfg(test)] mod named_tracer; diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 1be548db..54fa0faf 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,10 +1,19 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod auto_rebake; mod bake_cage_inputs; mod bake_checks; +mod bake_high_state; +mod bake_log; +mod bake_log_high; +mod bake_log_map; +mod bake_log_matching; +mod bake_map_state; mod bake_mesh; mod bake_meshes; +mod bake_sources; mod bake_task; +mod canceled_bake; mod high_poly_load; mod high_poly_missed; mod layout; @@ -12,6 +21,7 @@ mod merged_high; mod mesh_map_command; mod model_patch; mod paint_command; +mod painted_region; mod preserve_tiles; mod streamed_bake; mod streamed_map; @@ -19,6 +29,12 @@ mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; +pub use bake_high_state::BakeHighState; +pub use bake_log::BakeLog; +pub use bake_log_high::BakeLogHigh; +pub use bake_log_map::BakeLogMap; +pub use bake_log_matching::BakeLogMatching; +pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; @@ -27,6 +43,7 @@ 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, set_gpu_raytracing, settings_params}; pub use model_patch::settings_patch; +pub use painted_region::PaintedRegion; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; pub use texturecraft_bake::*; @@ -38,6 +55,7 @@ type MaterialColors = std::sync::Arc Vec { let mut commands = mesh_map_command::specs(); commands.extend(paint_command::specs()); + commands.extend(auto_rebake::specs()); commands.extend(tile_command::specs()); commands.extend(sync_command::specs()); commands diff --git a/crates/engine/src/bake/paint_command.rs b/crates/engine/src/bake/paint_command.rs index 1bbe2580..701c5f31 100644 --- a/crates/engine/src/bake/paint_command.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -3,7 +3,7 @@ use crate::{Result, Session, cmd}; use serde_json::Value; use std::sync::Arc; use texturecraft_bake::BakePaintMap; -use texturecraft_core::BakePaintTarget; +use texturecraft_core::{BakePaintTarget, BakedMap}; use texturecraft_geom::glam::Vec2; pub(super) fn specs() -> Vec { @@ -61,10 +61,13 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re 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(()) })?; + session.note_bake_paint(texture_set, None); + Ok(super::meshes_json(session)) } @@ -75,18 +78,31 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> session.doc.bake_paint.remove(&(texture_set, target)); Ok(()) })?; + session.note_bake_paint(texture_set, None); } + Ok(super::meshes_json(session)) } +/// Most UV points one `bake.paint` call takes +const MAX_STROKE_POINTS: usize = 100_000; +/// Brush radius in UV units: the default, and the smallest that still paints +const DEFAULT_RADIUS: f32 = 0.03; +const MIN_RADIUS: f32 = 0.00001; +/// Brush hardness when a call gives none: halfway between a soft and a hard edge +const DEFAULT_HARDNESS: f32 = 0.5; +/// Side of a new paint map in texels: the default, and the range a call may ask for +const DEFAULT_PAINT_SIZE_TEXELS: u64 = 1024; +const PAINT_SIZE_RANGE_TEXELS: std::ops::RangeInclusive = 16..=4096; + 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"))?; + .filter(|points| !points.is_empty() && points.len() <= MAX_STROKE_POINTS) + .ok_or_else(|| bad("bake.paint", format!("points must contain 1 to {MAX_STROKE_POINTS} UV coordinates")))?; + let points = points .iter() .map(|point| { @@ -97,17 +113,19 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } }) .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 radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?; + let hardness = number(parameters, "hardness", DEFAULT_HARDNESS, 0.0, 1.0)?; let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; let size = match parameters.get("size") { - None => 1024, + None => DEFAULT_PAINT_SIZE_TEXELS, 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")); + if !PAINT_SIZE_RANGE_TEXELS.contains(&size) { + return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZE_RANGE_TEXELS.start(), PAINT_SIZE_RANGE_TEXELS.end()))); } + let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0, @@ -116,13 +134,30 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> BakePaintTarget::Cage => "Paint Cage", BakePaintTarget::Skew => "Paint Skew Correction", }; + session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| { + // Skew painting starts with Auto-rebake on for the Normal map, which shows the skew best, unless the set picked one + let first_skew = target == BakePaintTarget::Skew && !session.doc.bake_paint.contains_key(&(texture_set, target)); + let set = session.doc.project.texture_set_mut(texture_set)?; + if first_skew && set.auto_rebake.is_none() { + set.auto_rebake = Some(BakedMap::Normal); + } + 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())) })?; + + // Bilinear sampling extends each dab's reach by one paint texel + let paint_texel = session.doc.bake_paint.get(&(texture_set, target)).map_or(0.0, |map| 1.0 / map.width.min(map.height).max(1) as f32); + let reach = Vec2::splat(radius + paint_texel); + let uv_min = points.iter().fold(Vec2::INFINITY, |min, point| min.min(*point)) - reach; + let uv_max = points.iter().fold(Vec2::NEG_INFINITY, |max, point| max.max(*point)) + reach; + + session.note_bake_paint(texture_set, Some((uv_min, uv_max))); + Ok(super::meshes_json(session)) } diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs new file mode 100644 index 00000000..15e93985 --- /dev/null +++ b/crates/engine/src/bake/painted_region.rs @@ -0,0 +1,79 @@ +//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked + +use texturecraft_bake::{TexelBox, region_keeps_pixels}; +use texturecraft_core::{BakeSource, BakedMap}; +use texturecraft_geom::glam::Vec2; + +use crate::{Result, Session}; + +/// The UV box painted since the last bake of a texture set's auto-rebake map +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PaintedRegion { + pub uv_min: Vec2, + pub uv_max: Vec2, + /// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes + pub stroke: u64, +} + +/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it +const MARGIN_TEXELS: u32 = 1; + +impl Session { + /// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`) + pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) { + let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE)); + let (uv_min, uv_max) = match self.doc.painted_regions.get(&texture_set) { + Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)), + None => (uv_min, uv_max), + }; + self.painted_strokes += 1; + self.doc.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); + } + + /// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke` + pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) { + let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake); + let painted_since = self.doc.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); + if !painted_since && auto.is_none_or(|map| stored.contains(&map)) { + self.doc.painted_regions.remove(&texture_set); + } + } + + /// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke) + pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> { + let regions = self.doc.painted_regions.iter(); + regions + .filter_map(|(index, region)| { + let set = self.doc.project.texture_sets.get(*index)?; + let map = set.auto_rebake.filter(|map| set.baked.contains(map))?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + from_high.then_some(())?; + let current = self.bake_source(*index, map).ok()?; + + // Only painting changed it: a map without a record is never out of date + let up_to_date = set.bake_sources.get(&map).is_none_or(|record| *record == current); + up_to_date.then_some((*index, map, current, region.stroke)) + }) + .collect() + } + + /// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map + pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result { + let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?; + let Some(region) = self.doc.painted_regions.get(&texture_set) else { return Ok(task) }; + + let (width, height) = task.settings.common.output_size(); + let stored = + self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map)); + let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) }; + + let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size); + let painted = TexelBox { + min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)), + max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)), + }; + task.previous_maps = stored.clone(); + task.region = Some(painted.grown(MARGIN_TEXELS, width, height)); + Ok(task) + } +} diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs index 55aecbca..4b2895df 100644 --- a/crates/engine/src/bake/streamed_bake.rs +++ b/crates/engine/src/bake/streamed_bake.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use std::sync::Arc; -use texturecraft_core::BakedMap; +use texturecraft_core::{BakeSource, 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 @@ -11,4 +11,8 @@ pub struct StreamedBake { pub height: u32, pub maps: BTreeMap>>, pub tracer: String, + /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) + pub sources: BTreeMap, + /// The task's [`crate::BakeTask::painted_stroke`] + pub painted_stroke: u64, } diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs new file mode 100644 index 00000000..c21d8d49 --- /dev/null +++ b/crates/engine/src/bake_log_cmds.rs @@ -0,0 +1,43 @@ +//! The `bake.log` query: the Baking Log's rows for automation + +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "bake.log", + "Baking log", + [], + None, + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}], matching: null | {lowSuffix, highSuffix, pairs: [{low: name | null, high: name | null}]}}. The latest bake map by map in bake order, the high poly files each set bakes from, and how parts paired by name, as the Baking Log shows them; `reason` says why a map or file failed; a `null` side of a pair is a part with no partner; `matching` is null when no set matched by mesh name. Empty before the first bake", + always, + log + )] +} + +fn log(session: &mut Session, _: &Value) -> Result { + let log = &session.bake_log; + let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::>>()?; + let high_polys = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::>>()?; + let matching = log.matching.as_ref().map(|matching| { + let pairs: Vec = matching.pairs.iter().map(|pair| json!({ "low": pair.low, "high": pair.high })).collect(); + json!({ "lowSuffix": matching.low_suffix, "highSuffix": matching.high_suffix, "pairs": pairs }) + }); + + Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": high_polys, "matching": matching })) +} + +/// One row: its `state` (and `reason`), its texture set, and an item identified by `key` +fn entry(state: &impl serde::Serialize, texture_set: usize, set_name: &str, key: &str, value: Value) -> Result { + let mut entry = serde_json::to_value(state).map_err(|error| bad("bake.log", error.to_string()))?; + + if let Some(fields) = entry.as_object_mut() { + fields.insert("textureSet".into(), json!(texture_set)); + fields.insert("setName".into(), json!(set_name)); + fields.insert(key.into(), value); + } + + Ok(entry) +} diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index d8a03d8b..c1740632 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,9 +1,9 @@ //! 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. +//! ([`Session::apply_streamed_bake`]). The UI can apply eligible finished maps on cancellation. +//! Already applied sets keep their results and undo steps. The preview shows one raw map at a time. +//! Maps and texture sets that are still pending show their neutral value. mod preview_set; mod preview_show; diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 28d96d7b..f2f23a67 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -146,6 +146,15 @@ pub fn specs() -> Vec { cmd!("brush.preset.delete", "Delete a brush preset", [], None, "{name} — one of the user's presets (built-ins are read-only)", always, delete), cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save), cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load), + cmd!( + "brush.preset.export", + "Export brush preset", + [], + None, + "{name, path} — one of the user's presets as a .tcbrush file, as its library folder holds it", + always, + export + ), ] } @@ -325,6 +334,26 @@ fn load(_: &mut Session, _: &Value) -> Result { Err(bad("brush.preset.load", "file paths are not available in the browser")) } +/// Writes user preset `name` to `path` as the library folder holds it +#[cfg(not(target_arch = "wasm32"))] +fn export(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "brush.preset.export"; + let name = name_param(params, "name", CMD)?; + let path = strp(params, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + let preset = session.brush_presets.find(&name).and_then(|index| session.brush_presets.list.get(index)); + let preset = preset.ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?; + let bytes = serde_json::to_vec_pretty(preset).map_err(|error| bad(CMD, error.to_string()))?; + + std::fs::write(path, bytes).map_err(|error| bad(CMD, format!("cannot write {path}: {error}")))?; + + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.export", "file paths are not available in the browser")) +} + #[cfg(test)] mod tests { use super::*; @@ -406,6 +435,31 @@ mod tests { assert_eq!(names(&test_session), ["a/b"]); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_exported_preset_loads_as_the_same_brush() { + let dir = std::env::temp_dir().join(format!("tc-brush-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut test_session = session(); + run(&mut test_session, "tool.brush", json!({"size": 41, "hardness": 70})).unwrap(); + run(&mut test_session, "brush.preset.store", json!({"name": "Ink pen"})).unwrap(); + run(&mut test_session, "tool.brush", json!({"size": 5})).unwrap(); + + let path = dir.join("shared.tcbrush"); + run(&mut test_session, "brush.preset.export", json!({"name": "ink pen", "path": path.to_str().unwrap()})).unwrap(); + + let mut fresh = session(); + assert!(fresh.load_brush_presets(dir.clone()).is_empty()); + assert_eq!(names(&fresh), ["Ink pen"], "the file carries the preset's name"); + assert_eq!(fresh.brush_presets.list[0].brush, test_session.brush_presets.list[0].brush, "the stored brush, not the current one"); + assert!( + run(&mut test_session, "brush.preset.export", json!({"name": "Airbrush", "path": path.to_str().unwrap()})).is_err(), + "built-ins are not exported" + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn presets_persist_in_the_folder() { diff --git a/crates/engine/src/brush_preset_cmds/user_brushes.rs b/crates/engine/src/brush_preset_cmds/user_brushes.rs index 921df2d5..3acb6712 100644 --- a/crates/engine/src/brush_preset_cmds/user_brushes.rs +++ b/crates/engine/src/brush_preset_cmds/user_brushes.rs @@ -45,6 +45,12 @@ impl UserBrushes { self.dir.as_ref().map(|directory| directory.join(format!("{}.{BRUSH_EXT}", sanitize_file_stem(name.trim())))) } + /// The file user preset `name` is mirrored to (None: no such preset, or the presets live in memory only) + pub fn file_for(&self, name: &str) -> Option { + let preset = self.list.get(self.find(name)?)?; + preset.file.clone().or_else(|| self.file_of(&preset.name)) + } + /// The file a preset named `name` that was never written would have. #[cfg(not(target_arch = "wasm32"))] pub(super) fn file_of(&self, name: &str) -> Option { diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 49cead62..0b7b1630 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -31,7 +31,7 @@ impl CommandSpec { /// that only return data or do nothing without parameters, and the ones that replace the /// open project (the menu asks to save first). pub fn bindable(&self) -> bool { - const NOT_FROM_A_KEY: [&str; 13] = [ + const NOT_FROM_A_KEY: &[&str] = &[ "project.inspect", "project.templates", "project.new", @@ -43,8 +43,10 @@ impl CommandSpec { "textureSet.parts", "bake.settings", "bake.preview", + "bake.log", "camera.set", "textureSet.settings", + "resource.status", ]; const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"]; !(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params) @@ -139,11 +141,13 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::project_cmds::specs()); v.extend(crate::bake::specs()); v.extend(crate::bake_preview::specs()); + v.extend(crate::bake_log_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::pbr_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); + v.extend(crate::resource_update_cmds::specs()); v.extend(crate::material_lib::specs()); v.extend(crate::link_cmds::specs()); v.extend(crate::smart_masks::specs()); @@ -371,7 +375,18 @@ mod tests { ] { assert!(!bindable(id), "{id} needs a parameter"); } - for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] { + for id in [ + "layer.move", + "layer.list", + "project.inspect", + "edit.history", + "export.presets", + "tool.state", + "project.new", + "camera.set", + "layer.blend", + "bake.log", + ] { assert!(!bindable(id), "{id} is a query or has several forms"); } } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 28595a1f..ac846ba5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -13,14 +13,39 @@ use texturecraft_core::{NormalFormat, PROJECT_EXT}; use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::PlannedFile; use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry}; -use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile}; +use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, MapPreview, Padding, ProjectFile}; use texturecraft_geom::glam::Vec2; -use texturecraft_geom::{Mesh, primitives}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}; use crate::session::{Document, Session}; use crate::{EngineError, Result, cmd}; +/// export.preview's picture width when the params name none +const DEFAULT_PREVIEW_SIDE_PIXELS: u32 = 128; + +type BakePaintMaps = BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc>; + +fn prepare_archive(archive: &mut ProjectFile, uv_source: Option<&Mesh>, bake_paint: &BakePaintMaps) { + let project = &mut archive.project; + project.format_version = project.save_format_version(); + + // Drop pixel images whose size no longer matches their texture set + let size_of = |id: texturecraft_core::LayerId| { + project.locate(id).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| { + project.effect(id).and_then(|(owner, _)| project.locate(owner)).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size) + }) + }; + archive.pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height()))); + archive.pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); + + archive.mesh_uvs = uv_source.map(texturecraft_formats::mesh_import::corner_uvs); + archive.bake_paint = bake_paint + .iter() + .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() })) + .collect(); +} + pub fn specs() -> Vec { vec![ cmd!( @@ -60,7 +85,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -69,7 +94,7 @@ pub fn specs() -> Vec { "Export Mesh...", ["File"], None, - "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", + "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj), recomputeNormals?: bool (default false: smooth area-weighted normals replace the stored normals on the exported copy only); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", always, export_mesh ), @@ -78,10 +103,19 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)", + "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with or null, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)", always, plan ), + cmd!( + "export.preview", + "Preview an output map", + [], + None, + "{map: index into the preset's maps, side?: px (default 128, at most 512), plus the params of export.plan (the first texture set `ts` names)} → {width, height, channels: [\"R\", ...], pixels: [8-bit values as an sRGB file stores them, channels interleaved, row by row]}, or null when the texture set writes no file for the map", + always, + preview + ), ] } @@ -115,19 +149,38 @@ fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Op impl Session { /// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included). pub fn mesh_obj_bytes(&self) -> Result> { - texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe) + self.mesh_obj_bytes_with_normals(false) + } + + /// [`Session::mesh_obj_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result> { + let mut mesh = self.source_mesh(); + if recompute_normals { + mesh.compute_smooth_normals(); + } + texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe) } /// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like /// [`Session::mesh_usd`]'s), to write next to it, named after `stem` (the OBJ file's). pub fn mesh_obj_with_mtl(&mut self, stem: &str) -> Result<(Vec, texturecraft_formats::NamedFiles)> { - // shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is - // one image); their tiles export through Export textures with `$udim` names. + self.mesh_obj_with_mtl_and_normals(stem, false) + } + + /// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec, texturecraft_formats::NamedFiles)> { + // OBJ keeps UDIM UVs, while each MTL map can hold only one image + // Export tiled textures separately with `$udim` names let mut mesh = self.source_mesh(); - // A mesh without materials has one implicit material (and texture set). + if recompute_normals { + mesh.compute_smooth_normals(); + } + + // A mesh without materials has one implicit material and texture set if mesh.materials.is_empty() { mesh.materials.push("default".into()); } + let files = self.material_files(texturecraft_formats::usd_export_options(), false, mesh.materials.len())?; texturecraft_formats::obj_with_mtl(&mesh, &self.doc.project.name, stem, &files).map_err(fe) } @@ -136,16 +189,36 @@ impl Session { /// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a /// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space. pub fn mesh_glb_bytes(&mut self) -> Result> { + self.mesh_glb_bytes_with_normals(false) + } + + /// [`Session::mesh_glb_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result> { let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?; let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect(); - texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe) + let mut mesh = Cow::Borrowed(self.mesh.as_ref()); + if recompute_normals { + mesh.to_mut().compute_smooth_normals(); + } + + texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe) } /// The working mesh as USD with a UsdPreviewSurface per material (textures like /// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside. pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result { + self.mesh_usd_with_normals(format, false) + } + + /// [`Session::mesh_usd`], optionally replacing normals on the exported copy only. + pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result { let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?; - texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe) + let mut mesh = Cow::Borrowed(self.mesh.as_ref()); + if recompute_normals { + mesh.to_mut().compute_smooth_normals(); + } + + texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe) } /// The texture sets of the first `materials` materials rendered with `opts` (as a tile atlas @@ -184,7 +257,7 @@ impl Session { // Packed mesh files can have spare capacity that the project would otherwise retain let mut source = bytes.into_owned(); source.shrink_to_fit(); - session.mesh_source = Some((extension, source)); + session.mesh_source = Some((extension, Arc::new(source))); session.doc.project.mesh_file = leaf_of(file_name); session.doc.project.mesh_rebuild_uvs = rebuild_uvs; session.doc.project.cameras = imported.cameras; @@ -232,6 +305,7 @@ impl Session { pixels: project_file.pixels, baked: project_file.baked, resources, + painted_regions: Default::default(), }, mesh, project_file.mesh, @@ -245,109 +319,163 @@ impl Session { Ok(session) } - /// The project with independently owned resource bytes. - pub fn project_file(&self) -> ProjectFile { - let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect(); - self.project_with_resources(resources) - } - - /// A save snapshot that shares immutable resource payloads with the document. - pub fn project_snapshot(&self) -> ProjectFile>> { - self.project_with_resources(self.doc.resources.clone()) - } - - /// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper. - fn saved_uv_layout(&self) -> Option> { - (self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source)) - } - - fn project_with_resources(&self, resources: BTreeMap) -> ProjectFile { - let mut pixels = self.doc.pixels.clone(); - - // 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 - .project - .effect(id) - .and_then(|(owner, _)| self.doc.project.locate(owner)) - .and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)) - .map(TextureSet::size) - }) - }; - 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(); - let mut project = self.doc.project.clone(); - project.format_version = project.save_format_version(); - + /// Capture just the archive inputs. The caller prepares derived data before writing. + fn capture_archive(&self, resources: BTreeMap, store_mesh_bytes: impl Fn(&Arc>) -> Bytes) -> ProjectFile { + let bake_mesh = |mesh: &crate::BakeMesh| (mesh.name.clone(), store_mesh_bytes(&mesh.bytes)); ProjectFile { - project, - pixels, + project: self.doc.project.clone(), + pixels: self.doc.pixels.clone(), baked: self.doc.baked.clone(), - mesh: self.mesh_source.clone(), - mesh_uvs: self.saved_uv_layout(), - high_poly, - cage, - bake_paint: self.saved_bake_paint(), + mesh: self.mesh_source.as_ref().map(|(extension, bytes)| (extension.clone(), store_mesh_bytes(bytes))), + mesh_uvs: None, + high_poly: self.doc.bake_meshes.high.iter().map(bake_mesh).collect(), + cage: self.doc.bake_meshes.cage.as_ref().map(bake_mesh), + bake_paint: BTreeMap::new(), thumbnail: None, resources, warnings: Vec::new(), } } + /// The project with independently owned resource and mesh bytes. + pub fn project_file(&self) -> ProjectFile { + let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect(); + let mut archive = self.capture_archive(resources, |bytes| bytes.as_ref().clone()); + prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint); + archive + } + + /// A save snapshot that shares immutable resource and mesh payloads with the document. + pub fn project_snapshot(&self) -> ProjectFile>, Arc>> { + let mut archive = self.capture_archive(self.doc.resources.clone(), Arc::clone); + prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint); + archive + } + + /// The imported geometry needed to save rebuilt corner UVs and skip unwrapping on reopen. + fn saved_uv_source(&self) -> Option<&Arc> { + (self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then_some(&self.source) + } + pub fn to_project_bytes(&self) -> Result> { let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?; reservation.save_bytes(&self.project_snapshot()).map_err(fe) } /// Render every export file for texture sets `sets` (in memory; works on the web). A file - /// named like one an earlier set exports is left out, with a warning (see - /// [`texturecraft_formats::skip_repeated_names`]). + /// named like one an earlier set exports is left out, with a warning. pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result> { - let mut files = self.render_export_files(sets, opts, |_, plans| plans)?; - texturecraft_formats::skip_repeated_names(&mut files); - Ok(files) + self.export_file_jobs(sets.iter().map(|&set| (set, opts))) } + /// Render one in-memory batch, using each set's own export settings when supplied. + pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator) -> Result> { + self.render_export_jobs(jobs, |_, plans| plans) + } + + #[cfg(not(target_arch = "wasm32"))] fn render_export_files( &mut self, sets: &[usize], options: &ExportOptions, + select: impl FnMut(usize, Vec) -> Vec, + ) -> Result> { + self.render_export_jobs(sets.iter().map(|&set| (set, options)), select) + } + + fn render_export_jobs<'a>( + &mut self, + jobs: impl IntoIterator, mut select: impl FnMut(usize, Vec) -> Vec, ) -> Result> { + let project = &self.doc.project; + let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); + let mut pending = Vec::new(); + for (set_index, options) in jobs { + let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?; + let plans = select(set_index, plans); + if !plans.is_empty() { + pending.push((set_index, options, plans)); + } + } + + // Keep each winning plan with the options of the job that produced it + let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan))); + let plans = texturecraft_formats::export::keep_first_planned_names(plans); + if pending.len() > 1 { + texturecraft_formats::export::validate_export_paths(plans.iter().map(|(_, plan)| plan.name.as_str())).map_err(fe)?; + } + + for (job, plan) in plans { + pending[job].2.push(plan); + } + pending.retain(|(_, _, plans)| !plans.is_empty()); + + let mut psd_bytes = 0; + for (set_index, options, plans) in &pending { + let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?; + texturecraft_formats::export::check_psd_batch(set, options, plans, &mut psd_bytes).map_err(fe)?; + } + if self.solo.is_none() { self.update(); } - let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); - let empty = Default::default(); - for &set_index in sets { - let cache = self.caches.get(set_index).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; - let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?; - let plans = select(set_index, plans); - if plans.is_empty() { - continue; - } - - let composite = - self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; - let coverage = cache.gbuf.coverage_mask(); - let input = ExportInput { - project: &self.doc.project, - ts: set_index, - composite: &composite, - baked: self.doc.baked.get(&set_index).unwrap_or(&empty), - coverage: &coverage, - mesh_name: &mesh_name, - }; - out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?); + for (set_index, options, plans) in pending { + let files = self.with_export_input( + set_index, + &mesh_name, + |grid| Cow::Owned(grid.coverage_mask()), + |input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe), + )?; + out.extend(files); } Ok(out) } + + /// Run `with` on texture set `set_index`'s export input: its document composite, coverage and baked maps + fn with_export_input( + &self, + set_index: usize, + mesh_name: &str, + coverage: impl FnOnce(&UvGBuffer) -> Cow<'_, [Coverage]>, + with: impl FnOnce(&ExportInput) -> Result, + ) -> Result { + let missing = || EngineError::Other(format!("no texture set {set_index}")); + let cache = self.caches.get(set_index).ok_or_else(missing)?; + let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?; + let coverage = coverage(&cache.gbuf); + let empty = Default::default(); + let input = ExportInput { + project: &self.doc.project, + ts: set_index, + composite: &composite, + baked: self.doc.baked.get(&set_index).unwrap_or(&empty), + coverage: &coverage, + mesh_name, + }; + with(&input) + } + + /// A picture of output map `map` for the first texture set named in `params`, with each side at most `side` pixels. + /// Returns None when the map writes no file. + pub fn export_preview(&mut self, params: &Value, map: usize, side: u32) -> Result> { + let options = export_options(self, params, "export.preview")?; + let Some(&set_index) = sets_param(self, params, "export.preview")?.first() else { return Ok(None) }; + + if self.solo.is_none() { + self.update(); + } + let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); + self.with_export_input( + set_index, + &mesh_name, + |grid| Cow::Borrowed(&grid.tri), + |input| MapPreview::sample_triangles(input, &options, map, side).map_err(fe), + ) + } } fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> { @@ -409,12 +537,12 @@ pub fn export_options(session: &Session, params: &Value, cmd: &str) -> Result Result> { let mut overrides = std::collections::BTreeMap::new(); let Some(list) = params.get("maps").filter(|value| !value.is_null()) else { return Ok(overrides) }; - let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?}"))?; + let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?, size?}"))?; for settings in list { let index = u64p(settings, "map").and_then(|value| usize::try_from(value).ok()).filter(|index| *index < map_count); let index = index.ok_or_else(|| bad(cmd, format!("`maps`: `map` must be the index of one of the preset's {map_count} maps")))?; @@ -433,6 +561,10 @@ fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result Result { v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`")) } +fn preview(session: &mut Session, params: &Value) -> Result { + let map = u64p(params, "map").and_then(|map| usize::try_from(map).ok()); + let map = map.ok_or_else(|| bad("export.preview", "`map` (an output map index) is required"))?; + let side = u64p(params, "side").map_or(DEFAULT_PREVIEW_SIDE_PIXELS, |side| side.clamp(1, u64::from(texturecraft_formats::MAX_PREVIEW_SIDE)) as u32); + + Ok(match session.export_preview(params, map, side)? { + Some(preview) => json!({ + "width": preview.width, + "height": preview.height, + "channels": preview.channels.iter().map(|dest| format!("{dest:?}")).collect::>(), + "pixels": preview.pixels, + }), + None => Value::Null, + }) +} + fn plan(session: &mut Session, params: &Value) -> Result { use texturecraft_formats::export::{list_set_outputs, scale_export_side}; @@ -479,18 +627,23 @@ fn plan(session: &mut Session, params: &Value) -> Result { let block_size = set.block_resolution(); for (_, output) in set_outputs { let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile)); - let size = scale_export_side(source_size, block_size, options.size); + + // A map's own size wins over the export's; a PSD is the size of its largest layer + let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size); files.push(json!({ "ts": set_index, "map": output.map, "file": output.name, + "tile": output.tile, + "udimPattern": output.udim_name, "format": output.format.extension(), "bitDepth": output.bit_depth, "dithering": output.dither, "size": size, "sourceSize": source_size, "warnings": output.warnings, + "layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::>(), })); } } @@ -537,21 +690,22 @@ mod native { } pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result { - let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") }; - let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?; - reservation.save(Path::new(&path), &s.project_snapshot()).map_err(fe)?; - - if adopt { - s.path = Some(path.clone()); - s.modified = false; - } - s.log.info("Project", format!("Saved {path}")); - Ok(json!({ "path": path })) + let output = s.save_task(path, adopt).run(None)?; + output.apply(s); + Ok(json!({ "path": output.path })) } } #[cfg(not(target_arch = "wasm32"))] pub use native::{absolute, open_path, read_mesh}; +#[cfg(not(target_arch = "wasm32"))] +mod save_output; +#[cfg(not(target_arch = "wasm32"))] +mod save_target; +#[cfg(not(target_arch = "wasm32"))] +mod save_task; +#[cfg(not(target_arch = "wasm32"))] +pub use {save_output::SaveOutput, save_task::SaveTask}; /// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the /// mesh file `mesh`, remembering its path for Reimport mesh. @@ -661,7 +815,7 @@ impl Session { } None => match &self.mesh_source { Some((ext, bytes)) => { - let layout = self.saved_uv_layout(); + let layout = self.saved_uv_source().map(|source| texturecraft_formats::mesh_import::corner_uvs(source)); let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?; (mesh, None, Vec::new(), self.doc.project.mesh_file.clone()) } @@ -671,7 +825,8 @@ impl Session { check_materials(&self.doc.project, &mesh)?; let mut doc = self.doc.clone(); - if let Some((ext, _)) = replacement_source.as_ref().or(self.mesh_source.as_ref()) { + let extension = replacement_source.as_ref().map(|(extension, _)| extension).or_else(|| self.mesh_source.as_ref().map(|(extension, _)| extension)); + if let Some(ext) = extension { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; doc.project.mesh_rebuild_uvs = rebuild_uvs; @@ -695,6 +850,10 @@ impl Session { next.modified = true; next.project_id = self.project_id; + + // Keep the stroke counter aligned with the painted regions in the cloned document + next.painted_strokes = self.painted_strokes; + let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); // Keep the stored source in the current session until reimport succeeds @@ -703,6 +862,7 @@ impl Session { } self.switch_to(next); + Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n }))) } } @@ -716,6 +876,7 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { let reserved_patterns: Vec<_> = taken_names.keys().filter(|name| name.contains("")).cloned().collect(); let material = params.get("materialX").and_then(Value::as_bool).unwrap_or(false); let usd_asset = usd_asset_param(session, params, &options, &sets)?; + let shader_sets = crate::shader_parameters::shader_parameters_param(&session.doc.project, params, &sets, "file.exportTextures")?; let mut warnings = Vec::new(); let mut udim_patterns = Vec::new(); @@ -775,6 +936,22 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { if let Some(exports) = &usd_asset { written.extend(write_usd_asset(session, dir, exports, &mut warnings)); } + if let Some(shader_sets) = shader_sets { + let name = crate::shader_parameters::shader_parameters_file(&session.doc.project.name); + let path = dir.join(&name); + let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets); + + // Check the name against this command's files and the earlier commands' `reservedNames`, as the web download and headless export do + let roots = written.iter().filter_map(|written| written.strip_prefix(dir).ok()?.components().next()?.as_os_str().to_str()); + let checked = crate::shader_parameters::check_shader_parameters_name(&name, roots.chain(taken_names.keys().map(String::as_str))); + + // The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is + let text = checked.and_then(|()| serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string())); + match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) { + Ok(()) => written.push(path), + Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), + } + } session.log.info("MapExporter", format!("Exported {} textures to {}", written.len(), dir.display())); let mut response = json!({ "files": written.iter().map(|path| path.display().to_string()).collect::>(), "warnings": warnings }); @@ -816,7 +993,7 @@ fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, s /// warning: the textures of the command are already written. #[cfg(not(target_arch = "wasm32"))] fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Option { - match build_usd_asset(session, dir, exports) { + match build_usd_asset(session, dir, exports, warnings) { Ok(path) => Some(path), Err(error) => { warnings.push(format!("{USD_ASSET_FAILED}: {error}")); @@ -826,7 +1003,7 @@ fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset } #[cfg(not(target_arch = "wasm32"))] -fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result { +fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Result { use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings}; let project = &session.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); @@ -847,6 +1024,15 @@ fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset // A map that lost any file (a tile of a UDIM map) is not bound: its `` name would read a file it does not own kept.retain(|file| !skipped_maps.contains(&file.map)); + let mut unsupported = HashSet::new(); + for file in kept.iter().filter(|file| !file.format.usable_by_usd_asset() && unsupported.insert(file.format)) { + let format = file.format.extension().to_ascii_uppercase(); + let warning = + format!("The USD asset doesn't read {format} files, so the material of texture set \"{}\" leaves out those maps", texture_set.name); + if !warnings.contains(&warning) { + warnings.push(warning); + } + } by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept)); } } @@ -893,8 +1079,20 @@ fn reserve_export_names( let mut blocked_maps = HashSet::new(); plans.retain(|plan| { let name = plan.name.to_ascii_lowercase(); - if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) { - blocked_maps.insert(plan.map); + let reserved = reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)); + if !reserved && let Entry::Vacant(entry) = taken_names.entry(name) { + entry.insert(Some(set_index)); + return true; + } + + // A set warning outlives the file that carried it + for warning in plan.warnings.iter().filter(|warning| texturecraft_formats::export::is_set_warning(warning)) { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + blocked_maps.extend(plan.maps()); + if reserved { warnings.push(format!( "\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names", plan.name @@ -902,12 +1100,6 @@ fn reserve_export_names( return false; } - if let Entry::Vacant(entry) = taken_names.entry(name) { - entry.insert(Some(set_index)); - return true; - } - - blocked_maps.insert(plan.map); if fallback { warnings.push(format!( "MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names", @@ -984,11 +1176,11 @@ fn material_map_options(options: &ExportOptions, project_normal: NormalFormat) - continue; } - let mut overrides = MapOverride::default(); + let settings = replacement.and_then(|(index, _)| options.maps.get(&index)); + let mut overrides = MapOverride { size: settings.and_then(|settings| settings.size), ..MapOverride::default() }; let requested_format = replacement.map(|(index, _)| selected_format(index)).or(options.format_override); if requested_format.is_none_or(material_format) { overrides.format = requested_format; - let settings = replacement.and_then(|(index, _)| options.maps.get(&index)); overrides.bit_depth = settings.and_then(|settings| settings.bit_depth).or(options.bit_depth_override).or_else(|| replacement.map(|(_, selected)| selected.bit_depth)); overrides.dither = settings.and_then(|settings| settings.dither); @@ -1159,7 +1351,7 @@ fn write_materialx( #[cfg(not(target_arch = "wasm32"))] fn export_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.exportMesh")?; - let out = s.mesh_export(path, strp(p, "format"))?; + let out = s.mesh_export_with_normals(path, strp(p, "format"), crate::commands::boolp(p, "recomputeNormals").unwrap_or(false))?; let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new("")); let texture_paths: Vec = out.textures.iter().map(|(name, _)| dir.join(name)).collect(); let main_path = std::path::PathBuf::from(&out.path); @@ -1196,6 +1388,12 @@ impl Session { /// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default: /// from the extension, else OBJ). The extension is appended when it doesn't match. pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result { + self.mesh_export_with_normals(path, format, false) + } + + /// [`Session::mesh_export`], optionally computing smooth area-weighted normals on the + /// exported copy. The project's source and render meshes are never changed. + pub fn mesh_export_with_normals(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { let ext = match format { Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(), Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))), @@ -1203,14 +1401,16 @@ impl Session { None => "obj".into(), }; let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") }; + let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) { - ("glb", _) => (self.mesh_glb_bytes()?, Vec::new()), + ("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()), (_, Some(format)) => { - let usd = self.mesh_usd(format)?; + let usd = self.mesh_usd_with_normals(format, recompute_normals)?; (usd.bytes, usd.textures) } - _ => self.mesh_obj_with_mtl(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"))?, + _ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?, }; + Ok(MeshExport { path, bytes, textures }) } } @@ -1402,6 +1602,72 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn mesh_export_can_recompute_normals_without_changing_the_project() { + let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y); + std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y); + let mut expected = s.source_mesh(); + expected.compute_smooth_normals(); + let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] { + let path = dir.join(format!("cube-{format}.{suffix}")); + let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap(); + let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap(); + let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh; + + assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex"); + for (position, actual) in back.positions.iter().zip(&back.normals) { + let wanted = expected + .positions + .iter() + .zip(&expected.normals) + .find_map(|(expected_position, normal)| ((*expected_position - *position).length() < 1e-4).then_some(*normal)) + .unwrap_or_else(|| panic!("{format}: exported position {position:?} is missing from the source")); + assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}"); + } + } + + assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged"); + assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged"); + + let stored_path = dir.join("stored.obj"); + let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap(); + let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap(); + let stored = texturecraft_formats::import_mesh_bytes("stored.obj", &stored).unwrap().mesh; + assert!(stored.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the default keeps stored normals for compatibility"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn recomputed_normals_weld_uv_seams_in_exported_mesh() { + use texturecraft_geom::glam::Vec3; + + // The UV seam duplicates edge 0–2 at vertices 3 and 4 + let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)]; + let mesh = Mesh::from_parts( + positions, + Some(vec![Vec3::Y; 6]), + vec![Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.5), Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.5, 1.0)], + vec![0, 1, 2, 3, 4, 5], + "Default", + ) + .unwrap(); + let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap(); + + let bytes = s.mesh_glb_bytes_with_normals(true).unwrap(); + let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh; + + for point in [Vec3::ZERO, Vec3::Y] { + let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect(); + assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices"); + assert!(normals.windows(2).all(|pair| (pair[0] - pair[1]).length() < 1e-5), "{point:?}: UV split normals disagree: {normals:?}"); + } + } + #[test] fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() { let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); @@ -1540,11 +1806,18 @@ f 1/1 2/2 3/3 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 + // Keep the triangle count fixed while changing the geometry 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(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + let cage = crate::bake::BakeMesh { + name: "cage".into(), + folder: None, + bytes: Default::default(), + mesh: s.mesh.clone(), + base_color: Vec::new(), + fingerprint: 0, + }; s.doc.bake_meshes.cage = Some(cage); let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); diff --git a/crates/engine/src/file_cmds/save_output.rs b/crates/engine/src/file_cmds/save_output.rs new file mode 100644 index 00000000..6676ed50 --- /dev/null +++ b/crates/engine/src/file_cmds/save_output.rs @@ -0,0 +1,29 @@ +use crate::session::Session; + +/// An archive that was written successfully. Only the same project can adopt its path. +pub struct SaveOutput { + pub path: String, + pub(super) project_id: u64, + pub(super) saved_revision: Option, + pub(super) adopt: bool, +} + +impl SaveOutput { + /// Apply the saved path without clearing edits made since the snapshot. + pub fn apply(&self, session: &mut Session) { + if session.project_id != self.project_id { + return; + } + + if self.adopt { + session.path = Some(self.path.clone()); + + // A stroke started after capture changes the revision only when committed + if self.saved_revision == Some(session.save_revision) { + session.modified = false; + } + } + + session.log.info("Project", format!("Saved {}", self.path)); + } +} diff --git a/crates/engine/src/file_cmds/save_target.rs b/crates/engine/src/file_cmds/save_target.rs new file mode 100644 index 00000000..7f156d27 --- /dev/null +++ b/crates/engine/src/file_cmds/save_target.rs @@ -0,0 +1,6 @@ +pub(super) struct SaveTarget { + pub(super) project_id: u64, + pub(super) saved_revision: Option, + pub(super) adopt: bool, + pub(super) path: String, +} diff --git a/crates/engine/src/file_cmds/save_task.rs b/crates/engine/src/file_cmds/save_task.rs new file mode 100644 index 00000000..c1241560 --- /dev/null +++ b/crates/engine/src/file_cmds/save_task.rs @@ -0,0 +1,53 @@ +use std::path::Path; +use std::sync::Arc; + +use texturecraft_core::PROJECT_EXT; +use texturecraft_formats::{ProjectFile, project_file::SaveProgress}; +use texturecraft_geom::Mesh; + +use super::{BakePaintMaps, SaveOutput, ext_of, fe, prepare_archive, save_target::SaveTarget}; +use crate::Result; +use crate::session::Session; + +/// A manual save of the document at the moment it was requested. Large payloads are shared +/// until the worker assembles the archive. +pub struct SaveTask { + target: SaveTarget, + archive: ProjectFile>, Arc>>, + bake_paint: BakePaintMaps, + uv_source: Option>, +} + +impl Session { + pub fn save_task(&self, path: &str, adopt: bool) -> SaveTask { + let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") }; + let saved_revision = (!self.stroke_active()).then_some(self.save_revision); + + SaveTask { + target: SaveTarget { project_id: self.project_id, saved_revision, adopt, path }, + archive: self.capture_archive(self.doc.resources.clone(), Arc::clone), + bake_paint: self.doc.bake_paint.clone(), + uv_source: self.saved_uv_source().cloned(), + } + } +} + +impl SaveTask { + /// Complete the atomic write on the worker. Waiting for a previous save to release the + /// RAM allowance also happens here. + pub fn run(mut self, progress: Option<&SaveProgress>) -> Result { + let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?; + prepare_archive(&mut self.archive, self.uv_source.as_deref(), &self.bake_paint); + drop(self.uv_source); + drop(self.bake_paint); + + let path = Path::new(&self.target.path); + match progress { + Some(progress) => reservation.save_with_progress(path, &self.archive, progress), + None => reservation.save(path, &self.archive), + } + .map_err(fe)?; + + Ok(SaveOutput { path: self.target.path, project_id: self.target.project_id, saved_revision: self.target.saved_revision, adopt: self.target.adopt }) + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 14863420..4daaace0 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, Generator, Layer, LayerKind, NormalFormat, Projection, Sampling, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, NormalFormat, Projection, Sampling, Source}; use crate::Session; use crate::session::StackTarget; @@ -162,6 +162,9 @@ fn generator_json(generator: &Generator) -> Value { if let Some(light) = &generator.light { out["light"] = json!(light); } + if generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction) { + out["direction"] = json!(generator.direction); + } if let Some(texture) = &generator.texture { out["texture"] = json!(texture); } @@ -261,6 +264,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { }) }) .collect(); + + let out_of_date: std::collections::BTreeMap<_, Vec<_>> = + session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect())).collect(); + json!({ "index": index, "name": texture_set.name, @@ -273,6 +280,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "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)), + "outOfDate": out_of_date, + "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 4a1f6c7b..f33e4167 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -324,8 +324,8 @@ fn select(s: &mut Session, p: &Value) -> Result { } Some(Value::String(t)) if t == "content" => StackTarget::Content, Some(v) => match v.as_u64() { - Some(e) if s.doc.project.effect(LayerId(e)).is_some_and(|(owner, _)| owner == id) => StackTarget::Effect(LayerId(e)), - _ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer")), + Some(effect) if selectable_effect(&s.doc.project, id, LayerId(effect)) => StackTarget::Effect(LayerId(effect)), + _ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer or of the mask it draws with")), }, None => StackTarget::Content, }; @@ -334,6 +334,15 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] })) } +/// Whether the effect belongs to the layer or to the mask it draws with. +fn selectable_effect(project: &Project, layer: LayerId, effect_id: LayerId) -> bool { + let Some((owner, _)) = project.effect(effect_id) else { return false }; + + owner == layer + || (owner == project.mask_owner(layer) + && project.layers.get(&owner).and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|effect| effect.id == effect_id))) +} + fn rename(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.rename", p)?; let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.rename", "`name` is required"))?.to_string(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 148af463..d55a55c9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod add_mask_cmds; mod anchored_micro_edit; pub mod bake; +pub mod bake_log_cmds; pub mod bake_preview; pub mod brush_preset_cmds; pub mod camera_cmds; @@ -51,6 +52,7 @@ pub mod material_lib; mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; +mod mesh_map_sampler; pub mod meshmap_cmds; mod meshmap_file_name; pub mod meshmap_import_cmds; @@ -73,10 +75,20 @@ pub mod preview; mod procedural_params; pub mod project_cmds; pub mod quick_mask; +// Reloading resource files reads paths on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod reloaded_file; +// Remembered file comparisons exist on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod resource_check; pub mod resource_cmds; +pub mod resource_state; +pub mod resource_status; +pub mod resource_update_cmds; pub mod session; mod session_log; pub mod set_cmds; +pub mod shader_parameters; pub mod smart_masks; mod solo; mod stylized_lighting_params; @@ -102,6 +114,8 @@ pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; pub use project_cmds::sample_session; +pub use resource_state::ResourceState; +pub use resource_status::ResourceStatus; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label, stroke_template, @@ -127,6 +141,8 @@ pub enum EngineError { BadParams { cmd: String, msg: String }, #[error(transparent)] Core(#[from] texturecraft_core::CoreError), + #[error("bake failed: bake cancelled")] + BakeCancelled, #[error("{0}")] Other(String), } diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index a20182f6..73a4317e 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -344,6 +344,68 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Prefix of the folders [`stage_handoff_package`] makes in the temp folder. +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_PREFIX: &str = "texturecraft-open-"; + +/// Folders from earlier hand-offs older than this are removed (MaterialCraft may still have a young one open). +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); + +/// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the +/// file's path (for [`open_in_materialcraft`]). A fixed `/` is guessable: on a shared `/tmp` another user +/// could plant a file or link there first and the write would go through it. The folder name is random, is created +/// exclusively (mode `0700` on Unix) and the file is created with `create_new` (mode `0600`), so nothing planted is ever written through. +/// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go. +#[cfg(not(target_arch = "wasm32"))] +pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result { + stage_handoff_package_in(&std::env::temp_dir(), file_name, package) +} + +#[cfg(not(target_arch = "wasm32"))] +fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[u8]) -> Result { + use std::io::Write; + let io = |e: std::io::Error| EngineError::Other(format!("cannot stage the package for MaterialCraft: {e}")); + if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) { + return Err(EngineError::Other(format!("`{file_name}` is not a plain file name"))); + } + sweep_old_handoffs(base, HANDOFF_MAX_AGE); + // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind. + let mut builder = tempfile::Builder::new(); + builder.prefix(HANDOFF_PREFIX); + // tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly. + #[cfg(unix)] + builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); + let dir = builder.tempdir_in(base).map_err(io)?; + let path = dir.path().join(file_name); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(&path).map_err(io)?; + file.write_all(package).map_err(io)?; + file.sync_all().map_err(io)?; + let _ = dir.keep(); + Ok(path) +} + +/// Remove hand-off folders in `base` last changed more than `max_age` ago. Only real folders with our prefix are +/// touched (never a link), and every failure is ignored: a leftover folder costs disk space, not work. +#[cfg(not(target_arch = "wasm32"))] +fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) { + let Ok(entries) = std::fs::read_dir(base) else { return }; + for entry in entries.flatten() { + if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age); + if meta.is_dir() && old { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + /// 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(".mcmat") { @@ -623,6 +685,7 @@ impl Session { for name in old_names.iter().filter(|name| !used_names.contains(name)) { session.doc.resources.remove(name); + session.doc.project.resource_sources.remove(name); } Ok(names) @@ -711,4 +774,82 @@ mod tests { assert_eq!(typed(&p, &json!("#+f+f+f")), None); assert!(typed(&p, &json!("#ff8000")).is_some()); } + + #[cfg(not(target_arch = "wasm32"))] + fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A file another user planted at the old, guessable `/` is never written through. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_is_not_written_through_a_planted_link() { + let base = scratch("planted"); + let victim = base.join("victim.txt"); + std::fs::write(&victim, b"precious").unwrap(); + // The old code wrote `/` with `fs::write`; a hard link there reaches the victim on every platform. + std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap(); + + let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap(); + + assert_eq!(std::fs::read(&victim).unwrap(), b"precious"); + assert_eq!(std::fs::read(&path).unwrap(), b"package"); + assert_ne!(path.parent().unwrap(), base, "the file is inside a folder of its own"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Every hand-off gets its own empty-until-written folder, even when the name repeats. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_packages_get_distinct_folders() { + let base = scratch("distinct"); + let a = super::stage_handoff_package_in(&base, "m.mcraft", b"a").unwrap(); + let b = super::stage_handoff_package_in(&base, "m.mcraft", b"b").unwrap(); + assert_ne!(a.parent(), b.parent()); + assert_eq!((std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()), (b"a".to_vec(), b"b".to_vec())); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + assert_eq!(std::fs::metadata(&a).unwrap().permissions().mode() & 0o777, 0o600); + } + std::fs::remove_dir_all(&base).unwrap(); + } + + /// A name with a path in it cannot leave the new folder. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_rejects_names_that_are_paths() { + let base = scratch("names"); + for bad in ["", "..", "a/b.mcraft", "../x.mcraft"] { + assert!(super::stage_handoff_package_in(&base, bad, b"x").is_err(), "{bad}"); + } + assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "a rejected name leaves nothing behind"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Old hand-off folders are swept; young ones, other folders and files stay. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_sweep_removes_only_old_handoff_folders() { + let base = scratch("sweep"); + let old = base.join("texturecraft-open-old"); + let other = base.join("somebody-elses-folder"); + let file = base.join("texturecraft-open-file"); + for dir in [&old, &other] { + std::fs::create_dir(dir).unwrap(); + } + std::fs::write(&file, b"x").unwrap(); + // Zero age limit: everything with the prefix that is a folder counts as old. + super::sweep_old_handoffs(&base, std::time::Duration::ZERO); + assert!(!old.exists() && other.exists() && file.exists()); + let young = base.join("texturecraft-open-young"); + std::fs::create_dir(&young).unwrap(); + super::sweep_old_handoffs(&base, std::time::Duration::from_secs(3600)); + assert!(young.exists()); + std::fs::remove_dir_all(&base).unwrap(); + } } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index d8b1dcef..9d496630 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -70,6 +70,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); project.texture_sets.push(set); + Document { bake_meshes: Default::default(), bake_paint: BTreeMap::new(), @@ -77,6 +78,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), } } @@ -99,7 +101,7 @@ impl Session { images_used(&mini.project, root, &mut used, 0); let resources = used.into_iter().filter_map(|name| self.doc.resources.get(&name).map(|bytes| (name, Arc::clone(bytes)))).collect(); - let snapshot = texturecraft_formats::ProjectFile { + let snapshot = texturecraft_formats::ProjectFile::>> { project: mini.project, pixels: mini.pixels, baked: BTreeMap::new(), @@ -145,6 +147,7 @@ impl Session { project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), + painted_regions: Default::default(), resources, }; diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 68792d5c..1a5a95d0 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -34,17 +34,25 @@ pub fn specs() -> Vec { /// Loads an image file named in the document (relative to it): its bytes, or why not. pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; +type LocatedImage = (Vec, Option); +type LocatedLoader<'a> = &'a dyn Fn(&str) -> std::result::Result; + impl Session { /// Add `material` as a fill layer on the active texture set, loading its images with `load`. /// Returns the reply of `file.importMaterialX`. pub fn import_material(&mut self, material: Material, name: Option<&str>, load: Loader) -> Result { + self.import_material_with_sources(material, name, &|file| load(file).map(|bytes| (bytes, None))) + } + + fn import_material_with_sources(&mut self, material: Material, name: Option<&str>, load: LocatedLoader) -> Result { let mut warnings = material.warnings.clone(); let ts = self.ts(); let available = self.doc.project.texture_set(ts).map(|t| t.channel_list()).unwrap_or_default(); let mut fill = Fill { projection: Projection::Uv { scale: material.uv_tiling, rotation: 0.0, offset: [0.0, 0.0] }, ..Fill::default() }; - // Resources to add (name and encoded bytes), and their decoded images for the session. + let mut added: Vec<(String, Arc>)> = Vec::new(); let mut decoded = Vec::new(); + let mut sources = Vec::new(); let mut names: BTreeMap = BTreeMap::new(); let mut channels: Vec = Vec::new(); for (channel, value) in &material.channels { @@ -52,15 +60,17 @@ impl Session { warnings.push(format!("{} was skipped: this texture set has no such channel", channel.id())); continue; } + let source = match value { Mtlx::Constant(c) => Source::Uniform(*c), Mtlx::Image(file) => { let resource = match names.get(file) { Some(n) => n.clone(), None => { - let loaded = - load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string())); - let (bytes, image) = match loaded { + let loaded = load(file).and_then(|(bytes, source)| { + texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image, source)).map_err(|e| e.to_string()) + }); + let (bytes, image, source) = match loaded { Ok(v) => v, Err(e) => { warnings.push(format!("{} was skipped: {file}: {e}", channel.id())); @@ -69,11 +79,11 @@ impl Session { }; let leaf = file.rsplit(['/', '\\']).next().unwrap_or(file); let base = texturecraft_formats::sanitize_resource_name(leaf); - let (mut unique, mut n) = (base.clone(), 2); - while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) { - unique = format!("{n}_{base}"); - n += 1; - } + let unique = crate::resource_cmds::unique_resource_name(base, |name| { + self.doc.resources.contains_key(name) || added.iter().any(|(added_name, _)| added_name == name) + }); + + sources.extend(source.map(|source| (unique.clone(), source))); added.push((unique.clone(), Arc::new(bytes))); decoded.push((unique.clone(), crate::resource_cmds::decoded(image))); names.insert(file.clone(), unique.clone()); @@ -90,12 +100,14 @@ impl Session { let why = if warnings.is_empty() { String::new() } else { format!(" ({})", warnings.join("; ")) }; return Err(EngineError::Other(format!("file.importMaterialX: nothing to import from {:?}{why}", material.name))); } + let layer_name = name.map(str::to_string).unwrap_or_else(|| self.doc.project.next_layer_name(ts, &material.name)); let resource_names: Vec = added.iter().map(|(n, _)| n.clone()).collect(); let id = self.edit("Import MaterialX material", |s| { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels)) })?; @@ -119,34 +131,42 @@ fn import(s: &mut Session, p: &Value) -> Result { if !meta.is_file() || meta.len() > texturecraft_formats::materialx_read::MAX_BYTES as u64 { return Err(bad(cmd, format!("{path} is not a MaterialX file of a readable size"))); } + let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?; let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?; - let load = |file: &str| -> std::result::Result, String> { - // `` stands for a tile number; the first tile is read. + let load = |file: &str| -> std::result::Result { + // Import the first tile of a UDIM image let file = file.replace("", "1001"); let rel = Path::new(&file); let outside = "the file is outside the material's folder"; if rel.is_absolute() || rel.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) { return Err(outside.into()); } + let full = dir.join(rel).canonicalize().map_err(|e| e.to_string())?; if !full.starts_with(&dir) { return Err(outside.into()); } + let meta = std::fs::metadata(&full).map_err(|e| e.to_string())?; - // A pipe or device in the folder would block the read (a pipe reports no length). + + // Avoid blocking on pipes and devices if !meta.is_file() { return Err("it is not a regular file".into()); } + let len = meta.len(); if len > crate::resource_cmds::MAX_BYTES as u64 { return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20)); } - std::fs::read(&full).map_err(|e| e.to_string()) + + let source = full.to_str().map(crate::resource_update_cmds::file_source); + let bytes = std::fs::read(&full).map_err(|e| e.to_string())?; + Ok((bytes, source)) }; - s.import_material(material, strp(p, "name"), &load) + s.import_material_with_sources(material, strp(p, "name"), &load) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/mesh_map_sampler.rs b/crates/engine/src/mesh_map_sampler.rs new file mode 100644 index 00000000..e11207d1 --- /dev/null +++ b/crates/engine/src/mesh_map_sampler.rs @@ -0,0 +1,79 @@ +//! Sample image resources into a mesh-map atlas or compare them with an existing atlas. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_compose::ImageRes; +use texturecraft_core::{BakedMap, NormalFormat, TileGrid, udim_at}; + +use crate::commands::bad; +use crate::{Result, Session}; + +pub(crate) struct MeshMapSampler<'a> { + width: u32, + height: u32, + components: usize, + flip_green: bool, + grid: Option, + first: &'a ImageRes, + images: &'a BTreeMap>, +} + +impl<'a> MeshMapSampler<'a> { + pub(crate) fn new(session: &Session, cmd: &str, texture_set: usize, map: BakedMap, images: &'a BTreeMap>) -> Result { + let set = session.doc.project.texture_set(texture_set)?; + let grid = set.tile_grid(); + if let Some(tile) = 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) = crate::meshmap_cmds::image_map_size(session, cmd, texture_set)?; + let first = images.values().next().ok_or_else(|| bad(cmd, "no image to use"))?; + + // Both tangent-space normal maps follow the project's green-channel convention + let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX; + Ok(Self { width, height, components: map.components(), flip_green, grid, first, images }) + } + + fn row(&self, y: usize) -> impl Iterator + '_ { + let v = (y as f32 + 0.5) / self.height as f32; + (0..self.width).map(move |x| { + let u = (x as f32 + 0.5) / self.width as f32; + let mut pixel = match self.grid { + None => self.first.sample(u, v), + Some(grid) => { + let uv = grid.from_atlas([u, v]); + udim_at(uv).and_then(|tile| self.images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) + } + }; + if self.flip_green { + pixel[1] = 1.0 - pixel[1]; + } + + pixel + }) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn matches(&self, current: &[f32]) -> bool { + let row_len = self.width as usize * self.components; + current.len() == row_len * self.height as usize + && current + .par_chunks_exact(row_len) + .enumerate() + .all(|(y, row)| row.chunks_exact(self.components).zip(self.row(y)).all(|(stored, sampled)| stored == &sampled[..self.components])) + } + + pub(crate) fn render(&self) -> (u32, Vec) { + let row_len = self.width as usize * self.components; + let mut pixels = vec![0.0; row_len * self.height as usize]; + pixels.par_chunks_exact_mut(row_len).enumerate().for_each(|(y, row)| { + for (output, sampled) in row.chunks_exact_mut(self.components).zip(self.row(y)) { + output.copy_from_slice(&sampled[..self.components]); + } + }); + + (self.width, pixels) + } +} diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..1db13ac5 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -4,10 +4,9 @@ use std::collections::BTreeMap; use std::sync::Arc; -use rayon::prelude::*; use serde_json::{Value, json}; use texturecraft_compose::{ImageRes, ImageStore}; -use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat, UDIM_RANGE, udim_at}; +use texturecraft_core::{BakedMap, MAX_RESOLUTION, Project, UDIM_RANGE}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::set_cmds::ts_param; @@ -45,39 +44,41 @@ fn set(s: &mut Session, p: &Value) -> Result { None => BTreeMap::from([(FIRST_TILE, image)]), }; - let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?; + let resolution = s.edit("Use image as mesh map", |s| { + let resolution = use_images(s, CMD, ts, map, &images)?; + detach_imported_sources(&mut s.doc.project, ts, |previous| previous == map); + Ok(resolution) + })?; + Ok(json!({ "map": map.id(), "resolution": resolution })) } +/// A bake, a manual assignment or a clear ends the import link but keeps the image resource +pub(crate) fn detach_imported_sources(project: &mut Project, texture_set: usize, replaced: impl Fn(BakedMap) -> bool) { + for source in project.resource_sources.values_mut() { + if source.mesh_map.is_some_and(|slot| slot.texture_set == texture_set && replaced(slot.map)) { + source.mesh_map = None; + } + } +} + /// 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}"))); - } +/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `texture_set` in the caller's edit; returns its width +pub(crate) fn use_images(session: &mut Session, command: &str, texture_set: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let (width, data) = crate::mesh_map_sampler::MeshMapSampler::new(session, command, texture_set, map, images)?.render(); - let (width, height) = image_map_size(s, cmd, ts)?; - - // Bent normals are tangent-space maps like the normal map, so both follow the project's normal format - let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && 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(); + let entry = session.doc.baked.entry(texture_set).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); + + let set = session.doc.project.texture_set_mut(texture_set)?; + set.baked.insert(map); + + // Imported pixels have no bake provenance + set.bake_sources.remove(&map); + Ok(width) } @@ -133,39 +134,26 @@ fn udim_in(name: &str) -> Option { }) } -/// `w` × `h` texels of `comps` values each from `sample` (atlas UV → RGBA), as stored in the -/// file (mesh maps hold data, not colors, so nothing is linearized); `flip_green` reads a -/// DirectX normal or bent normal map. -fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Vec { - let mut out = vec![0.0; w as usize * h as usize * comps]; - out.par_chunks_mut(w as usize * comps).enumerate().for_each(|(y, row)| { - let v = (y as f32 + 0.5) / h as f32; - for (x, texel) in row.chunks_exact_mut(comps).enumerate() { - let mut c = sample((x as f32 + 0.5) / w as f32, v); - if flip_green { - c[1] = 1.0 - c[1]; - } - for (o, c) in texel.iter_mut().zip(c) { - *o = c; - } - } - }); - out -} - -fn clear(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.meshMap.clear"; - 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.id()))); +fn clear(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.meshMap.clear"; + let texture_set = ts_param(session, params, COMMAND)?; + let map = map_param(params, COMMAND)?; + if !session.doc.baked.get(&texture_set).is_some_and(|baked| baked.maps.contains_key(&map)) { + return Err(bad(COMMAND, format!("texture set {texture_set} has no {} map", map.id()))); } - s.edit("Clear mesh map", |s| { - if let Some(b) = s.doc.baked.get_mut(&ts) { - b.maps.remove(&map); + + session.edit("Clear mesh map", |session| { + if let Some(baked) = session.doc.baked.get_mut(&texture_set) { + baked.maps.remove(&map); } - s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + + let set = session.doc.project.texture_set_mut(texture_set)?; + set.baked.remove(&map); + set.bake_sources.remove(&map); + detach_imported_sources(&mut session.doc.project, texture_set, |previous| previous == map); + Ok(()) })?; + Ok(Value::Null) } diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 20913de2..b99af08b 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -4,12 +4,13 @@ use std::collections::BTreeMap; use std::path::Path; use serde_json::{Value, json}; -use texturecraft_core::BakedMap; +use texturecraft_core::{BakedMap, MeshMapSlot, ResourceSource}; 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::resource_update_cmds::file_source; use crate::{Result, Session, cmd}; const CMD: &str = "textureSet.meshMap.import"; @@ -84,11 +85,20 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result() as u64; let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + + // The slot follows only its latest file + for earlier in s.doc.project.resource_sources.values_mut().filter(|earlier| earlier.mesh_map == Some(slot)) { + earlier.mesh_map = None; + } + s.doc.project.resource_sources.insert(name.clone(), source); + 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()); @@ -98,7 +108,8 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result Vec { shapes.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image).collect() } +/// Points the stored paths of `kind` that paint with image resource `from` (as mask image or brush alpha) at `to` +pub(crate) fn rename_path_images(kind: &mut EffectKind, from: &str, to: &str) { + let EffectKind::Path(shapes) = kind else { return }; + + for shape in shapes { + for pointer in ["/mask_image", "/brush/alpha_image"] { + if let Some(image) = shape.paint.pointer_mut(pointer) + && image.as_str() == Some(from) + { + *image = serde_json::Value::String(to.to_string()); + } + } + } +} + /// 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(); @@ -925,28 +940,28 @@ impl Session { } /// [`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)> { + fn repaint_path(&mut self, effect_id: 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) => { + let painted = match self.put_path(effect_id, index, shape) { + Ok(report) => report, + Err(error) => { self.doc = before; - return Err(e); + return Err(error); } }; // 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); + let set = project.effect(effect_id).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); + let tiles = changed_tiles(&before.pixels, &self.doc.pixels, effect_id); + self.mark_painted(self.ts(), Some(PaintTarget::Layer(effect_id)), tiles); } else { self.invalidate_changed(&before); } - self.revision = self.revision.wrapping_add(1); - self.modified = true; + + self.mark_modified(); Ok((painted, before)) } diff --git a/crates/engine/src/pbr_cmds.rs b/crates/engine/src/pbr_cmds.rs index d5b3d4aa..0abe090c 100644 --- a/crates/engine/src/pbr_cmds.rs +++ b/crates/engine/src/pbr_cmds.rs @@ -80,6 +80,9 @@ pub fn specs() -> Vec { pub type FileList = Vec<(String, u64)>; /// Reads a file of the list by name. pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; +/// The file on disk a file of the list is read from (None: an archive entry or bytes in memory), +/// asked right before reading it. +type Locator<'a> = &'a dyn Fn(&str) -> Option; mod pbr_options; mod take; @@ -137,10 +140,16 @@ impl Session { /// Import the maps found among `files` as one fill layer on the active texture set; `load` /// reads a file by name. Returns the reply of `file.importPbrFolder`. pub fn import_pbr(&mut self, files: &FileList, load: Loader, options: &PbrOptions) -> Result { - self.import_pbr_with_budget(files, load, options, import_memory_budget()) + self.import_pbr_with_budget(files, load, &|_| None, options, import_memory_budget()) } - fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, options: &PbrOptions, memory_budget: u64) -> Result { + /// [`Session::import_pbr`] that records the disk files `locate` names, so the Resources Updater can read them again + #[cfg(not(target_arch = "wasm32"))] + fn import_pbr_located(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions) -> Result { + self.import_pbr_with_budget(files, load, locate, options, import_memory_budget()) + } + + fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions, memory_budget: u64) -> Result { let set = detect_with(files, &options.choose)?; if set.is_empty() { return Err(EngineError::Other(format!( @@ -193,6 +202,10 @@ impl Session { let mut fill = Fill { projection: options.projection.clone(), ..Fill::default() }; let mut added: Vec<(String, Arc>)> = Vec::new(); let mut decoded = Vec::new(); + + // Disk files read by name, and the resources that hold one of them unchanged + let mut file_sources: BTreeMap = BTreeMap::new(); + let mut resource_sources: Vec<(String, texturecraft_core::ResourceSource)> = Vec::new(); let mut channels: Vec = Vec::new(); let mut total_texels = 0u64; let mut retained_bytes = 0u64; @@ -231,6 +244,9 @@ impl Session { let loaded = if allowed_texels == 0 { Err("not enough memory is available to import more textures".to_string()) } else { + if let Some(source) = locate(&file) { + file_sources.insert(file.clone(), source); + } load(&file).and_then(|bytes| { if bytes.len() as u64 > MAX_FILE_BYTES { return Err(format!("the file is over {} MB", MAX_FILE_BYTES >> 20)); @@ -288,10 +304,15 @@ impl Session { } }; let base = texturecraft_formats::sanitize_resource_name(&resource_name); - let (mut unique, mut suffix_index) = (base.clone(), 2); - while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) { - unique = format!("{suffix_index}_{base}"); - suffix_index += 1; + let unique = crate::resource_cmds::unique_resource_name(base, |name| { + self.doc.resources.contains_key(name) || added.iter().any(|(added_name, _)| added_name == name) + }); + + // Only a resource holding the file's own bytes can be compared with it later + if take == Take::Whole + && let Some(source) = file_sources.get(&file) + { + resource_sources.push((unique.clone(), source.clone())); } added.push((unique.clone(), resource_bytes)); @@ -316,6 +337,7 @@ impl Session { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(resource_sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name.clone(), LayerKind::Fill(fill), &channels)) })?; @@ -420,7 +442,12 @@ fn import(s: &mut Session, p: &Value) -> Result { if options.name.is_none() { options.name = found.name.clone(); } - s.import_pbr(&found.files, &|name| found.load(name), &options) + s.import_pbr_located( + &found.files, + &|name| found.load(name), + &|name| found.disk_path(name).map(|path| crate::resource_update_cmds::file_source(&path)), + &options, + ) } #[cfg(not(target_arch = "wasm32"))] @@ -462,7 +489,7 @@ mod tests { let mut session = Session::new_project("test", crate::geom::primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); let load = |_: &str| Ok(bytes.clone()); - let result = session.import_pbr_with_budget(&files, &load, &PbrOptions::default(), 64); + let result = session.import_pbr_with_budget(&files, &load, &|_| None, &PbrOptions::default(), 64); assert!(result.unwrap_err().to_string().contains("more than 1 texels")); assert!(session.doc.resources.is_empty()); @@ -471,7 +498,7 @@ mod tests { assert_eq!(allowed_source_texels(256, 64, 3), 2); let never_load = |_: &str| -> std::result::Result, String> { panic!("no source should load after the budget is spent") }; - let result = session.import_pbr_with_budget(&files, &never_load, &PbrOptions::default(), 0); + let result = session.import_pbr_with_budget(&files, &never_load, &|_| None, &PbrOptions::default(), 0); assert!(result.unwrap_err().to_string().contains("not enough memory")); } diff --git a/crates/engine/src/pbr_cmds/native/found.rs b/crates/engine/src/pbr_cmds/native/found.rs index 454203a6..8b9adafc 100644 --- a/crates/engine/src/pbr_cmds/native/found.rs +++ b/crates/engine/src/pbr_cmds/native/found.rs @@ -11,6 +11,16 @@ pub(in crate::pbr_cmds) struct Found { } impl Found { + /// The file on disk `name` is read from (None for an archive entry or a name not in the list) + pub(in crate::pbr_cmds) fn disk_path(&self, name: &str) -> Option { + let path = match &self.source { + Origin::Folder { root } => root.join(name), + Origin::Files(paths) => paths.iter().find(|p| p.file_name().is_some_and(|n| n.to_string_lossy() == name))?.clone(), + Origin::Zip(_) => return None, + }; + path.to_str().map(str::to_string) + } + /// Reads one file of the list. Archive entries are read through a limit, since their /// declared size can lie. pub(in crate::pbr_cmds) fn load(&self, name: &str) -> std::result::Result, String> { diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index 73152301..9395ae2d 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -2,17 +2,19 @@ //! dialog's Output templates tab list, read, save and remove. On the desktop the user presets //! are mirrored as `.json` files in a library folder (see [`Session::load_export_presets`]). +use std::borrow::Cow; use std::collections::HashSet; use serde_json::{Value, json}; use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem}; -use texturecraft_formats::{ExportPreset, builtin_preset, builtin_presets, preset_from_json}; +use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::{Result, Session, cmd}; /// Most user presets kept (and read from the library folder). const MAX_USER_PRESETS: usize = 512; +const BUILTIN_PRESET_PREFIX: &str = "builtin:"; /// The user's export presets. #[derive(Clone, Debug, Default)] @@ -51,6 +53,16 @@ fn same_name(a: &str, b: &str) -> bool { a.trim().eq_ignore_ascii_case(b.trim()) } +/// A qualified selector names a built-in independently of a saved library entry. +pub fn unqualified_preset_name(name: &str) -> &str { + let mut name = name.trim(); + while name.get(..BUILTIN_PRESET_PREFIX.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(BUILTIN_PRESET_PREFIX)) { + name = &name[BUILTIN_PRESET_PREFIX.len()..]; + } + + name +} + /// Library file stem: two names with the same stem would share a file. fn file_key(name: &str) -> String { sanitize_file_stem(name.trim()).to_ascii_lowercase() @@ -63,8 +75,25 @@ impl UserPresets { /// `name` belongs to a built-in or to a user preset other than `skip` (or shares its file). fn taken(&self, name: &str, skip: Option) -> bool { - builtin_preset(name).is_some() - || self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name))) + let keeps_name = skip.and_then(|index| self.list.get(index)).is_some_and(|preset| same_name(&preset.name, name)); + (!keeps_name && builtin_preset(unqualified_preset_name(name)).is_some()) || self.user_name_taken(name, skip) + } + + fn user_name_taken(&self, name: &str, skip: Option) -> bool { + let key = file_key(name); + self.list.iter().enumerate().any(|(i, preset)| Some(i) != skip && (same_name(&preset.name, name) || file_key(&preset.name) == key)) + } + + /// Restore a saved preset under the name existing settings use. + pub fn restore(&mut self, preset: ExportPreset) -> std::result::Result<(), String> { + preset.validate().map_err(|error| error.to_string())?; + let reserved = builtin_preset(&preset.name).is_some_and(|builtin| !NEW_BUILTIN_PRESET_NAMES.contains(&builtin.name.as_str())); + if reserved || self.user_name_taken(&preset.name, None) || self.list.len() >= MAX_USER_PRESETS { + return Err(format!("preset \"{}\" exists already or the library is full", preset.name)); + } + + self.list.push(preset); + Ok(()) } /// The first available name, adding a numbered suffix and shortening the base to fit. @@ -119,7 +148,21 @@ impl UserPresets { impl Session { /// A built-in or user export preset by name (case-insensitive). pub fn export_preset(&self, name: &str) -> Option { - builtin_preset(name).or_else(|| self.export_presets.find(name).and_then(|i| self.export_presets.list.get(i).cloned())) + self.export_presets.find(name).and_then(|index| self.export_presets.list.get(index).cloned()).or_else(|| builtin_preset(unqualified_preset_name(name))) + } + + pub fn has_user_export_preset(&self, name: &str) -> bool { + self.export_presets.find(name).is_some() + } + + /// Use the familiar built-in name unless the user's library already owns that selector. + pub fn builtin_export_preset_id<'a>(&self, name: &'a str) -> Cow<'a, str> { + let mut id = Cow::Borrowed(name); + while self.has_user_export_preset(&id) { + id = Cow::Owned(format!("{BUILTIN_PRESET_PREFIX}{id}")); + } + + id } /// Use `dir` as the user preset library: read its `*.json` presets (replacing the list) and @@ -133,10 +176,8 @@ impl Session { files.sort(); let mut lib = UserPresets { list: Vec::new(), dir: Some(dir) }; for path in files.into_iter().take(MAX_USER_PRESETS) { - match texturecraft_formats::load_preset(&path).map_err(|e| e.to_string()) { - Ok(p) if lib.taken(&p.name, None) => warnings.push(format!("{}: preset \"{}\" exists already", path.display(), p.name)), - Ok(p) => lib.list.push(p), - Err(e) => warnings.push(format!("{}: {e}", path.display())), + if let Err(error) = texturecraft_formats::load_preset(&path).map_err(|error| error.to_string()).and_then(|preset| lib.restore(preset)) { + warnings.push(format!("{}: {error}", path.display())); } } self.export_presets = lib; @@ -144,10 +185,12 @@ impl Session { } } -fn list(s: &mut Session, _: &Value) -> Result { - let entry = |p: &ExportPreset, builtin: bool| json!({"name": p.name, "maps": p.maps.len(), "builtin": builtin}); - let builtins = builtin_presets(); - Ok(json!(builtins.iter().map(|p| entry(p, true)).chain(s.export_presets.list.iter().map(|p| entry(p, false))).collect::>())) +fn list(session: &mut Session, _: &Value) -> Result { + let entry = |name: &str, maps: usize, builtin: bool| json!({"name": name, "maps": maps, "builtin": builtin}); + let builtins = builtin_preset_catalog().iter().map(|preset| entry(&session.builtin_export_preset_id(&preset.name), preset.maps.len(), true)); + let custom = session.export_presets.list.iter().map(|preset| entry(&preset.name, preset.maps.len(), false)); + + Ok(json!(builtins.chain(custom).collect::>())) } fn name_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> { @@ -216,11 +259,16 @@ fn save(session: &mut Session, params: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { const CMD: &str = "export.preset.remove"; let name = name_param(p, CMD)?; - if builtin_preset(name).is_some() { - return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be removed"))); - } - let i = s.export_presets.find(name).ok_or_else(|| bad(CMD, format!("no user export preset `{name}`")))?; - let removed = s.export_presets.list.remove(i); + let Some(index) = s.export_presets.find(name) else { + let message = if builtin_preset(unqualified_preset_name(name)).is_some() { + format!("\"{name}\" is a built-in preset and can't be removed") + } else { + format!("no user export preset `{name}`") + }; + return Err(bad(CMD, message)); + }; + + let removed = s.export_presets.list.remove(index); s.export_presets.delete(&removed.name); Ok(Value::Null) } @@ -409,6 +457,36 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn feedback_existing_preset_keeps_its_name_and_export_maps() { + let dir = tempfile::tempdir().unwrap(); + let name = "Roblox SurfaceAppearance (separate maps)"; + let custom = preset(name); + std::fs::write(dir.path().join(format!("{}.json", sanitize_file_stem(name))), custom.to_string()).unwrap(); + let mut s = session(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); + + let warnings = s.load_export_presets(dir.path().to_path_buf()); + + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom); + let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1); + assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png")); + + let listed = run(&mut s, "export.presets", json!({})).unwrap(); + let names = listed.as_array().unwrap(); + assert!(names.iter().any(|entry| entry["name"] == name && entry["builtin"] == false)); + let builtin = format!("builtin:{name}"); + assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true)); + let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap(); + assert!(builtin_plan.as_array().unwrap().len() > 1); + run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap(); + run(&mut s, "export.preset.remove", json!({"name": name})).unwrap(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn the_library_folder_mirrors_saves_renames_and_removals() { diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index c5da6d34..a9018f4f 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -1,4 +1,4 @@ -//! Project-level commands: new project, sample project, smart materials, inspection. +//! Project-level commands: new project, rename, sample project, smart materials, inspection. use serde_json::{Value, json}; use texturecraft_compose::BakedMaps; @@ -63,16 +63,23 @@ fn new(s: &mut Session, p: &Value) -> Result { Ok(crate::inspect::session(s)) } -fn rename(s: &mut Session, p: &Value) -> Result { - let name = strp(p, "name") - .map(str::trim) - .filter(|name| !name.is_empty() && name.chars().count() <= MAX_PROJECT_NAME_CHARS && !name.chars().any(char::is_control)) - .ok_or_else(|| bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters")))?; +/// Trim and validate a proposed name without changing the project. +pub fn validate_project_name(name: &str) -> Result<&str> { + let name = name.trim(); + if name.is_empty() || name.chars().nth(MAX_PROJECT_NAME_CHARS).is_some() || name.chars().any(char::is_control) { + return Err(bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters"))); + } + + Ok(name) +} + +fn rename(session: &mut Session, params: &Value) -> Result { + let name = validate_project_name(strp(params, "name").unwrap_or_default())?; // The same name is not an undo step and leaves a saved project unmodified - if name != s.doc.project.name { - s.edit("Rename project", |s| { - s.doc.project.name = name.to_string(); + if name != session.doc.project.name { + session.edit("Rename project", |session| { + session.doc.project.name = name.to_owned(); Ok(()) })?; } diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs new file mode 100644 index 00000000..2a8902b0 --- /dev/null +++ b/crates/engine/src/reloaded_file.rs @@ -0,0 +1,44 @@ +//! An image file read again for a resource, checked before the project changes + +use texturecraft_core::ResourceSource; +use texturecraft_formats::DecodedImage; + +use crate::Result; +use crate::resource_cmds::{MAX_BYTES, read_image_file}; +use crate::resource_update_cmds::file_source; + +/// A resource's new bytes, their decoded pixels and the file they came from +pub(crate) struct ReloadedFile { + pub name: String, + pub bytes: Vec, + pub image: DecodedImage, + pub source: ResourceSource, +} + +impl ReloadedFile { + pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result { + let source = file_source(path); + let bytes = read_image_file(cmd, path, MAX_BYTES as u64)?; + + Self::decode(cmd, name, source, bytes) + } + + pub(crate) fn read_changed(cmd: &str, name: &str, previous: &ResourceSource, stored: &[u8], decoded: bool) -> Result> { + let mut source = file_source(&previous.path); + let bytes = read_image_file(cmd, &previous.path, MAX_BYTES as u64)?; + let unchanged = bytes == stored; + if unchanged && decoded { + return Ok(None); + } + + source.mesh_map = previous.mesh_map; + let file = Self::decode(cmd, name.to_owned(), source, bytes)?; + Ok((!unchanged).then_some(file)) + } + + fn decode(cmd: &str, name: String, source: ResourceSource, bytes: Vec) -> Result { + let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{}: {error}", source.path)))?; + + Ok(Self { name, bytes, image, source }) + } +} diff --git a/crates/engine/src/resource_check.rs b/crates/engine/src/resource_check.rs new file mode 100644 index 00000000..f7505daa --- /dev/null +++ b/crates/engine/src/resource_check.rs @@ -0,0 +1,23 @@ +//! A remembered comparison of a resource with its file, so an unchanged file is not read again + +use std::sync::{Arc, Weak}; + +use crate::resource_status::ResourceStatus; + +/// What reading a resource's file found, kept while the file's size and time stay the same +#[derive(Clone, Debug)] +pub(crate) struct ResourceCheck { + pub path: String, + pub size: u64, + pub modified_ms: u64, + /// The resource bytes the file was compared with (an update or undo replaces them) + pub bytes: Weak>, + pub status: ResourceStatus, +} + +impl ResourceCheck { + /// Whether this verdict still holds for the file and the resource's bytes + pub(crate) fn holds_for(&self, path: &str, size: u64, modified_ms: u64, bytes: &Arc>) -> bool { + self.path == path && self.size == size && self.modified_ms == modified_ms && std::ptr::eq(self.bytes.as_ptr(), Arc::as_ptr(bytes)) + } +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 39d9fb6c..024243c3 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -24,6 +24,16 @@ pub fn specs() -> Vec { ), cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), + cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export), + cmd!( + "resource.rename", + "Rename resource", + [], + None, + "{name, to} — everything that uses the image follows it; `to` keeps the old extension when it has none", + always, + rename + ), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), cmd!( "layer.add.image", @@ -45,6 +55,30 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb)) } +/// Disambiguate a sanitized resource name without losing its archive key on save. +pub(crate) fn unique_resource_name(base: String, taken: impl Fn(&str) -> bool) -> String { + if !taken(&base) { + return base; + } + + let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |start| base.split_at(start)); + let mut index = 2; + loop { + let discriminator = format!("{index}_"); + let available = MAX_RESOURCE_NAME_LEN - discriminator.len(); + + // An unusually long extension must leave room for the name itself + let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") }; + let stem = &stem[..stem.len().min(available - extension.len())]; + let name = format!("{discriminator}{stem}{extension}"); + if !taken(&name) { + return name; + } + + index += 1; + } +} + impl Session { /// 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 { @@ -79,19 +113,7 @@ impl Session { base.insert_str(0, &prefix); } - let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start)); - let mut name = base.clone(); - let mut duplicate_index = 2; - while self.doc.resources.contains_key(&name) || crate::fill_alpha::library_alpha_of(&name).is_some() { - let discriminator = format!("{duplicate_index}_"); - let available = MAX_RESOURCE_NAME_LEN - discriminator.len(); - - // Leave room for a stem even for names that end in an unusually long extension - let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") }; - let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem); - name = format!("{discriminator}{stem}{extension}"); - duplicate_index += 1; - } + let name = unique_resource_name(base, |name| self.doc.resources.contains_key(name) || crate::fill_alpha::library_alpha_of(name).is_some()); self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); @@ -146,6 +168,16 @@ impl Session { self.drop_missing_image_view(); } + /// Undo and redo restore resource bytes under the same name (the Resources Updater replaces + /// them in place): the pixels decoded from the bytes `other` held are stale + pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) { + for (name, bytes) in &self.doc.resources { + if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) { + self.images.remove(name); + } + } + } + /// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back pub(crate) fn drop_missing_image_view(&mut self) { if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) { @@ -172,8 +204,16 @@ 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 prefix = strp(p, "prefix").unwrap_or(""); + + let source = crate::resource_update_cmds::file_source(path); let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; + + let name = s.edit("Import resource", |session| { + let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + session.doc.project.resource_sources.insert(name.clone(), source); + Ok(name) + })?; Ok(json!({ "name": name })) } @@ -255,28 +295,146 @@ fn remove(s: &mut Session, p: &Value) -> Result { s.edit("Remove resource", |s| { s.doc.resources.remove(&name); + s.doc.project.resource_sources.remove(&name); Ok(()) })?; s.sync_images(); Ok(Value::Null) } -/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) -fn remove_unused(s: &mut Session, _: &Value) -> Result { - let mut used = Vec::new(); - for set in &s.doc.project.texture_sets { - for root in &set.stack { - crate::material_lib::images_used(&s.doc.project, *root, &mut used, 0); +/// Writes resource `name`'s bytes, as imported, to `path` +#[cfg(not(target_arch = "wasm32"))] +fn export(s: &mut Session, p: &Value) -> Result { + let command = "resource.export"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?; + let path = strp(p, "path").ok_or_else(|| bad(command, "`path` is required"))?; + let bytes = s.doc.resources.get(name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; + + std::fs::write(path, bytes.as_slice()).map_err(|error| bad(command, format!("cannot write {path}: {error}")))?; + + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.export", "file paths are not available in the browser")) +} + +/// Renames image resource `name` to `to` and every reference to it, in one undo step +fn rename(s: &mut Session, p: &Value) -> Result { + let command = "resource.rename"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string(); + let to = strp(p, "to").ok_or_else(|| bad(command, "`to` is required"))?.trim(); + if !s.doc.resources.contains_key(&name) { + return Err(bad(command, format!("no resource `{name}`"))); + } + + let mut to = sanitize_resource_name(to); + if std::path::Path::new(&to).extension().is_none() + && let Some(extension) = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()) + { + // The stem gives way, so a long name keeps its extension + let stem_room = MAX_RESOURCE_NAME_LEN.saturating_sub(extension.len() + 1); + to.truncate(stem_room); + to = format!("{to}.{extension}"); + } + if to == name { + return Ok(json!({ "name": name })); + } + if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() { + return Err(bad(command, format!("a resource named `{to}` exists already"))); + } + + s.edit("Rename resource", |s| { + let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; + s.doc.resources.insert(to.clone(), bytes); + // The Resources Updater keeps following the file the image came from + if let Some(source) = s.doc.project.resource_sources.remove(&name) { + s.doc.project.resource_sources.insert(to.clone(), source); + } + rename_references(&mut s.doc.project, &name, &to); + + // Refuse rather than leave a reference this rename does not know about pointing at nothing + if project_images(&s.doc.project).contains(&name) { + return Err(bad(command, format!("`{name}` is used somewhere it can't be renamed"))); + } + + Ok(()) + })?; + + for tool_image in s.tool_images_mut().filter(|tool_image| **tool_image == name) { + tool_image.clone_from(&to); + } + + // The decoded pixels are the same: they move instead of decoding again + if let Some(image) = s.images.remove(&name) { + s.images.insert(to.clone(), image); + } + if s.library_alphas.remove(&name) { + s.library_alphas.insert(to.clone()); + } + s.path_cache = None; + s.sync_images(); + Ok(json!({ "name": to })) +} + +/// Points every layer, effect, stored path and the environment that read image resource `from` at `to` +fn rename_references(project: &mut texturecraft_core::Project, from: &str, to: &str) { + for layer in project.layers.values_mut() { + let fill_images: Vec<&mut String> = match &mut layer.kind { + LayerKind::Fill(fill) => fill.images_mut().collect(), + _ => Vec::new(), + }; + let effects = layer.mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()).chain(&mut layer.content_effects); + let mut images = fill_images; + for effect in effects { + crate::path_tool::rename_path_images(&mut effect.kind, from, to); + images.extend(effect.images_mut()); + } + + for image in images.into_iter().filter(|image| *image == from) { + *image = to.to_string(); } } + + if project.display.environment_resource() == Some(from) { + project.display.environment = format!("{}{to}", texturecraft_core::project::ENV_RESOURCE_PREFIX); + } +} + +/// Every image resource a layer, mask effect, stored path or the environment of `project` uses +fn project_images(project: &texturecraft_core::Project) -> Vec { + let mut used = Vec::new(); + for set in &project.texture_sets { + for root in &set.stack { + crate::material_lib::images_used(project, *root, &mut used, 0); + } + } + used.extend(project.display.environment_resource().map(str::to_string)); + used +} + +/// [`project_images`] and the images the brush alpha, the projection stencil and the mask brush use +fn images_in_use(s: &Session) -> Vec { + let mut used = project_images(&s.doc.project); used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone())); used.extend(s.tool.brush.alpha_image.clone()); used.extend(s.tool.mask_image.clone()); - used.extend(s.doc.project.display.environment_resource().map(str::to_string)); + used.extend(s.doc.project.resource_sources.iter().filter_map(|(name, source)| { + let slot = source.mesh_map?; + s.doc.baked.get(&slot.texture_set).is_some_and(|baked| baked.maps.contains_key(&slot.map)).then(|| name.clone()) + })); + used +} + +/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step) +fn remove_unused(s: &mut Session, _: &Value) -> Result { + let used = images_in_use(s); let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); if !unused.is_empty() { s.edit("Remove unused resources", |s| { s.doc.resources.retain(|k, _| !unused.contains(k)); + s.doc.project.resource_sources.retain(|k, _| !unused.contains(k)); Ok(()) })?; s.sync_images(); @@ -331,6 +489,120 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + #[test] + fn export_writes_the_imported_bytes() { + let mut session = crate::sample_session(128, 32).unwrap(); + let bytes = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let name = session.import_resource_bytes("icon.png", bytes.clone()).unwrap(); + let path = std::env::temp_dir().join(format!("texturecraft-export-resource-{}.png", std::process::id())); + + crate::commands::execute(&mut session, "resource.export", &json!({"name": name, "path": path.to_str().unwrap()})).unwrap(); + + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is the resource as imported"); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn a_renamed_image_stays_in_use_everywhere_it_was() { + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let name = session.import_resource_bytes("photo.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap(); + session.tool.brush.alpha_image = Some(name.clone()); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); + + assert_ne!(renamed, name); + assert!(renamed.ends_with(".png"), "the extension stays: {renamed}"); + let used = images_in_use(&session); + assert!(used.contains(&renamed) && !used.contains(&name), "every use follows the rename: {used:?}"); + assert!(session.images.contains_key(&renamed) && !session.images.contains_key(&name)); + + session.undo().unwrap(); + + assert!(project_images(&session.doc.project).contains(&name), "undo brings the old name back"); + assert!(session.images.contains_key(&name)); + assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&name), "the brush alpha follows the undo"); + + session.redo().unwrap(); + + assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo"); + } + + #[test] + fn a_renamed_image_keeps_following_its_file() { + let path = std::env::temp_dir().join(format!("texturecraft-rename-source-{}.png", std::process::id())); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.25].into_iter()).unwrap()).unwrap(); + let mut session = crate::sample_session(128, 32).unwrap(); + let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap(); + // An equal-size file counts as changed once its time moved, as a later save's does + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap(); + let updated = crate::execute(&mut session, "resource.update", &json!({"names": [renamed]})).unwrap(); + + std::fs::remove_file(&path).unwrap(); + assert_eq!(updated["updated"], json!([renamed]), "the renamed image reads its changed file again: {updated}"); + } + + #[test] + fn renaming_a_linked_materials_package_moves_a_material_effects_link_with_it() { + use std::collections::BTreeMap; + use texturecraft_core::{Effect, EffectKind, MaterialLink}; + + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let package = session.import_resource_bytes("package.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": package})).unwrap(); + let layer_id = session.selected_layer().unwrap(); + let link = MaterialLink { + name: "linked".into(), + package: package.clone(), + graph: String::new(), + params: Vec::new(), + presets: Vec::new(), + inputs: Vec::new(), + size: 1, + resolution: None, + mapping: BTreeMap::new(), + outputs: BTreeMap::from([("basecolor".to_string(), package.clone())]), + }; + let effect_id = session.doc.project.alloc_id(); + let material = Effect::new(effect_id, EffectKind::Material(Fill { link: Some(Box::new(link)), ..Fill::default() })); + session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(material); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": package, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); + + let effect = &session.doc.project.layers[&layer_id].content_effects[0]; + let EffectKind::Material(fill) = &effect.kind else { panic!("the effect stays a material") }; + let link = fill.link.as_ref().unwrap(); + assert_ne!(renamed, package); + assert_eq!(link.package, renamed, "the link's package follows the rename"); + assert_eq!(link.outputs.values().collect::>(), [&renamed], "the link's cooked outputs follow the rename"); + } + + #[test] + fn renaming_an_image_a_generator_reads_as_its_grunge_moves_the_grunge_with_it() { + use texturecraft_core::{Effect, EffectKind, Generator, GeneratorKind}; + + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let grunge = session.import_resource_bytes("grunge.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": grunge})).unwrap(); + let layer_id = session.selected_layer().unwrap(); + let generator = Generator { grunge: Some(Source::image(grunge.clone())), ..Generator::new(GeneratorKind::EdgeWear) }; + let effect_id = session.doc.project.alloc_id(); + session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(Effect::new(effect_id, EffectKind::Generator(generator))); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": grunge, "to": "worn"})).unwrap()["name"].as_str().unwrap().to_string(); + + let EffectKind::Generator(generator) = &session.doc.project.layers[&layer_id].content_effects[0].kind else { panic!("the effect stays a generator") }; + assert_ne!(renamed, grunge); + assert_eq!(generator.grunge, Some(Source::image(renamed)), "the generator's grunge follows the rename"); + } + #[test] fn file_reads_obey_the_remaining_byte_budget() { let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs new file mode 100644 index 00000000..2e33cb63 --- /dev/null +++ b/crates/engine/src/resource_state.rs @@ -0,0 +1,16 @@ +//! One row of the Resources Updater: an image resource, its file and how they compare + +use crate::resource_status::ResourceStatus; + +/// An image resource, the file it came from and whether that file changed on disk +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResourceState { + /// The resource's name in the project. + pub name: String, + /// How the resource compares with its file now. + pub status: ResourceStatus, + /// The file it was imported from or relinked to (None: made in the app or imported without a path). + pub path: Option, + /// Why the file could not be checked (with [`ResourceStatus::Missing`]). + pub error: Option, +} diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs new file mode 100644 index 00000000..fc5273d6 --- /dev/null +++ b/crates/engine/src/resource_status.rs @@ -0,0 +1,44 @@ +//! Whether a resource still matches the file it was imported from + +/// How a resource compares with its file on disk (materials have none). The order is the Resources Updater's +/// list order: what needs attention first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ResourceStatus { + /// The file changed since it was read: Update reads it again. + Outdated, + /// The file is gone, or cannot be read. + Missing, + /// The file still holds the resource's bytes. + UpToDate, + /// Made in the app or imported without a file path: there is nothing to compare with. + NoSource, + /// A linked MaterialCraft package stored in the project, without a source file to compare. + Material, +} + +impl ResourceStatus { + pub const ALL: [ResourceStatus; 5] = + [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource, ResourceStatus::Material]; + + /// The id used by the control protocol + pub fn id(self) -> &'static str { + match self { + ResourceStatus::Outdated => "outdated", + ResourceStatus::Missing => "missing", + ResourceStatus::UpToDate => "upToDate", + ResourceStatus::NoSource => "noSource", + ResourceStatus::Material => "material", + } + } + + /// The name shown in the Resources Updater (English; the shell translates it) + pub fn label(self) -> &'static str { + match self { + ResourceStatus::Outdated => "Outdated", + ResourceStatus::Missing => "Missing", + ResourceStatus::UpToDate => "Up to date", + ResourceStatus::NoSource => "No source file", + ResourceStatus::Material => "Material", + } + } +} diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs new file mode 100644 index 00000000..af29e4da --- /dev/null +++ b/crates/engine/src/resource_update_cmds.rs @@ -0,0 +1,395 @@ +//! The Resources Updater: compare image resources with the files they came from, read changed +//! files again and point a resource at another file. Each change is one undo step, and every +//! layer, mask and view using a changed resource recomposites; a mesh map imported from a changed +//! file is resampled while it still holds what the file gave it. + +use serde_json::{Value, json}; +use texturecraft_core::ResourceSource; + +use crate::commands::{CommandSpec, always, bad}; +use crate::resource_state::ResourceState; +use crate::resource_status::ResourceStatus; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "resource.status", + "Check resources on disk", + [], + None, + "{} → {resources: [{name, status: outdated|missing|upToDate|noSource|material, path?, error?}] (outdated first; material: a stored MaterialCraft package), total, outdated}", + always, + |s, _| Ok(status(s)) + ), + cmd!( + "resource.update", + "Update resources", + [], + None, + "{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step", + always, + update + ), + cmd!( + "resource.relink", + "Relink resource", + [], + None, + "{name: image resource, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", + always, + relink + ), + ] +} + +impl Session { + /// Project images and linked MaterialCraft packages, ordered by status and then by name. + /// Equal-size files are compared when their modification time changed or is unknown. + /// A known time lets later checks reuse the verdict. + pub fn resource_states(&mut self) -> Vec { + let mut states = self.compare_resources(); + let materials = self.material_packages().into_iter(); + states.extend(materials.map(|name| ResourceState { name, status: ResourceStatus::Material, path: None, error: None })); + states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); + states + } + + /// The packages of linked MaterialCraft materials (fill layers and material effects) the project holds + fn material_packages(&self) -> std::collections::BTreeSet { + use texturecraft_core::{EffectKind, Fill, LayerKind}; + + let package_of = |fill: &Fill| fill.link.as_ref().map(|link| link.package.clone()); + let mut packages = std::collections::BTreeSet::new(); + for layer in self.doc.project.layers.values() { + if let LayerKind::Fill(fill) = &layer.kind { + packages.extend(package_of(fill)); + } + for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + if let EffectKind::Material(fill) = &effect.kind { + packages.extend(package_of(fill)); + } + } + } + + packages.retain(|name| self.doc.resources.contains_key(name)); + packages + } + + /// Whether `name` is an image resource the Resources Updater lists + fn is_image_resource(&self, name: &str) -> bool { + self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name)) + } + + #[cfg(not(target_arch = "wasm32"))] + fn compare_resources(&mut self) -> Vec { + let mut checks = std::mem::take(&mut self.resource_checks); + let names: Vec = self.doc.resources.keys().filter(|name| self.is_image_resource(name)).cloned().collect(); + let mut states = Vec::with_capacity(names.len()); + for name in names { + let (Some(bytes), source) = (self.doc.resources.get(&name), self.doc.project.resource_sources.get(&name)) else { continue }; + let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(&name, source, bytes, &mut checks)); + states.push(ResourceState { path: source.map(|source| source.path.clone()), name, status, error }); + } + + checks.retain(|name, _| self.doc.resources.contains_key(name)); + self.resource_checks = checks; + states + } + + #[cfg(target_arch = "wasm32")] + fn compare_resources(&mut self) -> Vec { + let sources = &self.doc.project.resource_sources; + let browser = "file paths are not available in the browser"; + let names = self.doc.resources.keys().filter(|name| self.is_image_resource(name)); + names + .map(|name| match sources.get(name) { + Some(source) => { + ResourceState { name: name.clone(), status: ResourceStatus::Missing, path: Some(source.path.clone()), error: Some(browser.into()) } + } + None => ResourceState { name: name.clone(), status: ResourceStatus::NoSource, path: None, error: None }, + }) + .collect() + } + + /// Stream changed files into one undo step. A mesh map is compared before its first tile is replaced. + #[cfg(not(target_arch = "wasm32"))] + fn install_reloaded(&mut self, label: &str, files: impl Iterator) -> Result> { + let mut files = files.peekable(); + if files.peek().is_none() { + return Ok(Vec::new()); + } + + let mut updated = Vec::new(); + let result = self.edit(label, |session| { + let mut slots = std::collections::BTreeMap::new(); + for file in files { + if let Some(slot) = file.source.mesh_map { + slots.entry((slot.texture_set, slot.map)).or_insert_with(|| session.mesh_map_matches(slot.texture_set, slot.map)); + } + + let name = file.name; + if crate::fill_alpha::matches_saved_picture(&name, &file.image) { + session.library_alphas.insert(name.clone()); + } else { + session.library_alphas.remove(&name); + } + + session.images.insert(name.clone(), crate::resource_cmds::decoded(file.image)); + session.doc.resources.insert(name.clone(), std::sync::Arc::new(file.bytes)); + session.doc.project.resource_sources.insert(name.clone(), file.source); + updated.push(name); + } + + for ((texture_set, map), matches) in slots { + if matches { + let images = session.mesh_map_images(texture_set, map).ok_or_else(|| bad("resource.update", "a mesh map source image is missing"))?; + crate::meshmap_cmds::use_images(session, "resource.update", texture_set, map, &images)?; + } + } + Ok(()) + }); + + if let Err(error) = result { + // The edit restored the encoded bytes, so rebuild any cache entries replaced before rollback + for name in &updated { + self.images.remove(name); + } + self.sync_images(); + return Err(error); + } + + Ok(updated) + } + + #[cfg(not(target_arch = "wasm32"))] + fn mesh_map_images( + &self, + texture_set: usize, + map: texturecraft_core::BakedMap, + ) -> Option>> { + let mut images = std::collections::BTreeMap::new(); + for (name, source) in &self.doc.project.resource_sources { + if let Some(slot) = source.mesh_map.filter(|slot| slot.texture_set == texture_set && slot.map == map) { + images.insert(slot.tile, self.images.get(name)?.clone()); + } + } + + Some(images) + } + + #[cfg(not(target_arch = "wasm32"))] + fn mesh_map_matches(&self, texture_set: usize, map: texturecraft_core::BakedMap) -> bool { + let Some(current) = self.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)) else { return false }; + let Some(images) = self.mesh_map_images(texture_set, map) else { return false }; + + crate::mesh_map_sampler::MeshMapSampler::new(self, "resource.update", texture_set, map, &images).is_ok_and(|sampler| sampler.matches(current)) + } +} + +/// How `stored` (a resource's bytes) compares with the file `source` names now, reusing the +/// remembered verdict in `checks` while the file's size and time stay the same +#[cfg(not(target_arch = "wasm32"))] +fn compare_with_file( + name: &str, + source: &ResourceSource, + stored: &std::sync::Arc>, + checks: &mut std::collections::HashMap, +) -> (ResourceStatus, Option) { + let path = std::path::Path::new(&source.path); + let metadata = match std::fs::metadata(path) { + Ok(metadata) if metadata.is_file() => metadata, + Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))), + Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))), + }; + + let size = metadata.len(); + if size != stored.len() as u64 { + return (ResourceStatus::Outdated, None); + } + + let modified_ms = modified_ms(&metadata); + if modified_ms != 0 && modified_ms == source.modified_ms { + return (ResourceStatus::UpToDate, None); + } + + if let Some(check) = checks.get(name) + && check.holds_for(&source.path, size, modified_ms, stored) + { + return (check.status, None); + } + + // A newer time alone is not a change: the file may have been saved again unchanged + let status = match file_matches(path, stored) { + Ok(true) => ResourceStatus::UpToDate, + Ok(false) => ResourceStatus::Outdated, + Err(error) => return (ResourceStatus::Missing, Some(error.to_string())), + }; + if modified_ms == 0 { + // An unknown time cannot establish that the next check sees the same file contents + checks.remove(name); + } else { + let bytes = std::sync::Arc::downgrade(stored); + checks.insert(name.to_string(), crate::resource_check::ResourceCheck { path: source.path.clone(), size, modified_ms, bytes, status }); + } + + (status, None) +} + +/// Compare without allocating a second copy of the resource. Read to the checked end to detect I/O errors and growth. +#[cfg(not(target_arch = "wasm32"))] +fn file_matches(path: &std::path::Path, stored: &[u8]) -> Result { + use std::io::{ErrorKind, Read}; + + const CMD: &str = "resource.status"; + const CHUNK_BYTES: usize = 32 * 1024; + let read_error = |error| bad(CMD, format!("cannot read {}: {error}", path.display())); + let too_large = || bad(CMD, format!("{} is too large (limit {} bytes)", path.display(), crate::resource_cmds::MAX_BYTES)); + let mut file = crate::resource_cmds::open_resource_file(CMD, path)?; + let len = file.metadata().map_err(read_error)?.len(); + if len > crate::resource_cmds::MAX_BYTES as u64 { + return Err(too_large()); + } + + let mut chunk = [0; CHUNK_BYTES]; + let mut equal = len == stored.len() as u64; + for start in (0..len as usize).step_by(CHUNK_BYTES) { + let end = (start + CHUNK_BYTES).min(len as usize); + let part = &mut chunk[..end - start]; + match file.read_exact(part) { + Ok(()) => equal = equal && stored.get(start..end) == Some(part), + Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(false), + Err(error) => return Err(read_error(error)), + } + } + + if file.read(&mut [0]).map_err(read_error)? > 0 { + return Err(too_large()); + } + + Ok(equal) +} + +/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none) +#[cfg(not(target_arch = "wasm32"))] +fn modified_ms(metadata: &std::fs::Metadata) -> u64 { + let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok()); + since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) +} + +/// The record for an image about to be read from `path`: its absolute path and its current +/// modification time, taken before reading so a write during the read still shows as a change +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn file_source(path: &str) -> ResourceSource { + let absolute = std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()); + let modified_ms = std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)); + ResourceSource { path: absolute, modified_ms, mesh_map: None } +} + +/// The browser reads no paths; the record keeps the name it was given +#[cfg(target_arch = "wasm32")] +pub(crate) fn file_source(path: &str) -> ResourceSource { + ResourceSource { path: path.to_string(), modified_ms: 0, mesh_map: None } +} + +fn status(s: &mut Session) -> Value { + let states = s.resource_states(); + let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count(); + let resources: Vec = states + .iter() + .map(|state| { + let mut row = json!({"name": state.name, "status": state.status.id()}); + if let Some(path) = &state.path { + row["path"] = json!(path); + } + if let Some(error) = &state.error { + row["error"] = json!(error); + } + + row + }) + .collect(); + + json!({"resources": resources, "total": states.len(), "outdated": outdated}) +} + +#[cfg(not(target_arch = "wasm32"))] +fn update(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.update"; + + let names: Vec = match p.get("names") { + None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(), + Some(Value::Array(names)) => { + names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::>()? + } + Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")), + }; + + // Validate the complete selection before opening files + let mut selected = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for name in names { + let bytes = s.doc.resources.get(&name).ok_or_else(|| bad(CMD, format!("no resource `{name}`")))?; + let Some(source) = s.doc.project.resource_sources.get(&name) else { + let reason = if s.images.contains_key(&name) { + format!("`{name}` has no source file: relink it to a file first") + } else { + format!("`{name}` has no source file: only image resources can be relinked") + }; + return Err(bad(CMD, reason)); + }; + + if seen.insert(name.clone()) { + let decoded = s.images.contains_key(&name); + selected.push((name, source.clone(), bytes.clone(), decoded)); + } + } + + let mut failed = Vec::new(); + let files = selected.into_iter().filter_map(|(name, source, stored, decoded)| { + match crate::reloaded_file::ReloadedFile::read_changed(CMD, &name, &source, &stored, decoded) { + Ok(file) => file, + Err(error) => { + failed.push(json!({"name": name, "error": error.to_string()})); + None + } + } + }); + let updated = s.install_reloaded("Update resources", files)?; + + if updated.is_empty() && !failed.is_empty() { + let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect(); + return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; ")))); + } + + Ok(json!({"updated": updated, "failed": failed})) +} + +#[cfg(not(target_arch = "wasm32"))] +fn relink(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.relink"; + + let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string(); + let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + if !s.is_image_resource(&name) { + return Err(bad(CMD, format!("no image resource `{name}`"))); + } + + // A relinked mesh map file still feeds its mesh map + let mut file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + file.source.mesh_map = s.doc.project.resource_sources.get(&name).and_then(|source| source.mesh_map); + let path = file.source.path.clone(); + s.install_reloaded("Relink resource", std::iter::once(file))?; + + Ok(json!({"name": name, "path": path})) +} + +#[cfg(target_arch = "wasm32")] +fn update(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.update", "file paths are not available in the browser")) +} + +#[cfg(target_arch = "wasm32")] +fn relink(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.relink", "file paths are not available in the browser")) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index cb69ffb3..faf91c9a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -33,6 +33,9 @@ pub struct Document { pub resources: BTreeMap>>, /// High-definition meshes and cage for baking (saved inside the project) pub bake_meshes: crate::BakeMeshes, + /// Skew and cage paint bounds since each set's last Auto-rebake. Undo restores the bounds + /// with their maps. The project file omits these bounds. + pub(crate) painted_regions: BTreeMap, } /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). @@ -425,9 +428,15 @@ pub struct Session { pub project_id: u64, /// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas). pub(crate) source: Arc, + /// Fingerprint of the bake inputs in `source`, computed on first use + pub(crate) low_poly_fingerprint: std::sync::OnceLock, + /// Fingerprint of the packed mesh file, computed only for bakes that read its material colors. + pub(crate) low_material_file_fingerprint: std::sync::OnceLock, + /// Skew and cage strokes so far + pub(crate) painted_strokes: u64, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. - pub mesh_source: Option<(String, Vec)>, + pub mesh_source: Option<(String, Arc>)>, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -451,6 +460,8 @@ pub struct Session { pub solo: Option, /// The live bake preview while the app bakes (see [`crate::bake_preview`]). pub bake_preview: Option, + /// The latest bake, map by map (the Baking Log) + pub bake_log: crate::bake::BakeLog, /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, @@ -462,6 +473,9 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, + /// Resources whose file was read for the Resources Updater, by name: the verdict stays while the file's size and time do + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resource_checks: std::collections::HashMap, /// Temporary texel mask limiting paint strokes (not saved, not in the history). pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). @@ -478,6 +492,9 @@ pub struct Session { /// (see [`crate::commands::check_enabled`]). pub project_open: bool, pub modified: bool, + /// Edits to saved data, independent of viewport and tool changes. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) save_revision: u64, /// Bumps on every document change. pub revision: u64, /// Messages for the UI (status bar / toasts). @@ -522,9 +539,12 @@ impl Session { mesh_id: next_mesh_id(), project_id: next_mesh_id(), source, + low_poly_fingerprint: Default::default(), + low_material_file_fingerprint: Default::default(), + painted_strokes: 0, mesh, bvh: Arc::new(bvh), - mesh_source, + mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), caches, undo: Vec::new(), redo: Vec::new(), @@ -540,12 +560,15 @@ impl Session { view_image: None, solo: None, bake_preview: None, + bake_log: Default::default(), viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] + resource_checks: std::collections::HashMap::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, @@ -554,6 +577,8 @@ impl Session { path: None, project_open: true, modified: false, + #[cfg(not(target_arch = "wasm32"))] + save_revision: 0, revision: 1, log: crate::log::SessionLog::new(), log_id: next_mesh_id(), @@ -583,6 +608,10 @@ impl Session { pub fn switch_to(&mut self, mut next: Session) { // Invalidate caches even when both projects were loaded with the same revision next.revision = self.revision.wrapping_add(1); + #[cfg(not(target_arch = "wasm32"))] + { + next.save_revision = self.save_revision.wrapping_add(1); + } next.viewport = self.viewport; next.export_presets = std::mem::take(&mut self.export_presets); @@ -635,6 +664,7 @@ impl Session { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }, mesh, mesh_source, @@ -735,8 +765,7 @@ impl Session { self.path_steps = Default::default(); } - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { self.undo.push((label.to_string(), before)); } @@ -747,8 +776,7 @@ impl Session { /// 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.mark_modified(); self.invalidate_changed(other); } @@ -874,14 +902,23 @@ impl Session { /// Mark the document changed and every texture set dirty. pub fn touched(&mut self) { - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); self.sync_caches(); for c in &mut self.caches { c.invalidate_all(); } } + /// Mark saved data changed without invalidating the texture sets. + pub fn mark_modified(&mut self) { + self.modified = true; + self.revision = self.revision.wrapping_add(1); + #[cfg(not(target_arch = "wasm32"))] + { + self.save_revision = self.save_revision.wrapping_add(1); + } + } + /// Make caches agree with the project's texture sets (resolution or channel changes). pub fn sync_caches(&mut self) { let sets = self.doc.project.texture_sets.clone(); @@ -964,6 +1001,7 @@ impl Session { 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.forget_replaced_images(¤t); self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) @@ -984,19 +1022,21 @@ impl Session { 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.forget_replaced_images(¤t); self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) } fn after_history(&mut self, other: &Document) { + self.follow_renamed_resources(other); + // Pending operations may still hold layer IDs from the discarded snapshot self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id); - self.modified = true; + self.mark_modified(); // Layers picked together belong to the stack they were picked in self.multi.clear(); - self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); // An undone add or duplicate takes the selected effect away @@ -1013,6 +1053,38 @@ impl Session { } } + /// The image names the tools and the 2D view read, which a resource rename follows + pub(crate) fn tool_images_mut(&mut self) -> impl Iterator { + [ + self.tool.stencil.as_mut().map(|stencil| &mut stencil.image), + self.tool.brush.alpha_image.as_mut(), + self.tool.mask_image.as_mut(), + self.view_image.as_mut(), + ] + .into_iter() + .flatten() + } + + /// Points tool images at a resource's name on this side of an undone or redone rename + fn follow_renamed_resources(&mut self, other: &Document) { + let names: Vec = self.tool_images_mut().map(|name| name.clone()).collect(); + let renames: Vec<(String, String)> = names + .into_iter() + .filter(|name| !self.doc.resources.contains_key(name)) + .filter_map(|name| { + let bytes = other.resources.get(&name)?; + let to = self.doc.resources.iter().find(|(_, here)| Arc::ptr_eq(here, bytes)).map(|(here, _)| here.clone())?; + Some((name, to)) + }) + .collect(); + + for (name, to) in renames { + for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == name) { + tool_image.clone_from(&to); + } + } + } + // ----------------------------------------------------------------------------------------- // Compositing diff --git a/crates/engine/src/shader_parameters.rs b/crates/engine/src/shader_parameters.rs new file mode 100644 index 00000000..12a04674 --- /dev/null +++ b/crates/engine/src/shader_parameters.rs @@ -0,0 +1,93 @@ +//! Export shader parameters: the project's shader, its settings and the texture sets using it, as JSON + +use serde_json::{Value, json}; +use texturecraft_core::Project; +use texturecraft_formats::ExportedFile; + +use crate::Result; +use crate::commands::bad; + +/// The project's one shader, its parameters and the names of `sets` (they all use it) +pub fn shader_parameters(project: &Project, sets: &[usize]) -> Value { + let display = &project.display; + let model = if display.spec_gloss { "specularGlossiness" } else { "metallicRoughness" }; + let names: Vec<&str> = sets.iter().filter_map(|ts| project.texture_sets.get(*ts)).map(|set| set.name.as_str()).collect(); + + json!({ + "shaders": [{ + "model": model, + "parameters": { + "aoIntensity": display.ao_intensity, + "ior": display.ior, + "scatterColor": display.scatter_color, + "scatterRadius": display.scatter_radius, + "displacement": display.displacement, + "parallax": display.parallax, + }, + "textureSets": names, + }] + }) +} + +/// The JSON file's name for project `name` +pub fn shader_parameters_file(name: &str) -> String { + format!("{}_shaders.json", texturecraft_formats::export::sanitize_file_stem(name)) +} + +/// Refuse the file name `name` when one of the export's texture paths (`/`-separated, relative to the export folder) is that file or lies in a folder of that name, ignoring case +pub fn check_shader_parameters_name<'a>(name: &str, texture_paths: impl IntoIterator) -> std::result::Result<(), String> { + if texture_paths.into_iter().any(|path| path.split('/').next().is_some_and(|root| root.eq_ignore_ascii_case(name))) { + return Err(format!("\"{name}\" is already used by a texture file or folder")); + } + + Ok(()) +} + +/// Build the download or headless sidecar after checking its name against every texture path. +pub fn shader_parameters_sidecar(project: &Project, sets: &[usize], textures: &[ExportedFile]) -> std::result::Result { + let name = shader_parameters_file(&project.name); + check_shader_parameters_name(&name, textures.iter().map(|texture| texture.name.as_str()))?; + + let bytes = serde_json::to_vec_pretty(&shader_parameters(project, sets)).map_err(|error| error.to_string())?; + Ok(ExportedFile { name, bytes, width: 0, height: 0, warnings: Vec::new() }) +} + +/// The texture sets `shaderParameters` asks to list: `true` takes the command's own `sets`, a list gives them all; None when it asks for no file +pub fn shader_parameters_param(project: &Project, params: &Value, sets: &[usize], cmd: &str) -> Result>> { + match params.get("shaderParameters") { + None | Some(Value::Null | Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(sets.to_vec())), + Some(Value::Array(indexes)) => indexes + .iter() + .map(|index| { + index + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < project.texture_sets.len()) + .ok_or_else(|| bad(cmd, "`shaderParameters` lists texture set indexes")) + }) + .collect::>>() + .map(Some), + Some(_) => Err(bad(cmd, "`shaderParameters` must be true, false or a list of texture set indexes")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_json_names_the_shader_its_settings_and_its_texture_sets() { + let mut session = crate::sample_session(128, 32).unwrap(); + session.doc.project.display.ior = 1.33; + + let value = shader_parameters(&session.doc.project, &[1]); + + let shader = &value["shaders"][0]; + + assert_eq!(shader["model"], "metallicRoughness"); + assert!((shader["parameters"]["ior"].as_f64().unwrap() - 1.33).abs() < 1e-6); + assert_eq!(shader["textureSets"], json!([session.doc.project.texture_sets[1].name])); + assert!(shader_parameters_file("Material Ball").ends_with("_shaders.json")); + } +} diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index bbe0e243..f50026a8 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -243,6 +243,7 @@ impl Session { pixels: pf.pixels, baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }; let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index db283d7e..e07370fc 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -36,6 +36,7 @@ pub struct ProjectTemplate { pub spec_gloss: bool, pub parallax: bool, pub ior: f32, + pub ior_specular: bool, pub scatter_color: [f32; 3], pub scatter_radius: f32, } @@ -51,6 +52,7 @@ impl Default for ProjectTemplate { spec_gloss: d.spec_gloss, parallax: d.parallax, ior: d.ior, + ior_specular: d.ior_specular, scatter_color: d.scatter_color, scatter_radius: d.scatter_radius, } @@ -116,7 +118,7 @@ pub fn specs() -> Vec { "Project templates", [], None, - "{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss}]", + "{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss, iorSpecular}]", always, list ), @@ -189,28 +191,36 @@ impl Session { matches.next().is_none().then(|| template.clone()) } - /// Start this (new, unpainted) project from template `t`: its channels on every texture set - /// and layer, normal format and shader settings. The resolution is the caller's choice. - pub fn apply_template(&mut self, t: &ProjectTemplate) { - let p = &mut self.doc.project; - p.normal_format = t.normal_format; - let d = &mut p.display; - (d.spec_gloss, d.parallax, d.ior, d.scatter_color, d.scatter_radius) = (t.spec_gloss, t.parallax, t.ior, t.scatter_color, t.scatter_radius); - for ts in 0..p.texture_sets.len() { - if let Some(set) = p.texture_sets.get_mut(ts) { - set.channels = t.channels.clone(); + /// Apply the template's channels and shader settings to a new, unpainted project. + /// The caller chooses the texture set resolution. + pub fn apply_template(&mut self, template: &ProjectTemplate) { + let project = &mut self.doc.project; + project.normal_format = template.normal_format; + + let display = &mut project.display; + display.spec_gloss = template.spec_gloss; + display.parallax = template.parallax; + display.ior = template.ior; + display.ior_specular = template.ior_specular; + display.scatter_color = template.scatter_color; + display.scatter_radius = template.scatter_radius; + + for set_index in 0..project.texture_sets.len() { + if let Some(set) = project.texture_sets.get_mut(set_index) { + set.channels = template.channels.clone(); } - let wanted: Vec = t.channels.iter().map(|(c, _)| *c).collect(); - for (id, _) in p.walk(ts) { - if let Ok(l) = p.layer_mut(id) { - let mode = if l.is_group() { texturecraft_core::BlendMode::Passthrough } else { texturecraft_core::BlendMode::Normal }; - l.channels.retain(|c, _| wanted.contains(c)); - for c in &wanted { - l.channels.entry(*c).or_insert(ChannelBlend { mode, opacity: 1.0 }); + + for (id, _) in project.walk(set_index) { + if let Ok(layer) = project.layer_mut(id) { + let mode = if layer.is_group() { texturecraft_core::BlendMode::Passthrough } else { texturecraft_core::BlendMode::Normal }; + layer.channels.retain(|channel, _| template.channels.iter().any(|(wanted, _)| channel == wanted)); + for &(channel, _) in &template.channels { + layer.channels.entry(channel).or_insert(ChannelBlend { mode, opacity: 1.0 }); } } } } + self.touched(); self.modified = false; } @@ -277,6 +287,7 @@ fn list(s: &mut Session, _: &Value) -> Result { "normalFormat": if t.normal_format == NormalFormat::DirectX { "directX" } else { "openGl" }, "channels": t.channels.iter().map(|(c, _)| c.id()).collect::>(), "specGloss": t.spec_gloss, + "iorSpecular": t.ior_specular, }) }; Ok(json!(builtin_templates().iter().map(|t| entry(t, true)).chain(s.templates.list.iter().map(|t| entry(t, false))).collect::>())) @@ -296,6 +307,7 @@ fn save(session: &mut Session, params: &Value) -> Result { spec_gloss: display.spec_gloss, parallax: display.parallax, ior: display.ior, + ior_specular: display.ior_specular, scatter_color: display.scatter_color, scatter_radius: display.scatter_radius, }; diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 5ef73b8b..9d102c13 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -1,7 +1,7 @@ //! Edit, viewport and display commands. use serde_json::{Value, json}; -use texturecraft_core::project::ENVIRONMENTS; +use texturecraft_core::project::{ENVIRONMENTS, MAX_INDEX_OF_REFRACTION, MIN_INDEX_OF_REFRACTION}; use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping}; use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p, vec3}; @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Display settings", [], None, - "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}, projectionGizmos? (the selected fill's projection gizmos show in the 3D view)}", + "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), iorSpecular? (use IOR for dielectric reflectance at normal incidence in Metallic Roughness), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}, projectionGizmos? (the selected fill's projection gizmos show in the 3D view)}", always, display ), @@ -314,6 +314,8 @@ fn display(s: &mut Session, p: &Value) -> Result { let scatter_color = color_param("display.set", p, "scatterColor")?; let (environment_before, rotation_before) = (s.doc.project.display.environment.clone(), s.doc.project.display.env_rotation); let settings = &mut s.doc.project.display; + let (ior_before, ior_specular_before, spec_gloss_before) = (settings.ior, settings.ior_specular, settings.spec_gloss); + if let Some(picked) = environment { settings.environment = picked; } @@ -329,7 +331,7 @@ fn display(s: &mut Session, p: &Value) -> Result { ("sharpen", &mut settings.sharpen, 0.0, 1.0), ("grain", &mut settings.grain, 0.0, 1.0), ("scatterRadius", &mut settings.scatter_radius, 0.0, 1.0), - ("ior", &mut settings.ior, 1.0, 3.0), + ("ior", &mut settings.ior, MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION), ("shadowOpacity", &mut settings.shadow_opacity, 0.0, 1.0), ] { if let Some(value) = f32p(p, key) { @@ -366,6 +368,7 @@ fn display(s: &mut Session, p: &Value) -> Result { ("postEffects", &mut settings.post_effects), ("taa", &mut settings.taa), ("specGloss", &mut settings.spec_gloss), + ("iorSpecular", &mut settings.ior_specular), ("parallax", &mut settings.parallax), ("displacement", &mut settings.displacement), ("soloUnlit", &mut settings.solo_unlit), @@ -376,6 +379,9 @@ fn display(s: &mut Session, p: &Value) -> Result { } } + let saved_settings_changed = + settings.ior_specular != ior_specular_before || (settings.ior_specular && (settings.ior != ior_before || settings.spec_gloss != spec_gloss_before)); + // The field of view applies to the view only when set (a saved camera keeps its own) if f32p(p, "fov").is_some() { s.camera.fov = s.doc.project.display.fov; @@ -388,7 +394,12 @@ fn display(s: &mut Session, p: &Value) -> Result { cache.invalidate_all(); } } - s.revision = s.revision.wrapping_add(1); + if saved_settings_changed { + s.mark_modified(); + } else { + s.revision = s.revision.wrapping_add(1); + } + Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null)) } diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs index d416e183..7cf156c1 100644 --- a/crates/engine/tests/bake_preview.rs +++ b/crates/engine/tests/bake_preview.rs @@ -1,5 +1,5 @@ //! 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 +//! painting is paused, ending the preview 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. @@ -208,14 +208,14 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { 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 + // Compare the streamed pixels with a full bake to verify each preview is complete 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 + // The UI applies eligible maps separately through keep_canceled_bake session.bake_preview_end(); assert_eq!(session.doc.baked.get(&0).cloned(), before); diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs new file mode 100644 index 00000000..3c9f33ed --- /dev/null +++ b/crates/engine/tests/it/auto_rebake.rs @@ -0,0 +1,231 @@ +//! Auto-rebake: one map per texture set, due when it goes out of date, rebaked alone + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute, sample_session}; + +/// A plane with its position and ID maps baked +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + session +} + +fn due_maps(session: &Session) -> Vec<(usize, BakedMap)> { + session.auto_rebake_due().into_iter().map(|(set, map, _)| (set, map)).collect() +} + +#[test] +fn one_map_per_set_is_auto_rebaked_and_it_is_due_only_once_out_of_date() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "id" })).unwrap(); + let turned_on = execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert_eq!(turned_on, json!({ "ts": 0, "autoRebake": "position" }), "the second map replaces the first"); + assert!(due_maps(&session).is_empty(), "up to date: {:?}", due_maps(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(due_maps(&session), [(0, BakedMap::Position)]); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + assert!(due_maps(&session).is_empty(), "turned off: {:?}", due_maps(&session)); + assert!(execute(&mut session, "bake.autoRebake", &json!({ "map": "glow" })).is_err()); +} + +#[test] +fn the_auto_rebake_map_is_saved_with_the_project_and_undone_like_an_edit() { + let mut session = baked_plane(); + let before = session.to_project_bytes().unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position)); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["autoRebake"], json!("position")); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None); + assert_eq!(Session::from_project_bytes(&before).unwrap().doc.project.texture_sets[0].auto_rebake, None, "older projects have none"); +} + +#[test] +fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "maps": ["id"], "positionMode": "boundingBox" })).unwrap(); + let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + + let task = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + assert_eq!(task.maps(), [BakedMap::Position], "an unchecked map bakes when asked for"); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", session.bake_changes(0, BakedMap::Position)); + let baked = session.baked(0).unwrap(); + assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::>(), [BakedMap::Id], "the checks stay"); +} + +#[test] +fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 128 })).unwrap(); + + let maps = session.auto_rebake_maps(0, BakedMap::Position); + let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let baked = session.baked(0).unwrap(); + assert!(baked.maps.contains_key(&BakedMap::Id), "the ID map survives the new size: {:?}", baked.maps.keys().collect::>()); + assert!(session.out_of_date_maps(0).is_empty(), "{:?}", session.out_of_date_maps(0)); +} + +#[test] +fn an_unchanged_uv_atlas_size_rebakes_only_the_auto_rebake_map() { + let mut session = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let maps = session.auto_rebake_maps(0, BakedMap::Position); + let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let id_after = &session.baked(0).unwrap().maps[&BakedMap::Id]; + assert!(std::sync::Arc::ptr_eq(&id_before, id_after), "an unchanged atlas size leaves the other map alone"); +} + +#[test] +fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "nothing painted since the bake"); + let before = session.baked(0).unwrap().maps[&BakedMap::Position].clone(); + + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3], [0.4, 0.35]], "radius": 0.05, "size": 64 })).unwrap(); + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)]); + assert!(session.auto_rebake_due().is_empty(), "painting is not a settings change: {:?}", due_maps(&session)); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let region = task.region.expect("a stroke rebakes only its box"); + let mut whole = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + whole.tracer = None; + let whole = whole.run(&Progress::new()).unwrap().maps.remove(&BakedMap::Position).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + + let width = output.resolution as usize; + assert!(((region.max.0 - region.min.0) as usize) < width / 2, "the box is far smaller than the map: {region:?}"); + let components = BakedMap::Position.components(); + let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components)); + let mut changed = 0; + for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() { + assert_eq!(rebaked, baked_whole, "texel {index} matches a whole bake"); + if region.contains(index % width, index / width) { + changed += usize::from(rebaked != kept); + } else { + assert_eq!(rebaked, kept, "texel {index} outside the box"); + } + } + assert!(changed > 0, "the stroke changed the map inside its box"); + + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); +} + +#[test] +fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + let stroke = |at: f32| json!({ "points": [[at, at]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.skew.paint", &stroke(0.3)).unwrap(); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + execute(&mut session, "bake.skew.paint", &stroke(0.7)).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); +} + +#[test] +fn undoing_the_rebake_of_a_stroke_makes_its_box_due_again() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3]], "radius": 0.05, "size": 64 })).unwrap(); + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + + session.undo().unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the map is back to its pixels from before the stroke, which is still painted"); + session.redo().unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "redo brings the rebake back"); +} + +#[test] +fn a_bake_after_a_mesh_reimport_takes_the_strokes_painted_before_it() { + let 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\nf 1/1 3/3 4/4\n"; + let mut session = Session::from_mesh_bytes_with_uvs("quad.obj", quad.as_bytes(), 128, "quad", None, false).unwrap(); + session.add_high_poly_bytes("quad_high.obj", quad.replace("v 1 1 0", "v 1 1 0.1").into_bytes()).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + + session.reimport_mesh(None, false).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert!(painted.is_empty(), "the bake after the reimport took the stroke: {painted:?}"); +} + +#[test] +fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 0, "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "ts": 0, "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + let second = &mut session.doc.project.texture_sets[1].bake.maps.ao; + second.is_enabled = true; + second.parameters.rays.rays = 0; + + assert!(execute(&mut session, "bake.run", &json!({ "ts": "all" })).is_err(), "set 1's AO has no rays to cast"); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "set 0's stroke is still waiting for its rebake"); +} + +#[test] +fn the_first_skew_stroke_turns_auto_rebake_on_for_the_normal_map_once() { + let mut session = super::bake::leaning_session(true); + let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.cage.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "cage painting leaves it alone"); + + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Normal)); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "undone with the stroke"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position), "a map picked before stays"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "turned off after skew painting started, it stays off"); +} diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 4035c0f1..47f196dd 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -435,6 +435,35 @@ fn textured_glb(mesh: &Mesh, dy: f32, png: &[u8]) -> Vec { glb } +#[test] +fn reimporting_a_low_poly_texture_changes_opacity_provenance() { + use texturecraft_engine::core::BakeChange; + use texturecraft_engine::formats::MeshFile; + + let mesh = primitives::builtin("plane").unwrap(); + let name = "painted.glb"; + let mut session = Session::from_mesh_bytes(name, &textured_glb(&mesh, 0.0, &quadrants_png()), 128, "painted").unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "opacity" })).unwrap(); + let prior_opacity = session.baked(0).unwrap().maps[&BakedMap::Opacity].clone(); + let mut opaque = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255; 4])).write_to(&mut std::io::Cursor::new(&mut opaque), image::ImageFormat::Png).unwrap(); + + let replacement = MeshFile { name: name.into(), bytes: textured_glb(&mesh, 0.0, &opaque), warnings: Vec::new() }; + session.reimport_mesh(Some(replacement), false).unwrap(); + + assert_eq!(session.bake_changes(0, BakedMap::Opacity), [BakeChange::LowPoly]); + assert!(session.bake_changes(0, BakedMap::Position).is_empty()); + assert_eq!(session.out_of_date_maps(0).len(), 1); + assert_eq!(session.auto_rebake_due().first().map(|entry| entry.1), Some(BakedMap::Opacity)); + + execute(&mut session, "bake.run", &json!({})).unwrap(); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_ne!(reopened.baked(0).unwrap().maps[&BakedMap::Opacity], prior_opacity); + assert!(reopened.auto_rebake_due().is_empty()); +} + #[test] fn opacity_samples_a_textured_gltf_high_poly() { let mut session = plane_session(); @@ -526,13 +555,14 @@ fn opacity_samples_textures_next_to_a_high_poly() { 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 { +/// Two parallel planes, with tilted low-poly vertex normals when `lean` is true. +pub(super) 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(); diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs new file mode 100644 index 00000000..95f85d5a --- /dev/null +++ b/crates/engine/tests/it/bake_log.rs @@ -0,0 +1,198 @@ +//! The Baking Log's record of the latest bake, map by map + +use std::collections::BTreeSet; + +use serde_json::json; +use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair}; +use texturecraft_engine::compose::BakedMaps; +use texturecraft_engine::core::{BakedMap, MeshMatchMode}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute, sample_session}; + +#[test] +fn bake_run_lists_every_checked_map_of_the_set_as_baked() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let set_name = &session.doc.project.texture_sets[0].name; + let rows = &session.bake_log.maps; + let maps: BTreeSet = rows.iter().map(|row| row.map).collect(); + + assert_eq!(maps, BTreeSet::from([BakedMap::Position, BakedMap::Opacity])); + assert!(rows.iter().all(|row| row.state == BakeMapState::Baked && &row.set_name == set_name), "{rows:?}"); + assert!(!session.bake_log.is_running()); +} + +#[test] +fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { + let mut session = sample_session(256, 64).unwrap(); + for set in &mut session.doc.project.texture_sets { + set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]); + } + let log = &mut session.bake_log; + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + + log.set_started(0); + log.map_baked(0, BakedMap::Normal); + log.map_baked(0, BakedMap::Curvature); + log.set_finished(0); + log.set_started(1); + log.map_baked(1, BakedMap::Normal); + + let baking: Vec<_> = log.maps.iter().filter(|row| row.state == BakeMapState::Baking).map(|row| (row.texture_set, row.map)).collect(); + assert_eq!(baking, [(1, BakedMap::Curvature)], "the next map of the running set is the one in progress"); + + log.cancel(Some(1)); + + let state_of = |set: usize| log.maps.iter().filter(move |row| row.texture_set == set).map(|row| row.state.clone()).collect::>(); + assert!(state_of(0).iter().all(|state| *state == BakeMapState::Baked), "{:?}", log.maps); + assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps); + assert!(!log.is_running()); +} + +#[test] +fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + + assert_eq!(log["running"], false); + let maps: BTreeSet<&str> = log["maps"].as_array().unwrap().iter().map(|row| row["map"].as_str().unwrap()).collect(); + assert_eq!(maps, BTreeSet::from(["opacity", "position"])); + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "baked" && row["textureSet"] == 0 && row.get("reason").is_none()), "{log}"); + + session.bake_log.set_failed(0, "The high poly file could not be read."); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}"); +} + +#[test] +fn a_bake_lists_the_high_polys_each_set_loads_and_skips_a_set_baking_from_its_low_poly() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + session.doc.project.texture_sets[1].bake.high_poly.use_low_as_high = true; + + execute(&mut session, "bake.run", &json!({ "ts": [0, 1], "resolution": 64, "maps": ["opacity"], "dilation": 0 })).unwrap(); + + let highs: Vec<_> = session.bake_log.highs.iter().map(|row| (row.texture_set, row.file.as_str(), row.state.clone())).collect(); + assert_eq!(highs, [(0, "ball_high.obj", BakeHighState::Loaded)]); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["highPolys"][0]["state"], "loaded", "{log}"); +} + +#[test] +fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_cancel_the_rest_canceled() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let log = &mut session.bake_log; + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + let state = |log: &BakeLog, set: usize| log.highs.iter().find(|high| high.texture_set == set).map(|high| high.state.clone()); + + log.set_started(0); + + assert_eq!(state(log, 0), Some(BakeHighState::Loading)); + assert!(log.is_loading_high_polys()); + + log.set_failed(0, "The cage file could not be read."); + log.set_started(1); + log.cancel(Some(1)); + + assert_eq!(state(log, 0), Some(BakeHighState::Failed("The cage file could not be read.".into()))); + assert_eq!(state(log, 1), Some(BakeHighState::Canceled)); + assert!(!log.is_loading_high_polys()); +} + +#[test] +fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_with() { + 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", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.begin_bake_log(&[0, 1]); + + assert_eq!(session.bake_log.matching, None, "matching \"Always\" lists no pairs"); + + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + } + session.begin_bake_log(&[0, 1]); + + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + let matching = session.bake_log.matching.clone().unwrap(); + assert_eq!( + matching.pairs, + [pair(Some("Box_low"), Some("Box_high")), pair(Some("Lid_low"), None), pair(None, Some("Extra_high"))], + "Box_high is paired by the other set" + ); + assert_eq!(matching.issue_count(), 2); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); +} + +#[test] +fn a_high_part_counts_as_unused_only_when_no_set_of_the_bake_matches_always() { + 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", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_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; + + session.begin_bake_log(&[0, 1]); + + let matching = session.bake_log.matching.clone().unwrap(); + assert!(matching.pairs.iter().all(|pair| pair.low.is_some()), "the set matching \"Always\" bakes from Extra_high: {:?}", matching.pairs); + assert_eq!(matching.issue_count(), 0); +} + +#[test] +fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() { + let mut session = sample_session(256, 64).unwrap(); + let before = session.baked(0).cloned().unwrap(); + let resolution = before.resolution * 2; + let data = std::sync::Arc::new(vec![0.5; (resolution * resolution) as usize * BakedMap::Normal.components()]); + let finished = BakedMaps { resolution, maps: [(BakedMap::Normal, data)].into() }; + + let kept = session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + assert!(kept.is_empty(), "{kept:?}"); + assert_eq!(session.baked(0).map(|baked| baked.maps.keys().copied().collect::>()), Some(before.maps.keys().copied().collect())); + assert_eq!(session.baked(0).map(|baked| baked.resolution), Some(before.resolution)); +} + +#[test] +fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() { + let mut session = sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["id", "position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + let task = session.bake_task_for(0, &[BakedMap::Id, BakedMap::Position]).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(BakedMap::Id, stored.maps[&BakedMap::Id].clone())].into() }; + + let kept = session.keep_canceled_bake(0, finished, &task.sources, task.painted_stroke).unwrap(); + + assert_eq!(kept, [BakedMap::Id]); + assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date"); +} + +#[test] +fn a_canceled_bakes_log_line_names_the_set_as_the_texture_set_list_does() { + let mut session = sample_session(256, 64).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let (map, data) = stored.maps.iter().next().map(|(map, data)| (*map, data.clone())).unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(map, data)].into() }; + + session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + let name = session.doc.project.texture_sets[0].name.clone(); + let line = session.log.iter().find(|line| line.contains("canceled bake")).map(|line| line.message.clone()).unwrap(); + assert!(line.contains(&format!("texture set {name} ")), "the first set is not numbered 0: {line}"); +} diff --git a/crates/engine/tests/it/bake_out_of_date.rs b/crates/engine/tests/it/bake_out_of_date.rs new file mode 100644 index 00000000..61654bb8 --- /dev/null +++ b/crates/engine/tests/it/bake_out_of_date.rs @@ -0,0 +1,189 @@ +//! Out-of-date mesh maps: what each map was baked from, compared with what a bake would read now + +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeChange, BakedMap, CageType, IdColorSource, MeshMatchMode}; +use texturecraft_engine::formats::MeshFile; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position map baked by `bake.run` +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + session +} + +fn changes(session: &Session) -> Vec { + session.bake_changes(0, BakedMap::Position) +} + +#[test] +fn a_map_goes_out_of_date_when_its_settings_or_the_shared_ones_change_and_a_bake_brings_it_back() { + let mut session = baked_plane(); + assert!(changes(&session).is_empty(), "fresh bake: {:?}", changes(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(changes(&session), [BakeChange::MapSettings]); + execute(&mut session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + assert_eq!(changes(&session), [BakeChange::Settings, BakeChange::MapSettings]); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["outOfDate"], json!({ "position": ["settings", "mapSettings"] })); + + execute(&mut session, "bake.run", &json!({})).unwrap(); + assert!(changes(&session).is_empty(), "rebaked: {:?}", changes(&session)); +} + +#[test] +fn the_record_is_saved_with_the_project() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(changes(&reopened), [BakeChange::MapSettings]); +} + +#[test] +fn maps_saved_before_records_existed_and_imported_maps_never_go_out_of_date() { + let mut old = baked_plane(); + old.doc.project.texture_sets[0].bake_sources.clear(); + let mut old = Session::from_project_bytes(&old.to_project_bytes().unwrap()).unwrap(); + execute(&mut old, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&old).is_empty(), "{:?}", changes(&old)); + + let mut imported = baked_plane(); + let mut png = Vec::new(); + image::RgbImage::from_pixel(4, 4, image::Rgb([128, 64, 32])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + imported.import_resource_bytes("position.png", png).unwrap(); + execute(&mut imported, "textureSet.meshMap.set", &json!({ "map": "position", "image": "position.png" })).unwrap(); + execute(&mut imported, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&imported).is_empty(), "{:?}", changes(&imported)); +} + +#[test] +fn adding_a_high_poly_puts_the_maps_out_of_date() { + let mut session = baked_plane(); + + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + + assert_eq!(changes(&session), [BakeChange::HighPoly]); +} + +#[test] +fn replacing_low_poly_vertex_colors_marks_the_id_map_out_of_date() { + let triangle = |color: &str| format!("o Painted\nv 0 0 0 {color}\nv 1 0 0 {color}\nv 0 1 0 {color}\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"); + let name = "painted.obj"; + let mut session = Session::from_mesh_bytes_with_uvs(name, triangle("1 0 0").as_bytes(), 128, "painted", None, false).unwrap(); + session.doc.project.texture_sets[0].bake.maps.id.parameters.source = IdColorSource::VertexColor; + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["id"], "dilation": 0 })).unwrap(); + let previous = session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + + let replacement = MeshFile { name: name.into(), bytes: triangle("0 1 0").into_bytes(), warnings: Vec::new() }; + session.reimport_mesh(Some(replacement), false).unwrap(); + + assert_eq!(session.bake_changes(0, BakedMap::Id), [BakeChange::LowPoly]); + execute(&mut session, "bake.run", &json!({})).unwrap(); + assert_ne!(session.baked(0).unwrap().maps[&BakedMap::Id], previous); + assert!(session.bake_changes(0, BakedMap::Id).is_empty()); +} + +#[test] +fn reimporting_a_quad_as_triangles_invalidates_its_tangent_frame() { + let corners = "v 0 0 0\nv 1 0 0\nv 1 1 0.6\nv 0 1 0\nvt 0 0.1\nvt 1 0\nvt 0.9 1\nvt 0.3 0.8\nvn 0 0 1\n"; + let quad = format!("{corners}f 1/1/1 2/2/1 3/3/1 4/4/1\n"); + let triangles = format!("{corners}f 1/1/1 2/2/1 3/3/1\nf 1/1/1 3/3/1 4/4/1\n"); + let mut session = Session::from_mesh_bytes("surface.obj", quad.as_bytes(), 128, "surface").unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["normal"], "dilation": 0 })).unwrap(); + let previous = session.mesh.clone(); + + let replacement = MeshFile { name: "surface.obj".into(), bytes: triangles.into_bytes(), warnings: Vec::new() }; + session.reimport_mesh(Some(replacement), false).unwrap(); + + assert_eq!(session.mesh.indices, previous.indices); + assert_ne!(session.mesh.tangents, previous.tangents); + assert_eq!(session.bake_changes(0, BakedMap::Normal), [BakeChange::LowPoly]); +} + +#[test] +fn renaming_a_low_poly_part_invalidates_its_by_name_bake() { + let triangle = |part: &str, height: f32| format!("o {part}\nv 0 0 {height}\nv 1 0 {height}\nv 0 1 {height}\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"); + let name = "parts.obj"; + let mut session = Session::from_mesh_bytes_with_uvs(name, triangle("Body_low", 0.0).as_bytes(), 128, "parts", None, false).unwrap(); + session.add_high_poly_bytes("detail.obj", triangle("Body_high", 0.05).into_bytes()).unwrap(); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + assert!(session.bake_name_pairs(0).unwrap().unwrap().iter().any(|pair| !pair.unpaired())); + + let replacement = MeshFile { name: name.into(), bytes: triangle("Trim_low", 0.0).into_bytes(), warnings: Vec::new() }; + session.reimport_mesh(Some(replacement), false).unwrap(); + + assert!(session.bake_name_pairs(0).unwrap().unwrap().iter().all(|pair| pair.unpaired())); + assert_eq!(changes(&session), [BakeChange::LowPoly]); +} + +#[test] +fn a_cage_file_counts_only_for_sets_that_bake_with_it() { + let mut session = baked_plane(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let cage: String = (0..session.mesh.triangle_count()).map(|_| "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n").collect(); + session.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + assert!(changes(&session).is_empty(), "the cage type is not Custom File: {:?}", changes(&session)); + + session.doc.project.texture_sets[0].bake.cage.kind = CageType::CustomFile; + assert!(changes(&session).contains(&BakeChange::Cage), "{:?}", changes(&session)); +} + +#[test] +fn a_setting_changed_while_the_bake_runs_leaves_the_new_map_out_of_date() { + let mut session = baked_plane(); + let task = session.bake_task(0).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let streamed_once = AtomicBool::new(false); + let output = task.run_streaming(&Progress::new(), &mut |_| streamed_once.store(true, Ordering::Relaxed)).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(streamed_once.load(Ordering::Relaxed)); + assert_eq!(changes(&session), [BakeChange::MapSettings]); +} + +/// Two quads side by side, one texture set each, lifted by `lift` where a high poly or cage stands off the low poly +fn two_parts(lift: f32) -> String { + let mut obj = String::new(); + for left in [0.0, 2.0] { + let right = left + 1.0; + obj += &format!("v {left} 0 {lift}\nv {right} 0 {lift}\nv {right} 1 {lift}\nv {left} 1 {lift}\n"); + } + obj += "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n"; + obj += "usemtl Left\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\nusemtl Right\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n"; + obj +} + +#[test] +fn a_reopened_project_keeps_every_sets_maps_up_to_date() { + let mut session = Session::from_mesh_bytes_with_uvs("parts.obj", two_parts(0.0).as_bytes(), 128, "parts", None, false).unwrap(); + session.add_high_poly_bytes("parts_high.obj", two_parts(0.05).into_bytes()).unwrap(); + session.set_cage_bytes("parts_cage.obj", two_parts(0.2).into_bytes()).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake.cage.kind = CageType::CustomFile; + } + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position", "normal"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 1, "map": "normal" })).unwrap(); + let records = |session: &Session| session.doc.project.texture_sets.iter().map(|set| set.bake_sources.clone()).collect::>(); + assert_eq!(session.set_count(), 2); + assert!(records(&session).iter().all(|sources| sources.len() == 2), "both maps of both sets are recorded"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(records(&reopened), records(&session), "the records are saved as they were"); + for texture_set in 0..reopened.set_count() { + assert!(reopened.out_of_date_maps(texture_set).is_empty(), "set {texture_set}: {:?}", reopened.out_of_date_maps(texture_set)); + } + assert!(reopened.auto_rebake_due().is_empty(), "opening the project starts no rebake"); +} diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index 278bfc04..c8929988 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -246,6 +246,42 @@ fn anchor_effects_added_through_instance_validate_against_source() { assert!(session.doc.project.layer(LayerId(source)).unwrap().mask.is_none()); } +#[test] +fn an_instance_selects_the_effects_of_the_mask_it_draws_with() { + let mut s = session(); + let source = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let source_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + let source_content = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let other = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let other_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": source})).unwrap(), "layer"); + let select = |s: &mut Session, effect: u64| execute(s, "layer.select", &json!({"layer": instance, "target": effect})); + + // The instance inherits its source mask + select(&mut s, source_mask).unwrap(); + + assert_eq!(s.selected_layer(), Some(LayerId(instance))); + assert_eq!(s.target, StackTarget::Effect(LayerId(source_mask))); + + // The source's content and unrelated layers remain outside the selection + for effect in [source_content, other_mask] { + let error = select(&mut s, effect).unwrap_err().to_string(); + assert!(error.contains("an effect id of this layer or of the mask it draws with"), "{error}"); + } + assert_ne!(other, instance); + + // A local mask overrides the source mask + execute(&mut s, "layer.select", &json!({"layer": instance})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let own = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + + assert!(select(&mut s, source_mask).is_err()); + select(&mut s, own).unwrap(); + assert_eq!(s.target, StackTarget::Effect(LayerId(own))); +} + #[test] fn mask_anchor_points_feed_layers_above_and_folders_take_them() { let mut s = session(); diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index e4f0e56f..dca3a215 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -27,3 +27,161 @@ fn the_new_file_types_dithering_and_diffusion_export() { assert!(plan.as_array().unwrap().iter().all(|f| f["dithering"] == false), "float files are never dithered"); assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err()); } + +#[test] +fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { + const SMALL_SIDE: u32 = 128; + let mesh = texturecraft_engine::geom::primitives::udim_plane(); + let mut session = texturecraft_engine::Session::new_project("test", mesh, "builtin:udim_plane", None, SMALL_SIDE).unwrap(); + let preset = + json!({"name": "Roughness", "maps": [{"file": "rough", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]}); + let options = |size| texturecraft_engine::file_cmds::export_options(&session, &json!({"preset": preset, "size": size, "padding": "none"}), "test").unwrap(); + let small = options(SMALL_SIDE); + let large = options(4096); + let first = session.export_files(&[0], &small).unwrap(); + assert!(first.len() > 1, "the mesh supplies multiple PSD tiles"); + + let jobs = std::iter::once((0, &small)).chain(std::iter::repeat_n((0, &large), 4)); + let batch = session.export_file_jobs(jobs).unwrap(); + + assert_eq!(batch.len(), first.len()); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.name == original.name && kept.bytes == original.bytes)); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.warnings.len() > original.warnings.len())); + println!("Kept {} PSDs totaling {} encoded bytes", batch.len(), batch.iter().map(|file| file.bytes.len()).sum::()); +} + +#[test] +fn a_psd_file_and_another_sets_folder_conflict_during_planning() { + use texturecraft_engine::core::Channel; + use texturecraft_engine::file_cmds::export_options; + + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let sets = &mut session.doc.project.texture_sets; + sets[0].name = "Body".into(); + sets[0].channels.retain(|(channel, _)| *channel != Channel::Metallic); + sets[1].name = "Trim".into(); + let preset = json!({"name": "Conflicting outputs", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}, + {"file": "$mesh_Body.psd/detail", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Metallic"}}]]} + ]}); + let dir = tempfile::tempdir().unwrap(); + let mut params = json!({"preset": preset, "padding": "none", "dir": dir.path()}); + + params["ts"] = json!(0); + let body = execute(&mut session, "export.plan", ¶ms).unwrap(); + params["ts"] = json!(1); + let trim = execute(&mut session, "export.plan", ¶ms).unwrap(); + let file = body[0]["file"].as_str().unwrap(); + let nested_file = trim.as_array().unwrap().iter().find_map(|file| file["file"].as_str().filter(|name| name.contains('/'))).unwrap(); + assert_eq!(nested_file.split('/').next(), Some(file), "separate plans collide when combined"); + + for order in [[0, 1], [1, 0]] { + params["ts"] = json!(order); + let plan_error = execute(&mut session, "export.plan", ¶ms).unwrap_err(); + let options = export_options(&session, ¶ms, "export.plan").unwrap(); + let render_error = session.export_files(&order, &options).unwrap_err(); + let write_error = execute(&mut session, "file.exportTextures", ¶ms).unwrap_err(); + + for error in [plan_error, render_error, write_error] { + assert!(error.to_string().contains("folder"), "{error}"); + } + assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none()); + } +} + +#[test] +fn a_map_size_wins_over_the_export_size_in_the_plan() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + + let plan = execute(&mut session, "export.plan", &json!({"ts": 0, "size": 512, "maps": [{"map": 0, "size": 128}]})).unwrap(); + + let (overridden, inherited): (Vec<_>, Vec<_>) = plan.as_array().unwrap().iter().partition(|file| file["map"] == 0); + + assert!(!overridden.is_empty() && !inherited.is_empty(), "{plan}"); + assert!(overridden.iter().all(|file| file["size"] == 128), "{plan}"); + assert!(inherited.iter().all(|file| file["size"] == 512), "{plan}"); + assert!(execute(&mut session, "export.plan", &json!({"ts": 0, "maps": [{"map": 0, "size": 100}]})).is_err()); +} + +#[test] +fn shader_parameters_write_the_shaders_json_next_to_the_textures() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join(texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name)); + + let result = execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "ts": 1, "shaderParameters": [0, 1]})).unwrap(); + + assert!(result["files"].as_array().unwrap().iter().any(|f| f.as_str() == Some(file.to_str().unwrap())), "{result}"); + let written: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let names: Vec<&str> = session.doc.project.texture_sets.iter().take(2).map(|set| set.name.as_str()).collect(); + + assert_eq!(written["shaders"][0]["textureSets"], json!(names)); + assert!(execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "shaderParameters": "yes"})).is_err()); +} + +#[test] +fn a_shaders_json_that_cannot_be_written_is_a_warning_after_the_textures() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join(texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name)); + std::fs::create_dir_all(&file).unwrap(); + + let result = execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true})).unwrap(); + + let files = result["files"].as_array().unwrap(); + + assert!(!files.is_empty() && files.iter().all(|f| f.as_str() != Some(file.to_str().unwrap())), "{result}"); + let warnings = result["warnings"].as_array().unwrap(); + + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("The shader settings file was not written"))), "{result}"); +} + +#[test] +fn a_shaders_json_named_like_an_earlier_commands_folder_is_a_warning() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let name = texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name); + let reserved = format!("{}/Color.png", name.to_uppercase()); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true, "reservedNames": [reserved]}), + ) + .unwrap(); + + assert!(!dir.path().join(&name).exists(), "{result}"); + let warnings = result["warnings"].as_array().unwrap(); + + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("already used by a texture file or folder"))), "{result}"); +} + +#[test] +fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let roughness = json!([["L", {"Channel": {"channel": "Roughness"}}]]); + let colour = json!([["R", {"Channel": {"channel": "BaseColor"}}], ["G", {"Channel": {"channel": "BaseColor", "component": 1}}], ["B", {"Channel": {"channel": "BaseColor", "component": 2}}], ["A", {"Constant": 0.5}]]); + let mut preset = json!({"name": "Two and a PSD", "maps": [ + {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, + {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, + ]}); + + // Four 16-bit RGBA layers at 8192 pixels exceed the 2 GiB PSD limit + for layer in 0..4 { + preset["maps"].as_array_mut().unwrap().push(json!({"file": format!("layer{layer}"), "format": "Psd", "bit_depth": 16, "channels": colour})); + } + let sizes: Vec<_> = (2..6).map(|map| json!({"map": map, "size": 8192})).collect(); + let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": sizes, "reservedNames": reserved}); + let plan = execute(&mut session, "export.plan", ¶ms(Vec::new())).unwrap(); + let first = plan[0]["file"].as_str().unwrap().to_owned(); + let second = plan[1]["file"].as_str().unwrap().to_owned(); + let psd_warning = + |warnings: &serde_json::Value| warnings.as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))); + assert!(plan.as_array().unwrap().len() == 2 && psd_warning(&plan[0]["warnings"]), "{plan}"); + + let result = execute(&mut session, "file.exportTextures", ¶ms(vec![first.clone()])).unwrap(); + + assert!(psd_warning(&result["warnings"]), "{result}"); + assert!(dir.path().join(&second).exists() && !dir.path().join(&first).exists(), "{result}"); +} diff --git a/crates/engine/tests/it/export_maps.rs b/crates/engine/tests/it/export_maps.rs index 991b5f32..f147ef1b 100644 --- a/crates/engine/tests/it/export_maps.rs +++ b/crates/engine/tests/it/export_maps.rs @@ -105,3 +105,24 @@ fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() { } assert_eq!(result["files"].as_array().unwrap().len(), names.len()); } + +#[test] +fn export_preview_shows_a_packed_map_small_and_nothing_for_a_left_out_one() { + let mut s = session(); + let preset = s.export_preset("Unity HDRP (Mask Map)").unwrap(); + let mask = preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let params = json!({"preset": preset.name, "ts": 0, "map": mask, "side": 16}); + + let preview = execute(&mut s, "export.preview", ¶ms).unwrap(); + let (width, height) = (preview["width"].as_u64().unwrap(), preview["height"].as_u64().unwrap()); + + assert!(width <= 16 && height > 0, "{preview}"); + assert_eq!(preview["channels"], json!(["R", "G", "B", "A"]), "the mask map packs four channels"); + assert_eq!(preview["pixels"].as_array().unwrap().len() as u64, width * height * 4); + + let left_out = json!({"preset": preset.name, "ts": 0, "map": mask, "maps": [{"map": mask, "enabled": false}]}); + + assert!(execute(&mut s, "export.preview", &left_out).unwrap().is_null(), "a map the export leaves out has no file to show"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name})).is_err(), "the map is required"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name, "map": preset.maps.len()})).is_err()); +} diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 29311091..399355f3 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -167,3 +167,26 @@ fn inspect_reports_the_reference_controls_set() { assert!(inspected.contains(&format!("\"{key}\"")) && inspected.contains(value), "{key} with {value} in {inspected}"); } } + +#[test] +fn inspect_reports_direction_only_on_the_earlier_model() { + let mut session = session(); + let earlier_dir = add(&mut session, json!({"generator": "direction", "direction": [1.0, 0.0, 0.0]})); + let light_dir = add(&mut session, json!({"generator": "direction", "lightHorizontal": 90.0})); + let earlier_pos = add(&mut session, json!({"generator": "position", "direction": [0.0, 0.0, 1.0]})); + let section_pos = add(&mut session, json!({"generator": "position", "sectionContrast": 0.25})); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap(); + let effects = inspected["layers"][0]["mask"]["effects"].as_array().unwrap(); + let gen_of = |effect_id: u64| &effects.iter().find(|entry| entry["id"] == effect_id).unwrap()["generator"]; + + assert_eq!(gen_of(earlier_dir)["direction"], json!([1.0, 0.0, 0.0])); + assert!(gen_of(earlier_dir).get("light").is_none()); + assert!(gen_of(light_dir).get("direction").is_none()); + assert!(gen_of(light_dir).get("light").is_some()); + + assert_eq!(gen_of(earlier_pos)["direction"], json!([0.0, 0.0, 1.0])); + assert!(gen_of(earlier_pos).get("section").is_none()); + assert!(gen_of(section_pos).get("direction").is_none()); + assert!(gen_of(section_pos).get("section").is_some()); +} diff --git a/crates/engine/tests/it/ior_specular.rs b/crates/engine/tests/it/ior_specular.rs new file mode 100644 index 00000000..239e6c0e --- /dev/null +++ b/crates/engine/tests/it/ior_specular.rs @@ -0,0 +1,107 @@ +//! The "Use IOR for specular reflection" shader setting persists with projects and templates +//! and stays off for projects and templates without it (texturecraft #749). + +use std::io::{Cursor, Write}; + +use serde_json::json; +use texturecraft_engine::{Session, execute, geom::primitives}; +use zip::{ZipWriter, write::SimpleFileOptions}; + +const IOR: f32 = 1.8; + +fn session() -> Session { + Session::new_project("Ior", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +fn opt_in(session: &mut Session) { + execute(session, "display.set", &json!({"iorSpecular": true, "ior": IOR})).unwrap(); +} + +fn new_project_uses_ior_specular(session: &mut Session, template: &str) -> bool { + execute(session, "project.new", &json!({"template": template})).unwrap(); + session.doc.project.display.ior_specular +} + +#[test] +fn the_opt_in_survives_save_and_reopen() { + let mut session = session(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("ior.tcraft"); + opt_in(&mut session); + + execute(&mut session, "file.saveAs", &json!({"path": path})).unwrap(); + execute(&mut session, "project.new", &json!({})).unwrap(); + let new_project_uses_it = session.doc.project.display.ior_specular; + execute(&mut session, "file.open", &json!({"path": path})).unwrap(); + + assert!(!new_project_uses_it, "a new project starts with the setting off"); + let display = &session.doc.project.display; + assert!(display.ior_specular); + assert_eq!(display.ior, IOR); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_older_save_cannot_clear_ior_specular_changes() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("ior.tcraft"); + + for params in [json!({"iorSpecular": false}), json!({"ior": 2.0}), json!({"specGloss": true})] { + let mut session = session(); + opt_in(&mut session); + let save = session.save_task(path.to_str().unwrap(), true); + + execute(&mut session, "display.set", ¶ms).unwrap(); + save.run(None).unwrap().apply(&mut session); + + assert!(session.modified, "the archive predates the edit {params}"); + let archived = texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap(); + assert_ne!(archived.doc.project.display, session.doc.project.display); + } +} + +#[test] +fn a_project_saved_before_the_setting_opens_with_it_off() { + let mut session = session(); + opt_in(&mut session); + let mut project = serde_json::to_value(&session.doc.project).unwrap(); + let removed = project["display"].as_object_mut().unwrap().remove("ior_specular"); + let mut archive = ZipWriter::new(Cursor::new(Vec::new())); + archive.start_file("project.json", SimpleFileOptions::default()).unwrap(); + archive.write_all(&serde_json::to_vec(&project).unwrap()).unwrap(); + let bytes = archive.finish().unwrap().into_inner(); + + let older = Session::from_project_bytes(&bytes).unwrap(); + + assert_eq!(removed, Some(json!(true)), "the stripped field is the saved setting"); + let display = &older.doc.project.display; + assert!(!display.ior_specular); + assert_eq!(display.ior, IOR, "the other shader settings still load"); +} + +#[test] +fn the_opt_in_survives_a_template_and_other_templates_leave_it_off() { + let library = tempfile::tempdir().unwrap(); + let mut author = session(); + author.load_templates(library.path().to_path_buf()); + opt_in(&mut author); + execute(&mut author, "project.template.save", &json!({"name": "Glass"})).unwrap(); + + // A template written before the setting existed + let older = json!({"name": "Older", "resolution": 128, "ior": IOR}); + std::fs::write(library.path().join("Older.json"), serde_json::to_vec(&older).unwrap()).unwrap(); + + let mut user = session(); + let warnings = user.load_templates(library.path().to_path_buf()); + let listed = execute(&mut user, "project.templates", &json!({})).unwrap(); + + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(new_project_uses_ior_specular(&mut user, "Glass")); + assert_eq!(user.doc.project.display.ior, IOR); + assert!(!new_project_uses_ior_specular(&mut user, "Older")); + for template in listed.as_array().unwrap() { + let name = template["name"].as_str().unwrap(); + assert_eq!(template["iorSpecular"], json!(name == "Glass"), "{name}"); + assert_eq!(new_project_uses_ior_specular(&mut user, name), name == "Glass", "{name}"); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 23517f4a..01f63de0 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -2,8 +2,11 @@ //! Keep feature tests in their own modules; the standalone session.rs target remains available. mod add_mask_items; +mod auto_rebake; mod bake; mod bake_checks; +mod bake_log; +mod bake_out_of_date; mod bake_resolution; mod bake_settings; mod bake_tiles; @@ -46,6 +49,7 @@ mod generator_wear; mod gradient_map; mod high_poly_missed; mod instances; +mod ior_specular; mod layer_multi_select; mod mask_clone_smudge; mod mask_export; @@ -64,6 +68,7 @@ mod polygon_fill; mod project_recovery; mod rebuilt_uv_layout; mod rename_project; +mod resource_updater; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index b69391bd..c6ee8dfe 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -197,11 +197,15 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() { ) .unwrap(); + // A PSD holds every map of the texture set as a layer let all = names(&result); - assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}"); + let template_file = if format == "psd" { ".psd".to_string() } else { format!("_baseColor.{ext}") }; + + assert!(all.iter().any(|f| f.ends_with(&template_file)), "{format}: the template's files keep the file type: {all:?}"); let mtlx = files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("{format}: no .mtlx in {all:?}")); let text = std::fs::read_to_string(mtlx).unwrap(); let wanted = if format == "tiff" { "tif" } else { "png" }; + assert!(text.contains(&format!("_base_color.{wanted}\"")), "{format}: {text}"); for file in referenced(&text) { assert!(dir.join(&file).is_file(), "{format}: {file} is not in {all:?}"); @@ -209,6 +213,27 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() { } } +#[test] +fn materialx_png_fallback_preserves_the_selected_maps_size() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("map-size-fallback"); + let options = json!({ + "dir": dir.display().to_string(), "preset": OPENPBR, "ts": 0, "size": 128, "materialX": true, + "maps": [{"map": 0, "format": "psd", "size": 256}] + }); + + let result = execute(&mut session, "file.exportTextures", &options).unwrap(); + + let files = files(&result); + + assert!(files.iter().any(|file| file.ends_with(".psd")), "{result}"); + let base = files.iter().find(|file| file.ends_with("_base_color.png")).unwrap(); + let roughness = files.iter().find(|file| file.ends_with("_specular_roughness.png")).unwrap(); + + assert_eq!(image::image_dimensions(base).unwrap(), (256, 256)); + assert_eq!(image::image_dimensions(roughness).unwrap(), (128, 128)); +} + #[test] fn the_openpbr_maps_follow_the_size_and_colour_space_of_the_export() { let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/engine/tests/it/rebuilt_uv_layout.rs b/crates/engine/tests/it/rebuilt_uv_layout.rs index 23570231..ab794ae1 100644 --- a/crates/engine/tests/it/rebuilt_uv_layout.rs +++ b/crates/engine/tests/it/rebuilt_uv_layout.rs @@ -56,6 +56,31 @@ fn a_rebuilt_project_reopens_with_its_saved_uv_layout_not_a_new_unwrap() { assert_eq!(corner_uvs(&resaved.source_mesh()), locked, "saving again keeps the layout"); } +#[test] +fn a_pending_save_keeps_the_rebuilt_layout_and_releases_unused_bake_geometry() { + let mut session = Session::from_project_bytes(&locked_archive()).unwrap(); + session.add_high_poly_bytes("high.obj", QUAD_OBJ.as_bytes().to_vec()).unwrap(); + let expected_layout = corner_uvs(&session.source_mesh()); + let high = &session.doc.bake_meshes.high[0]; + let encoded = std::sync::Arc::downgrade(&high.bytes); + let parsed = std::sync::Arc::downgrade(&high.mesh); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("saved.tcraft"); + + let save = session.save_task(path.to_str().unwrap(), true); + drop(session); + assert!(parsed.upgrade().is_none(), "only the source UV layout needs parsed geometry"); + assert!(encoded.upgrade().is_some(), "the pending archive shares the original file bytes"); + + save.run(None).unwrap(); + let reopened = texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap(); + + assert!(encoded.upgrade().is_none(), "the worker released the original bytes"); + assert_eq!(reopened.doc.bake_meshes.high[0].bytes.as_slice(), QUAD_OBJ.as_bytes()); + assert!(reopened.doc.project.mesh_rebuild_uvs); + assert_eq!(corner_uvs(&reopened.source_mesh()), expected_layout); +} + #[test] fn opening_a_builtin_project_refuses_rebuilt_mesh_uvs() { let mut file = texturecraft_engine::formats::load_project_bytes(&locked_archive()).unwrap(); diff --git a/crates/engine/tests/it/rename_project.rs b/crates/engine/tests/it/rename_project.rs index 5510163b..2bcca1a6 100644 --- a/crates/engine/tests/it/rename_project.rs +++ b/crates/engine/tests/it/rename_project.rs @@ -1,9 +1,8 @@ //! `project.rename`: the name `$project` stands for in export file names. use serde_json::json; -use texturecraft_engine::{Session, execute}; - use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; #[test] fn a_renamed_project_exports_under_its_new_name_until_undone() { @@ -13,22 +12,52 @@ fn a_renamed_project_exports_under_its_new_name_until_undone() { execute(&mut session, "project.rename", &json!({"name": " Knight final "})).unwrap(); - let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap().to_string(); - assert!(plan.contains("Knight_final_") && !plan.contains("hero_"), "{plan}"); + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + let renamed_file = plan[0]["file"].as_str().unwrap(); + assert!(renamed_file.starts_with("Knight_final_"), "{renamed_file}"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.name, "Knight final"); execute(&mut session, "edit.undo", &json!({})).unwrap(); + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + assert_eq!(session.doc.project.name, "hero"); + let restored_file = plan[0]["file"].as_str().unwrap(); + assert!(restored_file.starts_with("hero_"), "{restored_file}"); } #[test] fn an_unusable_or_unchanged_project_name_edits_nothing() { + use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); - for name in [json!(null), json!(7), json!(" "), json!("a\nb"), json!("x".repeat(129))] { - assert!(execute(&mut session, "project.rename", &json!({"name": name.clone()})).is_err(), "{name}"); + + for name in [json!(null), json!(7), json!(" "), json!("a\nb"), json!("界".repeat(MAX_PROJECT_NAME_CHARS + 1))] { + assert!(execute(&mut session, "project.rename", &json!({"name": name})).is_err(), "{name}"); } execute(&mut session, "project.rename", &json!({"name": "hero"})).unwrap(); assert_eq!(session.doc.project.name, "hero"); assert!(!session.modified, "nothing changed"); + assert!(!session.can_undo()); + + let at_limit = "界".repeat(MAX_PROJECT_NAME_CHARS); + let result = execute(&mut session, "project.rename", &json!({"name": format!(" {at_limit} ")})).unwrap(); + + assert_eq!(result["name"], at_limit); +} + +#[test] +fn a_renamed_project_is_inserted_into_the_template_as_literal_text() { + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap(); + preset["maps"][0]["file"] = json!("$project/$mesh"); + + execute(&mut session, "project.rename", &json!({"name": "Knight/$mesh"})).unwrap(); + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + + let file = plan[0]["file"].as_str().unwrap(); + assert!(file.starts_with("Knight__mesh/cube."), "{file}"); } diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs new file mode 100644 index 00000000..ee71556d --- /dev/null +++ b/crates/engine/tests/it/resource_updater.rs @@ -0,0 +1,547 @@ +//! The Resources Updater: image resources remember their files, a changed file shows as outdated, +//! Update reads it again (one undo step, recompositing its layers) and Relink follows another file + +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{ResourceStatus, Session, execute}; + +const RESOLUTION: u32 = 128; +const SAMPLE_STRIDE: usize = 8; +const RED: [u8; 4] = [255, 0, 0, 255]; +const GREEN: [u8; 4] = [0, 255, 0, 255]; + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap() +} + +/// Write a `size` × `size` PNG of one colour (sizes differ between versions, so the file size changes too) +fn write_png(path: &Path, size: u32, color: [u8; 4]) { + image::RgbaImage::from_pixel(size, size, image::Rgba(color)).save(path).unwrap(); +} + +fn text(path: &Path) -> &str { + path.to_str().unwrap() +} + +/// Give the file at `path` the modification time `time` without changing its contents +fn set_modified(path: &Path, time: SystemTime) { + std::fs::File::options().write(true).open(path).unwrap().set_modified(time).unwrap(); +} + +fn modified(path: &Path) -> SystemTime { + std::fs::metadata(path).unwrap().modified().unwrap() +} + +fn import(s: &mut Session, path: &Path) -> String { + execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string() +} + +/// Import `path` and show it as a base colour fill; returns the resource name +fn import_as_fill(s: &mut Session, path: &Path) -> String { + let name = import(s, path); + execute(s, "layer.add.image", &json!({"name": name})).unwrap(); + s.update(); + name +} + +fn base_colors(s: &Session) -> Vec<[f32; 3]> { + let composite = &s.caches[s.ts()].composite; + let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE); + samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() +} + +fn status_of(s: &mut Session, name: &str) -> ResourceStatus { + s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status +} + +#[test] +fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("bricks.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + let before = base_colors(&s); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); + + write_png(&file, 8, GREEN); + let status = execute(&mut s, "resource.status", &Value::Null).unwrap(); + + assert_eq!(status["outdated"], json!(1)); + assert_eq!(status["resources"][0]["name"], json!(name)); + assert_eq!(status["resources"][0]["status"], json!("outdated")); + + let steps = s.history_labels().len(); + let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); + s.update(); + let after = base_colors(&s); + + assert_eq!(updated["updated"], json!([name])); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); + assert_eq!(s.images[&name].width, 8, "the new pixels are decoded"); + assert_ne!(after, before, "the fill using the resource recomposited"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name"); + assert_eq!(base_colors(&s), before); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); + + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 8); + assert_eq!(base_colors(&s), after); +} + +#[test] +fn outdated_resources_come_first_then_missing_up_to_date_unlinked_and_materials() { + let dir = tempfile::tempdir().unwrap(); + let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name)); + for file in [&fine, &gone, &changed] { + write_png(file, 4, RED); + } + let mut s = session(); + let png = std::fs::read(&fine).unwrap(); + s.import_resource_bytes("a_unlinked.png", png).unwrap(); + for file in [&fine, &gone, &changed] { + import(&mut s, file); + } + + // The environment map and the brush alpha are image resources like any other + let environment = format!("{}b_fine.png", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX); + execute(&mut s, "display.set", &json!({"environment": environment})).unwrap(); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "d_changed.png"}})).unwrap(); + + // A linked MaterialCraft material keeps its package as a resource without a file + s.doc.resources.insert("a_brick.mcmat".to_string(), Arc::new(b"package".to_vec())); + let layer = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let link = serde_json::from_value(json!({"name": "Brick", "package": "a_brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut s.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind { + fill.link = Some(link); + } + + std::fs::remove_file(&gone).unwrap(); + write_png(&changed, 8, GREEN); + + let states = s.resource_states(); + let order: Vec<&str> = states.iter().map(|state| state.name.as_str()).collect(); + let statuses: Vec<&str> = states.iter().map(|state| state.status.id()).collect(); + + assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png", "a_brick.mcmat"], "by status first, against the name order"); + assert_eq!(statuses, ["outdated", "missing", "upToDate", "noSource", "material"], "the alpha's and the environment's files are checked too"); + let error = execute(&mut s, "resource.update", &json!({"names": ["a_brick.mcmat"]})).unwrap_err(); + assert!(error.to_string().contains("only image resources can be relinked"), "{error}"); +} + +#[test] +fn a_same_size_file_is_compared_by_contents_once_per_time() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("same.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import(&mut s, &file); + let original = std::fs::read(&file).unwrap(); + let later = modified(&file) + Duration::from_secs(10); + + // Saved again unchanged: a new time alone is no change, and updating adds no step + set_modified(&file, later); + let steps = s.history_labels().len(); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); + assert_eq!(execute(&mut s, "resource.update", &json!({})).unwrap()["updated"], json!([])); + assert_eq!(s.history_labels().len(), steps); + + // Different bytes of the same size and time are not read again: the verdict for that size and time stands + let mut edited = original.clone(); + let last = edited.len() - 1; + edited[last] ^= 0xff; + std::fs::write(&file, &edited).unwrap(); + set_modified(&file, later); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate, "the remembered verdict is used"); + + // Another time reads the file, and its bytes differ + set_modified(&file, later + Duration::from_secs(10)); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); +} + +#[cfg(unix)] +#[test] +fn a_file_without_a_usable_timestamp_is_compared_on_each_check() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("archived.png"); + write_png(&path, 4, RED); + set_modified(&path, SystemTime::UNIX_EPOCH - Duration::from_secs(20)); + let mut session = session(); + let name = import(&mut session, &path); + assert_eq!(status_of(&mut session, &name), ResourceStatus::UpToDate); + + let mut changed = std::fs::read(&path).unwrap(); + changed[0] ^= 1; + std::fs::write(&path, changed).unwrap(); + set_modified(&path, SystemTime::UNIX_EPOCH - Duration::from_secs(10)); + + assert_eq!(status_of(&mut session, &name), ResourceStatus::Outdated); +} + +#[test] +fn a_missing_file_is_reported_and_updating_it_changes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("gone.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + std::fs::remove_file(&file).unwrap(); + let steps = s.history_labels().len(); + + let state = s.resource_states().into_iter().find(|state| state.name == name).unwrap(); + let error = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap_err(); + + assert_eq!(state.status, ResourceStatus::Missing); + assert!(state.error.is_some(), "the reason is shown"); + assert!(error.to_string().contains("nothing was updated"), "{error}"); + assert_eq!(s.history_labels().len(), steps); + assert_eq!(s.images[&name].width, 4, "the resource keeps its pixels"); +} + +#[test] +fn an_unreadable_file_fails_alone_while_the_others_update() { + let dir = tempfile::tempdir().unwrap(); + let (kept, gone) = (dir.path().join("kept.png"), dir.path().join("gone.png")); + write_png(&kept, 4, RED); + write_png(&gone, 4, RED); + let mut s = session(); + let kept_name = import_as_fill(&mut s, &kept); + let gone_name = import_as_fill(&mut s, &gone); + write_png(&kept, 8, GREEN); + std::fs::remove_file(&gone).unwrap(); + + let result = execute(&mut s, "resource.update", &json!({"names": [kept_name, gone_name]})).unwrap(); + + assert_eq!(result["updated"], json!([kept_name])); + assert_eq!(result["failed"][0]["name"], json!(gone_name)); + assert_eq!(s.images[&kept_name].width, 8); +} + +#[test] +fn relink_reads_another_file_and_follows_it_from_then_on() { + let dir = tempfile::tempdir().unwrap(); + let (first, second) = (dir.path().join("first.png"), dir.path().join("second.png")); + write_png(&first, 4, RED); + write_png(&second, 8, GREEN); + let mut s = session(); + let name = import_as_fill(&mut s, &first); + let before = base_colors(&s); + let steps = s.history_labels().len(); + + execute(&mut s, "resource.relink", &json!({"name": name, "path": text(&second)})).unwrap(); + s.update(); + + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(s.images[&name].width, 8, "the resource keeps its name and takes the new file's pixels"); + assert_ne!(base_colors(&s), before); + assert!(s.doc.project.resource_sources[&name].path.ends_with("second.png")); + + // The old file no longer matters, the new one does + write_png(&first, 16, GREEN); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); + write_png(&second, 16, RED); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link"); +} + +#[test] +fn relink_refuses_resources_that_are_not_images() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("picture.png"); + write_png(&file, 4, RED); + let mut s = session(); + s.doc.resources.insert("material.mcmat".to_string(), Arc::new(vec![1, 2, 3])); + let steps = s.history_labels().len(); + + let error = execute(&mut s, "resource.relink", &json!({"name": "material.mcmat", "path": text(&file)})).unwrap_err(); + + assert!(error.to_string().contains("no image resource"), "{error}"); + assert_eq!(*s.doc.resources["material.mcmat"], vec![1, 2, 3]); + assert_eq!(s.history_labels().len(), steps); +} + +#[test] +fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("kept.png"); + write_png(&file, 4, RED); + let mut s = session(); + let linked = import_as_fill(&mut s, &file); + let png = std::fs::read(&file).unwrap(); + let unlinked = s.import_resource_bytes("made.png", png).unwrap(); + + assert_eq!(status_of(&mut s, &unlinked), ResourceStatus::NoSource); + assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err()); + + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + write_png(&file, 8, GREEN); + + assert_eq!(status_of(&mut reopened, &linked), ResourceStatus::Outdated); +} + +#[test] +fn a_removed_resource_forgets_its_file() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("old.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import(&mut s, &file); + + execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); + let png = std::fs::read(&file).unwrap(); + let reused = s.import_resource_bytes("old.png", png).unwrap(); + + assert_eq!(reused, name, "the name is free again"); + assert_eq!(status_of(&mut s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); +} + +/// The material ball: texture sets "Ball" and "Base" +fn ball() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +fn ambient_occlusion(s: &Session) -> Vec { + s.doc.baked[&0].maps[&BakedMap::AmbientOcclusion].as_ref().clone() +} + +#[test] +fn an_imported_mesh_map_follows_its_changed_file_until_something_else_replaces_it() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + write_png(&file, 4, [60, 60, 60, 255]); + let mut s = ball(); + execute(&mut s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let name = s.doc.project.resource_sources.keys().next().expect("the file is remembered").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 8, [200, 200, 200, 255]); + execute(&mut s, "resource.update", &json!({})).unwrap(); + let updated = ambient_occlusion(&s); + + assert_ne!(updated, imported, "the mesh map is resampled from the new file"); + + // Another image in the slot is not overwritten by a later change of the file + let other = dir.path().join("other.png"); + write_png(&other, 4, [10, 10, 10, 255]); + let other_name = import(&mut s, &other); + execute(&mut s, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": other_name})).unwrap(); + let replaced = ambient_occlusion(&s); + write_png(&file, 16, [120, 120, 120, 255]); + let result = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap(); + + assert_eq!(result["updated"], json!([name]), "the resource itself still updates"); + assert_eq!(ambient_occlusion(&s), replaced, "the mesh map keeps the image set over it"); +} + +#[test] +fn an_explicit_mesh_map_replacement_breaks_the_import_link_even_when_pixels_match() { + let dir = tempfile::tempdir().unwrap(); + let original = dir.path().join("Ball_ao.png"); + let replacement = dir.path().join("replacement.png"); + let equal_color = [60, 60, 60, 255]; + write_png(&original, 4, equal_color); + write_png(&replacement, 4, equal_color); + let mut session = ball(); + let replacement_name = import(&mut session, &replacement); + execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&original)}]})).unwrap(); + let imported = ambient_occlusion(&session); + + execute(&mut session, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": replacement_name})).unwrap(); + write_png(&original, 8, [200, 200, 200, 255]); + let result = execute(&mut session, "resource.update", &Value::Null).unwrap(); + + assert_eq!(result["updated"], json!(["Ball_ao.png"])); + assert!(ambient_occlusion(&session) == imported, "replacing a map explicitly takes ownership even when the pixels were equal"); +} + +#[test] +fn a_file_import_replaces_bake_provenance_and_clear_detaches_the_link() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_position.png"); + write_png(&file, 4, RED); + let mut session = ball(); + execute(&mut session, "bake.run", &json!({"ts": 0, "resolution": 32, "maps": ["position"], "dilation": 0})).unwrap(); + execute(&mut session, "bake.settings", &json!({"ts": 0, "positionMode": "boundingBox"})).unwrap(); + assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "the previous bake is stale"); + + execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + write_png(&file, 8, [0, 0, 255, 255]); + let imported = session.baked(0).unwrap().maps[&BakedMap::Position].clone(); + execute(&mut session, "resource.update", &Value::Null).unwrap(); + + assert_ne!(*imported, *session.baked(0).unwrap().maps[&BakedMap::Position], "the replacement follows its file"); + assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "the imported map has no bake provenance"); + + execute(&mut session, "textureSet.meshMap.clear", &json!({"ts": 0, "map": "position"})).unwrap(); + assert!(session.doc.project.resource_sources["Ball_position.png"].mesh_map.is_none(), "clearing releases the file link"); + write_png(&file, 16, RED); + execute(&mut session, "resource.update", &Value::Null).unwrap(); + assert!(!session.baked(0).unwrap().maps.contains_key(&BakedMap::Position), "updating the old source leaves the slot empty"); +} + +#[test] +fn removing_unused_resources_keeps_the_file_that_feeds_an_imported_mesh_map() { + let dir = tempfile::tempdir().unwrap(); + let map_file = dir.path().join("Ball_ao.png"); + let unused_file = dir.path().join("unused.png"); + write_png(&map_file, 4, [60, 60, 60, 255]); + write_png(&unused_file, 4, RED); + let mut session = ball(); + let unused_name = import(&mut session, &unused_file); + execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&map_file)}]})).unwrap(); + let imported = ambient_occlusion(&session); + + let cleanup = execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(cleanup["removed"], json!([unused_name])); + write_png(&map_file, 8, [200, 200, 200, 255]); + let update = execute(&mut session, "resource.update", &Value::Null).unwrap(); + + assert_eq!(update["updated"], json!(["Ball_ao.png"])); + assert_ne!(ambient_occlusion(&session), imported); +} + +#[test] +fn updating_duplicate_names_replaces_each_image_once_and_releases_old_pixels() { + let dir = tempfile::tempdir().unwrap(); + let files = ["first.png", "second.png"].map(|name| dir.path().join(name)); + let mut session = session(); + let names = files.each_ref().map(|path| { + write_png(path, 4, RED); + import(&mut session, path) + }); + let old_pixels = names.each_ref().map(|name| Arc::downgrade(&session.images[name])); + for file in &files { + write_png(file, 8, GREEN); + } + + let result = execute(&mut session, "resource.update", &json!({"names": [&names[0], &names[1], &names[0]]})).unwrap(); + + assert_eq!(result["updated"], json!(names)); + assert!(old_pixels.iter().all(|pixels| pixels.upgrade().is_none()), "history keeps the encoded bytes, so replaced decoded images can drop"); + for name in names { + assert_eq!(session.images[&name].width, 8); + } +} + +#[test] +fn pbr_folder_and_materialx_imports_remember_their_image_files() { + let dir = tempfile::tempdir().unwrap(); + let long_name = |suffix: &str| format!("{}{suffix}", "m".repeat(texturecraft_formats::MAX_RESOURCE_NAME_LEN - suffix.len())); + let color = dir.path().join(long_name("_col.png")); + write_png(&color, 4, RED); + std::fs::create_dir(dir.path().join("tex")).unwrap(); + let base_name = long_name("_base.png"); + let base = dir.path().join("tex").join(&base_name); + write_png(&base, 4, GREEN); + let mtlx = dir.path().join("m.mtlx"); + let document = r#" + + + + +"#; + std::fs::write(&mtlx, document.replace("base.png", &base_name)).unwrap(); + let mut s = session(); + import(&mut s, &color); + import(&mut s, &base); + + let pbr = execute(&mut s, "file.importPbrFolder", &json!({"files": [text(&color)]})).unwrap(); + let materialx = execute(&mut s, "file.importMaterialX", &json!({"path": text(&mtlx)})).unwrap(); + let pbr_name = pbr["resources"][0].as_str().unwrap().to_string(); + let materialx_name = materialx["resources"][0].as_str().unwrap().to_string(); + + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(Path::new(&reopened.doc.project.resource_sources[&pbr_name].path).canonicalize().unwrap(), color.canonicalize().unwrap()); + assert_eq!(Path::new(&reopened.doc.project.resource_sources[&materialx_name].path).canonicalize().unwrap(), base.canonicalize().unwrap()); + + write_png(&color, 8, GREEN); + write_png(&base, 8, RED); + + let rows = reopened.resource_states(); + let missing: Vec<_> = [&pbr_name, &materialx_name] + .into_iter() + .filter(|name| !rows.iter().any(|row| row.name == name.as_str() && row.status == ResourceStatus::Outdated)) + .collect(); + assert!(missing.is_empty(), "both material imports must keep their source images after reopening: {missing:?}"); +} + +#[test] +fn a_mesh_map_imported_twice_follows_the_latest_file() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + let import_file = |s: &mut Session| execute(s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let mut s = ball(); + write_png(&file, 4, [60, 60, 60, 255]); + import_file(&mut s); + let first = s.doc.project.resource_sources.keys().next().unwrap().clone(); + write_png(&file, 8, [200, 200, 200, 255]); + import_file(&mut s); + let latest = s.doc.project.resource_sources.keys().find(|name| **name != first).expect("a second resource").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 16, [10, 10, 10, 255]); + execute(&mut s, "resource.update", &json!({"names": [latest]})).unwrap(); + + assert_ne!(ambient_occlusion(&s), imported, "the mesh map follows the file imported last"); + assert!(s.doc.project.resource_sources[&first].mesh_map.is_none(), "the earlier import no longer feeds the slot"); +} + +#[test] +fn an_undecodable_saved_resource_is_reported_even_when_its_file_is_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("broken.png"); + write_png(&file, 4, RED); + let mut session = session(); + let name = import(&mut session, &file); + let invalid = b"incomplete image".to_vec(); + std::fs::write(&file, &invalid).unwrap(); + session.doc.resources.insert(name.clone(), Arc::new(invalid)); + session.images.remove(&name); + + let result = execute(&mut session, "resource.update", &json!({"names": [name]})); + + assert!(result.unwrap_err().to_string().contains("nothing was updated")); + assert!(!session.images.contains_key(&name)); +} + +#[test] +fn a_rejected_update_restores_all_previously_decoded_images() { + let dir = tempfile::tempdir().unwrap(); + let mut session = session(); + let names = ["left.png", "right.png"].map(|name| { + let path = dir.path().join(name); + write_png(&path, 4, RED); + let imported = import_as_fill(&mut session, &path); + write_png(&path, 8, GREEN); + imported + }); + + // Make final document validation fail after both replacements have been processed + let layer = session.doc.project.layers.values_mut().next().unwrap(); + layer.kind = texturecraft_engine::core::LayerKind::Instance { source: layer.id }; + let steps = session.history_labels().len(); + + let result = execute(&mut session, "resource.update", &json!({"names": names})); + + assert!(result.unwrap_err().to_string().contains("would draw itself")); + assert_eq!(session.history_labels().len(), steps); + for name in names { + assert_eq!(session.images[&name].width, 4); + assert_eq!(status_of(&mut session, &name), ResourceStatus::Outdated); + } +} diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index e6ef7bd9..a130f813 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -407,3 +407,17 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { assert!(dir.join(&read.file).is_file(), "{} was written", read.file); } } + +#[test] +fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { + let mut s = ball(); + let dir = temp("psd"); + + let r = export(&mut s, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true})); + + assert!(files(&r).iter().any(|f| f.ends_with(".psd")), "{r}"); + let materials = read_back(&s, &dir); + + assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]); + assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}"); +} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 2319dbd7..8135b5b0 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -28,7 +28,6 @@ craft-image-codecs = { workspace = true } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } flate2 = { workspace = true } half = { workspace = true } -quick-xml = { workspace = true } zip = { workspace = true } exr = { workspace = true } serde = { workspace = true } diff --git a/crates/formats/README.md b/crates/formats/README.md index 66ee79e0..f32292cb 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -106,9 +106,13 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; collisions get `_2`, `_3`, … plus a warning. - A map is written only when one of its sources has data in the texture set (channel present, map baked, …); alpha from a missing channel is dropped. -- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour, deflate alpha), PGM 8/16 (gray; colour - becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, WebP 8 (lossless), PSD 8/16 (merged image, no - layers; alpha is an extra alpha channel, not transparency), EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. 8-bit files can be dithered +- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour, + deflate alpha), PGM 8/16 (gray; colour becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, + WebP 8 (lossless), PSD 8/16, EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. + PSD writes one file per texture set or UV tile, with each output map stored as a layer. + For tiled sets, `ExportOptions::atlas` writes one document for the whole set. Smaller maps + keep their sizes and align to the top left of the canvas. A `/` in a map + name creates a layer group inside the PSD. 8-bit files can be dithered (`ExportOptions::dither`, an 8×8 ordered pattern). When `ExportOptions::color_space` is unset, color maps default to sRGB in integer files and linear Rec.709 in float files. An explicit override can select another supported space. PGM writes sRGB or linear Rec.709 luminance and @@ -137,9 +141,24 @@ Built-in presets (each one lists the public specification its packing follows in | OpenPBR (separate maps) | one map per OpenPBR Surface input the set has: `base_color`, `base_metalness`, `specular_roughness`, `specular_roughness_anisotropy`, `coat_weight`, `coat_roughness`, `fuzz_weight`, `fuzz_color`, `fuzz_roughness`, `transmission_weight`, `subsurface_weight`, `emission_color`, `geometry_opacity`, `geometry_normal` (OpenGL), `height` (16-bit) | | Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | +| Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | +| glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | +| Redshift Standard Material (separate maps) | separate maps for the listed inputs when the set supplies their sources: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | +| Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | +| Sketchfab Metalness (separate maps) | `BaseColor` (no alpha), `Metalness`, `Roughness`, `Normal` (DirectX), `AmbientOcclusion`, `Emission` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | +The preset column gives the stable automation and saved-setting names. When a user preset shares +a table name, that name selects the user preset so saved settings keep working. To select the +built-in through automation, pass the exact `name` from its `builtin: true` entry in +`export.presets`. + +The export window describes four templates by their output. **Packed maps with a scattering mask** +targets Unreal Engine's subsurface input. **Separate coat, sheen and scattering maps** targets Redshift. +**Four maps with opacity in color** targets Roblox, and **Six maps with a negative-Y normal** +targets Sketchfab. + ### Project file (`project_file`) ```rust diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs new file mode 100644 index 00000000..f7be380c --- /dev/null +++ b/crates/formats/src/export/layered_psd.rs @@ -0,0 +1,242 @@ +//! A texture set's PSD: each output map a layer, a `/` in its name a layer group + +use craft_psd::{Compression, GroupSpec, LayerSpec, PixelData, PsdBuilder}; +use texturecraft_core::TextureSet; +use texturecraft_texel::linear_to_srgb; + +use super::encoding::Encoding; +use super::map_renderer::MapRenderer; +use super::{ + ExportOptions, ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, Padding, PlannedFile, PlannedLayer, check_psd_size, psd_size, + quantize_integer, quantize_u8, quantize_u16, +}; +use crate::{FormatError, Result}; + +/// Where alpha sits in an RGBA texel +const ALPHA_INDEX: usize = 3; + +/// Check the file limits and the working memory against `working_limit` (None: unlimited), returning the canvas size and estimated encoded bytes +pub(super) fn preflight<'a>( + set: &TextureSet, + options: &ExportOptions, + tile: Option, + depth: u8, + layers: impl Iterator + Clone, + working_limit: Option, +) -> Result<((u32, u32), u64)> { + let (canvas, file_bytes, working_bytes) = working_set(set, options, tile, depth, layers)?; + if working_limit.is_some_and(|limit| working_bytes >= limit) { + let (width, height) = canvas; + return Err(FormatError::Invalid(format!( + "a PSD at {width}×{height} would exceed the working memory budget; use a smaller export size, fewer PSD maps or another format" + ))); + } + + Ok((canvas, file_bytes)) +} + +/// The canvas size, estimated encoded bytes and peak working bytes of one PSD, after checking the file limits +fn working_set<'a>( + set: &TextureSet, + options: &ExportOptions, + tile: Option, + depth: u8, + layers: impl Iterator + Clone, +) -> Result<((u32, u32), u64, u64)> { + let texels = |(width, height)| u64::from(width) * u64::from(height); + let folder_count = layers.clone().map(|layer| layer.name.matches('/').count()).sum(); + let sizes = layers.map(|layer| psd_size(set, tile, options.map_size(layer.map))); + let (canvas, file_bytes) = check_psd_size(sizes.clone(), folder_count, depth)?; + let float_bytes_per_texel = (PSD_RGBA_PLANES * size_of::()) as u64; + let source_bytes = texels(psd_size(set, tile, None)).saturating_mul(float_bytes_per_texel); + let largest_layer_bytes = sizes.map(texels).max().unwrap_or(0) * float_bytes_per_texel; + + // The merged image is built a row at a time: a canvas row and a layer row in floating point + let merge_bytes = 2 * u64::from(canvas.0) * float_bytes_per_texel; + + // Resizing overlaps source and destination, and RGBA conversion can overlap two output buffers + let mut scratch_bytes = source_bytes.saturating_add(largest_layer_bytes).max(2 * largest_layer_bytes); + if matches!(options.padding, Padding::DilationDiffusion(_)) { + // A copied block, its weights, and the smaller pyramid levels fit within this source allowance + scratch_bytes = scratch_bytes.max(source_bytes.saturating_mul(3)); + } + + let mut padding_bytes = 0; + let mut padding_peak = 0; + if options.padding != Padding::None { + let atlas_texels = texels(set.size()); + padding_bytes = atlas_texels.saturating_mul(size_of::() as u64); + + // The atlas keeps its dilation indices after the frontiers are freed + padding_peak = padding_bytes.saturating_add(atlas_texels.saturating_mul((4 * size_of::()) as u64)); + } + + // The quantized layers kept so far and the merged image are part of the file; the encoder can hold staged pixels, planes and the output at once + let rendering = scratch_bytes.max(merge_bytes).saturating_add(file_bytes); + let encoding = 3 * file_bytes; + let working_bytes = padding_bytes.saturating_add(rendering.max(encoding)).max(padding_peak); + Ok((canvas, file_bytes, working_bytes)) +} + +/// Render each layer at its requested size, aligned to the upper-left corner of the PSD canvas. +pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u32, u32)) -> Result { + let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; + + // Only the current layer is in floating point; the others are kept as the file stores them + let mut pixels = Vec::with_capacity(layers.len()); + let mut embedded = None; + for layer in layers.iter().rev() { + let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; + embedded = map.embed.or(embedded); + let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; + let layer_pixels = rgba_pixel_data(map.data, map.component_count, &map.srgb, map.size.0, encoding)?; + pixels.push((layer.name.as_str(), map.size, layer_pixels)); + } + if let Some(space) = embedded { + warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name())); + } + + let composite = merged_image(size, bit_depth, &pixels)?; + + let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?; + if bytes.len() as u64 >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!("\"{name}\" would reach the 2 GiB PSD file limit; use a smaller export size or fewer PSD maps"))); + } + + Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings }) +} + +/// The merged image of `layers` (bottom first, as the file stores them), one row at a time +fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u32), PixelData)]) -> Result { + let row_len = width as usize * PSD_RGBA_PLANES; + let sample_count = row_len * height as usize; + let mut merged_row = vec![0.0f32; row_len]; + let mut layer_row = Vec::with_capacity(row_len); + let reserve_error = |error| FormatError::Invalid(format!("PSD merged image allocation failed: {error}")); + if depth == 16 { + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(merged_row.iter().map(|&value| quantize_u16(value))); + } + return Ok(PixelData::Rgba16(merged)); + } + + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(merged_row.iter().copied().map(quantize_u8)); + } + + Ok(PixelData::Rgba8(merged)) +} + +/// Row `y` of the merged image into `merged_row`, each layer's row decoded into `layer_row` in turn +fn merge_row(y: usize, width: u32, layers: &[(&str, (u32, u32), PixelData)], merged_row: &mut [f32], layer_row: &mut Vec) { + merged_row.fill(0.0); + for (_, (layer_width, layer_height), samples) in layers { + if y >= *layer_height as usize { + continue; + } + + let span = *layer_width as usize * PSD_RGBA_PLANES; + let range = y * span..(y + 1) * span; + layer_row.clear(); + match samples { + PixelData::Rgba8(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u8::MAX))), + PixelData::Rgba16(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u16::MAX))), + _ => continue, + } + over(merged_row, width, layer_row, *layer_width); + } +} + +/// Composite a straight-alpha RGBA layer at the top left of the canvas. +fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) { + let canvas_rows = canvas.chunks_exact_mut(canvas_width as usize * PSD_RGBA_PLANES); + let layer_rows = layer.chunks_exact(layer_width as usize * PSD_RGBA_PLANES); + for (canvas_row, layer_row) in canvas_rows.zip(layer_rows) { + let canvas_texels = canvas_row.as_chunks_mut::().0; + let layer_texels = layer_row.as_chunks::().0; + for (under, top) in canvas_texels.iter_mut().zip(layer_texels) { + let (top_alpha, under_alpha) = (top[ALPHA_INDEX], under[ALPHA_INDEX]); + let alpha = top_alpha + under_alpha * (1.0 - top_alpha); + if alpha <= 0.0 { + continue; + } + + for (value, top_value) in under.iter_mut().zip(top).take(ALPHA_INDEX) { + *value = (top_value * top_alpha + *value * under_alpha * (1.0 - top_alpha)) / alpha; + } + under[ALPHA_INDEX] = alpha; + } + } +} + +/// L, LA, RGB or RGBA samples quantized as the RGBA the PSD builder accepts: gray repeated, opaque without alpha, sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 +fn rgba_pixel_data(mut data: Vec, component_count: usize, srgb: &[bool], width: u32, encoding: Encoding) -> Result { + let component_count = component_count.max(1); + for texel in data.chunks_exact_mut(component_count) { + for (component, value) in texel.iter_mut().enumerate() { + *value = if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) }; + } + } + + // Widen each texel while quantizing, so no floating-point RGBA copy of the layer is made + let texel_count = data.len() / component_count; + let rgba = (0..texel_count * PSD_RGBA_PLANES).map(|index| { + let (texel, component) = (index / PSD_RGBA_PLANES, index % PSD_RGBA_PLANES); + let source = match component_count { + 1 | 2 if component < ALPHA_INDEX => Some(0), + 1 | 3 if component == ALPHA_INDEX => None, + 2 => Some(1), + _ => Some(component), + }; + source.map_or(1.0, |source| data.get(texel * component_count + source).copied().unwrap_or(0.0)) + }); + + if encoding.depth == 16 { + let mut pixels = Vec::new(); + pixels.try_reserve_exact(rgba.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; + pixels.extend(rgba.map(quantize_u16)); + return Ok(PixelData::Rgba16(pixels)); + } + + quantize_integer(encoding, width, PSD_RGBA_PLANES, rgba).map(PixelData::Rgba8) +} + +/// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front +pub(super) fn write_layers( + (width, height): (u32, u32), + depth: u8, + layers: Vec<(&str, (u32, u32), PixelData)>, + composite: PixelData, +) -> craft_psd::Result> { + let mut builder = PsdBuilder::new(width, height).depth(u16::from(depth)).compression(Compression::Raw); + + // The builder stacks bottom up, so the groups open and close in that order too + let mut open: Vec<&str> = Vec::new(); + for (path, (layer_width, layer_height), pixels) in layers { + let mut parts: Vec<&str> = path.split('/').collect(); + let name = parts.pop().unwrap_or_default(); + let shared = open.iter().zip(&parts).take_while(|(open, part)| open == part).count(); + for _ in shared..open.len() { + builder.end_group()?; + } + open.truncate(shared); + for group in parts.iter().skip(shared) { + builder.begin_group(GroupSpec::new(*group)); + open.push(group); + } + + builder.push_layer(LayerSpec::new(name, 0, 0, layer_width, layer_height, pixels)); + } + for _ in open { + builder.end_group()?; + } + + builder.composite(composite); + builder.to_bytes() +} diff --git a/crates/formats/src/export/map_override.rs b/crates/formats/src/export/map_override.rs index 5ea62f5c..aec6ef56 100644 --- a/crates/formats/src/export/map_override.rs +++ b/crates/formats/src/export/map_override.rs @@ -14,10 +14,13 @@ pub struct MapOverride { /// Instead of the export's dithering of 8-bit files. #[serde(default)] pub dither: Option, + /// Output size (power of two) instead of the export's + #[serde(default)] + pub size: Option, } impl Default for MapOverride { fn default() -> Self { - MapOverride { enabled: true, format: None, bit_depth: None, dither: None } + MapOverride { enabled: true, format: None, bit_depth: None, dither: None, size: None } } } diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs new file mode 100644 index 00000000..a4401503 --- /dev/null +++ b/crates/formats/src/export/map_preview.rs @@ -0,0 +1,134 @@ +//! A small picture of one output map, sampled from the texture set as the export samples it + +use rayon::prelude::*; +use texturecraft_texel::linear_to_srgb; + +use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Sampler, SourceRef, layout, list_outputs, rec709_luminance}; +use crate::{FormatError, Result}; + +/// The largest preview side: a preview is a glance, never a second export +pub const MAX_PREVIEW_SIDE: u32 = 512; + +/// One output map, small: its channels in file order and the 8-bit values an sRGB file of it stores (colour channels sRGB-encoded, data as is) +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MapPreview { + pub width: u32, + pub height: u32, + pub channels: Vec, + /// `channels.len()` values per pixel, row by row + pub pixels: Vec, +} + +impl MapPreview { + /// Output map `map` of `options`' template for `input`'s set, with each side at most `side` pixels. + /// Returns None when the map writes no file. Texels off the UV islands show the default. + pub fn sample(input: &ExportInput, options: &ExportOptions, map: usize, side: u32) -> Result> { + Self::sample_coverage(input, options, map, side, false) + } + + /// Sample the engine's triangle indices directly, using the UV rasterizer's uncovered sentinel. + pub fn sample_triangles(input: &ExportInput, options: &ExportOptions, map: usize, side: u32) -> Result> { + Self::sample_coverage(input, options, map, side, texturecraft_geom::NO_TRI) + } + + fn sample_coverage( + input: &ExportInput, + options: &ExportOptions, + map: usize, + side: u32, + uncovered: Coverage, + ) -> Result> { + let set = input.project.texture_set(input.ts)?; + let spec = options.preset.maps.get(map).ok_or_else(|| FormatError::Invalid(format!("the template has no output map {map}")))?; + let planned = list_outputs(input.project, input.ts, input.mesh_name, options)?; + let Some(file) = planned.iter().find(|file| file.maps().any(|written| written == map)) else { + return Ok(None); + }; + + let (composite_width, height) = (input.composite.resolution, input.composite.height); + if composite_width == 0 || height == 0 || input.coverage.len() as u64 != u64::from(composite_width) * u64::from(height) { + return Err(FormatError::Invalid(format!("composite size {composite_width}×{height} does not match its coverage"))); + } + + // The file's longer side bounds the preview: the map's own size, else the export size, else the set's + let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); + let file_side = |source| super::scale_export_side(source, tile_res, options.map_size(map)); + let source_side = composite_width.max(height); + let preview_side = side.clamp(1, MAX_PREVIEW_SIDE).min(file_side(composite_width).max(file_side(height))).min(source_side); + let width = super::scale_export_side(composite_width, source_side, Some(preview_side)); + let rows = super::scale_export_side(height, source_side, Some(preview_side)); + let sampler = Sampler::new(input, options, set, tile_res, uncovered); + let mut channel_layout = layout(set, spec); + let grayscale = file.format == FileFormat::Pgm; + if grayscale || matches!(file.format, FileFormat::Jpeg | FileFormat::Hdr) { + channel_layout.retain(|(dest, _)| *dest != Dest::A); + } + + let gray_source = channel_layout.first().filter(|(dest, _)| *dest == Dest::L); + let psd = file.format == FileFormat::Psd; + let rgb_from_gray = gray_source.filter(|_| { + matches!(file.format, FileFormat::Psd | FileFormat::Hdr | FileFormat::Webp) + || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2)) + }); + let channels = if grayscale { + vec![Dest::L] + } else if psd { + vec![Dest::R, Dest::G, Dest::B, Dest::A] + } else if rgb_from_gray.is_some() { + [Dest::R, Dest::G, Dest::B].into_iter().chain(channel_layout.iter().skip(1).map(|(dest, _)| *dest)).collect() + } else { + channel_layout.iter().map(|(dest, _)| *dest).collect() + }; + + let component_count = channels.len(); + let color = spec.is_color(); + let max_sample = f32::from(u8::MAX); + let preview_sample = |value: f32, dest| { + let stored = if color && dest != Dest::A { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; + (stored * max_sample + 0.5) as u8 + }; + + // Sample at the centre of each preview pixel + let source_texel = |pixel: u32, preview_side: u32, source_side: u32| { + ((u64::from(pixel) * 2 + 1) * u64::from(source_side) / (2 * u64::from(preview_side))).min(u64::from(source_side) - 1) as u32 + }; + + let mut pixels = vec![0u8; width as usize * rows as usize * component_count]; + pixels.par_chunks_mut(width as usize * component_count).enumerate().for_each(|(row, values)| { + let y = source_texel(row as u32, rows, height); + for (column, pixel) in values.chunks_exact_mut(component_count).enumerate() { + let x = source_texel(column as u32, width, composite_width); + let at = if sampler.covered(x, y) { At::Texel(x, y) } else { At::Default }; + let mut cache = None; + let mut sample = |&(dest, source): &(Dest, &SourceRef)| { + let sample = sampler.sample(source, at, &mut cache); + if spec.inverted.contains(&dest) { 1.0 - sample } else { sample } + }; + + if grayscale && let [luminance] = pixel { + let value = match channel_layout.as_slice() { + [red, green, blue] => rec709_luminance(sample(red), sample(green), sample(blue)), + [gray] => sample(gray), + _ => 0.0, + }; + *luminance = preview_sample(value, Dest::L); + } else if let (Some(gray), [red, green, blue, alpha @ ..]) = (rgb_from_gray, &mut *pixel) { + let value = preview_sample(sample(gray), Dest::L); + (*red, *green, *blue) = (value, value, value); + if let [alpha] = alpha { + *alpha = channel_layout.get(1).map_or(u8::MAX, |source| preview_sample(sample(source), Dest::A)); + } + } else { + for (output, channel) in pixel.iter_mut().zip(&channel_layout) { + *output = preview_sample(sample(channel), channel.0); + } + if psd && channel_layout.len() < component_count { + pixel[component_count - 1] = u8::MAX; + } + } + } + }); + + Ok(Some(MapPreview { width, height: rows, channels, pixels })) + } +} diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs new file mode 100644 index 00000000..3b493ab4 --- /dev/null +++ b/crates/formats/src/export/map_renderer.rs @@ -0,0 +1,133 @@ +use rayon::prelude::*; +use texturecraft_core::{TextureSet, TileGrid}; +use texturecraft_texel::{ColorSpace, DilationMap}; + +use super::rendered_map::RenderedMap; +use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Padding, Sampler, diffuse_blocks, layout, resize, scale_export_side, tile_side}; +use crate::{FormatError, MAX_IMAGE_SIZE, Result}; + +/// Renders the output maps of one texture set's export: the padding and sampling every map shares +pub(super) struct MapRenderer<'a> { + options: &'a ExportOptions, + set: &'a TextureSet, + sampler: Sampler<'a>, + dilation_map: Option, + grid: Option, + /// The composite's size + width: u32, + height: u32, + /// Texels per atlas block (the width for a set without UV tiles) + tile_res: u32, +} + +impl<'a> MapRenderer<'a> { + pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions) -> Result> { + let set = input.project.texture_set(input.ts)?; + let (width, height) = (input.composite.resolution, input.composite.height); + let grid = set.tile_grid(); + let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); + if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { + return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); + } + + if input.coverage.len() as u64 != u64::from(width) * u64::from(height) { + return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); + } + + // Padding stays inside each UV tile + let dilation_map = match options.padding { + Padding::None => None, + Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { + Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) + } + Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), + }; + let sampler = Sampler::new(input, options, set, tile_res, false); + Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) + } + + /// The export size of map `map_index`'s file of `tile` (None: the whole set) + pub(super) fn size(&self, map_index: usize, tile: Option) -> Result<(u32, u32)> { + let (_, _, w, h) = self.region(tile)?; + + // An atlas scales by the requested size per tile + let scale = |value| scale_export_side(value, self.tile_res, self.options.map_size(map_index)); + Ok((scale(w), scale(h))) + } + + /// The composite texels a file of `tile` covers: one tile, or the whole set + fn region(&self, tile: Option) -> Result<(u32, u32, u32, u32)> { + match (tile, self.grid) { + (Some(t), Some(g)) => { + let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; + + // A tile smaller than its block fills the block's top-left corner + let side = tile_side(self.set, t, self.tile_res); + Ok((bx * self.tile_res, by * self.tile_res, side, side)) + } + _ => Ok((0, 0, self.width, self.height)), + } + } + + /// Map `map_index` of the preset for `tile`, as `format` at `bit_depth` holds it + pub(super) fn render(&self, map_index: usize, tile: Option, format: FileFormat, bit_depth: u8) -> Result { + let options = self.options; + let map = options.preset.maps.get(map_index).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; + let channel_layout = layout(self.set, map); + let component_count = channel_layout.len(); + let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); + let (x0, y0, w, h) = self.region(tile)?; + let size = self.size(map_index, tile)?; + let sampler = &self.sampler; + let dilation_map = self.dilation_map.as_ref(); + let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); + + let mut data = vec![0.0f32; w as usize * h as usize * component_count]; + data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { + let y = y0 + row_y as u32; + for (column, x) in (x0..x0 + w).enumerate() { + let at = if sampler.covered(x, y) { + Some(At::Texel(x, y)) + } else { + match dilation_map.and_then(|d| d.source(x, y)) { + Some((sx, sy)) => Some(At::Texel(sx, sy)), + None => beyond_default.then_some(At::Default), + } + }; + let Some(at) = at else { continue }; + let mut cache = None; + for (component, (_, source)) in channel_layout.iter().enumerate() { + if let Some(value) = row.get_mut(column * component_count + component) { + let sample = sampler.sample(source, at, &mut cache); + *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; + } + } + } + }); + + // Diffuse into the texels the dilation did not reach + if let (Padding::DilationDiffusion(_), Some(dilation)) = (options.padding, dilation_map) { + let block = if tile.is_none() && self.grid.is_some() { self.tile_res } else { w.max(h) }; + diffuse_blocks(&mut data, (w as usize, h as usize), component_count, dilation, (x0 as usize, y0 as usize), block as usize); + } + + let mut data = resize(data, (w, h), component_count, size); + + // Integer sRGB converts in `encode`; other color spaces convert here + let space = options.space_for_map(map, format, bit_depth); + let float = format.holds_float(bit_depth); + let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; + if convert { + data.par_chunks_mut(component_count).for_each(|px| { + if let [r, g, b, ..] = px { + [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); + } + }); + } + let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); + + // A colour space the user chose is written into the colour maps (data maps have none) + let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); + Ok(RenderedMap { data, size, component_count, srgb, embed }) + } +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f2134a0c..824a37ea 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -21,21 +21,35 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; +use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; +mod layered_psd; mod map_override; +mod map_preview; +mod map_renderer; +mod planned_layer; +mod psd_budget; +mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; +pub use map_preview::{MAX_PREVIEW_SIDE, MapPreview}; +use map_renderer::MapRenderer; +pub use planned_layer::PlannedLayer; +use psd_budget::PsdBudget; /// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture /// width tilts the normal 45°, at any resolution. const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; +/// Glossiness a set lacks: the KHR_materials_pbrSpecularGlossiness glossinessFactor default +const MISSING_GLOSSINESS: SourceRef = SourceRef::Constant(1.0); const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Planes of a PSD image or layer: red, green, blue and alpha +const PSD_RGBA_PLANES: usize = 4; /// Preset limits (user presets are untrusted JSON). const MAX_MAPS: usize = 64; const MAX_TEMPLATE: usize = 256; @@ -91,11 +105,16 @@ pub enum FileFormat { Jng, /// Portable graymap (binary). Pgm, - /// A PSD containing only its merged image. + /// Photoshop document: every output map of a texture set in this format as a layer of one file Psd, } impl FileFormat { + /// Whether the texture can be referenced by the USD asset exporter. + pub fn usable_by_usd_asset(self) -> bool { + self != Self::Psd + } + pub const ALL: [FileFormat; 11] = [ FileFormat::Png, FileFormat::Jpeg, @@ -200,7 +219,7 @@ pub enum VirtualMap { Glossiness, /// Baked AO × AO channel (per the texture set's AO mixing). AoMixed, - /// Dielectric reflectance at normal incidence: 0.08 × specular level. + /// Dielectric reflectance at normal incidence: Specular Level scaled by the project's shader settings. F0, /// 1 − glossiness (specular/glossiness projects). Roughness, @@ -315,6 +334,11 @@ pub struct MapSpec { } impl MapSpec { + /// Whether this set supplies at least one source used by the output map. + pub fn is_available_for(&self, set: &TextureSet) -> bool { + self.channels.iter().any(|(_, source)| source_present(set, source)) + } + /// Whether a non-alpha destination draws from a color source. pub fn is_color(&self) -> bool { self.channels.iter().any(|(dest, source)| { @@ -424,6 +448,20 @@ pub struct ExportOptions { } impl ExportOptions { + /// The output size of the preset's map `map`: its own, else the export's (None: the texture set's) + pub fn map_size(&self, map: usize) -> Option { + self.maps.get(&map).and_then(|own| own.size).or(self.size) + } + + /// The format, depth and dithering of a map before any PSD document-wide promotion. + pub fn map_file_type(&self, map_index: usize, map: &MapSpec) -> (FileFormat, u8, bool) { + let own = self.maps.get(&map_index); + let format = own.and_then(|o| o.format).or(self.format_override).unwrap_or(map.format); + let depth = format.depth(own.and_then(|o| o.bit_depth).or(self.bit_depth_override).unwrap_or(map.bit_depth)); + let dither = depth == 8 && !format.holds_float(depth) && own.and_then(|o| o.dither).unwrap_or(self.dither); + (format, depth, dither) + } + /// The colour space colour maps use at this format's default depth. pub fn space_for(&self, format: FileFormat) -> ColorSpace { self.space_for_depth(format, format.default_depth()) @@ -472,14 +510,14 @@ impl ExportOptions { } /// What is exported: one texture set's composite with its baked maps and UV coverage (one flag -/// per composite texel, row-major). +/// per composite texel, row-major). A preview can also borrow the UV rasterizer's triangle indices. #[derive(Clone, Copy)] -pub struct ExportInput<'a> { +pub struct ExportInput<'a, Coverage = bool> { pub project: &'a Project, pub ts: usize, pub composite: &'a Composite, pub baked: &'a BakedMaps, - pub coverage: &'a [bool], + pub coverage: &'a [Coverage], pub mesh_name: &'a str, } @@ -508,6 +546,16 @@ pub struct PlannedFile { /// covers every tile refers to); None when the file isn't tiled. pub udim_name: Option, pub warnings: Vec, + /// A PSD's output maps, top layer first (`map` is the first); empty for a file of one map + pub layers: Vec, +} + +impl PlannedFile { + /// The output maps the file writes + pub fn maps(&self) -> impl Iterator + '_ { + let own = self.layers.is_empty().then_some(self.map); + own.into_iter().chain(self.layers.iter().map(|layer| layer.map)) + } } // --------------------------------------------------------------------------------------------- @@ -538,7 +586,12 @@ pub(crate) fn source_present(set: &TextureSet, s: &SourceRef) -> bool { /// does not have is dropped. fn layout<'m>(set: &TextureSet, map: &'m MapSpec) -> Vec<(Dest, &'m SourceRef)> { let get = |d: Dest| map.channels.iter().find(|(x, _)| *x == d).map(|(_, s)| s); - let alpha = get(Dest::A).filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))); + + // A glossiness alpha stays, fully glossy, so a specular/glossiness file is RGBA without the channel too + let alpha = match get(Dest::A) { + Some(SourceRef::Channel { channel: Channel::Glossiness, .. }) if !set.has_channel(Channel::Glossiness) => Some(&MISSING_GLOSSINESS), + alpha => alpha.filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))), + }; let black = &SourceRef::Constant(0.0); let mut out = match get(Dest::L) { Some(l) => vec![(Dest::L, l)], @@ -565,7 +618,11 @@ pub fn channel_label(map: &MapSpec) -> &'static str { /// Keep `[A-Za-z0-9_.-]`, replace everything else with `_`; never empty or a reserved device name. pub fn sanitize_file_stem(s: &str) -> String { - let mut out: String = s.chars().take(MAX_STEM).map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).collect(); + sanitize_stem_with_limit(s, MAX_STEM) +} + +fn sanitize_stem_with_limit(s: &str, limit: usize) -> String { + let mut out: String = s.chars().take(limit).map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).collect(); if out.trim_matches('.').is_empty() { out = "texture".into(); } @@ -575,43 +632,153 @@ pub fn sanitize_file_stem(s: &str) -> String { if reserved { out.insert(0, '_'); } + + out.truncate(limit); out } -/// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. -pub fn sanitize_file_path(s: &str) -> String { - s.split('/').map(sanitize_file_stem).collect::>().join("/") +/// Leave room for the set's name, a set index if shortened, and the eventual tile suffix. +fn psd_stem(mesh_name: &str, set_name: &str, set_index: usize, max_len: usize) -> String { + let full = sanitize_stem_with_limit(&format!("{mesh_name}_{set_name}"), max_len + 1); + if full.len() <= max_len { + return full; + } + + let set_index = set_index.to_string(); + let set_budget = max_len / 2 - set_index.len() - 2; + let set = sanitize_stem_with_limit(set_name, set_budget); + let mesh = sanitize_stem_with_limit(mesh_name, max_len - set.len() - set_index.len() - 2); + format!("{mesh}_{set}_{set_index}") } -/// The files `opts` produces for texture set `ts`, without rendering (for the export dialog). -/// Template variables: [`FILE_TOKENS`]. +/// Compare against the whole project so a separate export and a batch agree on names. +fn untiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, atlas: bool) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, MAX_STEM); + let taken = |candidate: &str| { + let tile = psd_tile_suffix(candidate); + project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index).any(|(index, other)| { + if atlas || other.uv_tiles.is_empty() { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM)) + } else { + tile.is_some_and(|(base, number)| { + other.uv_tiles.contains(&number) + && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - (candidate.len() - base.len()))) + }) + } + }) + }; + if taken(&stem) { disambiguated_psd_stem(&stem, set_index, MAX_STEM, taken) } else { stem } +} + +/// Only a canonical tile number can collide with a generated UDIM suffix. +fn psd_tile_suffix(stem: &str) -> Option<(&str, u32)> { + let (base, suffix) = stem.rsplit_once('.')?; + let number: u32 = suffix.parse().ok()?; + (number.to_string() == suffix).then_some((base, number)) +} + +/// Keep one UDIM base for all tiles of a set when any tile's ordinary name collides. +fn tiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, limit: usize) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, limit); + let other_sets = || project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index); + let collides = other_sets().any(|(index, other)| { + !other.uv_tiles.is_empty() + && stem.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + && other.uv_tiles.iter().any(|tile| set.uv_tiles.contains(tile)) + }); + if !collides { + return stem; + } + + // Reserve ordinary names so a generated suffix cannot take another document's name + disambiguated_psd_stem(&stem, set_index, limit, |candidate| { + other_sets().any(|(index, other)| { + if other.uv_tiles.is_empty() { + let untiled = psd_stem(mesh_name, &other.name, index, MAX_STEM); + psd_tile_suffix(&untiled).is_some_and(|(base, tile)| candidate.eq_ignore_ascii_case(base) && set.uv_tiles.contains(&tile)) + } else { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + } + }) + }) +} + +fn disambiguated_psd_stem(stem: &str, set_index: usize, limit: usize, taken: impl Fn(&str) -> bool) -> String { + let mut attempt = 0usize; + loop { + let suffix = if attempt == 0 { format!("_{set_index}") } else { format!("-{attempt}_{set_index}") }; + let name = format!("{}{suffix}", &stem[..stem.len().min(limit - suffix.len())]); + if !taken(&name) { + return name; + } + + attempt += 1; + } +} + +/// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. +pub fn sanitize_file_path(path: &str) -> String { + if !path.contains('/') { + return sanitize_file_stem(path); + } + + path.split('/').map(sanitize_file_stem).collect::>().join("/") +} + +/// Expand tokens in the template while keeping the substituted values literal. +fn expand_file_template(template: &str, variables: &[(&str, &str)]) -> String { + let mut expanded = String::with_capacity(template.len()); + let mut remaining = template; + while let Some(index) = remaining.find('$') { + let (literal, variable) = remaining.split_at(index); + expanded.push_str(literal); + if let Some((value, tail)) = variables.iter().find_map(|&(token, value)| variable.strip_prefix(token).map(|tail| (value, tail))) { + expanded.push_str(value); + remaining = tail; + } else { + expanded.push('$'); + remaining = &variable[1..]; + } + } + + expanded.push_str(remaining); + expanded +} + +/// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_outputs(project, ts, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_outputs`] with the PSD memory limits of `budget` +fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; - if let Some(s) = opts.size - && (!s.is_power_of_two() || s > MAX_IMAGE_SIZE) - { - return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}"))); + for requested_size in opts.size.iter().chain(opts.maps.values().filter_map(|own| own.size.as_ref())) { + if !requested_size.is_power_of_two() || *requested_size > MAX_IMAGE_SIZE { + return Err(FormatError::Invalid(format!("export size {requested_size} must be a power of two up to {MAX_IMAGE_SIZE}"))); + } } let mut used = BTreeSet::new(); let mut active_files = BTreeSet::new(); let mut active_dirs = BTreeSet::new(); let mut out = Vec::new(); + + // Bucket layers in tile order to move their names into the corresponding PSD + let mut psd_layers = Vec::new(); + let project_stem = project.name.replace('/', "_"); + let mesh_stem = mesh_name.replace('/', "_"); + let set_stem = set.name.replace('/', "_"); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; - let grid = set.tile_grid(); - let block_resolution = set.block_resolution(); - for (i, map) in opts.preset.maps.iter().enumerate() { - if !map.channels.iter().any(|(_, s)| source_present(set, s)) { + for (map_index, map) in opts.preset.maps.iter().enumerate() { + if !map.is_available_for(set) { continue; } - let own = opts.maps.get(&i); - let format = own.and_then(|o| o.format).or(opts.format_override).unwrap_or(map.format); - let bit_depth = format.depth(own.and_then(|o| o.bit_depth).or(opts.bit_depth_override).unwrap_or(map.bit_depth)); + let own = opts.maps.get(&map_index); + let (format, bit_depth, dither) = opts.map_file_type(map_index, map); let enabled = own.is_none_or(|o| o.enabled); - let psd_channels = (enabled && format == FileFormat::Psd).then(|| layout(set, map).len()); - let dither = bit_depth == 8 && !format.holds_float(bit_depth) && own.and_then(|o| o.dither).unwrap_or(opts.dither); let space = opts.space_for_map(map, format, bit_depth); let requested_space = opts.space_for_depth(format, bit_depth); let color_map = map.is_color(); @@ -624,52 +791,34 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export // Integer files clamp wide-gamut linear color to 0–1 let clamps = color_map && !format.holds_float(bit_depth) && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); - // Append `$udim` to names for separate UV tiles - let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; - for &tile in &tiles { - if let Some(channels) = psd_channels { - let size = match (tile, grid) { - (Some(tile), Some(_)) => { - let side = tile_side(set, tile, block_resolution); - let side = scale_export_side(side, block_resolution, opts.size); - (side, side) - } - (_, Some(grid)) => { - let side = opts.size.unwrap_or(block_resolution); - (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) - } - (_, None) => { - let side = opts.size.unwrap_or(block_resolution); - (side, side) - } - }; - check_psd_size(size, channels, bit_depth)?; - } + // A PSD layer needs only explicit tile tokens because its document name already holds the tile number + let template = if format != FileFormat::Psd && tiles[0].is_some() && !map.file.contains("$udim") { + std::borrow::Cow::Owned(format!("{}.$udim", map.file)) + } else { + std::borrow::Cow::Borrowed(map.file.as_str()) + }; + let channel = channel_label(map); + let expand_stem = |udim: &str| { + let expanded = expand_file_template( + &template, + &[ + ("$udim", udim), + ("$project", &project_stem), + ("$mesh", &mesh_stem), + ("$textureSet", &set_stem), + ("$channel", channel), + ("$colorSpace", color_space), + ], + ); + sanitize_file_path(&expanded) + }; - // A name of the project, mesh or texture set never adds a folder - let no_folder = |name: &str| name.replace('/', "_"); - let stem = template - .replace("$udim", &tile.unwrap_or(1001).to_string()) - .replace("$project", &no_folder(&project.name)) - .replace("$mesh", &no_folder(mesh_name)) - .replace("$textureSet", &no_folder(&set.name)) - .replace("$channel", channel_label(map)) - .replace("$colorSpace", color_space); - - // Replace the tile number with `` in the shared name - let token_stem = tile.map(|_| { - let t = template - .replace("$udim", "UDIMTOKEN") - .replace("$project", &no_folder(&project.name)) - .replace("$mesh", &no_folder(mesh_name)) - .replace("$textureSet", &no_folder(&set.name)) - .replace("$channel", channel_label(map)) - .replace("$colorSpace", color_space); - sanitize_file_path(&t) - }); - let stem = sanitize_file_path(&stem); + // A tiled raster's name with a placeholder for its tile, the same for every tile + let udim_template = (format != FileFormat::Psd && tiles[0].is_some()).then(|| expand_stem("UDIMTOKEN")); + for (tile_index, &tile) in tiles.iter().enumerate() { + let tile_number = tile.unwrap_or(1001).to_string(); + let stem = expand_stem(&tile_number); let ext = format.extension(); - let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); if color_map && format == FileFormat::Pgm @@ -689,59 +838,200 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export format.extension().to_uppercase() )); } + let packs_colour = |name: &str| { + (color_map && requested_space != space) + .then(|| format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())) + }; - // Compare names case-insensitively for Windows and macOS - let mut k = 2; - while used.contains(&name.to_ascii_lowercase()) { - name = format!("{stem}_{k}.{ext}"); - k += 1; + if format == FileFormat::Psd { + if enabled { + warnings.extend(packs_colour(&stem)); + if psd_layers.is_empty() { + psd_layers.resize_with(tiles.len(), Vec::new); + } + psd_layers[tile_index].push((PlannedLayer { map: map_index, name: stem, dither }, bit_depth, warnings)); + } + continue; } - if k > 2 { - warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); - } - let lower = name.to_ascii_lowercase(); - used.insert(lower.clone()); + + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); if !enabled { continue; } - if active_dirs.contains(&lower) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); - } - let mut prefix = lower.as_str(); - while let Some((folder, _)) = prefix.rsplit_once('/') { - if active_files.contains(folder) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); - } - active_dirs.insert(folder.to_owned()); - prefix = folder; - } - active_files.insert(lower); - - if color_map && requested_space != space { - warnings.push(format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())); - } + claim_path(&mut active_files, &mut active_dirs, &name)?; + warnings.extend(packs_colour(&name)); // Use a UDIM name only when substituting its tile recovers the output name // Truncation or literal placeholder text can make that substitution ambiguous - let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| { - let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() }; - format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "") - }); - out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings }); + let udim_name = udim_template + .as_deref() + .filter(|t| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &tile_number) == stem) + .map(|t| format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "")); + out.push(PlannedFile { name, map: map_index, format, bit_depth, dither, tile, udim_name, warnings, layers: Vec::new() }); } } + + // Reuse the base across tiles with the same suffix width + let mut tiled_bases = HashMap::new(); + + // Each tile's PSD maps are the layers of one file named after the texture set + let mut psd_failures = Vec::new(); + for (&tile, in_tile) in tiles.iter().zip(psd_layers) { + let Some((first_layer, ..)) = in_tile.first() else { continue }; + + let first_map = first_layer.map; + let bit_depth = in_tile.iter().map(|(_, depth, _)| *depth).max().unwrap_or(8); + let mut warnings = Vec::new(); + let mut layers = Vec::with_capacity(in_tile.len()); + let mut dither_requested = false; + for (mut layer, _, layer_warnings) in in_tile { + dither_requested |= layer.dither; + layer.dither &= bit_depth == 8; + layers.push(layer); + for warning in layer_warnings { + if !warnings.contains(&warning) { + warnings.push(warning); + } + } + } + if bit_depth == 16 && dither_requested { + warnings.push("PSD layers use the 16-bit document depth; 8-bit dithering was skipped".into()); + } + + let ext = FileFormat::Psd.extension(); + let (stem, udim_stem) = if let Some(number) = tile { + let suffix = format!(".{number}"); + let limit = MAX_STEM - suffix.len(); + let base = tiled_bases.entry(limit).or_insert_with(|| tiled_psd_stem(project, mesh_name, ts, set, limit)); + (format!("{base}{suffix}"), Some(format!("{base}."))) + } else { + (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) + }; + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) { + psd_failures.push((name, error)); + continue; + } + + claim_path(&mut active_files, &mut active_dirs, &name)?; + let udim_name = udim_stem.map(|stem| format!("{stem}{renamed}.{ext}")); + let dither = bit_depth == 8 && dither_requested; + out.push(PlannedFile { name, map: first_map, format: FileFormat::Psd, bit_depth, dither, tile, udim_name, warnings, layers }); + } + + // A PSD that cannot be written leaves the set's other files to export, its reason a warning on the first of them + for (name, error) in psd_failures { + let Some(first) = out.first_mut() else { return Err(error) }; + let reason = match error { + FormatError::Invalid(reason) | FormatError::TooLarge(reason) => reason, + other => other.to_string(), + }; + first.warnings.push(format!("\"{name}\" {PSD_NOT_WRITTEN}{reason}")); + } Ok(out) } -/// Plan a selection in export order, keeping only the first case-insensitive use of a name. -pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { - let mut files = Vec::new(); - for &set in sets { - files.extend(list_outputs(project, set, mesh_name, opts)?.into_iter().map(|file| (set, file))); +/// What a set's PSD planning failure says after the file name +const PSD_NOT_WRITTEN: &str = "was not written: "; + +/// Whether `warning` is about a PSD of the set that was not planned rather than the file carrying it, so it outlives that file +pub fn is_set_warning(warning: &str) -> bool { + warning.split_once(".psd\" ").is_some_and(|(name, rest)| name.starts_with('"') && rest.starts_with(PSD_NOT_WRITTEN)) +} + +/// `stem.ext`, or `stem_2.ext`… when an earlier file has the name ignoring case (as Windows and macOS file systems do): the name and the suffix added +fn unique_name(used: &mut BTreeSet, stem: &str, ext: &str, warnings: &mut Vec) -> (String, String) { + let mut name = format!("{stem}.{ext}"); + let mut renamed = String::new(); + let mut k = 2; + while used.contains(&name.to_ascii_lowercase()) { + renamed = format!("_{k}"); + name = format!("{stem}{renamed}.{ext}"); + k += 1; + } + if !renamed.is_empty() { + warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); } - Ok(keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings)) + used.insert(name.to_ascii_lowercase()); + (name, renamed) +} + +/// Record exported file `name` and its folders, refusing a name that is already a folder or a folder that is already a file, ignoring case +fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: &str) -> Result<()> { + let lower = name.to_ascii_lowercase(); + if dirs.contains(&lower) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); + } + + let mut prefix = lower.as_str(); + while let Some((folder, _)) = prefix.rsplit_once('/') { + if files.contains(folder) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another output exports that file"))); + } + + dirs.insert(folder.to_owned()); + prefix = folder; + } + files.insert(lower); + Ok(()) +} + +/// Reject file and folder conflicts across a selection's retained output paths, ignoring case. +pub fn validate_export_paths<'a>(names: impl IntoIterator) -> Result<()> { + let mut files = BTreeSet::new(); + let mut folders = BTreeSet::new(); + for name in names { + claim_path(&mut files, &mut folders, name)?; + } + + Ok(()) +} + +/// The size of a PSD layer of a texture set at `export_size` for `tile` (None: the whole set, an atlas of a UV-tiled one) +fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u32, u32) { + let block_resolution = set.block_resolution(); + match (tile, set.tile_grid()) { + (Some(tile), Some(_)) => { + let side = scale_export_side(tile_side(set, tile, block_resolution), block_resolution, export_size); + (side, side) + } + (_, Some(grid)) => { + let side = export_size.unwrap_or(block_resolution); + (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) + } + (_, None) => { + let side = export_size.unwrap_or(block_resolution); + (side, side) + } + } +} + +/// Plan a selection in export order, keeping only the first case-insensitive use of a name. +pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_set_outputs(project, sets, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_set_outputs`] with the PSD memory limits of `budget` +fn plan_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { + let mut files = Vec::new(); + for &index in sets { + let planned = plan_outputs(project, index, mesh_name, opts, budget)?; + files.extend(planned.into_iter().map(|file| (index, file))); + } + + let files = keep_first_planned_names(files); + if sets.len() > 1 { + validate_export_paths(files.iter().map(|(_, file)| file.name.as_str()))?; + } + + let mut psd_bytes = 0; + for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { + check_psd_batch_within(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes, budget)?; + } + + Ok(files) } // --------------------------------------------------------------------------------------------- @@ -755,11 +1045,12 @@ enum At { Default, } -struct Sampler<'a> { +struct Sampler<'a, Coverage = bool> { set: &'a TextureSet, comp: &'a Composite, baked: &'a BakedMaps, - coverage: &'a [bool], + coverage: &'a [Coverage], + uncovered: Coverage, /// Composite width. res: u32, /// Texels per atlas block (`res` for a classic set): the height slope and the Sobel window @@ -770,6 +1061,7 @@ struct Sampler<'a> { /// Normal convention overriding every normal output. normal_override: Option, project_normal: NormalFormat, + dielectric_f0_scale: f32, } fn unpack(v: [f32; 3]) -> Vec3 { @@ -783,7 +1075,26 @@ pub fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) / t.z.max(1e-4) - u).try_normalize().unwrap_or(base) } -impl Sampler<'_> { +impl<'a, Coverage> Sampler<'a, Coverage> { + /// The sampler of `input`'s texture set `set`, whose atlas blocks are `tile_res` texels wide + fn new(input: &ExportInput<'a, Coverage>, options: &ExportOptions, set: &'a TextureSet, tile_res: u32, uncovered: Coverage) -> Self { + Sampler { + set, + comp: input.composite, + baked: input.baked, + coverage: input.coverage, + uncovered, + res: input.composite.resolution, + tile_res, + scales: set.block_scales(), + normal_override: options.normal_format, + project_normal: input.project.normal_format, + dielectric_f0_scale: input.project.display.dielectric_f0_scale(), + } + } +} + +impl Sampler<'_, Coverage> { fn channel(&self, c: Channel, at: At) -> [f32; 3] { match at { At::Texel(x, y) if self.set.has_channel(c) => self.comp.value(c, x, y), @@ -801,7 +1112,7 @@ impl Sampler<'_> { } fn covered(&self, x: u32, y: u32) -> bool { - self.coverage.get((y as usize) * self.res as usize + x as usize).copied().unwrap_or(false) + self.coverage.get((y as usize) * self.res as usize + x as usize).is_some_and(|sample| sample != &self.uncovered) } /// Normal from the height channel (3×3 Sobel; uncovered neighbours repeat the centre). @@ -856,7 +1167,7 @@ impl Sampler<'_> { VirtualMap::NormalOpenGl => self.normal(at, NormalFormat::OpenGl, cache), VirtualMap::NormalDirectX => self.normal(at, NormalFormat::DirectX, cache), VirtualMap::Glossiness => [1.0 - self.channel(Channel::Roughness, at)[0]; 3], - VirtualMap::F0 => [0.08 * self.channel(Channel::SpecularLevel, at)[0]; 3], + VirtualMap::F0 => [self.dielectric_f0_scale * self.channel(Channel::SpecularLevel, at)[0]; 3], VirtualMap::Roughness => [1.0 - self.channel(Channel::Glossiness, at)[0]; 3], VirtualMap::SheenTint => self.channel(Channel::SheenColor, at).map(|c| c * self.channel(Channel::SheenWeight, at)[0]), VirtualMap::HeightNormal => { @@ -895,139 +1206,81 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result Result<()> { + check_psd_batch_within(set, options, planned, total_bytes, PsdBudget::TARGET) +} + +fn check_psd_batch_within(set: &TextureSet, options: &ExportOptions, planned: &[PlannedFile], total_bytes: &mut u64, budget: PsdBudget) -> Result<()> { + let mut estimate = *total_bytes; + for file in planned.iter().filter(|file| file.format == FileFormat::Psd) { + let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut estimate, file_bytes, budget.batch_bytes)?; + } + + *total_bytes = estimate; + Ok(()) +} + +fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64, limit: Option) -> Result<()> { + let estimate = total_bytes.saturating_add(file_bytes); + if limit.is_some_and(|limit| estimate > limit) { + return Err(FormatError::TooLarge("total PSD output would exceed 1 GiB; use a smaller export size, fewer PSD maps or separate exports".into())); + } + + *total_bytes = estimate; + Ok(()) +} + /// Render the retained plans from `list_outputs` for this input and these options. pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned: Vec) -> Result> { - let set = input.project.texture_set(input.ts)?; - let (width, height) = (input.composite.resolution, input.composite.height); - let grid = set.tile_grid(); - let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); - if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { - return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); - } - - if input.coverage.len() != width as usize * height as usize { - return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); - } + render_planned_maps_within(input, options, planned, PsdBudget::TARGET) +} +/// [`render_planned_maps`] with the PSD memory limits of `budget` +fn render_planned_maps_within(input: &ExportInput, options: &ExportOptions, planned: Vec, budget: PsdBudget) -> Result> { if planned.is_empty() { return Ok(Vec::new()); } - // Padding stays inside each UV tile - let dilation_map = match options.padding { - Padding::None => None, - Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { - Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) + let mut psd_sizes = Vec::new(); + if planned.iter().any(|file| file.format == FileFormat::Psd) { + let set = input.project.texture_set(input.ts)?; + let expected = set.size(); + let actual = (input.composite.resolution, input.composite.height); + if actual != expected { + return Err(FormatError::Invalid(format!( + "PSD composite size {}×{} does not match the planned texture set size {}×{}", + actual.0, actual.1, expected.0, expected.1 + ))); } - Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), - }; - let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); - let diffuse = matches!(options.padding, Padding::DilationDiffusion(_)); - let sampler = Sampler { - set, - comp: input.composite, - baked: input.baked, - coverage: input.coverage, - res: width, - tile_res, - scales: set.block_scales(), - normal_override: options.normal_format, - project_normal: input.project.normal_format, - }; + let mut psd_bytes = 0; + for file in &planned { + if file.format == FileFormat::Psd { + let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut psd_bytes, file_bytes, budget.batch_bytes)?; + psd_sizes.push(Some(size)); + } else { + psd_sizes.push(None); + } + } + } + + let renderer = MapRenderer::new(input, options)?; planned .into_iter() - .map(|planned_file| { - let map = options.preset.maps.get(planned_file.map).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; - let channel_layout = layout(set, map); - let component_count = channel_layout.len(); - let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); - - // The texels written: one tile, or the whole set - let (x0, y0, w, h) = match (planned_file.tile, grid) { - (Some(t), Some(g)) => { - let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; - - // A tile smaller than its block fills the block's top-left corner - let side = tile_side(set, t, tile_res); - (bx * tile_res, by * tile_res, side, side) - } - _ => (0, 0, width, height), - }; - - // An atlas scales by the requested size per tile - let scale = |value| scale_export_side(value, tile_res, options.size); - let size = (scale(w), scale(h)); - if planned_file.format == FileFormat::Psd { - check_psd_size(size, component_count, planned_file.bit_depth)?; + .zip(psd_sizes.into_iter().chain(std::iter::repeat(None))) + .map(|(planned_file, psd_size)| { + if let Some(size) = psd_size { + return layered_psd::render_psd(&renderer, planned_file, size); } - let mut data = vec![0.0f32; w as usize * h as usize * component_count]; - data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { - let y = y0 + row_y as u32; - for (column, x) in (x0..x0 + w).enumerate() { - let at = if sampler.covered(x, y) { - Some(At::Texel(x, y)) - } else { - match dilation_map.as_ref().and_then(|d| d.source(x, y)) { - Some((sx, sy)) => Some(At::Texel(sx, sy)), - None => beyond_default.then_some(At::Default), - } - }; - let Some(at) = at else { continue }; - let mut cache = None; - for (component, (_, source)) in channel_layout.iter().enumerate() { - if let Some(value) = row.get_mut(column * component_count + component) { - let sample = sampler.sample(source, at, &mut cache); - *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; - } - } - } - }); - - // Diffuse into the texels the dilation did not reach - if diffuse { - let known: Vec = (y0..y0 + h) - .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) - .map(|(x, y)| sampler.covered(x, y) || dilation_map.as_ref().is_some_and(|d| d.source(x, y).is_some())) - .collect(); - - // Keep diffusion within each UV tile when rendering an atlas - let block = if planned_file.tile.is_none() && grid.is_some() { tile_res } else { w.max(h) }; - diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize); - } - - let mut data = resize(data, (w, h), component_count, size); - - // Integer sRGB converts in `encode`; other color spaces convert here - let space = options.space_for_map(map, planned_file.format, planned_file.bit_depth); - let float = planned_file.format.holds_float(planned_file.bit_depth); - let rgb = component_count >= 3; + let map = renderer.render(planned_file.map, planned_file.tile, planned_file.format, planned_file.bit_depth)?; let mut warnings = planned_file.warnings; - let color_map = map.is_color(); - let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; - - if convert { - data.par_chunks_mut(component_count).for_each(|px| { - if let [r, g, b, ..] = px { - [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); - } - }); - } - let srgb: Vec = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - - // A colour space the user chose is written into the colour maps (data maps have none) - let embed = (options.color_space.is_some() && color_map && rgb).then_some(space); - let bytes = encode( - Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }, - size, - component_count, - data, - &srgb, - embed, - &mut warnings, - )?; - Ok(ExportedFile { name: planned_file.name, bytes, width: size.0, height: size.1, warnings }) + let encoding = Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }; + let bytes = encode(encoding, map.size, map.component_count, map.data, &map.srgb, map.embed, &mut warnings)?; + Ok(ExportedFile { name: planned_file.name, bytes, width: map.size.0, height: map.size.1, warnings }) }) .collect() } @@ -1043,21 +1296,40 @@ pub fn scale_export_side(source_side: u32, block_resolution: u32, export_size: O u32::try_from(scaled).unwrap_or(u32::MAX).max(u32::from(source_side > 0)) } -fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels: usize, known: &[bool], block: usize) { - // A whole image or a separately exported tile already occupies a contiguous buffer - if block >= width.max(height) { - diffuse_fill(data, (width, height), channels, known); - return; - } +fn diffuse_blocks( + data: &mut Vec, + (width, height): (usize, usize), + channels: usize, + dilation: &texturecraft_texel::DilationMap, + (origin_x, origin_y): (usize, usize), + block: usize, +) { + use texturecraft_texel::dilate::NONE; - for block_y in (0..height).step_by(block.max(1)) { - for block_x in (0..width).step_by(block.max(1)) { + for block_y in (0..height).step_by(block) { + for block_x in (0..width).step_by(block) { let (block_width, block_height) = (block.min(width - block_x), block.min(height - block_y)); + let source_rows = (origin_y + block_y..origin_y + block_y + block_height).map(|y| { + let start = y * dilation.width as usize + origin_x + block_x; + &dilation.src[start..start + block_width] + }); + let mut coverage = source_rows.flatten().map(|source| *source != NONE); + let Some(first) = coverage.next() else { continue }; + if coverage.clone().all(|covered| covered == first) { + continue; + } + + // The dilation map already identifies every known texel, including original UV coverage + let weights = std::iter::once(first).chain(coverage).map(f32::from).collect(); + if block_width == width && block_height == height { + diffuse_fill(data, (width, height), channels, weights); + return; + } + let rows = || (block_y..block_y + block_height).map(|y| (y * width + block_x)..(y * width + block_x + block_width)); let mut block_data: Vec = rows().flat_map(|row| data.get(row.start * channels..row.end * channels).unwrap_or_default().iter().copied()).collect(); - let block_known: Vec = rows().flat_map(|row| known.get(row).unwrap_or_default().iter().copied()).collect(); - diffuse_fill(&mut block_data, (block_width, block_height), channels, &block_known); + diffuse_fill(&mut block_data, (block_width, block_height), channels, weights); for (row, chunk) in rows().zip(block_data.chunks(block_width * channels)) { if let Some(destination) = data.get_mut(row.start * channels..row.end * channels) { destination.copy_from_slice(chunk); @@ -1067,17 +1339,12 @@ fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels } } -/// Fill the texels `known` leaves out of a `size` image of `n` components by pull-push +/// Fill the zero-weight texels of a `size` image of `n` components by pull-push /// diffusion: known texels are averaged down a pyramid, then every level fills its gaps from the /// smoothly upsampled level below, so a gap takes a soft blend of the nearby known colours. -fn diffuse_fill(data: &mut Vec, (w, h): (usize, usize), channels: usize, known: &[bool]) { - if known.iter().all(|channel| *channel) || !known.iter().any(|channel| *channel) { - return; - } - +fn diffuse_fill(data: &mut Vec, (w, h): (usize, usize), channels: usize, weights: Vec) { // Keep coverage weights alongside the colour samples at each level - let mut levels: Vec<(usize, usize, Vec, Vec)> = - vec![(w, h, std::mem::take(data), known.iter().map(|channel| if *channel { 1.0 } else { 0.0 }).collect())]; + let mut levels = vec![(w, h, std::mem::take(data), weights)]; let mut accumulator = vec![0.0f32; channels]; while let Some((width, height, colour, weight)) = levels.last() && (*width > 1 || *height > 1) @@ -1201,6 +1468,13 @@ const BAYER8: [u8; 64] = [ 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21, ]; +fn rec709_luminance(red: f32, green: f32, blue: f32) -> f32 { + // Rec.709 luminance weights apply before the display transfer + const WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722]; + let [red_weight, green_weight, blue_weight] = WEIGHTS; + red_weight * red + green_weight * green + blue_weight * blue +} + /// Encode a linear image as L, LA, RGB or RGBA at the requested width and height. fn encode( encoding: Encoding, @@ -1216,7 +1490,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1256,8 +1530,6 @@ fn encode( _ => {} } - // Rec.709 luminance weights convert linear RGB to PGM's single gray channel - const REC709_LUMINANCE_WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722]; let gray_srgb: [bool; 1]; let (integer_data, srgb, component_count): (Vec, &[bool], usize) = if format == FileFormat::Pgm && component_count > 1 { if component_count != 3 { @@ -1271,10 +1543,7 @@ fn encode( .chunks_exact(component_count) .map(|pixel| match pixel { [l, _] => *l, - [red, green, blue, ..] => { - let [red_weight, green_weight, blue_weight] = REC709_LUMINANCE_WEIGHTS; - red_weight * red + green_weight * green + blue_weight * blue - } + [red, green, blue, ..] => rec709_luminance(*red, *green, *blue), _ => 0.0, }) .collect(); @@ -1295,21 +1564,22 @@ fn encode( }; let transferred = integer_data - .iter() + .into_iter() .enumerate() - .map(|(index, value)| if srgb.get(index % component_count).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) }); + .map(|(index, value)| if srgb.get(index % component_count).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }); let (bytes, component_count) = if let Some(indices) = channel_indices { - // Transfer luminance once before TIFF repeats it across RGB + // Transfer each source sample once, then quantize directly in destination order let transferred: Vec = transferred.collect(); - drop(integer_data); - let remapped = remap(&transferred, component_count, indices); - drop(transferred); - (quantize_integer(encoding, size.0, indices.len(), remapped.into_iter())?, indices.len()) + let output_channels = indices.len(); + let sample_count = + (transferred.len() / component_count).checked_mul(output_channels).ok_or_else(|| encoding_error(&"remapped sample count overflows"))?; + let remapped = (0..sample_count).map(|sample| { + let pixel_start = sample / output_channels * component_count; + transferred[pixel_start + indices[sample % output_channels]] + }); + (quantize_integer(encoding, size.0, output_channels, remapped)?, output_channels) } else { - // Stream native-order samples directly into the integer buffer - let bytes = quantize_integer(encoding, size.0, component_count, transferred)?; - drop(integer_data); - (bytes, component_count) + (quantize_integer(encoding, size.0, component_count, transferred)?, component_count) }; let sample_type = if depth == 16 { SampleType::U16 } else { SampleType::U8 }; @@ -1321,9 +1591,9 @@ fn encode( FileFormat::Bmp => CodecFormat::Bmp, FileFormat::Webp => CodecFormat::WebP, FileFormat::Pgm => CodecFormat::Pnm, - FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)), FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), + FileFormat::Psd => return Err(encoding_error(&"a PSD holds the layers of several maps (`layered_psd`)")), }; let layout = match component_count { 1 => ChannelLayout::Gray, @@ -1339,6 +1609,14 @@ fn encode( write_raster(&image, codec_format).map_err(|error| encoding_error(&error)) } +fn quantize_u8(value: f32) -> u8 { + (value * f32::from(u8::MAX) + 0.5) as u8 +} + +fn quantize_u16(value: f32) -> u16 { + (value * f32::from(u16::MAX) + 0.5) as u16 +} + fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samples: impl ExactSizeIterator) -> Result> { let Encoding { format, depth, dither } = encoding; let byte_count = samples @@ -1349,7 +1627,7 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp bytes.try_reserve_exact(byte_count).map_err(|error| FormatError::Invalid(format!("{} sample buffer allocation failed: {error}", format.extension())))?; if depth == 16 { - bytes.extend(samples.flat_map(|value| ((value * f32::from(u16::MAX) + 0.5) as u16).to_ne_bytes())); + bytes.extend(samples.flat_map(|value| quantize_u16(value).to_ne_bytes())); } else { let width = width.max(1) as usize; let threshold = |sample_index: usize| { @@ -1363,42 +1641,56 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp if dither { bytes.extend(samples.enumerate().map(|(index, value)| (value * max_sample + threshold(index)).floor().clamp(0.0, max_sample) as u8)); } else { - bytes.extend(samples.map(|value| (value * max_sample + 0.5) as u8)); + bytes.extend(samples.map(quantize_u8)); } } Ok(bytes) } -fn check_psd_size((width, height): (u32, u32), channels: usize, depth: u8) -> Result<()> { - if width == 0 || height == 0 || width > PSD_MAX_SIDE_PIXELS || height > PSD_MAX_SIDE_PIXELS { - return Err(FormatError::Invalid(format!("PSD size {width}×{height} must be between 1 and {PSD_MAX_SIDE_PIXELS} pixels per side"))); +/// Return the canvas size and conservative file size after checking PSD format limits. +fn check_psd_size(sizes: impl IntoIterator, folder_count: usize, depth: u8) -> Result<((u32, u32), u64)> { + // A layer record with its names, and each of a group's two records, stays below this + const PSD_RECORD_BYTES: u64 = 2048; + + let (mut width, mut height) = (1, 1); + let mut layer_texels = 0; + let mut layer_count = 0; + for (layer_width, layer_height) in sizes { + if !(1..=PSD_MAX_SIDE_PIXELS).contains(&layer_width) || !(1..=PSD_MAX_SIDE_PIXELS).contains(&layer_height) { + return Err(FormatError::Invalid(format!("PSD size {layer_width}×{layer_height} must be between 1 and {PSD_MAX_SIDE_PIXELS} pixels per side"))); + } + + width = width.max(layer_width); + height = height.max(layer_height); + layer_texels += u64::from(layer_width) * u64::from(layer_height); + layer_count += 1; } - // Measure the flat file's overhead without allocating any pixel buffers - let overhead = flat_psd((width, height), channels, depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; - let sample_bytes = u64::from(width) * u64::from(height) * channels as u64 * u64::from(depth / 8); - if overhead + sample_bytes >= PSD_MAX_FILE_BYTES { - return Err(FormatError::Invalid(format!("PSD size {width}×{height} would reach the 2 GiB file limit; use a smaller export size or another format"))); + // Measure the merged image's overhead without allocating any pixel buffers + let merged = flat_psd((width, height), depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; + let records = PSD_RECORD_BYTES * (layer_count + 2 * folder_count as u64); + let texels = u64::from(width) * u64::from(height) + layer_texels; + let sample_bytes = texels * PSD_RGBA_PLANES as u64 * u64::from(depth / 8); + let file_bytes = merged + records + sample_bytes; + if file_bytes >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!( + "a PSD of {layer_count} maps at {width}×{height} would reach the 2 GiB file limit; use a smaller export size, fewer PSD maps or another format" + ))); } - Ok(()) + Ok(((width, height), file_bytes)) } -fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_psd::PsdFile { - use craft_psd::{ColorMode, Compression, Header, ImageData, ImageResource, PsdFile, Version}; - - const PSD_ALPHA_NAMES_RESOURCE_ID: u16 = 1006; - let color_mode = if channels <= 2 { ColorMode::Grayscale } else { ColorMode::Rgb }; - let header = Header::new(Version::Psd, width, height, channels as u16, u16::from(depth), color_mode); - - // A Pascal name marks the extra plane as a channel separate from merged transparency - let resources = if matches!(channels, 2 | 4) { vec![ImageResource::new(PSD_ALPHA_NAMES_RESOURCE_ID, b"\x05Alpha".to_vec())] } else { Vec::new() }; +/// A PSD of only an RGBA merged image with no pixels yet, to measure +fn flat_psd((width, height): (u32, u32), depth: u8) -> craft_psd::PsdFile { + use craft_psd::{ColorMode, Compression, Header, ImageData, PsdFile, Version}; + let header = Header::new(Version::Psd, width, height, PSD_RGBA_PLANES as u16, u16::from(depth), ColorMode::Rgb); PsdFile { header, color_mode_data: Vec::new(), - resources, + resources: Vec::new(), layer_info: None, layer_info_placement: Default::default(), global_layer_mask: None, @@ -1409,26 +1701,6 @@ fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_ps } } -/// Write a merged PSD image with raw planes, including an extra alpha plane when present. -fn psd(bytes: Vec, size: (u32, u32), channels: usize, depth: u8) -> craft_psd::Result> { - let mut file = flat_psd(size, channels, depth); - let planes = &mut file.image_data.data; - planes.try_reserve_exact(bytes.len()).map_err(|_| craft_psd::PsdError::OutOfMemory("cannot allocate PSD planes"))?; - if depth == 16 { - let samples = bytes.as_chunks::<2>().0; - for channel in 0..channels { - planes.extend(samples.iter().skip(channel).step_by(channels).flat_map(|sample| u16::from_ne_bytes(*sample).to_be_bytes())); - } - } else { - for channel in 0..channels { - planes.extend(bytes.iter().skip(channel).step_by(channels).copied()); - } - } - drop(bytes); - - file.to_bytes() -} - /// A JNG file: the colour as JPEG, alpha (when present) as lossless 8-bit deflate data. fn jng(bytes: &[u8], (w, h): (u32, u32), n: usize) -> std::result::Result, String> { use std::io::Write; @@ -1544,14 +1816,23 @@ pub fn skip_repeated_names(files: &mut Vec) { *files = keep_first_names(std::mem::take(files), |file| &file.name, |file| &mut file.warnings); } -fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { +/// Keep the first case-insensitive use of each filename and attach duplicate warnings to its plan. +pub fn keep_first_planned_names(files: impl IntoIterator) -> Vec<(T, PlannedFile)> { + keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings) +} + +fn keep_first_names(files: impl IntoIterator, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { + let files = files.into_iter(); let mut first = HashMap::new(); - let mut kept = Vec::with_capacity(files.len()); - for file in files { - let filename = name(&file); + let mut kept = Vec::with_capacity(files.size_hint().0); + for mut file in files { + let filename = name(&file).to_owned(); match first.entry(filename.to_ascii_lowercase()) { Entry::Occupied(previous) => { + // The later file's set warnings stay with the export + let moved: Vec<_> = warnings(&mut file).extract_if(.., |warning| is_set_warning(warning)).collect(); if let Some(winner) = kept.get_mut(*previous.get()) { + warnings(winner).extend(moved); warnings(winner).push(format!( "\"{}\" of a later texture set has the name of a file an earlier texture set exports, so it was not written; add $textureSet to the template's file names or rename a texture set", filename diff --git a/crates/formats/src/export/planned_layer.rs b/crates/formats/src/export/planned_layer.rs new file mode 100644 index 00000000..4f0adf39 --- /dev/null +++ b/crates/formats/src/export/planned_layer.rs @@ -0,0 +1,10 @@ +/// An output map written as a layer of a texture set's PSD (see [`super::list_outputs`]) +#[derive(Clone, Debug, PartialEq)] +pub struct PlannedLayer { + /// Index into the preset's maps + pub map: usize, + /// The map's file name, a `/` separating the groups the layer sits in + pub name: String, + /// 8-bit samples written with dithering + pub dither: bool, +} diff --git a/crates/formats/src/export/psd_budget.rs b/crates/formats/src/export/psd_budget.rs new file mode 100644 index 00000000..e6300254 --- /dev/null +++ b/crates/formats/src/export/psd_budget.rs @@ -0,0 +1,17 @@ +/// The memory limits PSD planning holds an export to: a browser tab's address space needs them, a native export renders one layer at a time without them +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct PsdBudget { + /// Pixel buffers of one document, including the renderer's padding and encoder + pub(super) working_bytes: Option, + /// Encoded documents one batch holds in memory, with headroom for a document's working buffers and ZIP packaging + pub(super) batch_bytes: Option, +} + +impl PsdBudget { + /// A browser tab's: the export and the app share its 4 GiB address space + pub(super) const WEB: Self = Self { working_bytes: Some(2 * 1024 * 1024 * 1024), batch_bytes: Some(1024 * 1024 * 1024) }; + /// A desktop export's: the machine bounds it, as it does every other file type + pub(super) const NATIVE: Self = Self { working_bytes: None, batch_bytes: None }; + /// The budget of the platform this build runs on + pub(super) const TARGET: Self = if cfg!(target_arch = "wasm32") { Self::WEB } else { Self::NATIVE }; +} diff --git a/crates/formats/src/export/rendered_map.rs b/crates/formats/src/export/rendered_map.rs new file mode 100644 index 00000000..df388464 --- /dev/null +++ b/crates/formats/src/export/rendered_map.rs @@ -0,0 +1,13 @@ +use texturecraft_texel::ColorSpace; + +/// One output map's linear samples at its export size, ready to encode +pub(super) struct RenderedMap { + /// Interleaved L, LA, RGB or RGBA samples + pub data: Vec, + pub size: (u32, u32), + pub component_count: usize, + /// Per component: whether encoding applies the sRGB transfer + pub srgb: Vec, + /// The colour space recorded in the file, when the user chose one for a colour map + pub embed: Option, +} diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 392148a1..49f4b812 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -373,6 +373,7 @@ fn every_format_encodes_and_decodes() { opts.format_override = Some(format); opts.bit_depth_override = Some(depth); let files = fx.render(&opts); + assert_eq!(files.len(), 4, "{format:?}"); for f in &files { assert!(f.name.ends_with(format.extension())); @@ -385,6 +386,7 @@ fn every_format_encodes_and_decodes() { // Roughness 0.25 everywhere survives every format (JPEG within its loss) let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1]; + assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}"); let base = find(&files, "_BaseColor."); match format { @@ -555,6 +557,34 @@ fn gray_map(file: &str, src: SourceRef) -> MapSpec { MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() } } +#[test] +fn an_output_with_its_own_size_keeps_it() { + let fx = Fx::new(&default_channels()); + let preset = ExportPreset { + name: "sizes".into(), + maps: vec![ + gray_map("small", SourceRef::Channel { channel: Channel::Roughness, component: 0 }), + gray_map("set_size", SourceRef::Channel { channel: Channel::Metallic, component: 0 }), + ], + }; + let mut options = ExportOptions::new(preset); + options.maps.insert(0, MapOverride { size: Some(32), ..MapOverride::default() }); + + for (export_size, other) in [(None, RES), (Some(128), 128)] { + let files = fx.render(&ExportOptions { size: export_size, ..options.clone() }); + + assert_eq!(find(&files, "small.png").width, 32, "its own size wins over {export_size:?}"); + assert_eq!(find(&files, "set_size.png").width, other); + } + + // A PSD is as large as its largest layer + options.format_override = Some(FileFormat::Psd); + assert_eq!(fx.render(&options)[0].width, RES); + + options.maps.insert(0, MapOverride { size: Some(100), ..MapOverride::default() }); + assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "a size that isn't a power of two is refused"); +} + #[test] fn validation_rejects_bad_presets() { let ok = ExportPreset { name: "Mine".into(), maps: vec![gray_map("$mesh_$textureSet_$channel ($colorSpace) $project", SourceRef::Constant(1.0))] }; @@ -729,6 +759,9 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() { // A folder stays in the placeholder name assert_eq!(udim_names("Base/$textureSet_$udim".into()), [Some("Base/Body_.png".to_string()), Some("Base/Body_.png".to_string())]); + + // A name without the token gets the tile as a suffix, and so does its placeholder + assert_eq!(udim_names("$textureSet".into()), [Some("Body..png".to_string()), Some("Body..png".to_string())]); } #[test] @@ -1121,45 +1154,121 @@ fn pgm_is_a_binary_graymap() { } #[test] -fn psd_holds_the_merged_image_planar() { +fn psd_holds_every_map_as_a_layer_over_their_merged_image() { let fx = Fx::new(&default_channels()); - let f = &fx.render(&one_map(FileFormat::Psd, 8, rgba_half_alpha()))[0]; - let b = &f.bytes; - assert_eq!(&b[0..4], b"8BPS"); - assert_eq!(u16::from_be_bytes([b[12], b[13]]), 4, "channels"); - assert_eq!((u32::from_be_bytes(b[14..18].try_into().unwrap()), u32::from_be_bytes(b[18..22].try_into().unwrap())), (64, 64)); - assert_eq!((u16::from_be_bytes([b[22], b[23]]), u16::from_be_bytes([b[24], b[25]])), (8, 3), "8-bit RGB"); - let parsed = craft_psd::PsdFile::from_bytes(b).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 4 * 64 * 64); - let plane = |c: usize| &samples[c * 64 * 64..(c + 1) * 64 * 64]; - assert!(plane(3).iter().all(|a| *a == 128), "alpha plane"); - let png = decode(&fx.render(&one_map(FileFormat::Png, 8, rgba_half_alpha()))[0]).to_rgba8(); - assert_eq!(plane(0)[64 * 10 + 40], png.get_pixel(40, 10)[0], "the red plane holds the same values as a PNG"); + let mut png_options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + png_options.bit_depth_override = Some(8); + let pngs = fx.render(&png_options); + let mut options = png_options.clone(); + options.format_override = Some(FileFormat::Psd); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, roughness()))[0]; - assert_eq!((u16::from_be_bytes([f16.bytes[12], f16.bytes[13]]), u16::from_be_bytes([f16.bytes[22], f16.bytes[23]])), (1, 16)); - assert_eq!(f16.bytes.len(), 26 + 12 + 2 + 2 * 64 * 64); + let planned = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + let files = fx.render(&options); - let mut gray_alpha = roughness(); - gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, gray_alpha))[0]; - let parsed = craft_psd::PsdFile::from_bytes(&f16.bytes).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 2 * 2 * 64 * 64); - assert!(samples[2 * 64 * 64..].as_chunks::<2>().0.iter().all(|sample| *sample == [128, 0])); + assert_eq!(planned.len(), 1, "one PSD for the texture set: {planned:?}"); + assert_eq!(planned[0].layers.len(), pngs.len()); + assert_eq!(files.len(), 1); + assert_eq!(files[0].name, "sphere_Body_Set.psd"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layers: Vec<_> = parsed.iter_layers().collect(); + + assert_eq!(layers.len(), pngs.len()); + + // The file stacks bottom up, so the first map is the top layer + for (layer, png) in layers.iter().rev().zip(&pngs) { + assert_eq!(format!("{}.png", layer.name()), png.name); + assert_eq!(layer.rgba8().unwrap().data, decode(png).to_rgba8().into_raw(), "{}: the layer holds the map's texels", png.name); + } + let top = layers.last().unwrap().rgba8().unwrap().data; + + assert!(top.as_chunks::<4>().0.iter().all(|texel| texel[3] == u8::MAX), "the base colour is opaque"); + assert_eq!(parsed.composite_rgba8().unwrap().data, top, "the merged image shows the opaque top layer"); + + options.bit_depth_override = Some(16); + let deep = &fx.render(&options)[0]; + + assert_eq!(craft_psd::PsdFile::from_bytes(&deep.bytes).unwrap().header.depth, 16); +} + +#[test] +fn psd_keeps_small_layers_at_the_requested_size() { + let fx = Fx::new(&default_channels()); + let mut options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + options.format_override = Some(FileFormat::Psd); + options.bit_depth_override = Some(8); + options.maps.insert(0, MapOverride { size: Some(RES / 2), ..Default::default() }); + options.maps.insert(1, MapOverride { size: Some(RES / 4), ..Default::default() }); + + let files = fx.render(&options); + let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layers: Vec<_> = psd.iter_layers().map(|layer| layer.rgba8().unwrap()).collect(); + let merged = psd.composite_rgba8().unwrap(); + + assert_eq!((merged.width, merged.height), (RES, RES)); + assert_eq!(layers.iter().map(|layer| (layer.width, layer.height)).collect::>(), [(RES, RES), (RES / 4, RES / 4), (RES / 2, RES / 2)]); + let pixel = |x: u32, y: u32| ((y * RES + x) * 4) as usize; + + assert_eq!(&merged.data[..4], &layers[2].data[..4]); + let outside_top_layers = pixel(RES - 1, 0); + + assert_eq!(&merged.data[outside_top_layers..outside_top_layers + 4], &layers[0].data[outside_top_layers..outside_top_layers + 4]); +} + +#[test] +fn psd_folder_templates_become_layer_groups_of_one_file_not_folders() { + let fx = Fx::new(&default_channels()); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("Body/$textureSet_Rough"), rough("Top/Inner/Leaf"), rough("Mask")] }; + let mut options = ExportOptions::new(preset); + options.format_override = Some(FileFormat::Psd); + + let files = fx.render(&options); + + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["sphere_Body_Set.psd"], "no folder for a PSD's layers"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + + // The tree lists bottom up and the first map is the top layer + let groups: Vec<_> = tree.iter().rev().filter(|node| node.is_group()).map(name).collect(); + + assert_eq!(groups, ["Body", "Top"]); + let body = tree.iter().find(|node| node.is_group() && name(node) == "Body").unwrap(); + + assert_eq!(body.children().iter().map(name).collect::>(), ["Body_Set_Rough"], "$textureSet is filled in inside a layer name"); + assert!(tree.iter().any(|node| !node.is_group() && name(node) == "Mask")); +} + +#[test] +fn psd_layer_groups_follow_the_slashes_of_their_names() { + let pixel = || craft_psd::PixelData::Rgba8(vec![10, 20, 30, 255]); + let layers = ["Mask", "Body/Rough", "Body/Color", "Top/Inner/Leaf"].into_iter().map(|name| (name, (1, 1), pixel())).collect(); + + let bytes = layered_psd::write_layers((1, 1), 8, layers, pixel()).unwrap(); + + let parsed = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + + assert_eq!( + tree.iter().map(|node| (name(node), node.is_group())).collect::>(), + [("Mask".to_string(), false), ("Body".to_string(), true), ("Top".to_string(), true)] + ); + assert_eq!(tree[1].children().iter().map(name).collect::>(), ["Rough", "Color"]); + let inner = &tree[2].children()[0]; + + assert!(inner.is_group() && name(inner) == "Inner"); + assert_eq!(inner.children().iter().map(name).collect::>(), ["Leaf"]); } #[test] fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { let mut fx = Fx::new(&default_channels()); - fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + + // Eight tile columns make a 32768-wide atlas while the individual PSDs stay within budget + fx.project.texture_sets[0].uv_tiles = vec![1001, 1008]; let mut options = one_map(FileFormat::Psd, 8, roughness()); - options.size = Some(16_384); + options.size = Some(4096); options.atlas = true; let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); @@ -1170,7 +1279,123 @@ fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { } #[test] -fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { +fn psd_plan_preserves_each_udim_suffix_after_truncating_the_stem() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + let options = one_map(FileFormat::Psd, 8, roughness()); + let mesh_name = "a".repeat(MAX_STEM); + + let plan = list_outputs(&fx.project, 0, &mesh_name, &options).unwrap(); + + assert_eq!(plan.len(), 2); + for (file, tile) in plan.iter().zip([1001, 1002]) { + assert!(file.name.ends_with(&format!(".{tile}.psd")), "{}", file.name); + assert_eq!(file.udim_name.as_ref().unwrap().replace("", &tile.to_string()), file.name); + } +} + +#[test] +fn feedback_psd_long_mesh_names_keep_distinct_texture_sets_and_tiles() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + let mut trim = fx.project.texture_sets[0].clone(); + trim.name = "Trim".into(); + fx.project.texture_sets.push(trim); + let options = one_map(FileFormat::Psd, 8, roughness()); + + let plan = list_set_outputs(&fx.project, &[0, 1], &"m".repeat(MAX_STEM), &options).unwrap(); + + assert_eq!(plan.len(), 4, "both tiles of both sets must survive deduplication"); + for (set, file) in plan { + let tile = file.tile.unwrap(); + let set_name = sanitize_file_stem(&fx.project.texture_sets[set].name); + assert!(file.name.contains(&set_name), "{}", file.name); + assert!(file.name.ends_with(&format!(".{tile}.psd")), "{}", file.name); + assert_eq!(file.udim_name.unwrap().replace("", &tile.to_string()), file.name); + } +} + +#[test] +fn feedback_reserved_export_stem_remains_bounded_and_idempotent() { + let raw = format!("CON.{}", "x".repeat(MAX_STEM)); + + let sanitized = sanitize_file_stem(&raw); + + assert!(sanitized.starts_with("_CON.")); + assert!(sanitized.len() <= MAX_STEM, "{} bytes", sanitized.len()); + assert_eq!(sanitize_file_stem(&sanitized), sanitized); +} + +#[test] +fn feedback_psd_dithering_tracks_the_document_depth() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.dither = true; + let mut second = options.preset.maps[0].clone(); + second.file = "second".into(); + options.preset.maps.push(second); + options.maps.insert(1, MapOverride { dither: Some(false), ..MapOverride::default() }); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert!(plan[0].dither && plan[0].layers[0].dither && !plan[0].layers[1].dither); + + options.preset.maps[1].bit_depth = 16; + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert_eq!(plan[0].bit_depth, 16); + assert!(!plan[0].dither && plan[0].layers.iter().all(|layer| !layer.dither)); + assert!(plan[0].warnings.iter().any(|warning| warning.contains("dithering") && warning.contains("16-bit"))); +} + +#[test] +fn feedback_psd_rejects_large_working_set_during_planning() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, rgba_half_alpha()); + options.size = Some(8192); + + let error = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err(); + + assert!(error.to_string().contains("working memory"), "{error}"); + options.size = Some(4096); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).is_ok()); +} + +#[test] +fn a_native_export_plans_psds_a_browser_tab_cannot_hold() { + let mut fx = Fx::new(&default_channels()); + let mut one = one_map(FileFormat::Psd, 8, rgba_half_alpha()); + one.size = Some(MAX_IMAGE_SIZE / 2); + let mut separate = ExportOptions::new(builtin_preset("Separate maps").unwrap()); + separate.format_override = Some(FileFormat::Psd); + separate.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1005).collect(); + + let plans = [list_outputs(&fx.project, 0, "sphere", &one), list_outputs(&fx.project, 0, "sphere", &separate)]; + + for plan in plans { + let plan = plan.unwrap(); + assert!(!plan.is_empty() && plan.iter().all(|file| file.format == FileFormat::Psd), "{plan:?}"); + } + assert!(list_set_outputs(&fx.project, &[0], "sphere", &separate).is_ok(), "a desktop batch holds every tile's PSD"); +} + +#[test] +fn a_psd_that_cannot_be_planned_leaves_the_sets_other_maps() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let mut psd = options.preset.maps[0].clone(); + (psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 16, rgba_half_alpha()); + options.preset.maps.push(psd); + options.size = Some(MAX_IMAGE_SIZE); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}"); + assert!(plan[0].warnings.iter().any(|warning| warning.contains(".psd") && warning.contains("2 GiB")), "{:?}", plan[0].warnings); +} + +#[test] +fn psd_plan_counts_every_layer_against_the_version_one_byte_limit() { let fx = Fx::new(&default_channels()); let mut options = one_map(FileFormat::Psd, 16, rgba_half_alpha()); options.size = Some(16_384); @@ -1178,19 +1403,26 @@ fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); assert!(error.to_string().contains("PSD") && error.to_string().contains("2 GiB"), "{error}"); - options.bit_depth_override = Some(8); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); - options.bit_depth_override = None; - options.preset.maps[0].channels.pop(); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); + options.size = Some(8192); + let layer_size = (8192, 8192); + for copy in ["second", "third"] { + assert!(check_psd_size(std::iter::repeat_n(layer_size, options.preset.maps.len()), 0, 16).is_ok()); + let mut map = options.preset.maps[0].clone(); + map.file = copy.into(); + options.preset.maps.push(map); + } + let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); + + assert!(error.to_string().contains("3 maps") && error.to_string().contains("2 GiB"), "{error}"); } #[test] -fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() { - // These RGBA16 planes are 32 bytes below 2 GiB before headers and the alpha name - let (width, height) = (10_924, 24_573); - assert!(check_psd_size((width, height), 4, 16).is_err()); - assert!(check_psd_size((width, height - 1), 4, 16).is_ok()); +fn psd_byte_limit_includes_the_merged_image_and_keeps_separate_tiles_valid() { + // One RGBA16 layer and the merged image: 87360 bytes over 2 GiB, a row less 87424 bytes below + let (width, height) = (10_924, 12_287); + + assert!(check_psd_size([(width, height)], 0, 16).is_err()); + assert!(check_psd_size([(width, height - 1)], 0, 16).is_ok()); let mut fx = Fx::new(&default_channels()); fx.project.texture_sets[0].uv_tiles = vec![1001, 1003, 1011]; @@ -1201,10 +1433,25 @@ fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() { let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); assert!(error.to_string().contains("2 GiB"), "{error}"); + options.size = Some(4096); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err().to_string().contains("working memory")); options.atlas = false; assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 3); } +#[test] +fn psd_rejects_a_composite_with_a_different_size_from_the_plan() { + let mut fx = Fx::new(&default_channels()); + let source_size = RES * 2; + fx.comp = Composite::new(&default_channels(), source_size); + fx.coverage.resize((source_size * source_size) as usize, true); + let options = one_map(FileFormat::Psd, 8, roughness()); + + let error = render_maps(&fx.input(), &options).unwrap_err(); + + assert!(error.to_string().contains("does not match the planned texture set size"), "{error}"); +} + #[test] fn jng_has_jpeg_colour_and_lossless_alpha() { use std::io::Read; @@ -1575,3 +1822,563 @@ fn write_files_accepts_a_long_nested_folder_and_stem() { assert!(paths[0].is_file()); std::fs::remove_dir_all(&dir).unwrap(); } + +#[test] +fn map_preview_bounds_the_longer_side_of_a_tall_atlas() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1031]; + fx.comp = Composite::with_size(&default_channels(), RES, RES * 4); + fx.coverage.resize((RES * RES * 4) as usize, true); + let options = one_map(FileFormat::Png, 8, roughness()); + let max_side = 32; + + let preview = MapPreview::sample(&fx.input(), &options, 0, max_side).unwrap().unwrap(); + + assert_eq!(preview.height, max_side); + assert_eq!(preview.width * 4, preview.height); + assert_eq!(preview.pixels.len(), (preview.width * preview.height) as usize); +} + +#[test] +fn a_map_preview_is_no_larger_than_the_maps_own_size() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let own = RES / 4; + options.maps.insert(0, MapOverride { size: Some(own), ..MapOverride::default() }); + let file = decode(&fx.render(&options)[0]); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert_eq!((preview.width, preview.height), file.dimensions(), "the preview shows the file at its own size"); + options.size = Some(RES / 2); + options.maps.clear(); + let export_sized = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert!(export_sized.width > preview.width && export_sized.width < RES, "the export size bounds a map without its own"); +} + +#[test] +fn a_map_preview_holds_the_values_its_file_stores() { + let mut fx = Fx::new(&default_channels()); + fx.set_all(Channel::Metallic, |x, _| [x as f32 / 63.0; 3]); + fx.set_all(Channel::Roughness, |_, y| [y as f32 / 63.0; 3]); + let mut options = ExportOptions::new(builtin_preset("Unity HDRP (Mask Map)").unwrap()); + let mask = options.preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let base = options.preset.maps.iter().position(|map| map.file.contains("BaseMap")).unwrap(); + options.preset.maps[mask].inverted.push(Dest::R); + let files = fx.render(&options); + + // The packed data map, one channel inverted, and the sRGB colour map + for (index, suffix) in [(mask, "MaskMap"), (base, "BaseMap")] { + let file = decode(find(&files, suffix)); + let preview = MapPreview::sample(&fx.input(), &options, index, RES).unwrap().unwrap(); + + assert_eq!((preview.width, preview.height), file.dimensions()); + assert_eq!(preview.channels.len(), usize::from(file.color().channel_count()), "{suffix}"); + assert!(preview.pixels == file.into_bytes(), "{suffix}: the preview shows what the file stores"); + } + + let small = MapPreview::sample(&fx.input(), &options, mask, 8).unwrap().unwrap(); + + assert!(small.width < RES && small.pixels.len() == (small.width * small.height) as usize * 4, "a smaller preview samples the same map"); + assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); +} + +#[test] +fn feedback_jpeg_previews_omit_the_alpha_channel() { + let fx = Fx::new(&default_channels()); + let mut la = roughness(); + la.push((Dest::A, SourceRef::Constant(0.5))); + for (channels, expected) in [(la, vec![Dest::L]), (rgba_half_alpha(), vec![Dest::R, Dest::G, Dest::B])] { + let mut options = one_map(FileFormat::Png, 8, channels); + let png_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap(); + options.maps.insert(0, MapOverride { format: Some(FileFormat::Jpeg), ..MapOverride::default() }); + + let jpeg_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap(); + let jpeg = decode(&fx.render(&options)[0]); + + assert_eq!(jpeg_preview.channels, expected); + assert_eq!(jpeg_preview.channels.len(), usize::from(jpeg.color().channel_count())); + let colors: Vec<_> = png_preview.pixels.chunks_exact(png_preview.channels.len()).flat_map(|pixel| pixel[..expected.len()].iter().copied()).collect(); + assert_eq!(jpeg_preview.pixels, colors); + } +} + +#[test] +fn webp_preview_matches_the_exported_channels_and_samples() { + let fx = Fx::new(&default_channels()); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.retain(|(dest, _)| *dest != Dest::A); + + for (layout, expected) in + [(roughness(), &[Dest::R, Dest::G, Dest::B][..]), (gray_alpha, &[Dest::R, Dest::G, Dest::B, Dest::A][..]), (rgb, &[Dest::R, Dest::G, Dest::B][..])] + { + let options = one_map(FileFormat::Webp, 8, layout); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let image = decode(&fx.render(&options)[0]); + + assert_eq!(preview.channels, expected); + assert_eq!(preview.channels.len(), usize::from(image.color().channel_count())); + assert_eq!(preview.pixels, image.as_bytes()); + } +} + +#[test] +fn pgm_preview_shows_exported_luminance_without_alpha() { + let fx = Fx::new(&default_channels()); + let mut gray_with_alpha = roughness(); + gray_with_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for channels in [gray_with_alpha, rgba_half_alpha()] { + let mut options = one_map(FileFormat::Png, 8, channels); + options.maps.insert(0, MapOverride { format: Some(FileFormat::Pgm), ..MapOverride::default() }); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let files = fx.render(&options); + let pgm_samples = files[0].bytes.strip_prefix(b"P5\n64 64\n255\n").unwrap(); + + assert_eq!(preview.channels, [Dest::L]); + assert_eq!(preview.pixels, pgm_samples); + } +} + +#[test] +fn hdr_and_tiff_previews_show_channels_written_by_the_encoder() { + let fx = Fx::new(&default_channels()); + let mut gray_with_alpha = roughness(); + gray_with_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let rgb = [Dest::R, Dest::G, Dest::B]; + let rgba = [Dest::R, Dest::G, Dest::B, Dest::A]; + + for (format, depth, layout, expected) in [ + (FileFormat::Hdr, 32, &gray_with_alpha, rgb.as_slice()), + (FileFormat::Hdr, 32, &rgba_half_alpha(), rgb.as_slice()), + (FileFormat::Tiff, 8, &gray_with_alpha, rgba.as_slice()), + (FileFormat::Tiff, 32, &gray_with_alpha, rgba.as_slice()), + (FileFormat::Tiff, 32, &roughness(), rgb.as_slice()), + ] { + let mut options = one_map(format, depth, layout.clone()); + if layout[0].0 == Dest::L { + options.preset.maps[0].inverted.push(Dest::L); + } + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let file = decode(&fx.render(&options)[0]); + let components = usize::from(file.color().channel_count()); + + assert_eq!(preview.channels, expected, "{format:?} at {depth} bits"); + assert_eq!(preview.channels.len(), components); + assert_eq!(preview.pixels.len(), (file.width() * file.height()) as usize * components); + let decoded_pixels = file.to_rgba32f(); + for (preview_pixel, decoded) in preview.pixels.chunks_exact(components).zip(decoded_pixels.pixels()) { + for (actual, sample) in preview_pixel.iter().zip(decoded.0) { + let value = if options.preset.maps[0].is_color() && format == FileFormat::Hdr { linear_to_srgb(sample) } else { sample }; + assert!((i32::from(*actual) - byte(value)).abs() <= 2, "{format:?} at {depth} bits: {actual} vs {value}"); + } + } + } +} + +#[test] +fn triangle_coverage_preserves_uncovered_texels_and_height_normal_neighbours_in_previews() { + let mut fixture = Fx::new(&default_channels()); + fixture.set_all(Channel::Height, |x, y| [(x + y) as f32 / RES as f32; 3]); + for (index, covered) in fixture.coverage.iter_mut().enumerate() { + *covered = index % 3 != 0; + } + let triangles: Vec<_> = fixture.coverage.iter().map(|covered| if *covered { 0 } else { texturecraft_geom::NO_TRI }).collect(); + let input = fixture.input(); + let triangle_input = + ExportInput { project: input.project, ts: input.ts, composite: input.composite, baked: input.baked, coverage: &triangles, mesh_name: input.mesh_name }; + let options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + + for map in 0..3 { + let expected = MapPreview::sample(&input, &options, map, RES).unwrap().unwrap(); + let actual = MapPreview::sample_triangles(&triangle_input, &options, map, RES).unwrap().unwrap(); + + assert_eq!(actual, expected); + } +} + +/// Tilts every normal of `fx` and returns the green byte an OpenGL normal map stores for it +fn tilt_normals(fx: &mut Fx) -> i32 { + let tilt = Vec3::new(0.3, 0.4, 0.0); + let tilt = Vec3::new(tilt.x, tilt.y, (1.0 - tilt.length_squared()).sqrt()); + fx.set_all(Channel::Normal, |_, _| (tilt * 0.5 + Vec3::splat(0.5)).to_array()); + byte(tilt.y * 0.5 + 0.5) +} + +#[test] +fn the_unreal_subsurface_template_writes_the_scatter_mask_beside_the_packed_maps() { + let mut channels = default_channels(); + channels.extend([Channel::AmbientOcclusion, Channel::Opacity, Channel::ScatterWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::AmbientOcclusion, |_, _| [0.6; 3]); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Unreal Engine Subsurface Profile (Packed)"); + + let mask = find(&files, "_SubsurfaceMask.png"); + + assert_eq!(decode(mask).color(), image::ColorType::L8, "the mask is one 8-bit channel"); + assert_close(pixel(mask), [byte(0.7), byte(0.7), byte(0.7), 255], "scatter weight in the mask"); + let [r, g, b, _] = pixel(find(&files, "_OcclusionRoughnessMetallic.png")); + assert_close([r, g, b, 0], [byte(0.6), byte(0.4), byte(0.8), 0], "R occlusion, G roughness, B metallic"); + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "opacity feeds the mask, not the base color's alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} + +#[test] +fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_channels() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::Normal, Channel::Height, Channel::Opacity]); + let specular = [0.2, 0.5, 0.8]; + fx.set_all(Channel::Specular, |_, _| specular); + fx.set_all(Channel::Glossiness, |_, _| [0.3; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8); + let srgb = specular.map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(specular_glossiness), [srgb[0], srgb[1], srgb[2], byte(0.3)], "sRGB specular, linear glossiness in alpha"); + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Diffuse.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB diffuse, opacity in alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} + +#[test] +fn the_gltf_specular_glossiness_file_is_rgba_and_fully_glossy_without_a_glossiness_channel() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Normal]); + fx.set_all(Channel::Specular, |_, _| [0.2, 0.5, 0.8]); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8, "the extension reads glossiness from alpha"); + assert_eq!(pixel(specular_glossiness)[3], 255, "glossinessFactor defaults to 1"); +} + +#[test] +fn the_redshift_template_writes_one_map_per_input_the_set_has() { + let mut channels = default_channels(); + channels.extend([Channel::ScatterWeight, Channel::CoatWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + fx.set_all(Channel::CoatWeight, |_, _| [0.2; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Redshift Standard Material (separate maps)"); + + let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect(); + for (input, expected) in [("Metalness", 0.8), ("ReflectionRoughness", 0.4), ("SubsurfaceWeight", 0.7), ("CoatWeight", 0.2)] { + let file = find(&files, &format!("_{input}.png")); + + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is one 8-bit channel: {names:?}"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); + assert!(!names.iter().any(|name| name.contains("Sheen") || name.contains("CoatRoughness")), "inputs the set lacks write no maps: {names:?}"); +} + +#[test] +fn the_roblox_template_writes_opacity_in_the_colour_alpha_and_opengl_normals() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Roblox SurfaceAppearance (separate maps)"); + + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Color.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB colour, opacity in alpha"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4)] { + let file = find(&files, &format!("_{input}.png")); + + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} + +#[test] +fn the_sketchfab_template_writes_directx_normals_and_one_map_per_channel() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Sketchfab Metalness (separate maps)"); + + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "no alpha on the base color"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4), ("AmbientOcclusion", 0.6)] { + let file = find(&files, &format!("_{input}.png")); + + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is linear grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} + +#[test] +fn feedback_psd_preview_matches_layer_rgba() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for channels in [roughness(), gray_alpha, rgba_half_alpha()] { + let options = one_map(FileFormat::Psd, 8, channels); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let files = fx.render(&options); + let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap().rgba8().unwrap(); + + assert_eq!(preview.channels, [Dest::R, Dest::G, Dest::B, Dest::A]); + assert!(preview.pixels == layer.data, "the preview shows the layer's stored channels"); + } +} + +#[test] +fn psd_layers_hold_the_samples_of_the_same_png_at_every_layout_and_depth() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let base_colour = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.pop(); + let layouts = [roughness(), vec![(Dest::L, base_colour(0))], gray_alpha, rgb, rgba_half_alpha()]; + + for channels in layouts { + for (depth, dither) in [(8, false), (8, true), (16, false)] { + let mut png_options = one_map(FileFormat::Png, depth, channels.clone()); + png_options.dither = dither; + let mut psd_options = png_options.clone(); + psd_options.format_override = Some(FileFormat::Psd); + + let png = decode(&fx.render(&png_options)[0]); + let psd = craft_psd::PsdFile::from_bytes(&fx.render(&psd_options)[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap(); + + let context = format!("{channels:?} at {depth} bits, dithering {dither}"); + if depth == 16 { + // Planes of big-endian samples: red, green, blue, then transparency + let planes: Vec> = [0, 1, 2, -1].into_iter().map(|id| layer.channel_bytes(id).unwrap()).collect(); + let texel_count = planes[0].len() / 2; + let samples: Vec = + (0..texel_count).flat_map(|texel| planes.iter().map(move |plane| u16::from_be_bytes([plane[2 * texel], plane[2 * texel + 1]]))).collect(); + assert!(samples == png.to_rgba16().into_raw(), "{context}"); + } else { + assert!(layer.rgba8().unwrap().data == png.to_rgba8().into_raw(), "{context}"); + } + } + } +} + +#[test] +fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001]; + let mut options = one_map(FileFormat::Psd, 8, roughness()); + let literal = format!("{}.1001", "a".repeat(MAX_STEM - ".1001".len())); + options.preset.maps[0].file = literal.clone(); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert_eq!(plan[0].layers[0].name, literal); + + options.preset.maps[0].file = "Group/Map.$udim".into(); + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].layers[0].name, "Group/Map.1001"); + + options.preset.maps[0].file = "Map".into(); + options.format_override = Some(FileFormat::Png); + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].name, "Map.1001.png"); +} + +#[test] +fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body".into(); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + for name in ["body.1001", "Body.1001_1", "Trim"] { + let mut untiled = fx.project.texture_sets[0].clone(); + untiled.name = name.into(); + untiled.uv_tiles.clear(); + fx.project.texture_sets.push(untiled); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + + let plans = list_set_outputs(&fx.project, &[1, 0, 2, 3], "sphere", &options).unwrap(); + + assert_eq!(plans.len(), 5); + assert_eq!(plans[1].1.name, "sphere_Body.1001.psd"); + assert_eq!(plans[2].1.name, "sphere_Body.1002.psd"); + assert_eq!(plans[3].1.name, "sphere_Body.1001_1.psd"); + assert_eq!(plans[4].1.name, "sphere_Trim.psd"); + let separate = list_outputs(&fx.project, 1, "sphere", &options).unwrap(); + assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning"); +} + +#[test] +fn psd_document_names_survive_sanitization_and_case_collisions() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body Coat".into(); + for (name, tiles) in [ + ("body_coat", vec![]), + ("Body_Coat_0", vec![]), + ("Body Coat", vec![1001, 1002]), + ("BODY_COAT", vec![1001]), + ("Trim", vec![]), + ("body_coat", vec![1011]), + ] { + let mut set = fx.project.texture_sets[0].clone(); + set.name = name.into(); + set.uv_tiles = tiles; + fx.project.texture_sets.push(set); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + let indices = [6, 5, 4, 3, 2, 1, 0]; + + let batch = list_set_outputs(&fx.project, &indices, "sphere", &options).unwrap(); + let separate: Vec<_> = indices + .into_iter() + .flat_map(|index| list_outputs(&fx.project, index, "sphere", &options).unwrap().into_iter().map(move |file| (index, file.name))) + .collect(); + + assert_eq!(batch.into_iter().map(|(index, file)| (index, file.name)).collect::>(), separate); + for (index, unchanged) in [(2, "sphere_Body_Coat_0.psd"), (5, "sphere_Trim.psd"), (6, "sphere_body_coat.1011.psd")] { + assert!(separate.iter().any(|(set, name)| *set == index && name == unchanged)); + } + let tiled = list_outputs(&fx.project, 3, "sphere", &options).unwrap(); + assert!(tiled[0].udim_name.is_some()); + assert_eq!(tiled[0].udim_name, tiled[1].udim_name, "tiles of one set keep the same pattern"); + + let atlas_options = ExportOptions { atlas: true, ..options }; + let atlas = list_set_outputs(&fx.project, &indices, "sphere", &atlas_options).unwrap(); + assert_eq!(atlas.len(), indices.len(), "atlas documents also need distinct names"); +} + +#[test] +fn psd_batch_budget_counts_only_retained_documents() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1006).collect(); + let mut other = fx.project.texture_sets[0].clone(); + other.name = "Other".into(); + fx.project.texture_sets.push(other); + + let once = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + let repeated = plan_set_outputs(&fx.project, &[0, 0], "sphere", &options, PsdBudget::WEB).unwrap(); + let distinct = plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB); + let (_, bytes_per_tile) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + + assert_eq!(once.len(), repeated.len()); + assert!(once.iter().zip(&repeated).all(|((_, first), (_, kept))| first.name == kept.name && kept.warnings.len() > first.warnings.len())); + assert!(matches!(distinct, Err(FormatError::TooLarge(message)) if message.contains("total PSD"))); + println!( + "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {:?}", + bytes_per_tile * once.len() as u64, + bytes_per_tile * (once.len() + repeated.len()) as u64, + PsdBudget::WEB.batch_bytes + ); +} + +#[test] +fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.padding = Padding::None; + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); + + let smaller = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + assert_eq!(smaller.len(), 7, "seven 128 MiB payloads fit with record overhead"); + fx.project.texture_sets[0].uv_tiles.extend(1008..1034); + + let oversized = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB); + assert!(matches!(&oversized, Err(error) if error.to_string().contains("total PSD")), "the 33 individually valid tiles must be rejected as a batch"); + + let set = &fx.project.texture_sets[0]; + let (width, height) = set.size(); + fx.comp = Composite::with_size(&default_channels(), width, height); + fx.coverage.resize((width * height) as usize, true); + let planned = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap(); + let error = render_planned_maps_within(&fx.input(), &options, planned, PsdBudget::WEB).unwrap_err(); + assert!(error.to_string().contains("total PSD"), "{error}"); + + let (_, estimated_bytes) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + println!( + "PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {:?}", + estimated_bytes * 33, + PsdBudget::WEB.batch_bytes + ); + + let mut small = fx.project.texture_sets[0].clone(); + small.uv_tiles = (1001..1006).collect(); + fx.project.texture_sets[0] = small.clone(); + small.name = "Other".into(); + fx.project.texture_sets.push(small); + assert!(plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[1], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB).is_err(), "the budget includes all selected sets"); + assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_ok(), "a desktop batch has no such budget"); +} + +#[test] +fn specular_glossiness_exports_ignore_the_ior_specular_setting() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::SpecularLevel]); + fx.set_all(Channel::Specular, |_, _| [0.3, 0.2, 0.1]); + fx.set_all(Channel::Glossiness, |_, _| [0.7; 3]); + fx.set_all(Channel::SpecularLevel, |_, _| [0.5; 3]); + (fx.project.display.spec_gloss, fx.project.display.ior) = (true, 1.8); + let channel = |channel| SourceRef::Channel { channel, component: 0 }; + let virt = |map| SourceRef::Virtual { map, component: 0 }; + let specular = MapSpec { + file: "specular".into(), + format: FileFormat::Png, + bit_depth: 16, + channels: [Dest::R, Dest::G, Dest::B] + .into_iter() + .zip(0u8..) + .map(|(dest, component)| (dest, SourceRef::Channel { channel: Channel::Specular, component })) + .collect(), + inverted: Vec::new(), + }; + let preset = ExportPreset { + name: "spec gloss".into(), + maps: vec![ + specular, + gray_map("gloss", channel(Channel::Glossiness)), + gray_map("rough", virt(VirtualMap::Roughness)), + gray_map("f0", virt(VirtualMap::F0)), + ], + }; + let options = ExportOptions::new(preset); + + let off = fx.render(&options); + fx.project.display.ior_specular = true; + let on = fx.render(&options); + + assert!(off.iter().any(|file| file.name.starts_with("f0")), "the F0 map is part of the comparison"); + assert_eq!(on, off, "Specular/Glossiness takes reflectance from the Specular color, not the IOR"); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a46a6f62..85356dce 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -42,8 +42,8 @@ pub mod project_file; pub mod zip_read; pub use export::{ - Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, - render_maps, skip_repeated_names, + Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MAX_PREVIEW_SIDE, MapOverride, MapPreview, MapSpec, Padding, PlannedFile, + SourceRef, VirtualMap, list_outputs, render_maps, skip_repeated_names, }; pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource}; pub use mesh_export::{ @@ -53,7 +53,7 @@ pub use mesh_export::{ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; -pub use presets::{DEFAULT_PRESET, builtin_preset, builtin_presets, preset_from_json, preset_to_json}; +pub use presets::{DEFAULT_PRESET, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, builtin_presets, preset_from_json, preset_to_json}; pub use project_file::{ BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, RamReservation, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, set_project_open_limit_gib, diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index a3f2bddb..9441b31e 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -386,11 +386,16 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: /// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion, /// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has /// no data for. `project_normal` is the project's normal convention, used by normal maps that -/// follow it. +/// follow it. Layered PSD files are omitted. pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec { let mut out: Vec = Vec::new(); let mut seen_maps = Vec::new(); for file in files { + // PSD stores several maps in one file + if !file.format.usable_by_usd_asset() { + continue; + } + // The first tile stands for all the tiles of a map if seen_maps.contains(&file.map) { continue; @@ -405,6 +410,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm (None, None) => file.name.clone(), (None, Some(_)) => continue, }; + let srgb = opts.space_for_map(map, file.format, file.bit_depth) == ColorSpace::Srgb; for slot in 0..SLOTS.len() { if out.iter().any(|binding| binding.slot == slot) { @@ -412,7 +418,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm } let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue }; - let normal = (slot == 3).then(|| { + let normal = (SLOTS[slot].0 == "Normal").then(|| { opts.normal_format.unwrap_or(match source { SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl, SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX, @@ -585,6 +591,7 @@ mod texture_binding_tests { tile: None, udim_name: None, warnings: Vec::new(), + layers: Vec::new(), } } diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index 25fa8bbd..3bf375cf 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -52,12 +52,34 @@ pub fn self_contained_mesh(name: &str, bytes: Vec, read: &mut dyn FnMut(&str } /// Read mesh file `path` with the files it references from its folder (see -/// [`self_contained_mesh`]), each at most [`MAX_MESH_FILE_BYTES`]. +/// [`self_contained_mesh`]), each at most [`MAX_MESH_FILE_BYTES`]. A referenced file is used only +/// when, after symbolic links and junctions are followed, it is still inside the mesh's folder; +/// one that leads outside counts as not found (a warning, like a missing file), while links that +/// stay inside the folder work. Hard links cannot be told apart by path: see [`read_inside`]. #[cfg(not(target_arch = "wasm32"))] pub fn read_mesh_file(path: &std::path::Path) -> Result { let bytes = crate::read_capped(path, MAX_MESH_FILE_BYTES)?; let dir = path.parent().unwrap_or_else(|| std::path::Path::new("")); - self_contained_mesh(&path.to_string_lossy(), bytes, &mut |rel| crate::read_capped(&dir.join(rel), MAX_MESH_FILE_BYTES).ok()) + self_contained_mesh(&path.to_string_lossy(), bytes, &mut |rel| read_inside(dir, rel)) +} + +/// `rel` (already checked by [`below`]) read from below `dir`, or None when it is missing, too big, +/// or, once symbolic links and junctions are followed, is not inside `dir`: `below` only looks at +/// the text of the path, so a link in the folder could otherwise lead to any file. +/// +/// Limit: a HARD link is an ordinary directory entry, so a hard link in the folder to a file +/// outside it looks like a file inside it and is read. Telling them apart needs the link count, +/// which std offers only on Unix (and a count above one is also what legitimate files can have); +/// we don't use `unsafe`, so it is not checked. Making a hard link needs write access to the +/// folder and read access to the target. +#[cfg(not(target_arch = "wasm32"))] +fn read_inside(dir: &std::path::Path, rel: &str) -> Option> { + let root = std::fs::canonicalize(if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir }).ok()?; + let file = std::fs::canonicalize(dir.join(rel)).ok()?; + if !file.starts_with(&root) { + return None; + } + crate::read_capped(&file, MAX_MESH_FILE_BYTES).ok() } /// `asset` as a path below the mesh's folder (`/`-separated, `.` and `..` resolved), or None when @@ -126,6 +148,69 @@ fn image_mime(path: &str) -> &'static str { mod tests { use super::*; + /// A link `link` inside `dir` leading to `target` (a folder): a symbolic link on Unix, a junction + /// on Windows. False when the system refuses to make one. + #[cfg(not(target_arch = "wasm32"))] + fn link_dir(link: &std::path::Path, target: &std::path::Path) -> bool { + #[cfg(unix)] + return std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + return std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success()); + #[cfg(not(any(unix, windows)))] + return false; + } + + /// Files are read through ordinary paths and links that stay inside the folder, but not through a link + /// (folder or file) that leads outside it. Fails when the system refuses to make the links (Unix + /// symbolic links and Windows junctions need no privilege), so it cannot pass without testing them. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_link_in_the_mesh_folder_cannot_lead_outside_it() { + let base = std::env::temp_dir().join(format!("tc-mesh-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (dir, outside) = (base.join("model"), base.join("secret")); + let result = std::panic::catch_unwind(|| { + std::fs::create_dir_all(dir.join("tex")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("key.txt"), b"private").unwrap(); + std::fs::write(dir.join("tex/a.png"), b"inside").unwrap(); + assert_eq!(read_inside(&dir, "tex/a.png").as_deref(), Some(&b"inside"[..]), "ordinary files below the folder are read"); + assert_eq!(read_inside(&dir, "tex/missing.png"), None); + assert!(link_dir(&dir.join("out"), &outside), "this system would not make a link"); + assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder"); + // A link that stays inside the folder is an ordinary shortcut and still works. + assert!(link_dir(&dir.join("shortcut"), &dir.join("tex")), "this system would not make a link"); + assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside"); + // A link to a single outside file (Unix symbolic links; Windows file links need privileges). + #[cfg(unix)] + { + std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap(); + assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file"); + } + // The mesh's own folder reached through a link is fine: both sides are resolved. + assert!(link_dir(&base.join("alias"), &dir), "this system would not make a link"); + assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link"); + + // The same through read_mesh_file: the outside bytes must not end up in the glTF. + std::fs::write( + dir.join("m.gltf"), + br#"{"asset": {"version": "2.0"}, "buffers": [{"uri": "out/key.txt", "byteLength": 7}, {"uri": "tex/a.png", "byteLength": 6}]}"#, + ) + .unwrap(); + let mesh = read_mesh_file(&dir.join("m.gltf")).unwrap(); + let text = String::from_utf8(mesh.bytes).unwrap(); + let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b); + assert!(!text.contains(&b64(b"private")), "outside bytes were inlined"); + assert!(text.contains(&b64(b"inside")), "the inside file is inlined"); + assert_eq!(mesh.warnings.len(), 1, "{:?}", mesh.warnings); + assert!(mesh.warnings[0].contains("out/key.txt"), "{:?}", mesh.warnings); + }); + let _ = std::fs::remove_dir_all(&base); + if let Err(e) = result { + std::panic::resume_unwind(e); + } + } + #[test] fn below_keeps_paths_inside_the_folder() { assert_eq!(below("tex/a.png").as_deref(), Some("tex/a.png")); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 6450878b..5e0d2468 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -25,7 +25,7 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4}; -use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids}; +use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap}; use texturecraft_geom::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh, UvGBuffer}; use crate::{FormatError, Result}; @@ -508,7 +508,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { 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), + _ => mesh.smooth_normals(), }; 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(); @@ -641,23 +641,6 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { - 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(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; - } - } - } - - 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). pub fn mesh_report(mesh: &Mesh) -> MeshReport { report(mesh, false, Vec::new()) diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 2f2879a4..0b34ceb5 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -94,8 +94,8 @@ pub fn builtin_presets() -> Vec { }), // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material preset("glTF PBR Metal Roughness", gltf_pbr_maps(|s| format!("$mesh_$textureSet_{s}"))), - // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material (R occlusion, G roughness, B metallic) and the base color, roughness, metallic and normal inputs of - // https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine + // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material + // Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine preset( "Unreal Engine (Packed)", vec![map("BaseColor", 8, base_with_alpha()), map("OcclusionRoughnessMetallic", 8, orm()), map("Normal", 8, normal(VirtualMap::NormalDirectX))], @@ -219,6 +219,77 @@ pub fn builtin_presets() -> Vec { map("clearcoatRoughness", 8, gray(ch(Channel::CoatRoughness, 0))), ], ), + // Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine (the Opacity input masks the scattering, so the base color has no alpha) + preset( + "Unreal Engine Subsurface Profile (Packed)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("OcclusionRoughnessMetallic", 8, orm()), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("SubsurfaceMask", 8, gray(ch(Channel::ScatterWeight, 0))), + ], + ), + // Spec: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md (diffuse with alpha, specular RGB with glossiness in A) + preset( + "glTF Specular Glossiness (archived extension)", + vec![ + map("Diffuse", 8, base_with_alpha()), + map("SpecularGlossiness", 8, { + let mut specular_glossiness = rgb(|k| ch(Channel::Specular, k)); + specular_glossiness.push((Dest::A, ch(Channel::Glossiness, 0))); + specular_glossiness + }), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emissive", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Standard_Material.html (the Standard Material inputs) + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Bump+Map.html (normal maps in OpenGL format) + preset("Redshift Standard Material (separate maps)", { + let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0))); + let rgb8 = |name: &str, c: Channel| map(name, 8, rgb(|k| ch(c, k))); + vec![ + rgb8("BaseColor", Channel::BaseColor), + gray8("Metalness", Channel::Metallic), + gray8("ReflectionRoughness", Channel::Roughness), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + rgb8("EmissionColor", Channel::Emissive), + gray8("Opacity", Channel::Opacity), + gray8("SubsurfaceWeight", Channel::ScatterWeight), + gray8("CoatWeight", Channel::CoatWeight), + gray8("CoatRoughness", Channel::CoatRoughness), + gray8("SheenWeight", Channel::SheenWeight), + rgb8("SheenColor", Channel::SheenColor), + gray8("SheenRoughness", Channel::SheenRoughness), + ] + }), + // Spec: https://create.roblox.com/docs/art/modeling/surface-appearance (ColorMap alpha is opacity) + // Spec: https://create.roblox.com/docs/art/modeling/texture-specifications (OpenGL normals only; grayscale metalness and roughness) + // Spec: https://create.roblox.com/docs/art/modeling/reimport (the file name suffix it assigns to each map) + preset( + "Roblox SurfaceAppearance (separate maps)", + vec![ + map("Color", 8, base_with_alpha()), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + ], + ), + // Spec: https://help.sketchfab.com/en/articles/16152630-pbr-maps (sRGB base color, linear grayscale metalness; no alpha, the docs don't say opacity reads it) + // Spec: https://help.sketchfab.com/en/articles/16152634-materials-pbr (roughness, AO and emission channels) + // Spec: https://help.sketchfab.com/en/articles/16152621-normal-map-bump-map (DirectX normals by default) + preset( + "Sketchfab Metalness (separate maps)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("AmbientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emission", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", @@ -240,11 +311,27 @@ pub const DEFAULT_PRESET: &str = "Document channels + Normal + AO (No Alpha)"; /// scripts still use it). const OLD_DEFAULT_PRESET: &str = "Document channels + Normal + AO"; +/// Names introduced with the export update, which could previously belong to saved user presets. +pub const NEW_BUILTIN_PRESET_NAMES: [&str; 5] = [ + "Unreal Engine Subsurface Profile (Packed)", + "glTF Specular Glossiness (archived extension)", + "Redshift Standard Material (separate maps)", + "Roblox SurfaceAppearance (separate maps)", + "Sketchfab Metalness (separate maps)", +]; + +/// The immutable built-in templates shared by menu and command lookups. +pub fn builtin_preset_catalog() -> &'static [ExportPreset] { + static CATALOG: std::sync::LazyLock> = std::sync::LazyLock::new(builtin_presets); + &CATALOG +} + /// A built-in preset by name (case-insensitive). pub fn builtin_preset(name: &str) -> Option { let name = name.trim(); let name = if name.eq_ignore_ascii_case(OLD_DEFAULT_PRESET) { DEFAULT_PRESET } else { name }; - builtin_presets().into_iter().find(|p| p.name.eq_ignore_ascii_case(name)) + + builtin_preset_catalog().iter().find(|preset| preset.name.eq_ignore_ascii_case(name)).cloned() } /// Parse and validate a user preset. diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 581d13d2..369707ee 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -42,11 +42,13 @@ mod load_budget; mod project_open_limit; mod ram_operation; mod ram_reservation; +mod save_progress; mod uv_layout; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, 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}; pub use ram_reservation::RamReservation; +pub use save_progress::SaveProgress; const KIND: &str = "project file"; #[cfg(test)] @@ -70,21 +72,21 @@ pub use bake_paint_data::BakePaintData; /// Everything a project file holds. #[derive(Clone, Debug)] -pub struct ProjectFile> { +pub struct ProjectFile, MeshBytes = Vec> { pub project: Project, pub pixels: PixelStore, /// Baked mesh maps per texture set index. pub baked: BTreeMap, /// Original mesh file: (extension, bytes). - pub mesh: Option<(String, Vec)>, + pub mesh: Option<(String, MeshBytes)>, /// Saved UV layout of `mesh` when its UVs were rebuilt: the UV of every triangle corner, in /// index order, as the mesh was first imported. pub mesh_uvs: Option>, /// High-definition mesh files for baking: (file name, bytes). Names are /// [`sanitize_resource_name`]d on save. - pub high_poly: Vec<(String, Vec)>, + pub high_poly: Vec<(String, MeshBytes)>, /// Baking cage mesh file: (file name, bytes). - pub cage: Option<(String, Vec)>, + pub cage: Option<(String, MeshBytes)>, pub bake_paint: BTreeMap<(usize, BakePaintTarget), BakePaintData>, pub thumbnail: Option>, /// Imported resources (images used by fills, alphas, stencils), by name: original bytes. @@ -93,7 +95,7 @@ pub struct ProjectFile> { pub warnings: Vec, } -impl ProjectFile { +impl ProjectFile { /// Check that the mesh source and the rebuild setting agree with the saved layout. pub fn validate_mesh_uvs(&self) -> Result<()> { if self.project.mesh_rebuild_uvs != self.mesh_uvs.is_some() { @@ -132,11 +134,15 @@ pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Resul } #[cfg(not(target_arch = "wasm32"))] -fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> { +fn write_project_atomic( + path: &std::path::Path, + project_file: &ProjectFile>, impl Borrow>>, + progress: Option<&SaveProgress>, +) -> 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)?; + write_project(&mut file, project_file, progress)?; file.into_inner().map_err(|error| error.into_error())?.sync_all()?; std::fs::rename(&temporary_path, path)?; Ok(()) @@ -210,7 +216,7 @@ fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) } /// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. -fn entries(project_file: &ProjectFile>>) -> Result>> { +fn entries(project_file: &ProjectFile>, impl Borrow>>) -> Result>> { project_file.validate_mesh_uvs()?; let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); @@ -227,6 +233,7 @@ fn entries(project_file: &ProjectFile>>) -> Result>>) -> Result>>) -> Result(out: W, pf: &ProjectFile>>) -> Result<()> { +fn write_project(out: W, pf: &ProjectFile>, impl Borrow>>, progress: Option<&SaveProgress>) -> Result<()> { let mut zip = ZipWriter::new(out); - entries::write_entries(&mut zip, entries(pf)?)?; + let mut entries = entries(pf)?; + if let Some(progress) = progress { + progress.track(&mut entries); + } + entries::write_entries(&mut zip, entries)?; zip.finish().map_err(zip_err)?; Ok(()) } diff --git a/crates/formats/src/project_file/ram_reservation.rs b/crates/formats/src/project_file/ram_reservation.rs index 72857c15..b6a7e2d6 100644 --- a/crates/formats/src/project_file/ram_reservation.rs +++ b/crates/formats/src/project_file/ram_reservation.rs @@ -2,6 +2,8 @@ use std::borrow::Borrow; use std::io::Cursor; use std::sync::{Condvar, Mutex}; +#[cfg(not(target_arch = "wasm32"))] +use super::SaveProgress; use super::{ProjectFile, ram_operation::RamOperation, write_project}; use crate::{FormatError, Result}; @@ -54,17 +56,28 @@ impl RamReservation { Some(Self(RamOperation::Save)) } - pub fn save_bytes(&mut self, project_file: &ProjectFile>>) -> Result> { + pub fn save_bytes(&mut self, project_file: &ProjectFile>, impl Borrow>>) -> Result> { self.check_save()?; let mut out = Cursor::new(Vec::new()); - write_project(&mut out, project_file)?; + write_project(&mut out, project_file, None)?; Ok(out.into_inner()) } #[cfg(not(target_arch = "wasm32"))] - pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> { + pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile>, impl Borrow>>) -> Result<()> { self.check_save()?; - super::write_project_atomic(path, project_file) + super::write_project_atomic(path, project_file, None) + } + + #[cfg(not(target_arch = "wasm32"))] + pub fn save_with_progress( + &mut self, + path: &std::path::Path, + project_file: &ProjectFile>, impl Borrow>>, + progress: &SaveProgress, + ) -> Result<()> { + self.check_save()?; + super::write_project_atomic(path, project_file, Some(progress)) } fn check_save(&self) -> Result<()> { diff --git a/crates/formats/src/project_file/save_progress.rs b/crates/formats/src/project_file/save_progress.rs new file mode 100644 index 00000000..17ccb27f --- /dev/null +++ b/crates/formats/src/project_file/save_progress.rs @@ -0,0 +1,45 @@ +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::entries::Entry; + +mod progress_writer; + +use progress_writer::ProgressWriter; + +// Leave room on the indicator for syncing and replacing the archive +const MAX_PAYLOAD_PROGRESS: f32 = 0.95; + +/// Estimated archive progress, based on the payload processed by the entry writers. +/// Completing the archive, syncing it to disk, and replacing the destination can take longer. +#[derive(Default)] +pub struct SaveProgress { + total: AtomicU64, + processed: AtomicU64, +} + +impl SaveProgress { + pub fn fraction(&self) -> f32 { + let total = self.total.load(Ordering::Relaxed); + if total == 0 { + return 0.0; + } + + let processed = self.processed.load(Ordering::Relaxed).min(total); + MAX_PAYLOAD_PROGRESS * (processed as f64 / total as f64) as f32 + } + + pub(super) fn track<'a>(&'a self, entries: &mut [Entry<'a>]) { + self.processed.store(0, Ordering::Relaxed); + self.total.store(entries.iter().fold(0u64, |sum, entry| sum.saturating_add(entry.weight)), Ordering::Relaxed); + for entry in entries { + let body = std::mem::replace(&mut entry.body, Box::new(|_| Ok(()))); + let remaining = entry.weight; + entry.body = Box::new(move |target| { + let mut writer = ProgressWriter { target, progress: self, remaining, pending: 0 }; + body(&mut writer)?; + writer.report(); + Ok(()) + }); + } + } +} diff --git a/crates/formats/src/project_file/save_progress/progress_writer.rs b/crates/formats/src/project_file/save_progress/progress_writer.rs new file mode 100644 index 00000000..d3d75c01 --- /dev/null +++ b/crates/formats/src/project_file/save_progress/progress_writer.rs @@ -0,0 +1,37 @@ +use std::io::{self, Write}; +use std::sync::atomic::Ordering; + +use super::SaveProgress; + +// Batch updates to reduce contention between compression workers +const PROGRESS_UPDATE_BYTES: u64 = 64 * 1024; + +pub(super) struct ProgressWriter<'a> { + pub(super) target: &'a mut dyn Write, + pub(super) progress: &'a SaveProgress, + pub(super) remaining: u64, + pub(super) pending: u64, +} + +impl ProgressWriter<'_> { + pub(super) fn report(&mut self) { + self.progress.processed.fetch_add(std::mem::take(&mut self.pending), Ordering::Relaxed); + } +} + +impl Write for ProgressWriter<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let written = self.target.write(bytes)?; + let counted = (written as u64).min(self.remaining); + self.remaining -= counted; + self.pending += counted; + if self.pending >= PROGRESS_UPDATE_BYTES { + self.report(); + } + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + self.target.flush() + } +} diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 03d47845..395e6c5e 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -245,6 +245,27 @@ impl Mesh { self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } + /// Area-weighted smooth normals over welded positions, so UV and material seams do not split shading. + pub fn smooth_normals(&self) -> Vec { + let welded_vertices = crate::unwrap::weld_ids(&self.positions); + let mut normals = vec![Vec3::ZERO; self.positions.len()]; + for triangle in self.indices.as_chunks::<3>().0 { + let p = |i: u32| self.positions.get(i as usize).copied().unwrap_or_default(); + let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); + for v in triangle { + if let Some(accumulated) = welded_vertices.get(*v as usize).and_then(|welded| normals.get_mut(*welded as usize)) { + *accumulated += face; + } + } + } + welded_vertices.iter().map(|welded| normals.get(*welded as usize).and_then(|normal| normal.try_normalize()).unwrap_or(Vec3::Y)).collect() + } + + /// Replace normals with [`Mesh::smooth_normals`] on this mesh. + pub fn compute_smooth_normals(&mut self) { + self.normals = self.smooth_normals(); + } + /// The faces MikkTSpace sees: each importer quad (a fan pair marked in [`Mesh::diagonals`]) /// as one four-corner face, like Blender hands it over, and every other triangle as a /// triangle. Polygons with more than four corners stay fan triangles. The vertex and index @@ -315,8 +336,11 @@ impl Mesh { if self.uvs.len() != self.positions.len() { self.uvs = vec![Vec2::ZERO; self.positions.len()]; } - // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. - if crate::unwrap::all_triangles_degenerate(self) { + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. Its + // callbacks read a missing vertex as the origin, which the degenerate check cannot see, so + // an index past the last vertex skips it too. + let n = self.positions.len(); + if !self.indices.iter().all(|&i| (i as usize) < n) || crate::unwrap::all_triangles_degenerate(self) { self.simple_tangents(); } else { let faces = self.tangent_faces(); @@ -497,6 +521,9 @@ impl Mesh { /// A single-material mesh from raw attributes; computes missing normals and tangents. pub fn from_parts(positions: Vec, normals: Option>, uvs: Vec, indices: Vec, material: &str) -> Result { + if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) { + return Err(GeomError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len()))); + } let count = indices.len() as u32; let mut m = Mesh { normals: normals.unwrap_or_default(), @@ -910,4 +937,30 @@ mod tests { assert_eq!(m.uv_tiles(1).into_iter().collect::>(), vec![(1, 0)]); assert_eq!(m.uv_tiles(0).into_iter().collect::>(), vec![(0, 0)]); } + + /// An index past the last vertex reads as the origin in MikkTSpace's callbacks. With two + /// positions at the origin and one missing, the degenerate-mesh guard (which sees the missing + /// vertex as different) let it through while MikkTSpace saw every triangle as degenerate and + /// underflowed: a panic in debug builds, an out-of-bounds walk in release. + #[test] + fn from_parts_refuses_an_out_of_range_index_without_crashing() { + let positions = vec![Vec3::ZERO, Vec3::X]; + let uvs = vec![Vec2::ZERO, Vec2::X]; + let e = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2], "M").unwrap_err(); + assert!(e.to_string().contains("out of range"), "{e}"); + } + + #[test] + fn tangents_of_a_mesh_with_an_out_of_range_index_fall_back_without_crashing() { + for indices in [vec![0, 1, 2], vec![0, 0, 2], vec![0, 1, 5, 0, 1, 1]] { + let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::ZERO, Vec2::X, Vec2::Y], vec![0, 1, 2], "M").unwrap(); + m.positions.truncate(2); + m.normals.truncate(2); + m.uvs.truncate(2); + m.indices = indices; + m.compute_tangents(); + assert_eq!(m.tangents.len(), 2); + assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents); + } + } } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index c9f0692f..1e045f28 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -30,3 +30,4 @@ wasm-bindgen-futures = "0.4" [dev-dependencies] image = { workspace = true } +texturecraft-formats = { workspace = true } diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index f478f77a..0a8a357c 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -18,6 +18,10 @@ use texturecraft_geom::glam::Vec3; use crate::gpu_trace::{STACK, buffer, bvh_depth, bvh_rows, entry, scoped, storage}; const WORKGROUP: u32 = 64; +// The shader binds BVH nodes, triangles, input queries and results +const RAY_STORAGE_BUFFERS: u32 = 4; +// The hemisphere reduction stores one vec4 and one count per lane +const WORKGROUP_STORAGE_BYTES: u32 = WORKGROUP * (size_of::<[f32; 4]>() + size_of::()) as u32; /// Rays per dispatch: short dispatches keep slow GPUs clear of driver watchdogs. const RAYS_PER_DISPATCH: usize = 1 << 24; const NONE: u32 = u32::MAX; @@ -66,23 +70,11 @@ fn err(e: impl std::fmt::Display) -> BakeError { impl Gpu { fn new() -> Result { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); - let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; - let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?; - let info = adapter.get_info(); - if info.device_type == wgpu::DeviceType::Cpu { - return Err(format!("{} is a software renderer", info.name)); - } - let limits = adapter.limits(); - if limits.max_storage_buffers_per_shader_stage < 3 - || limits.max_compute_invocations_per_workgroup < WORKGROUP - || limits.max_compute_workgroup_size_x < WORKGROUP - { - return Err(format!("{} has no usable compute shaders", info.name)); - } + let (adapter, name, limits) = bake_adapter()?; let desc = wgpu::DeviceDescriptor { label: Some("tc_bake"), required_limits: limits, ..Default::default() }; let (device, queue) = pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device: {e}"))?; - // Errors are caught by the scopes around every call; never let wgpu's default handler panic. + + // Each GPU call has an error scope so the default handler should leave failures to those scopes device.on_uncaptured_error(Arc::new(|_| {})); let (layout, transfer, hemisphere) = scoped(&device, "GPU baking: pipelines", || { let params = wgpu::BindingType::Buffer { @@ -112,7 +104,7 @@ impl Gpu { (layout, pipe("transfer_main"), pipe("hemisphere_main")) })?; let stride = size_of::().next_multiple_of(device.limits().min_uniform_buffer_offset_alignment.max(1) as usize); - Ok(Gpu { device, queue, name: info.name, layout, transfer, hemisphere, stride }) + Ok(Gpu { device, queue, name, layout, transfer, hemisphere, stride }) } /// The largest storage buffer this device binds. @@ -122,6 +114,43 @@ impl Gpu { } } +/// Whether the adapter selected for mesh-map baking supports its compute shaders. +pub fn raytracing_available() -> bool { + static SUPPORTED: OnceLock = OnceLock::new(); + *SUPPORTED.get_or_init(|| bake_adapter().is_ok()) +} + +fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; + let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?; + let info = adapter.get_info(); + let limits = adapter.limits(); + let flags = adapter.get_downlevel_capabilities().flags; + if let Some(reason) = unsupported_adapter(info.device_type, flags, &limits) { + return Err(format!("{} {reason}", info.name)); + } + + Ok((adapter, info.name, limits)) +} + +fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> { + if device_type == wgpu::DeviceType::Cpu { + return Some("is a software renderer"); + } + + if !flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) + || limits.max_storage_buffers_per_shader_stage < RAY_STORAGE_BUFFERS + || limits.max_compute_invocations_per_workgroup < WORKGROUP + || limits.max_compute_workgroup_size_x < WORKGROUP + || limits.max_compute_workgroup_storage_size < WORKGROUP_STORAGE_BYTES + { + return Some("has no usable compute shaders"); + } + + None +} + /// The GPU [`Tracer`]. Its device is created on the first bake; without a hardware adapter /// every bake reports [`BakeError::Tracer`] (and runs on the CPU). #[derive(Default)] @@ -383,6 +412,22 @@ mod tests { use super::*; + #[test] + fn raytracing_requires_hardware_and_compute_support() { + let limits = wgpu::Limits::default(); + let compute = wgpu::DownlevelFlags::COMPUTE_SHADERS; + let no_compute = wgpu::Limits { max_compute_workgroup_size_x: 0, ..limits.clone() }; + let three_buffers = wgpu::Limits { max_storage_buffers_per_shader_stage: 3, ..limits.clone() }; + let no_shared_memory = wgpu::Limits { max_compute_workgroup_storage_size: 0, ..limits.clone() }; + + assert!(unsupported_adapter(wgpu::DeviceType::DiscreteGpu, compute, &limits).is_none()); + assert!(unsupported_adapter(wgpu::DeviceType::Cpu, compute, &limits).is_some()); + assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, wgpu::DownlevelFlags::empty(), &limits).is_some()); + assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &no_compute).is_some()); + assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &three_buffers).is_some(), "the bind group requires four storage buffers"); + assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &no_shared_memory).is_some()); + } + /// The GPU baker, or None (test skipped) without a hardware adapter. fn gpu() -> Option { let g = GpuBaker::new(); diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 5b04af34..5d092a0f 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -97,6 +97,7 @@ struct SceneConst { env_camera: bool, heights: Vec, ior: f32, + dielectric_f0_scale: f32, /// Focus depth (0: the orbit target) and lens radius in world units (0: pinhole). lens: [f32; 2], } @@ -348,8 +349,8 @@ impl GpuTracer { }; let same_geometry = self.geometry.as_ref().is_some_and(|g| Arc::ptr_eq(&g.mesh, &scene.mesh) && g.tri_set == scene.tri_set); if !same_geometry { - let nodes: Vec<(Vec3, Vec3, u32, u32)> = scene.bvh.nodes().collect(); - if bvh_depth(&nodes).is_none_or(|d| d >= STACK) { + let depth = bvh_depth(&scene.bvh.nodes().collect::>()); + if depth.is_none_or(|depth| depth >= STACK) { return Err("the mesh's BVH is too deep for GPU traversal".into()); } @@ -367,24 +368,23 @@ impl GpuTracer { })?); self.bind = None; } + if !self.env.as_ref().is_some_and(|e| Arc::ptr_eq(&e.image, &scene.env)) { let img = &scene.env; let (w, h) = (img.width as usize, img.height as usize); - let valid = w > 0 && h > 0 && img.data.len() >= w * h && img.width.max(img.height) <= limits.max_texture_dimension_2d; - let (tw, th, rgba): (u32, u32, Vec<[f32; 4]>) = - if valid { (img.width, img.height, img.data.iter().take(w * h).map(|c| [c[0], c[1], c[2], 1.0]).collect()) } else { (1, 1, vec![[0.0; 4]]) }; - let mut cdf = Vec::new(); - if let Some(l) = scene.light.as_ref().filter(|l| valid && l.width == w && l.height == h) { - cdf.extend_from_slice(&l.rows); - cdf.extend_from_slice(&l.cols); - cdf.extend_from_slice(&l.prob); - } - fits("environment table", cdf.len() * 4)?; - let light = !cdf.is_empty(); - if !light { - cdf.push(0.0); - } + let valid = w > 0 && h > 0 && img.width.max(img.height) <= limits.max_texture_dimension_2d && img.data.len() >= w * h; + let sampler = scene.light.as_ref().filter(|table| valid && table.width == w && table.height == h); + + // The shader binds one zero when importance sampling is disabled + let parts = sampler.map_or([&[0.0][..], &[], &[]], |table| [table.rows.as_slice(), table.cols.as_slice(), table.prob.as_slice()]); + fits("environment table", parts.iter().map(|part| std::mem::size_of_val(*part)).sum())?; + let env = scoped(device, "GPU path tracing: environment upload", || { + let (tw, th, rgba): (u32, u32, Vec<[f32; 4]>) = if valid { + (img.width, img.height, img.data.iter().take(w * h).map(|c| [c[0], c[1], c[2], 1.0]).collect()) + } else { + (1, 1, vec![[0.0; 4]]) + }; let tex = device.create_texture_with_data( queue, &wgpu::TextureDescriptor { @@ -400,16 +400,19 @@ impl GpuTracer { wgpu::util::TextureDataOrder::LayerMajor, bytemuck::cast_slice(&rgba), ); + drop(rgba); + EnvGpu { image: scene.env.clone(), view: tex.create_view(&Default::default()), - cdf: buffer(device, "tc_trace_cdf", bytemuck::cast_slice(&cdf)), - light, + cdf: buffer(device, "tc_trace_cdf", bytemuck::cast_slice(&parts.concat())), + light: sampler.is_some(), } })?; self.env = Some(env); self.bind = None; } + self.scene = Some(SceneConst { spec_gloss: scene.spec_gloss, eps: scene.eps, @@ -418,6 +421,7 @@ impl GpuTracer { env_camera: scene.env_camera, heights: scene.sets.iter().map(|s| s.height_strength).collect(), ior: scene.ior, + dielectric_f0_scale: scene.dielectric_f0_scale, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), }); Ok(()) @@ -609,7 +613,7 @@ impl GpuTracer { env: [sin, cos, 0.0, 0.0], sigma: sc.sigma.extend(0.0).to_array(), eye: cam.eye().extend(1.0).to_array(), - lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, 0.0], + lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, sc.dielectric_f0_scale], }; let mut sets = [[0.0f32; 4]; 256]; for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() { @@ -1017,6 +1021,33 @@ mod tests { assert_region_means_match("varying roughness, default base color", &gpu, &cpu.rgba8(&d), 48, 36, 3.0); } + #[test] + fn gpu_matches_cpu_with_ior_specular_reflectance() { + use Channel::*; + let Some((mut h, mut t)) = gpu() else { return }; + + // A dark, glossy dielectric shows mostly its F0 + let values = [(BaseColor, [0.02; 3]), (Metallic, [0.0; 3]), (Roughness, [0.15; 3]), (SpecularLevel, [1.0; 3])]; + let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false, background: crate::DEFAULT_BACKGROUND }; + let settings = TraceSettings { bounces: 4 }; + let mut sphere_brightness = Vec::new(); + + for ior_specular in [false, true] { + let display = texturecraft_core::DisplaySettings { ior: 1.8, ior_specular, ..Default::default() }; + let mut scene = sphere_scene(&mut h, crate::ibl::environment("Studio Contrast", 256), &values); + (scene.ior, scene.dielectric_f0_scale) = (display.ior, display.dielectric_f0_scale()); + let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); + let mut cpu = Tracer::new(48, 36); + for _ in 0..1024 { + cpu.pass(&scene, &camera(), &settings); + } + assert_region_means_match(&format!("IOR specular {ior_specular}"), &gpu, &cpu.rgba8(&d), 48, 36, 3.0); + sphere_brightness.push(gpu.as_chunks::<4>().0.iter().map(|pixel| pixel[..3].iter().map(|v| u32::from(*v)).sum::()).sum::()); + } + + assert!(sphere_brightness[1] > sphere_brightness[0], "IOR 1.8 reflects more than the legacy F0: {sphere_brightness:?}"); + } + /// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels. fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) { let lum = |img: &[u8], x: usize, y: usize| { diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 0fd677bf..64b44d9a 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -25,6 +25,7 @@ use std::collections::HashMap; use bytemuck::{Pod, Zeroable}; use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_core::project::LEGACY_DIELECTRIC_F0_SCALE; use texturecraft_core::{Channel, DisplaySettings, EnvAlignment, Project, ToneMapping}; use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; @@ -212,6 +213,8 @@ pub struct Shade { pub scatter: [f32; 3], /// Index of refraction of the Transmission channel. pub ior: f32, + /// Multiplier for Specular Level when shading a dielectric in Metallic/Roughness. + pub dielectric_f0_scale: f32, /// Depth of field (3D material view): focus depth along the view axis (0: the orbit /// target) and lens radius as a fraction of the mesh's bounding radius. pub dof: Option<[f32; 2]>, @@ -264,6 +267,7 @@ impl Shade { taa: d.taa, scatter: scatter_wrap(d), ior: d.ior, + dielectric_f0_scale: d.dielectric_f0_scale(), dof: d.dof.enabled.then_some([d.dof.focus_distance, d.dof.aperture]), displacement: d.displacement, solo_lit: !d.solo_unlit, @@ -320,6 +324,7 @@ impl Default for Shade { taa: false, scatter: scatter_wrap(&DisplaySettings::default()), ior: 1.5, + dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE, dof: None, sss_blur: None, refraction: false, @@ -2131,7 +2136,7 @@ impl Renderer { 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], + refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, s.dielectric_f0_scale], highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data), highlight_shift: highlight_shift(frame.size), set_hover: highlight_globals(s.set_hover, SET_HOVER_OPACITY, s, data), diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 8e82daa9..490ed2d5 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -23,7 +23,7 @@ struct Globals { scatter: vec4, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1) 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 - + refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w dielectric F0 scale 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 - set_hover: vec4, // rgb hovered set's scene color, a opacity @@ -430,6 +430,9 @@ const UV_CHECKER_FINE_CELLS: f32 = 256.0; // Offset alpha dithering between accumulated frames const DITHER_FRAME_STEP: vec2 = vec2(17.0, 59.0); +// Lit single-channel views keep the legacy specular level multiplier +const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; + fn shade_mesh(i: VOut, front: bool) -> Shaded { var n_geo = normalize(i.nrm); if (!front) { @@ -548,7 +551,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let rough = clamp(orm.g, SPECULAR_ROUGHNESS_FLOOR, 1.0); let metal = orm.b; let nov = clamp(abs(dot(n, v)), GRAZING_COSINE_FLOOR, 1.0); - var f0 = mix(vec3(0.08 * orm.a), albedo, metal); + let dielectric_f0_scale = select(g.refr.w, LEGACY_DIELECTRIC_F0_SCALE, solo_lit); + var f0 = mix(vec3(dielectric_f0_scale * orm.a), albedo, metal); var diffuse_col = albedo * (1.0 - metal); if (g.material.x > 0.5 && !solo_lit) { // Specular color gives F0 (a solo-lit channel view keeps its neutral material); remove its energy from diffuse diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index 5f6258e0..b4a4bba2 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -17,7 +17,7 @@ struct Params { env: vec4, // sin and cos of the environment rotation sigma: vec4, // subsurface extinction per color channel eye: vec4, // camera position - lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR + lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR, dielectric F0 scale // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds, height strength. sets: array, MAX_SETS>, }; @@ -332,7 +332,7 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { metallic = clamp(orm.b, 0.0, 1.0); let level = clamp(orm.a, 0.0, 1.0); diffuse = base * (1.0 - metallic); - f0 = mix(vec3(0.08 * level), base, metallic); + f0 = mix(vec3(P.lens.w * level), base, metallic); } // The coat normal packs x and y around 128 so flat stays exact diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 034330b0..a3f2780c 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -23,7 +23,7 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_compose::{Composite, ImageRes}; use texturecraft_core::Channel; -use texturecraft_core::project::{DisplaySettings, EnvAlignment, ToneMapping}; +use texturecraft_core::project::{DisplaySettings, EnvAlignment, LEGACY_DIELECTRIC_F0_SCALE, ToneMapping}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera}; @@ -63,6 +63,8 @@ pub struct TraceScene { pub(crate) radius: f32, /// Index of refraction of the Transmission channel. pub ior: f32, + /// Multiplier for Specular Level in the Metallic/Roughness model. + pub(crate) dielectric_f0_scale: f32, /// Thin lens: focus depth along the view axis (0: the camera's orbit target) and lens radius /// as a fraction of the mesh's bounding radius (the viewport's depth of field). pub lens: Option<[f32; 2]>, @@ -103,6 +105,7 @@ impl TraceScene { scatter_sigma: Vec3::ONE, radius, ior: 1.5, + dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE, lens: None, }; let d = DisplaySettings::default(); @@ -137,6 +140,7 @@ impl TraceScene { scene.spec_gloss = display.spec_gloss; scene.set_scatter(display.scatter_color, display.scatter_radius); scene.ior = display.ior; + scene.dielectric_f0_scale = display.dielectric_f0_scale(); scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]); scene @@ -201,16 +205,22 @@ impl EnvSampler { if w == 0 || h == 0 || env.data.len() < w * h { return None; } - let mut weight: Vec = env.data.iter().take(w * h).map(|c| luminance(Vec3::from(*c)).max(0.0)).collect(); - for (y, row) in weight.chunks_mut(w).enumerate() { + + let mut prob: Vec = env.data.iter().take(w * h).map(|c| luminance(Vec3::from(*c)).max(0.0)).collect(); + for (y, row) in prob.chunks_mut(w).enumerate() { let sin = (PI * (y as f32 + 0.5) / h as f32).sin(); row.iter_mut().for_each(|v| *v = (*v + 1e-4) * sin); } - let total: f32 = weight.iter().sum(); + + let total: f32 = prob.iter().sum(); if !total.is_finite() || total <= 0.0 { return None; } - let prob: Vec = weight.iter().map(|v| v / total).collect(); + + for probability in &mut prob { + *probability /= total; + } + let mut rows = Vec::with_capacity(h); let mut cols = Vec::with_capacity(w * h); let mut acc_rows = 0.0; @@ -224,6 +234,7 @@ impl EnvSampler { cols.push(acc); } } + Some(EnvSampler { width: w, height: h, rows, cols, prob }) } @@ -539,100 +550,115 @@ fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) - u * t.z).normalize_or(Vec3::Z) } -fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f32) -> Option { - let m = &scene.mesh; - let i = tri as usize * 3; - let idx = [*m.indices.get(i)? as usize, *m.indices.get(i + 1)? as usize, *m.indices.get(i + 2)? as usize]; - let p = idx.map(|k| m.positions.get(k).copied().unwrap_or(Vec3::ZERO)); - let mut geo = (p[1] - p[0]).cross(p[2] - p[0]).normalize_or(Vec3::Y); - let nrm = idx.map(|k| m.normals.get(k).copied().unwrap_or(geo)); - let mut n_geo = lerp3(nrm[0], nrm[1], nrm[2], u, v).normalize_or(geo); - let front = geo.dot(d) <= 0.0; +fn surface(scene: &TraceScene, triangle: u32, u: f32, v: f32, origin: Vec3, direction: Vec3, distance: f32) -> Option { + // Match the minimum roughness in the GPU tracer + const SPECULAR_ROUGHNESS_FLOOR: f32 = 0.045; + const SHEEN_ROUGHNESS_FLOOR: f32 = 0.07; + const HEIGHT_SLOPE_UV_DIVISOR: f32 = 16.0; + + let mesh = &scene.mesh; + let first_index = triangle as usize * 3; + let indices = [*mesh.indices.get(first_index)? as usize, *mesh.indices.get(first_index + 1)? as usize, *mesh.indices.get(first_index + 2)? as usize]; + let points = indices.map(|index| mesh.positions.get(index).copied().unwrap_or(Vec3::ZERO)); + let mut geo = (points[1] - points[0]).cross(points[2] - points[0]).normalize_or(Vec3::Y); + let normals = indices.map(|index| mesh.normals.get(index).copied().unwrap_or(geo)); + let mut interpolated_normal = lerp3(normals[0], normals[1], normals[2], u, v).normalize_or(geo); + + let front = geo.dot(direction) <= 0.0; if !front { geo = -geo; } - if n_geo.dot(geo) < 0.0 { - n_geo = -n_geo; + if interpolated_normal.dot(geo) < 0.0 { + interpolated_normal = -interpolated_normal; } - let uvs = idx.map(|k| m.uvs.get(k).copied().unwrap_or(Vec2::ZERO)); - let uv = uvs[0] * (1.0 - u - v) + uvs[1] * u + uvs[2] * v; - let tan = idx.map(|k| m.tangents.get(k).copied().unwrap_or(texturecraft_geom::glam::Vec4::X)); - let tw = lerp3(tan[0].truncate(), tan[1].truncate(), tan[2].truncate(), u, v); - let sign = if tan[0].w < 0.0 { -1.0 } else { 1.0 }; - let set = scene.tri_set.get(tri as usize).and_then(|s| scene.sets.get(*s)); - // The composite texel at offset (dx, dy) from the hit. - let texel = |s: &TraceSet, dx: i32, dy: i32| { - let (w, h) = (s.composite.resolution.max(1) as i32, s.composite.height.max(1) as i32); - (((uv.x * w as f32).floor() as i32 + dx).rem_euclid(w) as u32, ((uv.y * h as f32).floor() as i32 + dy).rem_euclid(h) as u32) - }; - let ch = |c: Channel, dx: i32, dy: i32| -> [f32; 3] { - let Some(s) = set else { return c.default_value() }; - let (x, y) = texel(s, dx, dy); - s.composite.value(c, x, y) - }; - let base = Vec3::from(ch(Channel::BaseColor, 0, 0)); - // A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink. - let k = set.map_or(0.0, |s| { - let (x, y) = texel(s, 0, 0); - s.height_strength * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) + let uvs = indices.map(|index| mesh.uvs.get(index).copied().unwrap_or(Vec2::ZERO)); + let uv = uvs[0] * (1.0 - u - v) + uvs[1] * u + uvs[2] * v; + let tangents = indices.map(|index| mesh.tangents.get(index).copied().unwrap_or(texturecraft_geom::glam::Vec4::X)); + let mesh_tangent = lerp3(tangents[0].truncate(), tangents[1].truncate(), tangents[2].truncate(), u, v); + let sign = if tangents[0].w < 0.0 { -1.0 } else { 1.0 }; + + let surface_texel = scene.tri_set.get(triangle as usize).and_then(|index| scene.sets.get(*index)).map(|set| { + let width = set.composite.resolution.max(1); + let height = set.composite.height.max(1); + let x = ((uv.x * width as f32).floor() as i32).rem_euclid(width as i32) as u32; + let y = ((uv.y * height as f32).floor() as i32).rem_euclid(height as i32) as u32; + (set, [width, height], [x, y]) }); - let n_height = if k != 0.0 { - let h = |dx, dy| ch(Channel::Height, dx, dy)[0]; - Vec3::new(-(h(1, 0) - h(-1, 0)) * 0.5 * k, (h(0, 1) - h(0, -1)) * 0.5 * k, 1.0).normalize_or(Vec3::Z) - } else { - Vec3::Z - }; - let detail = (Vec3::from(ch(Channel::Normal, 0, 0)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); - let n_ts = rnm(n_height, detail); - let tt = (tw - n_geo * n_geo.dot(tw)).normalize_or(n_geo.any_orthonormal_vector()); - let b = n_geo.cross(tt) * sign; - let mut n = (tt * n_ts.x + b * n_ts.y + n_geo * n_ts.z).normalize_or(n_geo); - if n.dot(-d) <= 0.0 { - n = n_geo; + let sample_channel = |channel: Channel| surface_texel.map_or_else(|| channel.default_value(), |(set, _, [x, y])| set.composite.value(channel, x, y)); + let base = Vec3::from(sample_channel(Channel::BaseColor)); + + // A unit height across one sixteenth of the UV width tilts 45° + // A smaller tile reduces the number of texels across that span + let height_normal = surface_texel.map_or(Vec3::Z, |(set, [width, height], [x, y])| { + let strength = set.height_strength * set.composite.resolution as f32 / HEIGHT_SLOPE_UV_DIVISOR * set.composite.block_scales.at(x, y); + if strength == 0.0 { + return Vec3::Z; + } + + // Neighbors wrap independently across each axis + let previous = |position, size| if position == 0 { size - 1 } else { position - 1 }; + let next = |position, size| if position + 1 == size { 0 } else { position + 1 }; + let height_at = |x, y| set.composite.value(Channel::Height, x, y)[0]; + let slope_x = height_at(next(x, width), y) - height_at(previous(x, width), y); + let slope_y = height_at(x, next(y, height)) - height_at(x, previous(y, height)); + Vec3::new(-slope_x * 0.5 * strength, slope_y * 0.5 * strength, 1.0).normalize_or(Vec3::Z) + }); + + let detail = (Vec3::from(sample_channel(Channel::Normal)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); + let tangent_normal = rnm(height_normal, detail); + let base_tangent = (mesh_tangent - interpolated_normal * interpolated_normal.dot(mesh_tangent)).normalize_or(interpolated_normal.any_orthonormal_vector()); + let bitangent = interpolated_normal.cross(base_tangent) * sign; + let mut normal = + (base_tangent * tangent_normal.x + bitangent * tangent_normal.y + interpolated_normal * tangent_normal.z).normalize_or(interpolated_normal); + if normal.dot(-direction) <= 0.0 { + normal = interpolated_normal; } - let scalar = |c: Channel| ch(c, 0, 0)[0].clamp(0.0, 1.0); + + let scalar = |channel| sample_channel(channel)[0].clamp(0.0, 1.0); let (sin, cos) = (scalar(Channel::AnisotropyAngle) * PI).sin_cos(); - let turned = tt * cos + b * sin; - let tangent = (turned - n * n.dot(turned)).normalize_or(n.any_orthonormal_vector()); - // Glossiness replaces roughness wherever a set has it (as in the viewport). - let roughness = match set { - Some(s) if s.composite.channels.contains_key(&Channel::Glossiness) => 1.0 - ch(Channel::Glossiness, 0, 0)[0], - _ => ch(Channel::Roughness, 0, 0)[0], + let turned_tangent = base_tangent * cos + bitangent * sin; + let tangent = (turned_tangent - normal * normal.dot(turned_tangent)).normalize_or(normal.any_orthonormal_vector()); + + // Match the viewport's preference for Glossiness when both channels exist + let roughness = match surface_texel { + Some((set, _, _)) if set.composite.channels.contains_key(&Channel::Glossiness) => 1.0 - sample_channel(Channel::Glossiness)[0], + _ => sample_channel(Channel::Roughness)[0], }; let (diffuse, f0, metallic) = if scene.spec_gloss { - let f0 = Vec3::from(ch(Channel::Specular, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE); + let f0 = Vec3::from(sample_channel(Channel::Specular)).clamp(Vec3::ZERO, Vec3::ONE); (base * (1.0 - f0.max_element()), f0, 0.0) } else { - let metallic = ch(Channel::Metallic, 0, 0)[0].clamp(0.0, 1.0); - let level = ch(Channel::SpecularLevel, 0, 0)[0].clamp(0.0, 1.0); - (base * (1.0 - metallic), Vec3::splat(0.08 * level).lerp(base, metallic), metallic) + let metallic = sample_channel(Channel::Metallic)[0].clamp(0.0, 1.0); + let level = sample_channel(Channel::SpecularLevel)[0].clamp(0.0, 1.0); + (base * (1.0 - metallic), Vec3::splat(scene.dielectric_f0_scale * level).lerp(base, metallic), metallic) }; - let coat_base = if n_geo.dot(-d) > 0.0 { n_geo } else { geo }; - let coat_n = match set { - Some(s) if s.composite.channels.contains_key(&Channel::CoatNormal) => { - let c = (Vec3::from(ch(Channel::CoatNormal, 0, 0)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); - let turned = (tt * c.x + b * c.y + coat_base * c.z).normalize_or(coat_base); - if turned.dot(-d) > 0.0 { turned } else { coat_base } + let coat_base = if interpolated_normal.dot(-direction) > 0.0 { interpolated_normal } else { geo }; + let coat_n = match surface_texel { + Some((set, _, _)) if set.composite.channels.contains_key(&Channel::CoatNormal) => { + let detail = (Vec3::from(sample_channel(Channel::CoatNormal)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); + let tilted = (base_tangent * detail.x + bitangent * detail.y + coat_base * detail.z).normalize_or(coat_base); + if tilted.dot(-direction) > 0.0 { tilted } else { coat_base } } _ => coat_base, }; + Some(Surface { - pos: o + d * t, + pos: origin + direction * distance, geo, - n, + n: normal, tangent, diffuse, f0, - roughness: roughness.clamp(0.045, 1.0), - emissive: Vec3::from(ch(Channel::Emissive, 0, 0)), - opacity: ch(Channel::Opacity, 0, 0)[0].clamp(0.0, 1.0), + roughness: roughness.clamp(SPECULAR_ROUGHNESS_FLOOR, 1.0), + emissive: Vec3::from(sample_channel(Channel::Emissive)), + opacity: sample_channel(Channel::Opacity)[0].clamp(0.0, 1.0), anisotropy: scalar(Channel::AnisotropyLevel), coat: scalar(Channel::CoatWeight), - coat_roughness: scalar(Channel::CoatRoughness).max(0.045), + coat_roughness: scalar(Channel::CoatRoughness).max(SPECULAR_ROUGHNESS_FLOOR), coat_n, - sheen: Vec3::from(ch(Channel::SheenColor, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE) * scalar(Channel::SheenWeight), - sheen_roughness: scalar(Channel::SheenRoughness).max(0.07), + sheen: Vec3::from(sample_channel(Channel::SheenColor)).clamp(Vec3::ZERO, Vec3::ONE) * scalar(Channel::SheenWeight), + sheen_roughness: scalar(Channel::SheenRoughness).max(SHEEN_ROUGHNESS_FLOOR), scatter: scalar(Channel::ScatterWeight), transmission: scalar(Channel::Transmission) * (1.0 - metallic), base: base.clamp(Vec3::ZERO, Vec3::ONE), @@ -1412,4 +1438,134 @@ mod tests { assert!(blurred > 3 * pinhole.max(10), "out of focus: {pinhole} -> {blurred} edge pixels"); assert!(focused < pinhole + pinhole / 2 + 10, "the silhouette (about the focus depth) stays sharp: {pinhole} -> {focused}"); } + + /// Specular Level 0.5 stands for OpenPBR's default specular weight of 1 + const OPENPBR_DEFAULT_SPECULAR_LEVEL: f32 = 0.5; + /// A non-default IOR for the opt-in comparisons + const DENSE_IOR: f32 = 1.8; + /// The 32-bit export and the shading read the same 16-bit texel: only float rounding separates them + const F0_TOLERANCE: f32 = 1e-5; + + /// One texture set holding a uniform dielectric with both shader models' channels. + fn dielectric_composite() -> Composite { + use Channel::*; + let values = [ + (BaseColor, [0.1; 3]), + (Metallic, [0.0; 3]), + (Roughness, [0.3; 3]), + (SpecularLevel, [OPENPBR_DEFAULT_SPECULAR_LEVEL; 3]), + (Specular, [0.3, 0.2, 0.1]), + (Glossiness, [0.7; 3]), + ]; + let channels: Vec = values.iter().map(|(channel, _)| *channel).collect(); + let mut composite = Composite::new(&channels, 8); + for (channel, value) in values { + let raw: Vec = value[..channel.components()].iter().map(|v| texturecraft_texel::to_u16(*v)).collect(); + let image = composite.channels.get_mut(&channel).unwrap(); + for y in 0..8 { + for x in 0..8 { + image.set(x, y, &raw); + } + } + } + composite + } + + /// A sphere covered by [`dielectric_composite`] under `display`. + fn dielectric_scene(display: &DisplaySettings) -> TraceScene { + let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); + let bvh = Arc::new(Bvh::new(&mesh)); + let sets = vec![TraceSet { material: 0, composite: dielectric_composite(), height_strength: 0.0 }]; + TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(crate::ibl::environment("Studio Soft", 32))) + } + + /// The F0 the CPU tracer shades the sphere's front with. + fn shaded_f0(display: &DisplaySettings) -> Vec3 { + let scene = dielectric_scene(display); + let (origin, direction) = (Vec3::new(0.0, 0.0, 4.0), Vec3::NEG_Z); + let hit = scene.bvh.closest(origin, direction, f32::MAX).unwrap(); + surface(&scene, hit.tri, hit.u, hit.v, origin, direction, hit.t).unwrap().f0 + } + + #[test] + fn height_normals_sample_across_both_texture_edges() { + let mut mesh = primitives::plane(1.0, 1); + mesh.uvs.fill(Vec2::ZERO); + let mesh = Arc::new(mesh); + let bvh = Arc::new(Bvh::new(&mesh)); + let mut composite = Composite::with_size(&[Channel::Height], 4, 5); + let height = composite.channels.get_mut(&Channel::Height).unwrap(); + height.set(3, 0, &[u16::MAX]); + height.set(0, 4, &[u16::MAX]); + let sets = vec![TraceSet { material: 0, composite, height_strength: 1.0 }]; + let scene = TraceScene::new(mesh, bvh, sets, Arc::new(crate::ibl::environment("Studio Soft", 8)), 0.0); + + let normal = surface(&scene, 0, 0.25, 0.25, Vec3::Y, Vec3::NEG_Y, 1.0).unwrap().n; + + assert!(normal.x.abs() > f32::EPSILON && normal.z.abs() > f32::EPSILON, "the opposite edges tilt both axes: {normal}"); + } + + /// The F0 map a 32-bit float export writes for [`dielectric_composite`] under `display`. + fn exported_f0(display: &DisplaySettings) -> f32 { + use texturecraft_formats::{Dest, ExportInput, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap}; + + let composite = dielectric_composite(); + let mut project = texturecraft_core::Project::new("F0", "builtin:sphere"); + let mut set = texturecraft_core::TextureSet::new("Set", 0, composite.resolution); + set.channels = composite.channels.keys().map(|channel| (*channel, texturecraft_core::ChannelFormat::default_for(*channel))).collect(); + project.texture_sets.push(set); + project.display = display.clone(); + let coverage = vec![true; (composite.resolution * composite.resolution) as usize]; + let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &Default::default(), coverage: &coverage, mesh_name: "sphere" }; + let f0 = |component| SourceRef::Virtual { map: VirtualMap::F0, component }; + let channels = vec![(Dest::R, f0(0)), (Dest::G, f0(1)), (Dest::B, f0(2))]; + let map = MapSpec { file: "f0".into(), format: FileFormat::Exr, bit_depth: 32, channels, inverted: Vec::new() }; + let options = ExportOptions::new(ExportPreset { name: "F0".into(), maps: vec![map] }); + + let files = texturecraft_formats::render_maps(&input, &options).unwrap(); + + let image = image::load_from_memory_with_format(&files[0].bytes, image::ImageFormat::OpenExr).unwrap().to_rgb32f(); + image.get_pixel(4, 4)[0] + } + + fn ior_display(ior: f32, ior_specular: bool, spec_gloss: bool) -> DisplaySettings { + DisplaySettings { ior, ior_specular, spec_gloss, ..DisplaySettings::default() } + } + + #[test] + fn exported_f0_matches_the_metallic_roughness_shading_in_both_modes() { + let (legacy, opt_in) = (ior_display(DENSE_IOR, false, false), ior_display(DENSE_IOR, true, false)); + + // OpenPBR: at specular weight 1 the dielectric F0 is the Fresnel reflectance of the IOR + let fresnel = ((DENSE_IOR - 1.0) / (DENSE_IOR + 1.0)).powi(2); + + let (legacy_shaded, legacy_exported) = (shaded_f0(&legacy), exported_f0(&legacy)); + let (opt_in_shaded, opt_in_exported) = (shaded_f0(&opt_in), exported_f0(&opt_in)); + let default_ior_shaded = shaded_f0(&ior_display(1.5, true, false)); + + for (mode, shaded, exported) in [("legacy", legacy_shaded, legacy_exported), ("IOR", opt_in_shaded, opt_in_exported)] { + assert!(shaded.abs_diff_eq(Vec3::splat(exported), F0_TOLERANCE), "{mode}: shaded {shaded}, exported {exported}"); + } + assert!((legacy_exported - LEGACY_DIELECTRIC_F0_SCALE * OPENPBR_DEFAULT_SPECULAR_LEVEL).abs() < F0_TOLERANCE, "legacy {legacy_exported}"); + assert!((opt_in_exported - fresnel).abs() < F0_TOLERANCE, "IOR {DENSE_IOR}: {opt_in_exported}, Fresnel {fresnel}"); + assert!(opt_in_exported > legacy_exported, "IOR {DENSE_IOR} reflects more than the legacy 1.5 equivalent"); + assert!(default_ior_shaded.abs_diff_eq(legacy_shaded, F0_TOLERANCE), "IOR 1.5 keeps the legacy reflectance: {default_ior_shaded}"); + } + + #[test] + fn specular_glossiness_shading_ignores_the_ior_specular_setting() { + let (off, on) = (ior_display(DENSE_IOR, false, true), ior_display(DENSE_IOR, true, true)); + let render = |display: &DisplaySettings| { + let (scene, mut tracer) = (dielectric_scene(display), Tracer::new(24, 16)); + for _ in 0..2 { + tracer.pass(&scene, &camera(), &TraceSettings::default()); + } + tracer.rgba8(&TraceDisplay::from_display(display)) + }; + + let (off_f0, on_f0) = (shaded_f0(&off), shaded_f0(&on)); + + assert_eq!(on_f0, off_f0, "the Specular color gives F0"); + assert_eq!(render(&on), render(&off)); + } } diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 62c9aa0a..751d4c0b 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,4 +1,5 @@ use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_core::DisplaySettings; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; @@ -789,6 +790,31 @@ fn specular_glossiness_takes_f0_from_the_specular_color() { assert!(sg.mean(200, 100, 280, 180) > 20.0); } +#[test] +fn ior_specular_changes_dielectric_reflections_in_the_viewport_only_for_metallic_roughness() { + let Some((mut h, frame)) = setup() else { return }; + + // A dark, glossy dielectric at full Specular Level shows mostly its F0 + fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[5, 5, 5, 255]); + fill(&mut h, &[0, 1], DisplayKind::Orm, &[255, 38, 0, 255]); + let mut view = |ior: f32, ior_specular: bool, spec_gloss: bool, name: &str| { + // Without temporal anti-aliasing each frame is the same still image + let display = DisplaySettings { ior, ior_specular, spec_gloss, taa: false, ..DisplaySettings::default() }; + render(&mut h, &Frame { shade: Shade::from_display(&display), ..frame.clone() }, name) + }; + + let legacy = view(1.8, false, false, "ior_specular_off"); + let opt_in = view(1.8, true, false, "ior_specular_on"); + let default_ior = view(1.5, true, false, "ior_specular_default_ior"); + let spec_gloss_off = view(1.8, false, true, "ior_specular_spec_gloss_off"); + let spec_gloss_on = view(1.8, true, true, "ior_specular_spec_gloss_on"); + + let (brighter, darker) = (opt_in.mean(200, 100, 280, 180), legacy.mean(200, 100, 280, 180)); + assert!(brighter > darker + 2.0, "IOR 1.8 reflects more than the legacy F0 ({brighter} vs {darker})"); + assert_same(&default_ior, &legacy, "IOR 1.5 keeps the legacy reflectance"); + assert_eq!(spec_gloss_on.px, spec_gloss_off.px, "Specular/Glossiness takes F0 from the Specular color"); +} + #[test] fn a_lit_metallic_view_ignores_the_specular_channel() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 322d3297..79f33f27 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -2,15 +2,22 @@ //! at a checkout: Inter for the interface (from its Latin catalog) and the CJK and Arabic //! faces; without it `CRAFT_FONTS` is empty and the UI uses egui's and the system's fonts. The //! 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`]). +//! faces are embedded without their Private Use Area ([`without_private_use`]), and a web build +//! embeds its CJK faces cut to the characters the shipped catalogs use ([`cut_to_catalogs`]): +//! the whole Japanese face alone is 4.5 MB of the wasm download. mod i18n_build; +use skera::{Plan, SubsetFlags, subset_font}; +use skrifa::raw::collections::IntSet; +use skrifa::raw::types::NameId; +use skrifa::{FontRef, GlyphId, MetadataProvider, Tag}; use std::fmt::Write as _; use std::path::PathBuf; /// The UI faces TextureCraft embeds (family, style) per manifest: desktop, then web (the web build -/// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB). +/// has a download budget: of the CJK faces only the Japanese one, cut to the catalogs' characters +/// by [`cut_to_catalogs`]). const MANIFESTS: &[(&str, Faces, Faces)] = &[ ("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]), // The interface font has regular and semibold faces @@ -25,12 +32,12 @@ const LATIN: Faces = &[("Inter", "Regular"), ("Inter", "SemiBold")]; type Faces = &'static [(&'static str, &'static str)]; fn main() { - i18n_build::embed(); + let catalogs = 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"); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) { - match MANIFESTS.iter().map(|(rel, desktop, web)| craft_fonts(&dir, rel, desktop, web)).collect::>() { + match MANIFESTS.iter().map(|(rel, desktop, web)| craft_fonts(&dir, rel, desktop, web, &catalogs)).collect::>() { Ok(entries) => src.push_str(&entries), Err(e) if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() => { println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()); @@ -47,7 +54,10 @@ fn main() { } /// One `CraftFont { .. }` initialiser per wanted line of manifest `rel`. -fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: &[(&str, &str)]) -> Result { +/// +/// `catalogs` is the characters the embedded catalogs use ([`i18n_build::embed`]): a web build +/// cuts its CJK faces to them. +fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: &[(&str, &str)], catalogs: &[char]) -> Result { let manifest = dir.join(rel); println!("cargo::rerun-if-changed={}", manifest.display()); if rel == LATIN_MANIFEST && !manifest.exists() { @@ -70,14 +80,21 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); - if rel == LATIN_MANIFEST { + let tags: Vec<&str> = scripts.split(',').map(str::trim).filter(|s| !s.is_empty()).collect(); + // The Latin faces lose their Private Use Area everywhere; a web build also cuts its CJK + // faces to the characters the shipped catalogs use. The desktop keeps its CJK faces whole: + // the same face draws text the app never ships, a user's Japanese file name. + let cut = rel == LATIN_MANIFEST || (wasm && !catalogs.is_empty() && tags.iter().any(|tag| CJK_SCRIPTS.contains(tag))); + if cut { let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; + let cut = + if rel == LATIN_MANIFEST { without_private_use(&bytes) } else { cut_to_catalogs(&bytes, catalogs) }.map_err(|e| format!("{file}: {e}"))?; let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(path.file_name().unwrap_or_default()); - std::fs::write(&out, without_private_use(&bytes).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{}: {e}", out.display()))?; + std::fs::write(&out, cut).map_err(|e| format!("{}: {e}", out.display()))?; path = out; } - let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); + let scripts: Vec = tags.iter().map(|s| format!("{s:?}")).collect(); let _ = writeln!( out, " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", @@ -89,26 +106,47 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: Ok(out) } +/// The scripts whose faces a web build cuts to the catalogs' characters: the CJK faces are most of +/// the web build's font download, and the whole Japanese face alone is 4.5 MB. +const CJK_SCRIPTS: [&str; 4] = ["Hans", "Hant", "Jpan", "Kore"]; + /// `font` without the characters of the Private Use Area (U+E000–U+F8FF): the icon font (Phosphor) /// draws there, and Inter, ahead of it in the fallback list, has alternates of its own there that /// would show instead of the icons. Everything else (layout features, hinting) is kept, as /// craft-libs' `craft-fonts-build` subsets. fn without_private_use(font: &[u8]) -> Result, String> { - use skera::{Plan, SubsetFlags, subset_font}; - use skrifa::raw::collections::IntSet; - use skrifa::raw::types::NameId; - use skrifa::{FontRef, GlyphId, MetadataProvider, Tag}; let font = FontRef::new(font).map_err(|e| e.to_string())?; let mut unicodes = IntSet::::empty(); unicodes.extend(font.charmap().mappings().map(|(c, _)| c).filter(|c| !(0xE000..=0xF8FF).contains(c))); + subset(&font, &unicodes) +} + +/// `font` with only the glyphs for the characters the shipped catalogs use, plus ASCII, Latin-1, +/// general punctuation (numbers, names and punctuation in the shipped strings), CJK punctuation +/// (U+3000–303F) and the kana blocks (U+3040–30FF), as craft-libs' `craft-fonts-build` keeps when +/// WordCraft cuts its interface face. The web build has one face per script. Shipped UI strings +/// and user-typed ASCII, Latin-1, punctuation and kana still draw; Han ideographs that are not in +/// the catalogs show as missing glyphs (the desktop build keeps the CJK faces whole, including a +/// user's Japanese file name). The whole Japanese face would otherwise be 4.5 MB of a download +/// that has to stay under the 24 MiB web size gate. +fn cut_to_catalogs(font: &[u8], catalogs: &[char]) -> Result, String> { + let font = FontRef::new(font).map_err(|e| e.to_string())?; + let mut unicodes = IntSet::::empty(); + unicodes.extend((0x20..=0xFF).chain(0x2000..=0x206F).chain(0x3000..=0x303F).chain(0x3040..=0x30FF).chain(catalogs.iter().map(|c| *c as u32))); + subset(&font, &unicodes) +} + +/// `font` with the glyphs for `unicodes` only; layout features, hinting and the face's names are +/// kept, as craft-libs' `craft-fonts-build` subsets. +fn subset(font: &FontRef, unicodes: &IntSet) -> Result, String> { let mut name_ids = IntSet::::empty(); name_ids.insert_range(NameId::new(0)..=NameId::new(6)); let mut languages = IntSet::::empty(); languages.insert(0x0409); let plan = Plan::new( &IntSet::::empty(), - &unicodes, - &font, + unicodes, + font, SubsetFlags::default(), &IntSet::::empty(), &IntSet::::all(), @@ -116,5 +154,5 @@ fn without_private_use(font: &[u8]) -> Result, String> { &name_ids, &languages, ); - subset_font(&font, &plan).map_err(|e| e.to_string()) + subset_font(font, &plan).map_err(|e| e.to_string()) } diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs index cf6ba7e4..58eaae8b 100644 --- a/crates/ui-egui/i18n_build.rs +++ b/crates/ui-egui/i18n_build.rs @@ -2,16 +2,16 @@ 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 { +/// The catalogs' Rust includes and the distinct characters they use, sorted: the web build cuts +/// its CJK interface face to those characters. +pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec), String> { 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); + return Ok((source, Vec::new())); }; if !dir.is_absolute() { @@ -32,6 +32,7 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { paths.sort(); let mut count = 0; let mut catalogs = Vec::new(); + let mut characters = 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()); @@ -52,6 +53,7 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { }; let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") }; let (app, app_text) = embed(&app)?; + characters.extend(shared_text.chars().chain(app_text.chars())); 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}),"); @@ -69,25 +71,30 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { } source.push_str("];\n"); - Ok(source) + characters.sort_unstable(); + characters.dedup(); + Ok((source, characters)) } /// 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() { +/// +/// Returns the distinct characters the embedded catalogs use: the web build cuts its CJK interface +/// face to them, since every character kept costs glyph data in the wasm download. +pub fn embed() -> Vec { 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, + let (source, characters) = match collect(dir.as_deref(), required) { + Ok(embedded) => embedded, 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() + ("pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into(), Vec::new()) } }; @@ -95,4 +102,5 @@ pub fn embed() { if let Err(error) = std::fs::write(&out, source) { println!("cargo::error=writing {}: {error}", out.display()); } + characters } diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs new file mode 100644 index 00000000..473e80ce --- /dev/null +++ b/crates/ui-egui/src/auto_rebake.rs @@ -0,0 +1,143 @@ +//! Auto-rebake: a texture set's auto-rebake map is baked again in the background once what it is baked from has stopped changing + +use texturecraft_engine::core::{BakeSource, BakedMap}; + +use crate::{BakeJob, TextureCraftApp, bake_report, state}; + +/// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts +const SETTLE_SECONDS: f64 = 0.5; + +/// An out-of-date auto-rebake map: set, map, what a bake reads now, and the newest stroke when only painting changed it +pub type Due = (usize, BakedMap, BakeSource, Option); + +/// What the app has seen of the out-of-date auto-rebake maps +#[derive(Default)] +pub struct AutoRebake { + /// The project these records are of: another project starts with none + project: u64, + /// The due maps and the frame time they were first seen as they are + pending: Option<(Vec, f64)>, + /// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes + tried: Vec, +} + +/// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed +pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.auto_rebake.project != app.session.project_id { + app.auto_rebake = AutoRebake { project: app.session.project_id, ..AutoRebake::default() }; + } + + if app.ui.mode != state::Mode::Baking { + app.auto_rebake.pending = None; + return; + } + + let stale = app.session.auto_rebake_due().into_iter().map(|(set, map, source)| (set, map, source, None)); + let painted = app.session.auto_rebake_painted().into_iter().map(|(set, map, source, stroke)| (set, map, source, Some(stroke))); + let due: Vec = stale.chain(painted).collect(); + if let Some(job) = &app.bake { + // Newest wins: a rebake whose map changed again while it ran starts over with the new settings + if job.rebake.as_ref().is_some_and(|rebake| !due.contains(rebake)) { + app.cancel_bake(); + } + return; + } + + app.auto_rebake.tried.retain(|tried| due.contains(tried)); + let waiting: Vec = due.into_iter().filter(|due| !app.auto_rebake.tried.contains(due)).collect(); + if waiting.is_empty() { + app.auto_rebake.pending = None; + return; + } + + let now = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); + + // A held press (a slider dragged and paused) is still editing: the wait starts once it is let go + if pointer_held(ctx, app.docks.floating_windows()) { + app.auto_rebake.pending = Some((waiting, now)); + return; + } + + match &app.auto_rebake.pending { + Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} + Some((seen, _)) if *seen == waiting => return, + _ => { + app.auto_rebake.pending = Some((waiting, now)); + return; + } + } + + app.auto_rebake.pending = None; + if let Some(rebake) = waiting.first().copied() { + app.auto_rebake.tried.push(rebake); + start(app, rebake); + } +} + +/// Whether a mouse button is down in the main window or in one of the floating panels' own `windows` +fn pointer_held(ctx: &egui::Context, windows: &[egui::ViewportId]) -> bool { + ctx.input(|input| input.pointer.any_down()) || windows.iter().any(|window| ctx.input_for(*window, |input| input.pointer.any_down())) +} + +/// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake +fn start(app: &mut TextureCraftApp, rebake: Due) { + let (set, map, ..) = rebake; + + // Restore the previous view before the rebake takes it over + app.live_preview.release(&mut app.session); + crate::id_color_pick::IdColorPick::end(app); + + // The progress footer names the maps this rebake makes, not every checked map of the set + let maps = app.session.auto_rebake_maps(set, map); + app.session.bake_preview_begin(vec![(set, maps.clone())]); + app.session.begin_map_bake_log(&[set], &maps); + app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; + app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Whether a press is held, seen from the main window after a button went down in a floating panel's window (`window_listed`) + fn held_after_a_press_in_a_floating_window(window_listed: bool) -> bool { + use std::{cell::RefCell, rc::Rc}; + + let window = egui::ViewportId::from_hash_of("floating panel"); + let context = egui::Context::default(); + context.set_embed_viewports(false); + + // Runs the window's pass inside its parent's, as eframe does + let arriving = Rc::new(RefCell::new(Vec::new())); + let queued = Rc::clone(&arriving); + egui::Context::set_immediate_viewport_renderer(move |context, viewport| { + let mut input = egui::RawInput { viewport_id: viewport.ids.this, events: queued.take(), ..Default::default() }; + input.viewports.insert(viewport.ids.this, egui::ViewportInfo { parent: Some(viewport.ids.parent), ..Default::default() }); + let mut output = context.run_ui(input, viewport.viewport_ui_cb); + output.textures_delta.clear(); + }); + + let at = egui::pos2(20.0, 20.0); + let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + *arriving.borrow_mut() = vec![egui::Event::PointerMoved(at), press]; + let windows: &[egui::ViewportId] = if window_listed { &[window] } else { &[] }; + let mut held = false; + + // The first pass hands the press to the window after the hold was read; the second reads it + for _ in 0..2 { + let mut output = context.run_ui(egui::RawInput::default(), |ui| { + held = pointer_held(ui.ctx(), windows); + ui.ctx().show_viewport_immediate(window, egui::ViewportBuilder::default(), |_, _| {}); + }); + output.textures_delta.clear(); + } + held + } + + #[test] + fn a_press_held_in_a_floating_panels_window_counts_as_held() { + assert!(held_after_a_press_in_a_floating_window(true), "the slider dragged in a floating panel is still editing"); + assert!(!held_after_a_press_in_a_floating_window(false), "the main window's own pointer is up"); + } +} diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs new file mode 100644 index 00000000..3c4493e2 --- /dev/null +++ b/crates/ui-egui/src/autosave_name.rs @@ -0,0 +1,188 @@ +//! Where a project's autosave copy goes. Each project has a file of its own, `-copy-.tcraft`, +//! even if several projects share a name or a project is renamed. + +use std::path::{Path, PathBuf}; + +use texturecraft_engine::core::PROJECT_EXT; +use texturecraft_engine::formats::export::sanitize_file_stem; + +use crate::TextureCraftApp; + +/// Hex digits of a copy's suffix +const SUFFIX_DIGITS: usize = 16; + +/// Between a copy's stem and its suffix, so a user's own file named like `report-20240115` is not taken for a copy +const COPY_MARK: &str = "-copy-"; + +/// The longest stem kept, so the suffix and the temporary files of a save still fit a file name +const MAX_STEM_CHARS: usize = 170; + +impl TextureCraftApp { + /// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the + /// same across restarts; an unsaved project's copy keeps its first autosave name until the project is saved + pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf { + let Some(saved) = self.session.path.as_deref() else { + let project = self.session.project_id; + if let Some((owner, name)) = &self.unsaved_autosave_file + && *owner == project + { + return folder.join(name); + } + + let name = file_name(&self.session.doc.project.name, new_suffix(project)); + let path = folder.join(&name); + self.unsaved_autosave_file = Some((project, name)); + return path; + }; + + let saved = absolute(Path::new(saved)); + + // A project opened from its autosave copy keeps writing there, rather than chaining suffixes + if is_copy_in(&saved, &absolute(folder)) { + return saved; + } + + let stem = saved.file_stem().map_or_else(|| self.session.doc.project.name.clone(), |stem| stem.to_string_lossy().into_owned()); + folder.join(file_name(&stem, hash(saved.as_os_str().as_encoded_bytes()))) + } +} + +fn file_name(stem: &str, suffix: u64) -> String { + let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect(); + format!("{stem}{COPY_MARK}{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}") +} + +/// `path` made absolute, as given when that fails +fn absolute(path: &Path) -> PathBuf { + std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()) +} + +/// `path` with links and, on Windows, the verbatim prefix resolved so two spellings of one folder compare equal; made absolute when that fails +fn resolved(path: &Path) -> PathBuf { + std::fs::canonicalize(path).unwrap_or_else(|_| absolute(path)) +} + +/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in the copy mark and a suffix +fn is_copy_in(path: &Path, folder: &Path) -> bool { + let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once(COPY_MARK)).map(|(_, suffix)| suffix); + path.parent().is_some_and(|parent| resolved(parent) == resolved(folder)) + && path.extension().is_some_and(|extension| extension == PROJECT_EXT) + && suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit())) +} + +/// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run +/// takes a different one +fn new_suffix(project: u64) -> u64 { + let now = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(); + let mut seed = Vec::new(); + seed.extend_from_slice(&std::process::id().to_le_bytes()); + seed.extend_from_slice(&now.to_le_bytes()); + seed.extend_from_slice(&project.to_le_bytes()); + hash(&seed) +} + +/// 64-bit FNV-1a: the same bytes give the same suffix in every release, which the standard hasher does not promise. +/// Wide enough that two paths are very unlikely to share one +fn hash(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3)) +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives; + + use super::*; + + fn project(name: &str) -> Session { + Session::new_project(name, primitives::cube(1.0), "builtin:cube", None, 128).unwrap() + } + + fn app(session: Session) -> TextureCraftApp { + TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session) + } + + fn name_of(path: &Path) -> &str { + path.file_name().and_then(|name| name.to_str()).unwrap() + } + + #[test] + fn unsaved_projects_with_one_name_get_different_copies_that_stay_put() { + let folder = Path::new("autosave"); + let mut first = app(project("hero")); + let mut second = app(project("hero")); + + let (one, other) = (first.autosave_path(folder), second.autosave_path(folder)); + + assert_ne!(one, other, "another instance never writes the same file"); + assert!(name_of(&one).starts_with("hero-") && name_of(&one).ends_with(".tcraft"), "{one:?}"); + assert_eq!(one.parent(), Some(folder)); + assert_eq!(first.autosave_path(folder), one, "the next autosave replaces this project's copy"); + + first.session.switch_to(project("hero")); + assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy"); + } + + #[test] + fn renaming_an_unsaved_project_keeps_its_autosave_copy() { + let folder = Path::new("autosave"); + let mut app = app(project("hero")); + let copy = app.autosave_path(folder); + + for name in ["Knight", "Knight final"] { + texturecraft_engine::execute(&mut app.session, "project.rename", &serde_json::json!({"name": name})).unwrap(); + + assert_eq!(app.autosave_path(folder), copy); + } + + app.session.switch_to(project("Knight")); + + assert_ne!(app.autosave_path(folder), copy); + } + + #[test] + fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() { + let folder = Path::new("autosave"); + let copy_of = |saved: &str| { + let mut app = app(project("hero")); + app.session.path = Some(saved.to_string()); + app.autosave_path(folder) + }; + + let first = copy_of("work/Hero_v1.tcraft"); + let second = copy_of("work/Hero_v2.tcraft"); + let same_name_elsewhere = copy_of("backup/Hero_v1.tcraft"); + + assert!(name_of(&first).starts_with("Hero_v1-"), "{first:?}"); + assert_ne!(first, second); + assert_ne!(first, same_name_elsewhere, "files of one name in two folders keep two copies"); + assert_eq!(copy_of("work/Hero_v1.tcraft"), first, "a later run finds the same copy"); + } + + #[test] + fn a_project_opened_from_its_copy_keeps_writing_to_it() { + let folder = std::env::temp_dir().join("tc-autosave"); + let mut app = app(project("hero")); + let copy = app.autosave_path(&folder); + + app.session.path = Some(copy.display().to_string()); + assert_eq!(app.autosave_path(&folder), copy); + + // A file there that is not a copy is the user's own: autosave leaves it alone + let own = folder.join("hero.tcraft"); + app.session.path = Some(own.display().to_string()); + assert_ne!(app.autosave_path(&folder), own); + + let dated = folder.join("hero-20240115.tcraft"); + app.session.path = Some(dated.display().to_string()); + assert_ne!(app.autosave_path(&folder), dated); + } + + #[test] + fn suffixes_have_a_fixed_width_and_long_names_are_cut() { + let narrow = file_name("hero", 1); + let wide = file_name("hero", u64::MAX); + assert_eq!(narrow.len(), wide.len(), "every suffix has the same width"); + assert!(file_name(&"a".repeat(500), 1).len() < 200); + } +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index 97dd4610..431999db 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -11,4 +11,6 @@ pub struct BakeJob { pub mesh_id: u64, /// The one map to bake (a row's quick bake) instead of the checked ones pub only: Option, + /// An auto-rebake: the set, the one map it bakes and what that map was baked from when it started; `None` bakes every checked map + pub rebake: Option, } diff --git a/crates/ui-egui/src/bake_mode/live_preview.rs b/crates/ui-egui/src/bake_mode/live_preview.rs index 06394cb6..c76f9001 100644 --- a/crates/ui-egui/src/bake_mode/live_preview.rs +++ b/crates/ui-egui/src/bake_mode/live_preview.rs @@ -97,7 +97,11 @@ pub(crate) fn map_settings_shown(app: &TextureCraftApp) -> Option Option { - map_settings_shown(app).filter(|_| app.ui.bake_visualization.map_preview && app.bake.is_none()) + if !app.ui.prefs.live_preview_baking || !app.ui.bake_visualization.map_preview || app.bake.is_some() { + return None; + } + + map_settings_shown(app) } /// A slider dragged in Mesh Map Settings changed a setting: a running drag bake finishes and shows before the newest value bakes, so pictures keep coming while the slider moves diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 7ec44f70..e5ec5597 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,15 +1,16 @@ -use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; +use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; -use serde_json::json; +use serde_json::{Value, json}; use texturecraft_engine::ViewMode; -use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use texturecraft_engine::core::{BakeChange, BakeSettings, BakeSyncGroup, BakedMap}; use super::glyph_look::GlyphLook; +use super::row_click::RowClick; use super::set_picker::SetPicker; use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; use crate::docking::Panel; -use crate::i18n::{baked_map_label, tr, trf}; +use crate::i18n::{bake_change_reason, baked_map_label, tr, trf}; use crate::property_sheet::{CHECK_SIZE, paint_check}; use crate::theme::{Tokens, semibold}; @@ -34,8 +35,13 @@ const ROW_INSET: f32 = 6.0; /// Side of a row's map thumbnail, and the air on its sides const THUMBNAIL_SIZE: f32 = 22.0; const THUMBNAIL_AIR: f32 = 9.0; -/// Side of a row's icon buttons and of the list menu button +/// Side of the header icon slots and of the list menu button const ROW_BUTTON_SIZE: f32 = 20.0; +/// Side of a row's hover icons, and the air right of each: four icons stay right of the row's middle in the Bakers column, so a click there selects the row +const ROW_ICON_SIZE: f32 = 18.0; +const ROW_ICON_GAP: f32 = 1.0; +/// Radius of the out-of-date clock on a thumbnail's corner +const CLOCK_BADGE_RADIUS: f32 = 6.0; /// Size of a row's glyphs const ROW_GLYPH_SIZE: f32 = 14.0; /// Size of the map names @@ -46,8 +52,10 @@ const ROW_RADIUS: u8 = 4; const HOVER_FACE_OPACITY: f32 = 0.5; /// Air above and below the hairline under Check All const RULE_AIR: f32 = 4.0; +/// Size of a row icon's tooltip title and reasons +const TOOLTIP_TEXT_SIZE: f32 = 12.0; -/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects) +/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects, a hover icon toggles Auto-rebake) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { let several_sets = app.session.doc.project.texture_sets.len() > 1; ui.add_space(HEADER_AIR); @@ -85,10 +93,21 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let drag_from_id = ui.scope_id().with("check_drag_from"); let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); + let texture_set = app.session.ts(); + let out_of_date = app.session.out_of_date_maps(texture_set); + for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { - app.ui.selected_baked_map = Some(map); - app.ui.dock.focus(Panel::MeshMapSettings); + let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); + match ui.push_id(map, |ui| row(app, ui, (map, changes), settings, map == selected, &mut check_drag, drag_from)).inner { + Some(RowClick::Row) => { + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); + } + Some(RowClick::AutoRebake) => { + let selection = if auto_rebake_map(app, texture_set) == Some(map) { Value::Null } else { json!(map.id()) }; + app.run("bake.autoRebake", json!({ "ts": texture_set, "map": selection })); + } + None => {} } } @@ -99,7 +118,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe if let (Some(value), true) = (check_drag, is_held) { data.insert_temp(check_drag_id, value); - // A pointer back from outside the window starts a new line, so rows it never crossed stay as they were + // Break the drag line when the pointer leaves the window if let Some(pointer) = pointer { data.insert_temp(drag_from_id, pointer); } else { @@ -239,21 +258,21 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock naming its `changes` (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check fn row( app: &mut TextureCraftApp, ui: &mut Ui, - map: BakedMap, + (map, changes): (BakedMap, &[BakeChange]), settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option, drag_from: Option, -) -> bool { +) -> Option { let several_sets = app.session.doc.project.texture_sets.len() > 1; 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)); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_selected, name)); let hovered = ui.rect_contains_pointer(rect); if is_selected { @@ -262,7 +281,7 @@ fn row( ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover.gamma_multiply(HOVER_FACE_OPACITY)); } - // Added after the row's own response, so the check and icons take the clicks over it + // Register the checkbox after the row so it gets first chance at clicks let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); let checkbox = ui.interact(check.expand(CHECK_HIT_AIR), ui.scope_id().with("include"), Sense::click()).on_hover_text(tr("Include in Bake")); checkbox.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, settings.maps.is_enabled(map), name)); @@ -272,35 +291,46 @@ fn row( } else if checkbox.clicked() && check_drag.is_none() { settings.maps.set_enabled(map, !settings.maps.is_enabled(map)); } - paint_check(ui.painter(), &tokens, check, Some(settings.maps.is_enabled(map)), checkbox.hovered()); + paint_check(ui.painter(), &tokens, check, Some(settings.maps.is_enabled(map)), checkbox.hovered()); crate::property_sheet::paint_keyboard_focus(ui, &checkbox, &tokens); + let texture = app.bake_map_thumbnails.texture(ui.ctx(), &app.session, app.session.ts(), map); let thumbnail_rect = Rect::from_min_size(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - THUMBNAIL_SIZE / 2.0), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); thumbnail(ui, thumbnail_rect, texture.as_ref()); - let mut icons_left = rect.right(); + let texture_set = app.session.ts(); + if !changes.is_empty() { + out_of_date_mark(ui, thumbnail_rect, name, changes); + } + let focus_in_row = || { ui.memory(|memory| memory.focused()) .and_then(|id| ui.ctx().read_response(id)) .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) }; - if is_selected || hovered || focus_in_row() { - let mut next_icon = || { - let slot = - Rect::from_center_size(pos2(icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); - icons_left = slot.left() - ROW_INSET / 2.0; - slot - }; - if several_sets { + let is_active = is_selected || hovered || focus_in_row(); + let is_auto_rebake = auto_rebake_map(app, texture_set) == Some(map); + + // Reserve Auto-rebake's slot before placing the hover-only icons + let mut icons_left = rect.right(); + let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); + let sync_slot = several_sets.then(&mut next_icon); + let toggle = next_icon(); + let mut toggled = false; + + if is_active { + if let Some(slot) = sync_slot { let shares = settings.sync.shares(BakeSyncGroup::Map(map)); let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; let glyph = if shares { icon::LINK } else { icon::LINK_BREAK }; - let sync = glyph_button(ui, next_icon(), glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); + let sync = glyph_button(ui, slot, glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); if sync.clicked() { SetPicker::open(app, &sync, SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); } } + + toggled = auto_rebake_toggle(ui, toggle, name, is_auto_rebake).clicked(); let baking = app.bake_progress().is_some(); let bolt = next_icon(); let bolt_label = trf("Bake {map} Only", &[("map", &name)]); @@ -308,12 +338,17 @@ fn row( let active = app.session.ts(); app.start_bake_of(vec![active], Some(map)); } + let shown = app.session.view == ViewMode::MeshMap(map); let look = if shown { GlyphLook::Pressed } else { GlyphLook::Plain }; if glyph_button(ui, next_icon(), icon::EYE, &trf("Show {map} in the Viewport", &[("map", &name)]), look).clicked() { let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) }; app.run("viewport.view", json!({ "mode": mode })); } + } else if is_auto_rebake { + toggled = auto_rebake_toggle(ui, toggle, name, true).clicked(); + } else { + icons_left = rect.right(); } let name_left = thumbnail_rect.right() + THUMBNAIL_AIR; @@ -356,7 +391,35 @@ fn row( response.request_focus(); } - response.clicked() + if toggled { + Some(RowClick::AutoRebake) + } else if response.clicked() { + Some(RowClick::Row) + } else { + None + } +} + +/// The map texture set `texture_set` rebakes on its own, if any +fn auto_rebake_map(app: &TextureCraftApp, texture_set: usize) -> Option { + app.session.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake) +} + +/// The Auto-rebake toggle in `rect`: bright while on or pointed at, dim while off +fn auto_rebake_toggle(ui: &mut Ui, rect: Rect, name: &str, is_on: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("auto_rebake"), Sense::click()); + let title = tr("Auto-rebake"); + let label = trf("Auto-rebake {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_on, &label)); + + let is_pointed = response.hovered() || response.has_focus(); + let color = if is_on || is_pointed { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::ARROWS_CLOCKWISE, FontId::proportional(ROW_GLYPH_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + }) } /// Start a checkbox drag at a primary press on `checkbox`; returns whether the drag's pointer crossed this row's checkbox column (the whole row height counts) since `drag_from` @@ -420,8 +483,10 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { let icon = ui.painter().layout_no_wrap(glyph.to_owned(), FontId::proportional(ROW_GLYPH_SIZE), tokens.text); let words = ui.painter().layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); let width = 2.0 * HEADER_BUTTON_PADDING + icon.size().x + HEADER_GLYPH_GAP + words.size().x; + let (rect, response) = ui.allocate_exact_size(vec2(width, HEADER_BUTTON_HEIGHT), Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), fill, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside); let x = rect.left() + HEADER_BUTTON_PADDING; @@ -430,3 +495,32 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); response } + +/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail, or its node's description, tells what changed +fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover()); + let title = tr("Out of date"); + let label = trf("Out of date: {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); + let reasons: Vec<&str> = changes.iter().map(|change| tr(bake_change_reason(*change))).collect(); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reasons.join(" "))); + + let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5; + ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel); + ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning); + + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for reason in reasons { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); +} + +/// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it +fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect { + let slot = Rect::from_center_size(pos2(*icons_left - ROW_ICON_SIZE / 2.0 - ROW_ICON_GAP, center_y), vec2(ROW_ICON_SIZE, ROW_ICON_SIZE)); + *icons_left = slot.left(); + slot +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 1efb19d3..2cba0c23 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -23,6 +23,7 @@ mod map_settings; mod map_thumbnails; mod mesh_map_bakers; pub use map_thumbnails::MapThumbnails; +mod row_click; mod set_picker; mod set_picker_purpose; mod set_picker_row; @@ -230,15 +231,16 @@ fn edit_settings( 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 false; - } + + // One drag is one undo step: a press's later changes continue its first one + let Some(merge) = crate::widgets::press_edit(ui, ui.make_persistent_id((scroll_id, "press")), settings != before || reset.is_some()) else { return false }; 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 })); + + app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch, "merge": merge })); true } diff --git a/crates/ui-egui/src/bake_mode/row_click.rs b/crates/ui-egui/src/bake_mode/row_click.rs new file mode 100644 index 00000000..5f77dfd0 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/row_click.rs @@ -0,0 +1,5 @@ +/// What a click on a Mesh Map Bakers row hit +pub(super) enum RowClick { + Row, + AutoRebake, +} diff --git a/crates/ui-egui/src/bake_report.rs b/crates/ui-egui/src/bake_report.rs index d0423de9..4a58c286 100644 --- a/crates/ui-egui/src/bake_report.rs +++ b/crates/ui-egui/src/bake_report.rs @@ -10,16 +10,19 @@ pub struct BakeReport { pub map_count: usize, /// Number of texture sets whose bake failed pub failed_set_count: usize, + /// A rebake the app started by itself (Auto-rebake): only a failure makes a toast + pub auto_rebake: bool, } impl BakeReport { - pub fn started(now: f64) -> Self { - BakeReport { started_at_seconds: now, ..Default::default() } + pub fn started(now_seconds: f64) -> Self { + BakeReport { started_at_seconds: now_seconds, ..Default::default() } } /// The toast text, the Log line and whether the toast is an error (some set failed) - pub fn summary(&self, now: f64) -> (String, String, bool) { - let time = duration_text((now - self.started_at_seconds).max(0.0)); + pub fn summary(&self, now_seconds: f64) -> (String, String, bool) { + let time = duration_text((now_seconds - self.started_at_seconds).max(0.0)); + let line = if self.failed_set_count == 0 { format!("Bake finished: {} maps in {time}", self.map_count) } else { @@ -35,6 +38,7 @@ impl BakeReport { tr("Failures are listed in the Log.") ) }; + (text, line, self.failed_set_count > 0) } } @@ -57,7 +61,7 @@ mod tests { #[test] fn success_names_maps_and_time() { - let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0 }; + let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0, auto_rebake: false }; let (text, line, failed) = report.summary(22.34); @@ -68,7 +72,7 @@ mod tests { #[test] fn failures_are_counted_and_point_to_the_log() { - let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2 }; + let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2, auto_rebake: false }; let (text, _, failed) = report.summary(125.0); diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs new file mode 100644 index 00000000..b29488f9 --- /dev/null +++ b/crates/ui-egui/src/baking_log.rs @@ -0,0 +1,378 @@ +//! The Baking Log panel: the latest bake under three tabs, read from the session's bake record + +use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeLogMatching, BakeMapState}; +use texturecraft_engine::core::BakedMap; + +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box}; +use crate::theme::{Tokens, semibold}; + +mod baking_log_tab; +mod high_poly_list; +mod matching_list; + +pub use baking_log_tab::BakingLogTab; + +/// Height of the tab strip, as the Properties section tabs +const STRIP_HEIGHT: f32 = 30.0; + +/// How far the first tab reaches left of the rows' side padding, as the Properties section tabs +const FIRST_TAB_OUTDENT: f32 = 4.0; + +/// Height of one row of a list +const ROW_HEIGHT: f32 = 24.0; + +/// Air above the first row +const LIST_TOP: f32 = 4.0; + +/// How far a hovered row's fill stays inside the panel's sides +const HOVER_INSET: f32 = 3.0; + +/// From the panel's left edge to a row's glyph centre, and to its name +const GLYPH_CENTER: f32 = SIDE_PADDING_POINTS + 6.0; +const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0; + +/// Size of a row's glyph and of its name +const GLYPH_SIZE: f32 = 13.0; +const NAME_SIZE: f32 = 12.0; + +/// Size of the open-settings arrow at an issue row's right end, and of the square it answers clicks in +const OPEN_ICON_SIZE: f32 = 14.0; +const OPEN_BUTTON_SIZE: f32 = 20.0; + +/// Height of the issues filter toggle, and its width without a count +const FILTER_HEIGHT: f32 = 22.0; +const FILTER_BUTTON_WIDTH: f32 = 30.0; + +/// How far the issues filter sits below the strip's centre, and how far it reaches past the side padding +const FILTER_DROP: f32 = 1.0; +const FILTER_OUTDENT: f32 = 4.0; + +/// Corner rounding of the issues filter's pressed and hovered fill +const FILTER_ROUNDING: f32 = 5.0; + +/// From the issues filter's left edge to its glyph's centre and to its count, and the glyph's size +const FILTER_GLYPH_CENTER: f32 = 15.0; +const FILTER_COUNT_LEFT: f32 = 26.0; +const FILTER_GLYPH_SIZE: f32 = 14.0; + +/// Air between the issue count and the toggle's right end +const FILTER_COUNT_GAP: f32 = 4.0; + +/// Height of the two lines the issues filter leaves when nothing is wrong, to centre them +const EMPTY_TEXT_HEIGHT: f32 = 40.0; + +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); + + // The tabs keep clear of the issues filter at its widest, so picking a tab never moves the edge they scroll under + let filter_room = BakingLogTab::ALL.into_iter().map(|tab| filter_width(ui, issue_count(&app.session.bake_log, tab))).fold(0.0, f32::max); + let tabs_right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT - filter_room - TAB_GAP; + if let Some(tab) = tabs(ui, strip.with_max_x(tabs_right.max(strip.left())), app.ui.baking_log_tab, &app.session.bake_log) { + app.ui.baking_log_tab = tab; + } + let tab = app.ui.baking_log_tab; + let issue_count = issue_count(&app.session.bake_log, tab); + if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { + app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; + } + + let issues_only = app.ui.baking_log_issues_only; + let log = &app.session.bake_log; + let baked = !log.maps.is_empty(); + if tab == BakingLogTab::MatchingByName && baked && log.matching.is_none() { + matching_not_enabled(ui); + return; + } + + if issues_only && issue_count == 0 { + no_issues(ui, tab); + return; + } + + let opened = egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + // Rows sit edge to edge at ROW_HEIGHT, as the matching list's rules need + ui.spacing_mut().item_spacing.y = 0.0; + ui.add_space(LIST_TOP); + match tab { + BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), + BakingLogTab::HighPolyParameters => { + high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only); + None + } + BakingLogTab::MatchingByName => { + if let Some(matching) = &app.session.bake_log.matching { + matching_list::matching_list(ui, matching, issues_only); + } + None + } + } + }) + .inner; + if let Some((texture_set, map)) = opened { + open_map_settings(app, texture_set, map); + } +} + +/// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does +fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + // A guard against a row naming a set the session no longer has + if texture_set >= app.session.set_count() { + return; + } + + if texture_set != app.session.ts() { + app.run("textureSet.select", json!({ "ts": texture_set })); + } + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); +} + +/// How many rows of `tab` have an issue, for the issues filter's count +fn issue_count(log: &BakeLog, tab: BakingLogTab) -> usize { + match tab { + BakingLogTab::BakingProcess => log.maps.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::HighPolyParameters => log.highs.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::MatchingByName => log.matching.as_ref().map_or(0, BakeLogMatching::issue_count), + } +} + +/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; they scroll sideways when wider than it +fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option { + let tokens = Tokens::get(ui.ctx()); + let names = BakingLogTab::ALL.map(|tab| tr(tab.name())); + let widths = names.map(|name| ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING); + let first_left = SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; + let content_width = first_left + widths.iter().sum::() + TAB_GAP * (widths.len() - 1) as f32; + + let mut strip_ui = ui.new_child(egui::UiBuilder::new().max_rect(strip).id_salt("baking_log_tabs")); + egui::ScrollArea::horizontal() + .id_salt("baking_log_tabs") + .auto_shrink([false, false]) + .show(&mut strip_ui, |ui| { + let (content, _) = ui.allocate_exact_size(vec2(content_width, strip.height()), Sense::hover()); + let mut picked = None; + let mut left = content.left() + first_left; + for ((tab, name), width) in BakingLogTab::ALL.into_iter().zip(names).zip(widths) { + if tab_button(ui, content, left, width, (tab, name), tab == shown, log) { + picked = Some(tab); + } + left += width + TAB_GAP; + } + picked + }) + .inner +} + +/// One tab `width` wide from `left` on the `strip`, scrolled into view when the focus reaches it; dots for its icon while its work runs +fn tab_button(ui: &mut Ui, strip: Rect, left: f32, width: f32, (tab, name): (BakingLogTab, &str), on: bool, log: &BakeLog) -> bool { + let tokens = Tokens::get(ui.ctx()); + let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); + if response.gained_focus() { + response.scroll_to_me(None); + } + + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, rect); + } + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let in_progress = match tab { + BakingLogTab::BakingProcess => log.is_running(), + BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), + BakingLogTab::MatchingByName => false, + }; + let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); + } + response.clicked() +} + +/// The issues filter's width when it counts `issue_count` rows +fn filter_width(ui: &Ui, issue_count: usize) -> f32 { + let count_width = if issue_count == 0 { + 0.0 + } else { + let tokens = Tokens::get(ui.ctx()); + ui.painter().layout_no_wrap(issue_count.to_string(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP + }; + FILTER_BUTTON_WIDTH + count_width +} + +/// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are +fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let count = (issue_count > 0).then(|| issue_count.to_string()); + let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT; + let center_y = strip.center().y + FILTER_DROP; + let rect = Rect::from_min_max(pos2(right - filter_width(ui, issue_count), center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); + + let name = match &count { + Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]), + None => tr("Show only rows with an issue").to_owned(), + }; + let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name)); + + let painter = ui.painter(); + if on { + painter.rect(rect, FILTER_ROUNDING, tokens.tool_active, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, FILTER_ROUNDING, tokens.row_hover); + } + let glyph_color = if count.is_some() { tokens.warning } else { tokens.text_dim }; + painter.text(pos2(rect.left() + FILTER_GLYPH_CENTER, center_y), Align2::CENTER_CENTER, ic::WARNING, FontId::proportional(FILTER_GLYPH_SIZE), glyph_color); + if let Some(count) = count { + painter.text(pos2(rect.left() + FILTER_COUNT_LEFT, center_y), Align2::LEFT_CENTER, count, semibold(NAME_SIZE), tokens.text); + } + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + response.on_hover_text(tr("Show only rows with an issue")).clicked() +} + +/// What the issues filter leaves when `tab` has no issue: one line for that tab, and how to see every row +fn no_issues(ui: &mut Ui, tab: BakingLogTab) { + let tokens = Tokens::get(ui.ctx()); + let message = match tab { + BakingLogTab::BakingProcess => tr("Every map so far baked without a problem."), + BakingLogTab::HighPolyParameters => tr("Every high poly file so far loaded."), + BakingLogTab::MatchingByName => tr("Every part so far has its partner."), + }; + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0); + child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text)); + child.label(egui::RichText::new(tr("Turn off the issues filter to see every row.")).size(NAME_SIZE).color(tokens.text_dim)); + ui.allocate_rect(area, Sense::hover()); +} + +/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting and its value in SemiBold +fn matching_not_enabled(ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let mut text = egui::text::LayoutJob::default(); + let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; + // One sentence to translate, its setting and value kept apart to set them in SemiBold + let sentence = tr("Set {setting} to {value} to pair parts by name."); + let (before, rest) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + let (between, after) = rest.split_once("{value}").unwrap_or((rest, "")); + text.append(before, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("Match"), 0.0, format(semibold(NAME_SIZE))); + text.append(between, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("By Mesh Name"), 0.0, format(semibold(NAME_SIZE))); + text.append(after, 0.0, format(FontId::proportional(NAME_SIZE))); + + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT / 2.0).max(0.0) / 2.0); + child.label(text); + ui.allocate_rect(area, Sense::hover()); +} + +/// One row per texture set and map (with an issue, if `issues_only`) in bake order, following the map being baked; returns the map to open +fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option<(usize, BakedMap)> { + let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); + let follow_id = Id::unique("baking_log_followed_map"); + let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); + ui.data_mut(|data| data.insert_temp(follow_id, followed)); + + let mut opened = None; + for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { + let (rect, open_clicked) = map_row(ui, row); + // Bring the next map into view too, so the list shows what comes after the map being baked + if newly_followed && followed == Some(index) { + ui.scroll_to_rect(rect.with_max_y(rect.bottom() + ROW_HEIGHT), None); + } + if open_clicked { + opened = Some((row.texture_set, row.map)); + } + } + opened +} + +/// A map's row: glyph, then " "; a map not baked tells why on hover and has an arrow to its settings; returns the row and whether the arrow was clicked +fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map))); + let (glyph, glyph_color, state) = match &row.state { + BakeMapState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeMapState::Baking => (ic::DOTS_THREE, tokens.accent, tr("Baking")), + BakeMapState::Baked => (ic::CHECK, tokens.text, tr("Baked")), + BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")), + BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + let reason = match &row.state { + BakeMapState::Failed(reason) => Some(reason.as_str()), + BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), + _ => None, + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + describe(ui, &response, reason); + let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name)); + let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); + + let painter = ui.painter(); + if row_hovered { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeMapState::Baking => (semibold(NAME_SIZE), tokens.text), + BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, &name, font, color); + if let Some(open) = &open + && (row_hovered || open.has_focus()) + { + let color = if open.hovered() || open.has_focus() { tokens.text } else { tokens.text_dim }; + painter.text(open.rect.center(), Align2::CENTER_CENTER, ic::ARROW_SQUARE_OUT, FontId::proportional(OPEN_ICON_SIZE), color); + if open.has_focus() { + crate::property_sheet::paint_focus_outline(painter, open.rect, tokens.text_strong); + } + } + + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } + let open_clicked = open.is_some_and(|open| open.clicked()); + (rect, open_clicked) +} + +/// Give a row's node the `reason` its tooltip shows, so a screen reader reads it without hovering +pub(super) fn describe(ui: &Ui, response: &egui::Response, reason: Option<&str>) { + if let Some(reason) = reason { + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reason)); + } +} + +/// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus +fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response { + let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); + let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE)); + let label = trf("Open the {name} settings", &[("name", &name)]); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", set_map)), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); + response.on_hover_text(label) +} diff --git a/crates/ui-egui/src/baking_log/baking_log_tab.rs b/crates/ui-egui/src/baking_log/baking_log_tab.rs new file mode 100644 index 00000000..ccff71b0 --- /dev/null +++ b/crates/ui-egui/src/baking_log/baking_log_tab.rs @@ -0,0 +1,36 @@ +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::i18n::n_; + +/// The Baking Log panel's tabs +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum BakingLogTab { + /// Every map of the latest bake and how it went + #[default] + BakingProcess, + /// The high poly files each texture set bakes from + HighPolyParameters, + /// Which low poly part bakes from which high poly part + MatchingByName, +} + +impl BakingLogTab { + pub const ALL: [BakingLogTab; 3] = [BakingLogTab::BakingProcess, BakingLogTab::HighPolyParameters, BakingLogTab::MatchingByName]; + + pub fn name(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => n_("Baking Process"), + BakingLogTab::HighPolyParameters => n_("High Poly Parameters"), + BakingLogTab::MatchingByName => n_("Matching by Name"), + } + } + + pub(crate) fn icon(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => ic::LIST_CHECKS, + BakingLogTab::HighPolyParameters => ic::CUBE, + BakingLogTab::MatchingByName => ic::ARROWS_LEFT_RIGHT, + } + } +} diff --git a/crates/ui-egui/src/baking_log/high_poly_list.rs b/crates/ui-egui/src/baking_log/high_poly_list.rs new file mode 100644 index 00000000..516e7d5b --- /dev/null +++ b/crates/ui-egui/src/baking_log/high_poly_list.rs @@ -0,0 +1,108 @@ +//! The Baking Log's High Poly Parameters tab: each texture set of the latest bake and the high poly files it loads + +use egui::{Align2, CornerRadius, FontId, Id, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh}; + +use super::{GLYPH_CENTER, GLYPH_SIZE, HOVER_INSET, NAME_LEFT, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::theme::{Tokens, semibold}; + +/// How far a file's row sits right of its texture set's row +const FILE_INDENT: f32 = 22.0; + +/// A row per texture set that loads high polys, folding open onto a row per file (with an issue, if `issues_only`) +pub(super) fn high_poly_list(ui: &mut Ui, highs: &[BakeLogHigh], issues_only: bool) { + let mut start = 0; + + while start < highs.len() { + let set = highs[start].texture_set; + let end = highs[start..].iter().position(|row| row.texture_set != set).map_or(highs.len(), |length| start + length); + let files: Vec<&BakeLogHigh> = highs[start..end].iter().filter(|row| !issues_only || row.state.is_issue()).collect(); + start = end; + + if files.is_empty() { + continue; + } + + if set_row(ui, set, &files[0].set_name) { + for row in files { + file_row(ui, row); + } + } + } +} + +/// A texture set's row: a caret and its name in SemiBold, named for what it holds; a click folds it. Returns whether it is open +fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool { + let tokens = Tokens::get(ui.ctx()); + let id = Id::unique(("baking_log_high_poly_set", set)); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, trf("{set}, High poly files", &[("set", &name)]))); + + let mut open = ui.data(|data| data.get_temp::(id)).unwrap_or(true); + if response.clicked() { + open = !open; + ui.data_mut(|data| data.insert_temp(id, open)); + } + + ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + + let center_y = rect.center().y; + let caret = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, caret, FontId::proportional(GLYPH_SIZE), tokens.text_dim); + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, semibold(NAME_SIZE), tokens.text); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + + open +} + +/// A high poly file's row under its texture set: glyph and file name; a file not loaded tells why on hover +fn file_row(ui: &mut Ui, row: &BakeLogHigh) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let (glyph, glyph_color, state) = match &row.state { + BakeHighState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeHighState::Loading => (ic::DOTS_THREE, tokens.accent, tr("Loading")), + BakeHighState::Loaded => (ic::CHECK, tokens.text, tr("Loaded")), + BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")), + BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + let reason = match &row.state { + BakeHighState::Failed(reason) => Some(reason.as_str()), + BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), + _ => None, + }; + + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file))); + super::describe(ui, &response, reason); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER + FILE_INDENT, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeHighState::Loading => (semibold(NAME_SIZE), tokens.text), + BakeHighState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color); + + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } +} diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs new file mode 100644 index 00000000..8f4e278b --- /dev/null +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -0,0 +1,138 @@ +//! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part + +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeLogMatching, NamePair}; + +use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::property_sheet::SIDE_PADDING_POINTS; +use crate::theme::{Tokens, semibold}; +use crate::widgets::elided; + +/// Size of the column captions +const CAPTION_SIZE: f32 = 11.0; + +/// Air between the end of a low poly name and the high poly column +const COLUMN_GAP: f32 = 8.0; + +/// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below +pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)]; + for (column, caption) in columns(rect).into_iter().zip(captions) { + column_text(ui, column, caption, CAPTION_SIZE, tokens.text_dim); + } + rule(ui, rect); + + for pair in matching.pairs.iter().filter(|pair| !issues_only || pair.unpaired()) { + pair_row(ui, pair); + } +} + +/// A column caption in capitals, with the set's `suffix` kept as typed +fn caption(template: &str, suffix: &str) -> String { + template.split("{suffix}").map(str::to_uppercase).collect::>().join(suffix) +} + +/// The low and high poly columns of `row`, each ending a gap short of the next column or the side padding +fn columns(row: Rect) -> [Rect; 2] { + let low = row.with_min_x(row.left() + SIDE_PADDING_POINTS).with_max_x(row.center().x - COLUMN_GAP); + let high = row.with_min_x(row.center().x).with_max_x(row.right() - SIDE_PADDING_POINTS); + [low, high] +} + +/// Paint `text` in `color` at the left end of `column`, centred on its height and cut short to its width; whether it was cut +fn column_text(ui: &Ui, column: Rect, text: String, size: f32, color: Color32) -> bool { + let galley = elided(ui.painter(), text, size, color, column.width()); + let cut_short = galley.elided; + ui.painter().galley(pos2(column.left(), column.center().y - galley.size().y / 2.0), galley, color); + cut_short +} + +/// The hairline under `row`, inside the side padding +fn rule(ui: &Ui, row: Rect) { + let tokens = Tokens::get(ui.ctx()); + let x = row.left() + SIDE_PADDING_POINTS..=row.right() - SIDE_PADDING_POINTS; + ui.painter().hline(x, row.bottom() - 0.5, Stroke::new(1.0, tokens.separator)); +} + +/// A pair's row: the low poly part, then the high poly part; a side with no partner is a warning glyph that tells why on hover +fn pair_row(ui: &mut Ui, pair: &NamePair) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let no_match = tr("No match"); + let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match)); + let reason = match (&pair.low, &pair.high) { + (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), + (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), + _ => None, + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); + super::describe(ui, &response, reason.as_deref()); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let mut cut_short = false; + for (column, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { + match part { + Some(part) => cut_short |= column_text(ui, column, part.clone(), NAME_SIZE, tokens.text), + None => { + painter.text(pos2(column.left(), column.center().y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning); + } + } + } + rule(ui, rect); + + // A name cut short shows in full on hover; the row's label carries it in full already + if reason.is_some() || cut_short { + response.on_hover_ui(|ui| { + if cut_short { + ui.label(egui::RichText::new(&name).size(NAME_SIZE).color(tokens.text)); + } + if let Some(reason) = reason { + ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Names longer than their column, in a list as narrow as a small docked log + #[test] + fn long_names_stay_in_their_own_column() { + let long = |side: &str| format!("Left_shoulder_strap_buckle_with_its_rivets_and_stitching_{side}"); + let matching = BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![NamePair { low: Some(long("low")), high: Some(long("high")) }], + }; + let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(320.0, 200.0)); + let context = egui::Context::default(); + let mut output = context.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| matching_list(ui, &matching, false)); + output.textures_delta.clear(); + + let texts: Vec = output + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(text.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert_eq!(texts.len(), 4, "two captions and two names"); + for (index, text) in texts.iter().enumerate() { + assert!(screen.contains_rect(*text), "text {index} {text:?} stays inside the list"); + for other in &texts[index + 1..] { + assert!(!text.intersects(*other), "text {index} {text:?} runs into {other:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 79050e12..8359fbe9 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -9,7 +9,7 @@ //! - `ui.menu.list`: the menu catalog with ids, shortcuts and whether each is live. //! - `ui.menu.invoke {id}`: behave like a menu click (may open a window; `ui.resetUi` asks first). //! `{id: "ui.layout.apply", name}` switches to the saved panel layout `name` (an error when there is none). -//! - `ui.reset`: reset the panels and every view setting at once, without the question the menu asks. +//! - `ui.reset`: reset the panels, view settings and interface language at once, without the question the menu asks. //! - `ui.set {...}`: merge fields into the UI state (e.g. `{"layout":"Only3D"}`). //! - `viewport.screenshot {view?: "3d"|"2d"}`: PNG of a viewport, base64. //! - `ui.screenshot`: PNG of the whole window (replies after the next frame). @@ -111,6 +111,12 @@ fn refresh_draft_preferences(draft: &mut Prefs, previous: &Prefs, current: &Pref gpu_raytracing, libraries, background, + show_world_axes, + show_keyboard_helper, + only_selected_material_when_painting, + save_preprocessed_scene_files, + live_preview_baking, + local_cache_directory, ); } @@ -142,6 +148,12 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para }, "command.run" => { let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") }; + + #[cfg(not(target_arch = "wasm32"))] + if app.save_job.is_some() && crate::manual_save::is_save(id) { + return err("A manual project save is already running"); + } + let command_params = params.get("params").cloned().unwrap_or(Value::Null); let before = app.session.camera; match texturecraft_engine::execute(&mut app.session, id, &command_params) { @@ -249,7 +261,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para // What Window > Reset UI does once the question is answered with Reset "ui.reset" => { - app.ui.adopt_layout(crate::UiState::default()); + app.ui.reset_ui(); ok(Value::Null) } "ui.set" => { diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs index 1f244d3e..837e3c98 100644 --- a/crates/ui-egui/src/display_settings.rs +++ b/crates/ui-egui/src/display_settings.rs @@ -43,7 +43,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { 0 => import_hdr = environment(app, ui, &mut display), 1 => camera(app, ui, &mut display), 2 => post_effects(ui, &mut display), - 3 => render_settings(ui, &mut display), + 3 => render_settings(app, ui, &mut display), _ => visualization(app, ui, &mut display), }); @@ -57,8 +57,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } app.session.doc.project.display = display; - app.session.modified = true; - app.session.revision = app.session.revision.wrapping_add(1); + app.session.mark_modified(); } if import_hdr { @@ -255,9 +254,19 @@ fn post_effects(ui: &mut Ui, display: &mut DisplaySettings) { } } -/// Temporal anti-aliasing -fn render_settings(ui: &mut Ui, display: &mut DisplaySettings) { +/// Temporal anti-aliasing and the viewport texture resolution (an app setting, not the project's) +fn render_settings(app: &mut TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) { ui.checkbox(&mut display.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)")); + ui.horizontal(|ui| { + ui.label(tr("Texture resolution")); + for (value, label) in [(0_u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] { + ui.selectable_value(&mut app.ui.prefs.viewport_texture, value, label); + } + }) + .response + .on_hover_text(tr( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + )); } /// The mesh wireframe and the single-channel views diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 4226e057..57c15011 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,7 +6,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, + BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Project, Projection, Sampling, Source, }; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; @@ -157,6 +157,13 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { app.session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.iter().rev().copied().collect()).unwrap_or_default(); let now = ui.input(|input| input.time); app.layer_panel.begin(&app.session, now); + let selected_stack = app.session.selected_layer().map(|layer| (layer, !targets_content(app))); + if matches!(app.session.target, StackTarget::Effect(_)) { + app.layer_panel.expanded_effects = selected_stack; + } else if app.layer_panel.expanded_effects != selected_stack { + app.layer_panel.expanded_effects = None; + } + egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { let mut count = 0; for id in stack { @@ -187,11 +194,30 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let material = response.dnd_hover_payload::().is_some_and(|drag| drag.asset.is_material()); if response.dnd_hover_payload::().is_some() || material { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent)); + crate::shelf_drag_ghost::accept(ui.ctx()); } }); select_all_layers(app, ui); } +/// Close the name editor when its effect leaves the open stack, even while the panel is hidden. +pub(crate) fn finish_hidden_effect_rename(app: &mut TextureCraftApp) { + if let Some((id, _)) = &app.ui.rename + && !app.session.doc.project.layers.contains_key(&LayerId(*id)) + && app.layer_panel.expanded_effects.is_none_or(|(layer, in_mask)| { + let project = &app.session.doc.project; + let effects = if in_mask { + mask_effects(project, layer) + } else { + project.layers.get(&layer).map(|layer| layer.content_effects.as_slice()).unwrap_or_default() + }; + !effects.iter().any(|effect| effect.id.0 == *id) + }) + { + finish_effect_rename(app); + } +} + /// Ctrl+A (Cmd+A on macOS) with the pointer over the Layers panel selects every row shown in the /// active texture set (folder rows and the layers of open folders). A focused text field (a /// rename, a number field) keeps the key for itself, and the key is left alone over other panels. @@ -286,6 +312,9 @@ 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 effect disclosure's square and glyph sizes in points. +const EFFECT_DISCLOSURE_SIZE: f32 = 13.0; +const EFFECT_DISCLOSURE_FONT_SIZE: f32 = 10.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; @@ -344,15 +373,6 @@ 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 @@ -362,8 +382,6 @@ const MAX_LAYER_TREE_DEPTH: usize = 12; const DROP_STROKE: f32 = 2.0; /// 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) { @@ -382,11 +400,6 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { (Rect::from_min_max(pos2(left, rect.top() + 4.0), pos2(name_right.max(left), rect.bottom() - 4.0)), show_blend) } -/// Whether `text` at font `size` is wider than `width`, so a row shows it shortened. -fn text_is_cut(painter: &egui::Painter, text: &str, size: f32, width: f32) -> bool { - painter.layout_no_wrap(text.to_owned(), egui::FontId::proportional(size), Color32::WHITE).size().x > width -} - /// 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)) @@ -397,18 +410,33 @@ fn level_x(left: f32, level: usize) -> f32 { left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5 } +/// The effects of the mask the layer draws with, including a mask inherited from its source. +fn mask_effects(project: &Project, layer: LayerId) -> &[Effect] { + project.layers.get(&project.mask_owner(layer)).and_then(|owner| owner.mask.as_ref()).map_or(&[], |mask| mask.effects.as_slice()) +} + 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 }; 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 mask_effects > 0 { - effect_group(app, ui, &layer, depth, true, false); + + if let Some((open_layer, in_mask)) = app.layer_panel.expanded_effects + && open_layer == id + { + // Read the mask after the layer row has handled its controls + let mask_snapshot; + let stack: &[Effect] = if in_mask { + mask_snapshot = mask_effects(&app.session.doc.project, id).to_vec(); + &mask_snapshot + } else { + &layer.content_effects + }; + + for (index, effect) in stack.iter().rev().enumerate() { + effect_row(app, ui, &layer, stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask); + } } // A line under the layer and its effects separates it from the next layer @@ -425,13 +453,17 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, } } -/// 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 { +/// Draw a visible thumbnail over its well, using the fallback until its picture arrives. +fn draw_thumbnail(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool, fallback: impl FnOnce()) { + if !ui.is_rect_visible(rect) { + return; + } + 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). + // The checkerboard shows through 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 { @@ -440,16 +472,12 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget } } - // 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) - { + if 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; + } else { + fallback(); } - - false } /// The row of `layer` at folder depth `depth`, the `index`th row of the stack (rows alternate shades). @@ -462,7 +490,8 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize 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()); + let (_, rect) = ui.allocate_space(vec2(ui.available_width(), row_height)); + let row = ui.interact(rect, ui.scope_id().with(("layer_row", layer.id.0)), Sense::click_and_drag()); row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name)); let painter = ui.painter().clone(); @@ -504,7 +533,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize painter.rect_stroke(rect.shrink(SOLO_OUTLINE_WIDTH * 0.5), 0.0, Stroke::new(SOLO_OUTLINE_WIDTH, tokens.warning), egui::StrokeKind::Inside); } - // 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_ui(|ui| { @@ -557,23 +585,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize // 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); - } + draw_thumbnail(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible, || { + content_glyph(&painter, &tokens, thumbnail, layer) + }); let content_label = tr("Select the layer content"); let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(content_label); painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); + let content_stack = (!layer.content_effects.is_empty()).then_some((layer.id, false)); if content_response.clicked() { let modifiers = ui.input(|input| input.modifiers); click_layer(app, modifiers, layer.id.0, Some("content")); + if !modifiers.shift && !modifiers.command { + app.layer_panel.toggle_effects(content_stack); + } + if !modifiers.alt && matches!(app.session.view, texturecraft_engine::ViewMode::Mask(_)) { app.run("viewport.view", json!({"mode": "material"})); } } thumbnail_context_menu(ui, &content_response, content_label, &layer.name, content_target, |ui| layer_context_menu(app, ui, layer, true)); + effect_stack_thumbnail(app, &painter, &tokens, &content_response, content_stack); x = thumbnail.right() + THUMBNAIL_SPACING; @@ -596,6 +630,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); let mask_label = tr("Select the mask (Alt+click: show it in the viewport, Shift+click: switch it on or off)"); let mask_response = ui.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()).on_hover_text(mask_label); + let mask_stack = (mask_effect_count > 0).then_some((layer.id, true)); if mask_response.clicked() { let modifiers = ui.input(|input| input.modifiers); if modifiers.shift && !modifiers.alt { @@ -610,11 +645,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize 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); + } else { + app.layer_panel.toggle_effects(mask_stack); } } } - if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask_enabled) { + draw_thumbnail(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_effect_count > 0 { @@ -626,13 +663,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize 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)); } - thumbnail_context_menu(ui, &mask_response, mask_label, &layer.name, mask_target, |ui| mask_management_menu(app, ui, layer, true)); + effect_stack_thumbnail(app, &painter, &tokens, &mask_response, mask_stack); ui.ctx().accesskit_node_builder(mask_response.id, |node| node.set_description(if mask_enabled { tr("Mask on") } else { tr("Mask off") })); if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { @@ -693,6 +730,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } 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()); + let name_elided = galley.elided; 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", @@ -707,14 +745,12 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize (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()); // A name or subtitle cut short by a narrow panel is shown in full on hover - if text_is_cut(&painter, &layer.name, LAYER_NAME_FONT_SIZE, name_rect.width()) - || text_is_cut(&painter, &subtitle, LAYER_SUBTITLE_FONT_SIZE, name_rect.width()) - { - row.clone().on_hover_text(format!("{}\n{subtitle}", layer.name)); + if name_elided || subtitle.elided { + row.clone().on_hover_text(format!("{}\n{}", layer.name, subtitle.text())); } - 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); } @@ -751,12 +787,14 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let modifiers = ui.input(|input| input.modifiers); if row.clicked() && !on_control && !renaming { click_layer(app, modifiers, layer.id.0, None); + app.layer_panel.expanded_effects = None; } if row.double_clicked() && !on_control && !renaming && show_name && !modifiers.shift && !modifiers.command { app.ui.rename = Some((layer.id.0, layer.name.clone())); } if row.drag_started() && !renaming { row.dnd_set_drag_payload(layer.id.0); + crate::shelf_drag_ghost::start_layer(ui.ctx(), &layer.name); } // A folder midpoint accepts child drops; a smart mask replaces the current mask @@ -771,6 +809,11 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(app, *dragged)); let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); + let shelf_mask = matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))); + let shelf_filter = matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group(); + if moving || shelf_material || shelf_mask || shelf_filter { + crate::shelf_drag_ghost::accept(&row.ctx); + } if moving || shelf_material { if inside { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); @@ -779,9 +822,9 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } else { painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } - } else if matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))) { + } else if shelf_mask { 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() { + } else if shelf_filter { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } if let Some(dragged) = dnd_release::(&row) @@ -869,73 +912,39 @@ fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) { } } -/// 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); - } - if folded { +/// Draw the effect disclosure on its thumbnail and expose the same state to AccessKit. +fn effect_stack_thumbnail(app: &TextureCraftApp, painter: &egui::Painter, tokens: &Tokens, response: &egui::Response, stack: Option<(LayerId, bool)>) { + let Some(stack) = stack else { return }; + let expanded = app.layer_panel.expanded_effects == Some(stack); + response.ctx.accesskit_node_builder(response.id, |node| node.set_expanded(expanded)); + if response.rect.width() < EFFECT_DISCLOSURE_SIZE { 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); - } + let size = vec2(EFFECT_DISCLOSURE_SIZE, EFFECT_DISCLOSURE_SIZE); + let badge = Rect::from_min_size(response.rect.max - size, size); + painter.rect_filled(badge, THUMBNAIL_ROUNDING, tokens.button); + painter.text( + badge.center(), + egui::Align2::CENTER_CENTER, + if expanded { ic::CARET_DOWN } else { ic::CARET_RIGHT }, + egui::FontId::proportional(EFFECT_DISCLOSURE_FONT_SIZE), + tokens.text_strong, + ); } -/// 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) { +/// Draw the line along the open effect stack and a branch to this row. +fn effect_tree_line(painter: &egui::Painter, tokens: &Tokens, rect: Rect, indent: f32, continues: 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); - } - } - 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); + + const BRANCH_WIDTH: f32 = INDENT * 0.6; + let stroke = Stroke::new(FOLDER_LINE_WIDTH, tokens.button_border); + let x = level_x(rect.left() + indent - INDENT, 0); + let end = if continues { rect.bottom() } else { rect.center().y }; + painter.vline(x, rect.top()..=end, stroke); + painter.hline(x..=x + BRANCH_WIDTH, rect.center().y, stroke); } /// The drag-and-drop payload of an effect row (the effect id). @@ -1018,7 +1027,6 @@ fn effect_row( effect: &Effect, row_index: usize, level: usize, - trunks: &[usize], last: bool, in_mask: bool, ) { @@ -1027,13 +1035,13 @@ fn effect_row( 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()); + let (_, rect) = ui.allocate_space(vec2(ui.available_width(), effect_row_height(layer_preview))); + let row = ui.interact(rect, ui.scope_id().with(("effect_row", effect_id.0)), 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 + // Alternate the shades of unselected rows from the top of the stack let background = if selected { tokens.row_selected } else if row.hovered() { @@ -1043,12 +1051,12 @@ fn effect_row( }; 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); + effect_tree_line(&painter, &tokens, rect, indent, !last); if selected { painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent); } - // The eye, then the stack as it is up to and including this effect (a hidden one shows what it bypasses) + // Hidden effects preview the result that bypasses them 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")); @@ -1059,16 +1067,16 @@ fn effect_row( // Content rows edit the displayed channel's blend let row_channel = (!in_mask && !app.ui.layer_material_view).then_some(channel); - if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) { + draw_thumbnail(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); - } + }); 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)); } - // The name, then the blend mode and opacity side by side at the right when the name keeps room to be read + // Hide blend controls when the name needs the room 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; @@ -1078,13 +1086,13 @@ fn effect_row( if renaming { let half_height = EFFECT_NAME_EDIT_HEIGHT * 0.5; let name_rect = Rect::from_min_max(pos2(name_left, rect.center().y - half_height), pos2(name_right, rect.center().y + half_height)); - effect_rename_editor(app, ui, name_rect, effect); + effect_rename_editor(app, ui, name_rect); } else { let name_width = (name_right - name_left).max(MIN_NAME_WIDTH); - if text_is_cut(&painter, &effect.name, EFFECT_NAME_FONT_SIZE, name_width) { + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, name_width); + if galley.elided { row.clone().on_hover_text(&effect.name); } - let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, name_width); painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); } if show_blend { @@ -1113,7 +1121,7 @@ fn effect_row( 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 + // The half of the target row under the pointer determines the insertion side if row.drag_started() { row.dnd_set_drag_payload(EffectDrag(effect_id.0)); } @@ -1159,7 +1167,7 @@ fn effect_row( button = button.shortcut_text(shortcut); } if ui.add_enabled(enabled, button).clicked() { - // Selected first: a paste lands above it, a duplicate takes the selection + // Select the row so it anchors a paste and its duplicate takes focus app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); app.run(command, json!({"effect": effect_id.0})); ui.close(); @@ -1194,8 +1202,8 @@ fn effect_row( }); } -/// The name editor of `effect` in `rect`: Enter or a click elsewhere renames, Escape cancels. -fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effect: &Effect) { +/// The effect name editor: Enter or a click elsewhere renames, Escape cancels. +fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center))); let Some((_, name_buffer)) = app.ui.rename.as_mut() else { return }; @@ -1206,17 +1214,22 @@ fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effe if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; } else if response.lost_focus() { - let name = name_buffer.trim().to_string(); - app.ui.rename = None; - if !name.is_empty() && name != effect.name { - app.run("effect.set", json!({"effect": effect.id.0, "name": name})); - } + finish_effect_rename(app); } else if !response.has_focus() { // Only until the field has focus (see the layer rename editor) response.request_focus(); } } +fn finish_effect_rename(app: &mut TextureCraftApp) { + let Some((id, name)) = app.ui.rename.take() else { return }; + + let name = name.trim(); + if !name.is_empty() && app.session.doc.project.effect(LayerId(id)).is_some_and(|(_, effect)| name != effect.name) { + app.run("effect.set", json!({"effect": id, "name": name})); + } +} + /// The Geometry mask tool: what a click does, and the selected layer's parts. fn geometry_tool_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); @@ -1373,7 +1386,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con let layer_id = layer.id.0; let keymap = app.ui.keymap.clone(); - // The row menu can act on several selected layers. A thumbnail identifies one layer. + // A thumbnail menu always acts on its own layer let several = if content_thumbnail { None } else { selection_with(app, layer.id) }; let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, params: Value, enabled: bool| { let mut button = egui::Button::new(label); @@ -1466,7 +1479,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con /// Mask management is available from the row and directly from the mask thumbnail. fn mask_management_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, mask_thumbnail: bool) { - // An instance inherits its source mask until it has its own. + // An instance inherits its source mask until it has its own let project = &app.session.doc.project; let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()); let (has_mask, mask_on) = (mask.is_some(), mask.is_some_and(|mask| mask.enabled)); @@ -1820,7 +1833,7 @@ pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { return None; } - ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, Tokens::get(ui.ctx()).accent), egui::StrokeKind::Inside); + crate::shelf_drag_ghost::outline_target(ui, resp.rect); match dnd_release::(resp).map(|d| d.asset.clone()) { Some(Asset::Texture(name)) => Some(name), _ => None, @@ -2781,12 +2794,12 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn open_link_in_materialcraft(app: &mut TextureCraftApp, layer: LayerId, link: &texturecraft_engine::core::MaterialLink) { 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 file_name = format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name)); let opened = app .session .link_package(layer) - .and_then(|package| std::fs::write(&path, package.as_slice()).map_err(|err| texturecraft_engine::EngineError::Other(err.to_string()))) - .and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); + .and_then(|package| texturecraft_engine::link_cmds::stage_handoff_package(&file_name, package.as_slice())) + .and_then(|path| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); match opened { Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false), Err(e) => app.toast(e.to_string(), true), diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 6c4f5f97..f6a7928f 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -28,6 +28,8 @@ use crate::theme::Tokens; pub enum Panel { Viewport, Assets, + /// A second Assets panel with its own search, type and folder (the Assets panel's folder button) + AssetsSecond, // Saved layouts name the bake panels by their earlier names #[serde(rename = "BakeMaps")] MeshMapSettings, @@ -81,7 +83,7 @@ impl Panel { use crate::state::Mode; match self { Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers | Self::BakingLog => mode == Mode::Baking, - Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting, + Self::Assets | Self::AssetsSecond | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting, Self::History => mode != Mode::Rendering, Self::Shader => mode != Mode::Baking, Self::Renderer => mode == Mode::Rendering, @@ -89,9 +91,10 @@ impl Panel { } } - pub const ALL: [Panel; 16] = [ + pub const ALL: [Panel; 17] = [ Panel::Viewport, Panel::Assets, + Panel::AssetsSecond, Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, @@ -112,6 +115,8 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", + // The second panel shows every type at first, so it's named for that, as the reference names it + Panel::AssetsSecond => "All", Panel::MeshMapSettings => "Mesh Map Settings", Panel::CommonSettings => "Common Settings", Panel::MeshMapBakers => "Mesh Map Bakers", @@ -186,8 +191,8 @@ pub fn default_workspace() -> Workspace { split(Axis::X, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column), ); let mut hidden: Vec<(Panel, Location)> = Panel::ALL.into_iter().filter_map(|panel| Some((panel, floating_location(panel.float_rect()?)))).collect(); - for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { - hidden.push((panel, Location::new(Some(TextureSetList), DockPlacement::tab(None)))); + for (panel, anchor) in [(MeshMapSettings, TextureSetList), (CommonSettings, TextureSetList), (MeshMapBakers, TextureSetList), (AssetsSecond, Assets)] { + hidden.push((panel, Location::new(Some(anchor), DockPlacement::tab(None)))); } Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, Vec::new()) @@ -308,27 +313,28 @@ impl Dock { self.replaced_unreadable } - /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport + /// Texture sets over the bakers, the two settings tabs, the Baking Log under both, then the viewport pub(crate) fn for_baking() -> Self { let painting = default_workspace(); let mut hidden = painting.hidden().to_vec(); - for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { + for panel in [Panel::Assets, Panel::AssetsSecond, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { if let Ok(location) = painting.layout().location(&panel) { hidden.push((panel, location)); } } - let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; + let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::BakingLog]; hidden.retain(|(panel, _)| !bake_panels.contains(panel)); let gutter_width = f32::from(crate::theme::GUTTER); let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); let columns = split(Axis::X, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); - let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::BakingLog])); let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec()); + Dock { workspace, raise: None, replaced_unreadable: false } } @@ -391,27 +397,34 @@ impl Dock { } } -/// What the dock area keeps between passes: the workspace it shows and the panels' specs. +/// What the dock area keeps between passes: the workspace it shows and the panels' specs #[derive(Default)] pub(crate) struct LiveDock { shown: Option>, specs: Tracked, - /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window. + /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window continue_move: Option<(Panel, egui::Vec2)>, + /// The OS windows of the floating panels, as the last pass's dock drew them + floating_windows: Vec, } impl LiveDock { - /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`. + /// The OS windows the last pass's dock drew floating panels in + pub(crate) fn floating_windows(&self) -> &[ViewportId] { + &self.floating_windows + } + + /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab` pub(crate) fn hand_over(&mut self, panel: Panel, grab: egui::Vec2) { self.continue_move = Some((panel, grab)); } - /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, - /// so an idle pass keeps the workspace's revision and the dock reads no spec. + /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, so an idle pass reads no spec fn shown(&mut self, workspace: &Workspace) -> Arc { if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) { return Arc::clone(shown); } + let shown = Arc::new(workspace.clone()); self.shown = Some(Arc::clone(&shown)); shown @@ -470,7 +483,7 @@ pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> b modal } -/// Draw the dock (viewport and panels) into `ui`. +/// Draw the dock (viewport and panels) into `ui` pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { // Rendering keeps disabled panels visible because it shares the painting dock let dock_mode = if app.ui.mode == crate::state::Mode::Rendering { crate::state::Mode::Painting } else { app.ui.mode }; @@ -484,12 +497,13 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let context = ui.ctx().clone(); refresh_specs(app); let shown = app.docks.shown(&app.ui.dock.workspace); - // The specs leave the app while its panels borrow it, and come back with their revision. + + // Move the specs out so the dock can borrow the app to draw panels let specs = std::mem::take(&mut app.docks.specs); let hand_over = app.docks.continue_move.take(); let raise = app.ui.dock.raise.take(); - // Panels arrange in a split tree around the viewport; floating title bars only move windows. - // Each closable tab has its close button, as each group header had one for its shown panel. + + // Keep drag targets on the dock so a floating title bar only moves its window let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false).tab_close_buttons(true); let (output, focused_windows) = { let tokens = Tokens::get(&context); @@ -504,7 +518,10 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let output = area.show(ui); (output, panels.focused_windows) }; + app.docks.specs = specs; + app.docks.floating_windows.clear(); + app.docks.floating_windows.extend(output.windows.iter().map(|(_, viewport)| *viewport)); // The popup needs the viewport the dock recorded this frame crate::rail_popup::show(app, &context); @@ -517,6 +534,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { } #[cfg(target_arch = "wasm32")] let _ = focused_windows; + if let Some(error) = &output.error { log::warn!("docking: {:?}", error.error); } @@ -589,7 +607,8 @@ fn min_size(panel: Panel) -> Vec2 { /// 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) { // No project open: the library and the log work, the other panels about a project stay empty - let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export); + let works_empty = + matches!(panel, Panel::Assets | Panel::AssetsSecond | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export); if !app.session.project_open && !works_empty { return; } @@ -599,6 +618,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { egui::Frame::new().inner_margin(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::AssetsSecond => crate::shelf_second::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), @@ -612,13 +632,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::Shader => crate::shader_settings::body(app, ui), Panel::History => crate::windows::history(app, ui), Panel::Log => crate::log_panel::body(app, ui), - Panel::BakingLog => { - egui::ScrollArea::vertical().show(ui, |ui| { - for entry in app.session.log.entries().iter().filter(|entry| entry.source == "Baker") { - ui.label(entry.line()); - } - }); - } + Panel::BakingLog => crate::baking_log::body(app, ui), Panel::Export => crate::export_panel::body(app, ui), Panel::Renderer => crate::render_mode::settings_body(app, ui), Panel::Viewport => {} @@ -759,16 +773,17 @@ mod tests { } #[test] - fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { + fn the_bake_dock_round_trips_with_the_baking_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] + [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::BakingLog, 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); } diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 7fd10cc4..aa7f223d 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -4,7 +4,7 @@ //! Maps dragged from the Input maps, Mesh maps and Converted maps panes onto an output map's //! channel swatches fill its channels. -use egui::{Color32, RichText, Ui, vec2}; +use egui::{Color32, Rect, RichText, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{BakedMap, Channel}; @@ -12,15 +12,20 @@ use texturecraft_engine::formats::export::{FILE_TOKENS, MAX_PRESET_NAME, sanitiz use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap}; use crate::TextureCraftApp; +use crate::export_window::{ExportLook, GUTTER, TAB_ROW_HEIGHT, drawn, template_label}; use crate::i18n::{n_, tr, trf}; -use crate::theme::{Tokens, caption}; +use crate::theme::Tokens; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::{chip, icon_button_without_tooltip}; +use crate::widgets::chip; mod channel_target; mod map_drag; mod map_lists; +mod map_preview_cache; +mod map_preview_pictures; +mod output_card; mod pending_drop; +mod planned_output; mod row_edit; mod source_pick; mod swatch_look; @@ -28,83 +33,197 @@ mod swatch_look; pub use channel_target::ChannelTarget; use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; +use map_preview_cache::MapPreviewCache; +use map_preview_pictures::MapPreviewPictures; +use output_card::OutputCard; pub use pending_drop::PendingDrop; +use planned_output::PlannedOutput; use row_edit::RowEdit; use source_pick::SourcePick; use swatch_look::SwatchLook; -const ICON_POINTS: f32 = 20.0; -/// Width of the Presets list -const LIST_WIDTH_POINTS: f32 = 220.0; -/// The tab's width in the reference-size window: a narrower window narrows the side panes in -/// proportion, so the output rows keep their room -const REFERENCE_TAB_WIDTH_POINTS: f32 = 1085.0; -/// The middle column's least width, and room for the separators and their spacing -const MIN_OUTPUTS_WIDTH_POINTS: f32 = 200.0; -const SEPARATOR_ALLOWANCE_POINTS: f32 = 6.0; -/// Width of the Input maps pane -const INPUTS_WIDTH_POINTS: f32 = 170.0; -/// Width of the pane with Mesh maps above Converted maps -const SIDE_MAPS_WIDTH_POINTS: f32 = 165.0; -/// Share of the side pane's height that Mesh maps take; Converted maps get the rest -const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; -/// The name "+" gives a new template, as in the reference +/// Initial name for a new template const NEW_PRESET: &str = "new_export_preset"; -/// Height of a Presets list row, and where its icon and name start -const PRESET_ROW_HEIGHT_POINTS: f32 = 18.0; -const PRESET_ICON_INDENT_POINTS: f32 = 2.0; -const PRESET_TEXT_INDENT_POINTS: f32 = 20.0; +// Layout in points from the window content's top left corner, the side panes from its right edge, measured on the locked mock -/// Height of a map list entry, the gap between entries, and where its marker and name sit -const ENTRY_HEIGHT_POINTS: f32 = 21.0; -const ENTRY_GAP_POINTS: f32 = 2.0; -const ENTRY_TEXT_INDENT_POINTS: f32 = 22.0; -const ENTRY_TEXT_SIZE_POINTS: f32 = 12.0; -const MARKER_INDENT_POINTS: f32 = 10.0; -const MARKER_SIZE_POINTS: f32 = 10.0; +/// Width of the Presets column +const PRESETS_WIDTH: f32 = 216.2; +/// Middle of the column titles +const HEADER_Y: f32 = 73.0; +/// Centre of the Presets header's first glyph, from the column's right edge +const PRESET_ICON_FROM_RIGHT: f32 = 14.0; +/// Step between the Presets header's glyphs +const PRESET_ICON_STEP: f32 = 22.0; +/// Size of the Presets header's glyphs +const PRESET_ICON_SIZE: f32 = 13.0; +/// Top of the lists under the titles +const LIST_TOP: f32 = 88.0; +/// Height of a Presets row +const PRESET_ROW_HEIGHT: f32 = 20.0; +/// Centre of a Presets row's file glyph +const PRESET_ICON_X: f32 = 16.0; +/// Where a Presets row's name starts +const PRESET_NAME_LEFT: f32 = 26.3; +/// Size of a Presets row's file glyph +const PRESET_ROW_ICON_SIZE: f32 = 12.0; +/// The column titles' left edge, inside their column +const TITLE_INDENT: f32 = 7.5; + +/// The middle column's margin to the dividers on both sides +const MIDDLE_MARGIN: f32 = 10.0; +/// Middle of the Current preset line +const CURRENT_PRESET_Y: f32 = 69.0; +/// Gap after "Current preset:" +const NAME_GAP: f32 = 5.0; +/// From the template's name to its lock's centre +const LOCK_GAP: f32 = 12.0; +/// Middle of the Output maps row +const OUTPUT_MAPS_Y: f32 = 106.0; +/// The air around a Create button's name +const CREATE_PADDING: f32 = 22.0; +/// Gap between the Create buttons +const CREATE_GAP: f32 = 6.0; +/// Gap before "Create:" +const CREATE_LABEL_GAP: f32 = 2.0; +/// Top of the first output map card +const CARDS_TOP: f32 = 127.0; +/// The count strip's top, above the body's bottom +const COUNT_TOP_ABOVE_BOTTOM: f32 = 24.0; +/// The count strip's bottom, above the body's bottom +const COUNT_BOTTOM_ABOVE_BOTTOM: f32 = 1.0; +/// The count's indent in its strip +const COUNT_TEXT_INDENT: f32 = 6.0; + +/// Height of an output map card +const CARD_HEIGHT: f32 = 48.0; +/// Gap below a card +const CARD_GAP: f32 = 6.0; +/// Corner radius of a card +const CARD_RADIUS: u8 = 3; +/// Inset of a card's swatches from its top and bottom +const CARD_INSET: f32 = 6.0; +/// Centre of a card's grip +const GRIP_X: f32 = 10.0; +/// Width of the grip's click area +const GRIP_WIDTH: f32 = 16.0; +/// Size of the grip's glyph +const GRIP_SIZE: f32 = 14.0; +/// Where a card's file name field starts +const NAME_FIELD_LEFT: f32 = 20.0; +/// Width of the file name field +const NAME_FIELD_WIDTH: f32 = 150.0; +/// The file name field's least width in a narrow window +const MIN_NAME_FIELD_WIDTH: f32 = 60.0; +/// Gap before the "$" button +const DOLLAR_GAP: f32 = 4.0; +/// Width of the "$" button +const DOLLAR_WIDTH: f32 = 22.0; +/// Gap between "$" and the swatches +const SWATCHES_GAP: f32 = 8.0; +/// The lists' and icons' rows, above and below the card's middle +const CARD_ROW_OFFSET: f32 = 10.0; +/// Centre of a card's icons, from its right edge +const CARD_ICON_FROM_RIGHT: f32 = 14.0; +/// From the icons to the lists' chevrons +const CARD_CHEVRON_STEP: f32 = 22.0; +/// Gap between a list's value and its chevron +const CARD_VALUE_GAP: f32 = 8.0; +/// Size of a card's icons +const CARD_ICON_SIZE: f32 = 12.0; +/// Values the cards' lists line up on, so cards with shorter ones keep the same column +const CARD_VALUE_SAMPLES: [&str; 3] = ["png", "8 bits", "16 bits"]; + +/// The Input maps divider, from the window's right edge +const INPUTS_DIVIDER_FROM_RIGHT: f32 = 342.3; +/// The Mesh maps divider, from the window's right edge +const SIDE_DIVIDER_FROM_RIGHT: f32 = 161.9; +/// Where the Input maps pane starts after its divider +const PANE_FROM_DIVIDER: f32 = 2.0; +/// Where it ends before the next one +const INPUTS_END_BEFORE_DIVIDER: f32 = 3.5; +/// Where the Mesh maps pane starts after its divider +const SIDE_PANE_FROM_DIVIDER: f32 = 4.0; +/// The divider between Mesh maps and Converted maps, below the body's middle +const SIDE_SPLIT_BELOW_MIDDLE: f32 = 10.0; +/// Gap between Mesh maps' last row and that divider +const MESH_BOTTOM_GAP: f32 = 6.0; +/// Middle of Converted maps' title, below the divider +const CONVERTED_TITLE_Y: f32 = 18.0; +/// Top of Converted maps' rows, below the divider +const CONVERTED_ROWS_TOP: f32 = 33.0; +/// A map entry's inset in its pane +const ENTRY_INSET: f32 = 3.0; +/// Height of a map entry +const ENTRY_HEIGHT: f32 = 20.0; +/// Pitch of the map entries +const ENTRY_PITCH: f32 = 21.0; +/// Height of a group's name row +const GROUP_HEIGHT: f32 = 18.0; +/// Indent of the titles and group names +const GROUP_INDENT: f32 = 4.0; +/// Where a used map's square starts +const MARKER_LEFT: f32 = 9.0; +/// Side of that square +const MARKER_SIZE: f32 = 10.0; +/// Its corner radius +const MARKER_RADIUS: u8 = 1; +/// How much lighter its edge is than its fill +const MARKER_EDGE_LIGHTEN: u8 = 40; +/// Where a map entry's name starts +const ENTRY_NAME_LEFT: f32 = 25.0; /// How strongly a map TextureCraft does not have yet is dimmed const UNAVAILABLE_FADE: f32 = 0.6; -/// An output map row: padding, gap below it, grip width, file name field width, icon size -const ROW_MARGIN_POINTS: f32 = 6.0; -const ROW_GAP_POINTS: f32 = 4.0; -const GRIP_WIDTH_POINTS: f32 = 5.0; -const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; -const ROW_ICON_POINTS: f32 = 16.0; -/// Width the "Output maps" title and the Create buttons need on one row -const OUTPUT_MAPS_ROW_WIDTH_POINTS: f32 = 420.0; -/// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a -/// row's right end, and the gaps between a row's controls (besides the swatches') -const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; -const DOLLAR_BUTTON_WIDTH_POINTS: f32 = 22.0; -const ROW_LISTS_WIDTH_POINTS: f32 = 100.0; -const ROW_GAPS: f32 = 4.0; -/// The accent frame around a drop target: its stroke and its gap to the target +/// Naming pattern's info glyph, from the window's right edge +const NAMING_INFO_FROM_RIGHT: f32 = 20.8; +/// Its dropdown's left edge, from the window's right edge +const NAMING_COMBO_LEFT_FROM_RIGHT: f32 = 182.4; +/// Its dropdown's right edge, from the window's right edge +const NAMING_COMBO_RIGHT_FROM_RIGHT: f32 = 34.0; +/// Its label's right edge, from the window's right edge +const NAMING_LABEL_FROM_RIGHT: f32 = 188.0; +/// Size of the info glyph +const INFO_SIZE: f32 = 14.0; + +/// The accent-free frame around a drop target: its stroke and its gap to the target const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; /// Side of the corner mark of an inverted swatch const INVERTED_MARK_POINTS: f32 = 8.0; +/// A swatch's file preview: the file's width, and the side of each channel's picture beside it +const PREVIEW_FILE_WIDTH_POINTS: f32 = 150.0; +const PREVIEW_CHANNEL_WIDTH_POINTS: f32 = 34.0; -/// A channel swatch: its side, the label's size and offset from the top, and the bars that show -/// which channels of the source it reads -const SWATCH_SIZE_POINTS: f32 = 32.0; -const SWATCH_TEXT_SIZE_POINTS: f32 = 11.0; -const SWATCH_TEXT_TOP_POINTS: f32 = 3.0; -const SWATCH_BAR_WIDTH_POINTS: f32 = 18.0; -const SWATCH_BAR_HEIGHT_POINTS: f32 = 2.0; -const SWATCH_BAR_BOTTOM_POINTS: f32 = 9.0; +/// Width of a channel swatch; its height is the card's less its inset +const SWATCH_WIDTH: f32 = 34.0; +/// Gap between swatches +const SWATCH_GAP: f32 = 2.0; +/// Middle of a swatch's letters, from its top +const SWATCH_LABEL_Y: f32 = 11.0; +/// A swatch's underline: its inset from the sides +const SWATCH_BAR_INSET: f32 = 6.0; +/// Its top, from the swatch's bottom +const SWATCH_BAR_BOTTOM: f32 = 10.0; +/// Its height +const SWATCH_BAR_HEIGHT: f32 = 2.0; -/// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to -/// keep the white label readable +/// Golden-ratio spacing keeps neighbouring map hues distinct const HUE_STEP: f32 = 0.618_034; const SWATCH_SATURATION: f32 = 0.45; -const SWATCH_VALUE_DARK: f32 = 0.42; -const SWATCH_VALUE_LIGHT: f32 = 0.62; +const SWATCH_VALUE: f32 = 0.42; -/// The bars of the R, G and B channels a swatch reads -const COMPONENT_COLORS: [Color32; 3] = [Color32::from_rgb(220, 70, 70), Color32::from_rgb(80, 190, 90), Color32::from_rgb(80, 120, 230)]; +/// The underline of R +const BAR_RED: Color32 = Color32::from_rgb(230, 70, 70); +/// The underline of G +const BAR_GREEN: Color32 = Color32::from_rgb(80, 200, 90); +/// The underline of B +const BAR_BLUE: Color32 = Color32::from_rgb(80, 130, 240); +/// The underline of A +const BAR_ALPHA: Color32 = Color32::from_rgb(220, 220, 220); +/// The underline of RGB and gray +const BAR_WHOLE: Color32 = Color32::WHITE; /// What a cleared channel writes: black, or opaque in the alpha channel const CLEARED_VALUE: f32 = 0.0; @@ -179,8 +298,6 @@ const CONSTANT_DRAG_SPEED: f64 = 0.005; /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; -/// Width of the Naming pattern list -const NAMING_PATTERN_WIDTH_POINTS: f32 = 150.0; /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { @@ -336,43 +453,50 @@ enum MapAction { Remove(usize), } -/// The Output templates tab: template list, the selected template's outputs, then the Input maps -/// pane and the pane with Mesh maps above Converted maps. -pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { +pub(crate) fn clear_map_previews(ctx: &egui::Context) { + MapPreviewCache::clear(ctx); +} + +/// The Output templates tab in `body`: presets, outputs, Input maps, then Mesh maps above Converted maps +pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, body: Rect, builtins: &[ExportPreset]) { + // Four swatches and the type menu share a row between the two map panes + const MIN_EDITOR_WIDTH: f32 = 960.0; + const MIN_EDITOR_HEIGHT: f32 = CARDS_TOP + 2.0 * CARD_HEIGHT + COUNT_TOP_ABOVE_BOTTOM; + let minimum = vec2(MIN_EDITOR_WIDTH, MIN_EDITOR_HEIGHT); + if body.width() >= minimum.x && body.height() >= minimum.y { + template_panes(app, ui, body, builtins); + return; + } + + ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { + egui::ScrollArea::both().id_salt("export_template_editor").auto_shrink([false; 2]).show(ui, |ui| { + let (content, _) = ui.allocate_exact_size(ui.available_size().max(minimum), egui::Sense::hover()); + template_panes(app, ui, content, builtins); + }); + }); +} + +fn template_panes(app: &mut TextureCraftApp, ui: &mut Ui, body: Rect, builtins: &[ExportPreset]) { sync_draft(app); - let height = ui.available_height(); + let top = body.top() - TAB_ROW_HEIGHT; let names = crate::export_window::template_groups(app, builtins).1; - let scale = (ui.available_width() / REFERENCE_TAB_WIDTH_POINTS).min(1.0); - let (list_width, inputs_width, side_width) = (LIST_WIDTH_POINTS * scale, INPUTS_WIDTH_POINTS * scale, SIDE_MAPS_WIDTH_POINTS * scale); - let mut list_action = None; - ui.vertical(|ui| { - ui.set_width(list_width); - ui.set_height(height); - list_action = preset_list(app, ui, &names); - }); - ui.separator(); - ui.vertical(|ui| { - // Leave room for the two map panes and three separators - let panes = inputs_width + side_width + 8.0 * ui.spacing().item_spacing.x + SEPARATOR_ALLOWANCE_POINTS; - ui.set_width((ui.available_width() - panes).max(MIN_OUTPUTS_WIDTH_POINTS)); - ui.set_height(height); - outputs(app, ui); - }); + let presets_right = body.left() + PRESETS_WIDTH; + let inputs_divider = body.right() - INPUTS_DIVIDER_FROM_RIGHT; + let side_divider = body.right() - SIDE_DIVIDER_FROM_RIGHT; + for x in [presets_right, inputs_divider, side_divider] { + drawn::divider(ui, Rect::from_min_max(pos2(x, body.top()), pos2(x + 1.0, body.bottom()))); + } + + let list_action = preset_list(app, ui, Rect::from_min_max(body.min, pos2(presets_right, body.bottom())), top, &names); + let middle = Rect::from_min_max(pos2(presets_right + 1.0 + MIDDLE_MARGIN, body.top()), pos2(inputs_divider - MIDDLE_MARGIN, body.bottom())); + ui.scope(|ui| outputs(app, ui, middle, top)); // The panes mark the maps the selected template's outputs read - let marked = marked_sources(app, &Tokens::get(ui.ctx())); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(inputs_width); - ui.set_height(height); - input_maps(ui, &marked); - }); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(side_width); - ui.set_height(height); - mesh_and_converted_maps(ui, height, &marked); - }); + let marked = marked_sources(app); + let inputs = Rect::from_min_max(pos2(inputs_divider + PANE_FROM_DIVIDER, body.top()), pos2(side_divider - INPUTS_END_BEFORE_DIVIDER, body.bottom())); + input_maps(ui, inputs, top, &marked); + let side = Rect::from_min_max(pos2(side_divider + SIDE_PANE_FROM_DIVIDER, body.top()), body.max); + mesh_and_converted_maps(ui, side, top, &marked); if let Some(a) = list_action { apply(app, ui.ctx(), a); } @@ -388,93 +512,105 @@ pub fn select(app: &mut TextureCraftApp, name: String) { } } -/// "Naming pattern" with its info icon, at the right end of the tab row (laid out right to left) -pub(crate) fn naming_pattern(ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { +/// "Naming pattern", its list and its info glyph at the tab row's right end +pub(crate) fn naming_pattern(ui: &mut Ui, window_right: f32, y: f32) { + let look = ExportLook::get(ui.ctx()); + let info_at = pos2(window_right - NAMING_INFO_FROM_RIGHT, y); + drawn::glyph(ui, info_at, ic::INFO, INFO_SIZE, look.text_dim); + let info = ui.interact(Rect::from_center_size(info_at, vec2(INFO_SIZE, INFO_SIZE)), ui.scope_id().with("exp_naming_info"), egui::Sense::hover()); + info.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, ic::INFO)); + info.on_hover_ui(|ui| { ui.label(tr("Choose how the input maps are named in this editor.")); ui.label(tr("The active texture set’s shader can affect the available map names.")); }); - egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + let combo = drawn::control_rect(window_right - NAMING_COMBO_LEFT_FROM_RIGHT, window_right - NAMING_COMBO_RIGHT_FROM_RIGHT, y); + drawn::combo(ui, combo, "exp_naming", NAMING_PATTERNS[0], |ui| { for p in NAMING_PATTERNS { let _ = ui.selectable_label(true, p); } }); - ui.label(tr("Naming pattern")); + let label = tr("Naming pattern"); + let left = window_right - NAMING_LABEL_FROM_RIGHT - drawn::text_width(ui, label, false); + drawn::label_at(ui, left, y, label, look.text, false); } -/// The Presets list: the templates sorted by name (built-in and user); a right click offers -/// Rename, Duplicate and Remove, F2 renames -fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Option { +/// The Presets list in `column` with its header's tools; a right click offers Rename, Duplicate and Remove, F2 renames +fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32, names: &[String]) -> Option { + let look = ExportLook::get(ui.ctx()); let mut act = None; - let sel = app.ui.export.preset.clone(); + let selected_name = app.ui.export.preset.clone(); let user = app.ui.export.draft.is_some(); - ui.horizontal(|ui| { - ui.label(caption(tr("Presets"))); + drawn::label_at(ui, column.left() + TITLE_INDENT, top + HEADER_Y, tr("Presets"), look.text, true); - // Copy, "−" and "+" from left to right, without tooltips as in the reference - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::New); - } - if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON_POINTS)).inner.clicked() - { - act = Some(ListAction::Remove(sel.clone())); - } - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::Duplicate(sel.clone())); - } - - // TextureCraft's template files: a focusable menu, as the row's right click is pointer only - let actions = icon_button_without_tooltip(ui, ic::DOTS_THREE, tr("Template actions"), false, ICON_POINTS); - let opened_now = actions.clicked(); - egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); - }); - }); - ui.add_space(2.0); - if std::mem::take(&mut app.ui.export.rename_key) && user { - act = Some(ListAction::StartRename(sel.clone())); + // Template actions, Duplicate, "−" and "+" from left to right, without tooltips as in the reference + let icon_at = |slot_from_right: f32| pos2(column.right() - PRESET_ICON_FROM_RIGHT - slot_from_right * PRESET_ICON_STEP, top + HEADER_Y); + if drawn::icon_button(ui, icon_at(0.0), ic::PLUS, PRESET_ICON_SIZE, tr("New template"), true, false).clicked() { + act = Some(ListAction::New); } - egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { - for name in names { - let is_user = app.session.export_presets.list.iter().any(|p| p.name == *name); - match app.ui.export.renaming.as_mut().filter(|_| *name == sel) { - Some(buf) => { - let r = ui.add(egui::TextEdit::singleline(buf).id(egui::Id::unique(RENAME_ID)).desired_width(f32::INFINITY)); - if r.lost_focus() { - act = Some(if ui.input(|i| i.key_pressed(egui::Key::Escape)) { - ListAction::Select(name.clone()) - } else { - ListAction::Rename(buf.clone()) + if drawn::icon_button(ui, icon_at(1.0), ic::MINUS, PRESET_ICON_SIZE, tr("Delete the selected template"), user, false).clicked() { + act = Some(ListAction::Remove(selected_name.clone())); + } + if drawn::icon_button(ui, icon_at(2.0), ic::COPY, PRESET_ICON_SIZE, tr("Duplicate the selected template"), true, false).clicked() { + act = Some(ListAction::Duplicate(selected_name.clone())); + } + + // TextureCraft's template files: a focusable menu, as the row's right click is pointer only + let actions = drawn::icon_button(ui, icon_at(3.0), ic::DOTS_THREE, PRESET_ICON_SIZE, tr("Template actions"), true, false); + let opened_now = actions.clicked(); + egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); + if std::mem::take(&mut app.ui.export.rename_key) && user { + act = Some(ListAction::StartRename(selected_name.clone())); + } + + // The rows scroll, the scroll bar in its strip at the column's right + let rows = Rect::from_min_max(pos2(column.left(), top + LIST_TOP), column.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + let width = rows.width() - GUTTER; + for name in names { + let is_user = app.session.export_presets.list.iter().any(|preset| preset.name == *name); + let (rect, _) = ui.allocate_exact_size(vec2(width, PRESET_ROW_HEIGHT), egui::Sense::hover()); + match app.ui.export.renaming.as_mut().filter(|_| *name == selected_name) { + Some(name_buffer) => { + let field = egui::TextEdit::singleline(name_buffer).id(egui::Id::unique(RENAME_ID)).margin(vec2(PRESET_NAME_LEFT, 0.0)); + let rename_field = ui.put(rect, field); + if rename_field.lost_focus() { + act = Some(if ui.input(|input| input.key_pressed(egui::Key::Escape)) { + ListAction::Select(name.clone()) + } else { + ListAction::Rename(name_buffer.clone()) + }); + } + } + None => { + let label = template_label(&app.session, name); + let response = preset_row(ui, rect, name, label, *name == selected_name, is_user).on_hover_text(name); + if response.double_clicked() && is_user { + act = Some(ListAction::StartRename(name.clone())); + } else if response.clicked() { + act = Some(ListAction::Select(name.clone())); + } + response.context_menu(|ui| { + let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); + if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::StartRename(name.clone())); + } + if ui.button(tr("Duplicate")).clicked() { + act = Some(ListAction::Duplicate(name.clone())); + } + if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::Remove(name.clone())); + } + + // TextureCraft's template files, after the reference's entries + ui.separator(); + template_file_items(ui, &mut act, *name == selected_name, false); }); } } - None => { - let r = preset_row(ui, name, *name == sel).on_hover_text(name); - if r.double_clicked() && is_user { - act = Some(ListAction::StartRename(name.clone())); - } else if r.clicked() { - act = Some(ListAction::Select(name.clone())); - } - r.context_menu(|ui| { - let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); - if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::StartRename(name.clone())); - } - if ui.button(tr("Duplicate")).clicked() { - act = Some(ListAction::Duplicate(name.clone())); - } - if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::Remove(name.clone())); - } - - // TextureCraft's template files, after the reference's entries - ui.separator(); - template_file_items(ui, &mut act, *name == sel, false); - }); - } } - } + }); }); act } @@ -497,25 +633,23 @@ fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: b } } -/// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in -/// the accent colour -fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT_POINTS), egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); - +/// A Presets row: a locked file glyph for a built-in template, the name cut with "…", the selected one in bold +fn preset_row(ui: &mut Ui, rect: Rect, name: &str, label: &str, selected: bool, is_user: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_preset_row", name)), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, label)); let painter = ui.painter(); - if response.hovered() { - painter.rect_filled(rect, tokens.radius, tokens.row_hover); + if selected { + painter.rect_filled(rect, 0.0, look.chrome); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, look.raised); } - let font = egui::TextStyle::Body.resolve(ui.style()); - painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT_POINTS, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); - let color = if selected { tokens.accent } else { tokens.text }; - let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); - job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT_POINTS); - let galley = painter.layout_job(job); - let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT_POINTS, rect.center().y - galley.size().y / 2.0); - painter.galley(top_left, galley, color); + let icon = if is_user { ic::FILE_TEXT } else { ic::FILE_LOCK }; + drawn::glyph(ui, pos2(rect.left() + PRESET_ICON_X, rect.center().y), icon, PRESET_ROW_ICON_SIZE, look.text_dim); + let shown = drawn::fitted(ui, label, rect.width() - PRESET_NAME_LEFT, false, selected); + let color = if selected { look.text } else { look.list_text }; + drawn::text_at(ui, rect.left() + PRESET_NAME_LEFT, rect.center().y, &shown, color, selected); + drawn::paint_focus(ui, &response); response } @@ -549,7 +683,7 @@ fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) { } ListAction::Duplicate(name) => { if let Some(p) = app.session.export_preset(&name) { - let name = format!("{}_copy", p.name).chars().take(MAX_PRESET_NAME).collect(); + let name = format!("{}_copy", template_label(&app.session, &name)).chars().take(MAX_PRESET_NAME).collect(); save_new(app, &ExportPreset { name, ..p }); } } @@ -733,9 +867,9 @@ pub fn load_library(app: &mut TextureCraftApp, storage: Option<&dyn eframe::Stor app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, skipped.into_iter().map(|w| format!("Export template skipped: {w}"))); } #[cfg(target_arch = "wasm32")] - for p in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { - if let Ok(v) = serde_json::to_value(&p) { - app.run("export.preset.save", json!({ "preset": v, "unique": true })); + for preset in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { + if let Err(error) = app.session.export_presets.restore(preset) { + app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, [format!("Export template skipped: {error}")]); } } } @@ -751,89 +885,105 @@ pub fn save_library(app: &TextureCraftApp, storage: &mut dyn eframe::Storage) { let _ = (app, storage); } -/// The selected template's output maps (editable for user templates). -fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The selected template's output maps in `column`, editable for user templates +fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { + let look = ExportLook::get(ui.ctx()); let tokens = Tokens::get(ui.ctx()); let (mut preset, editable) = match (&app.ui.export.draft, selected(app)) { (Some(d), _) => (d.clone(), true), (None, Some(b)) => (b, false), (None, None) => { - ui.label(RichText::new(tr("Select an output template")).color(tokens.text_dim)); + MapPreviewCache::clear(ui.ctx()); + drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); return; } }; - let preview = preview_names(app, &preset); + let params = plan_params(app, &preset); + let preview = match ¶ms { + Ok(params) => MapPreviewCache::plan(app, ui.ctx(), params), + Err(error) => { + MapPreviewCache::clear(ui.ctx()); + Err(error.clone()) + } + }; let mut edit = RowEdit::default(); - // The selected template in a strip, "Current preset:" in bold - egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); - ui.label(&preset.name); - if !editable { - ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); - } - }); - }); + // "Current preset:" in bold, the template's name, a lock on a built-in one + let y = top + CURRENT_PRESET_Y; + let title = tr("Current preset:"); + let name_left = column.left() + drawn::text_width(ui, title, true) + NAME_GAP; + drawn::label_at(ui, column.left(), y, title, look.text, true); + let name = drawn::label_at(ui, name_left, y, template_label(&app.session, &app.ui.export.preset), look.text, false); + if !editable { + let lock_at = pos2(name.rect.right() + LOCK_GAP, y); + drawn::glyph(ui, lock_at, ic::LOCK_SIMPLE, CARD_ICON_SIZE, look.text_dim); + let lock = + ui.interact(Rect::from_center_size(lock_at, vec2(CARD_ICON_SIZE, CARD_ICON_SIZE)), ui.scope_id().with("exp_preset_lock"), egui::Sense::hover()); + lock.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Read-only template"))); + lock.on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); + } - // "Output maps", with the Create buttons at the right end of the same row, or of the next one - // when the column is too narrow for both - let create_buttons = |ui: &mut Ui, edit: &mut RowEdit| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add_enabled_ui(editable, |ui| { - for (label, layout, split, file) in CREATE.iter().rev() { - if ui.button(tr(label)).clicked() { - edit.action = Some(MapAction::Add(*layout, *split, file)); - } - } - ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); - }); - }); - }; - if ui.available_width() >= OUTPUT_MAPS_ROW_WIDTH_POINTS { - ui.horizontal(|ui| { - ui.label(caption(tr("Output maps"))); - create_buttons(ui, &mut edit); - }); - } else { - ui.label(caption(tr("Output maps"))); - ui.horizontal(|ui| create_buttons(ui, &mut edit)); - } - if let Err(e) = &preview { - ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); + // A built-in template's cards and buttons keep their full look: the lock says they are read-only + ui.visuals_mut().disabled_alpha = 1.0; + let y = top + OUTPUT_MAPS_Y; + drawn::label_at(ui, column.left(), y, tr("Output maps"), look.text, true); + let mut right = column.right(); + for (label, layout, split, file) in CREATE.iter().rev() { + let width = drawn::text_width(ui, tr(label), false) + CREATE_PADDING; + if drawn::button(ui, drawn::control_rect(right - width, right, y), tr(label), false, editable).clicked() { + edit.action = Some(MapAction::Add(*layout, *split, file)); + } + right -= width + CREATE_GAP; } + let create = tr("Create:"); + drawn::label_at(ui, right - CREATE_LABEL_GAP - drawn::text_width(ui, create, false), y, create, look.text, false); + let mut changed = false; let map_count = preset.maps.len(); let mut split = app.ui.export.draft_split.clone(); split.resize(map_count, false); - // Leave room for the footer text and the framed count below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN_POINTS; - egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { - ui.add_enabled_ui(editable, |ui| { - // Every row takes the column's width, not the width a wider row before it left - let row_width = ui.available_width(); - for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { - let file = preview.as_ref().ok().and_then(|names| names.get(index).cloned().flatten()); - let planned = match file { - Some(file) => format!("{} {file}", ic::ARROW_RIGHT), - None => tr("Not exported: no source in this texture set").to_string(), - }; - changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, &planned, &mut edit)).inner; - ui.add_space(ROW_GAP_POINTS); - } + // The cards scroll between the header and the count strip; their lists line up on one column + let strip = + Rect::from_min_max(pos2(column.left(), column.bottom() - COUNT_TOP_ABOVE_BOTTOM), pos2(column.right(), column.bottom() - COUNT_BOTTOM_ABOVE_BOTTOM)); + let cards = Rect::from_min_max(pos2(column.left(), top + CARDS_TOP), pos2(column.right(), strip.top() - CARD_GAP)); + let values = + preset.maps.iter().flat_map(|map| [map.format.extension().to_string(), crate::export_window::depth_label(Some(map.format), map.bit_depth, false)]); + let value_width = values.chain(CARD_VALUE_SAMPLES.map(str::to_string)).map(|value| drawn::text_width(ui, &value, false)).fold(0.0, f32::max); + ui.scope_builder(egui::UiBuilder::new().max_rect(cards), |ui| { + egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).show(ui, |ui| { + let height = map_count as f32 * (CARD_HEIGHT + CARD_GAP); + let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); + ui.add_enabled_ui(editable, |ui| { + for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { + let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); + let top = area.top() + index as f32 * (CARD_HEIGHT + CARD_GAP); + let card = Rect::from_min_size(pos2(area.left(), top), vec2(area.width(), CARD_HEIGHT)); + let row = OutputCard { index, count: map_count, value_width }; + changed |= output_row(ui, card, &row, map, row_split, planned, &mut edit); + } + }); }); }); - ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); - // Count only maps that have sources in the current set - if let Ok(names) = &preview { - let exported = names.iter().flatten().count(); - egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); - }); + // The hovered output's pictures show from the next frame on + if let (Some(index), Ok(params), Ok(plan)) = (edit.hovered_output, ¶ms, &preview) + && plan.get(index).is_some_and(Option::is_some) + { + MapPreviewCache::fill(app, ui.ctx(), params, index); + } + + // Count only maps that have sources in the current set; an edit that cannot be saved says why there + ui.painter().rect_filled(strip, 0.0, look.control); + let text_left = strip.left() + COUNT_TEXT_INDENT; + match &preview { + Ok(planned) => { + let exported = planned.iter().flatten().count(); + drawn::label_at(ui, text_left, strip.center().y, &trf("{n} output maps will be exported", &[("n", &exported)]), look.text, false); + } + Err(e) => { + drawn::label_at(ui, text_left, strip.center().y, &trf("Not saved: {error}", &[("error", e)]), tokens.danger, false); + } } if !editable { return; @@ -916,92 +1066,157 @@ fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec Result>, String> { - let mut p = crate::export_window::set_params(app, app.session.ts()); - p["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; +/// The `export.plan` and `export.preview` params of `preset` for the current texture set with the window's settings +fn plan_params(app: &TextureCraftApp, preset: &ExportPreset) -> Result { + let mut params = crate::export_window::set_params(app, app.session.ts()); + let export = &app.ui.export; + let same_template = params.get("preset").and_then(Value::as_str) == Some(export.preset.as_str()); - // The set's map overrides apply only to its own template - if let Some(p) = p.as_object_mut() { - p.remove("maps"); + if !same_template && let Some(params) = params.as_object_mut() { + params.remove("maps"); + } else if let (Some(_), Some(maps)) = (&export.draft, params.get_mut("maps").and_then(Value::as_array_mut)) { + // Draft positions have no override until they map to a saved output + maps.retain_mut(|settings| { + let Some(saved_index) = settings["map"].as_u64().and_then(|index| usize::try_from(index).ok()) else { return false }; + let Some(draft_index) = export.draft_maps.iter().position(|origin| *origin == Some(saved_index)) else { return false }; + + settings["map"] = json!(draft_index); + true + }); } - let plan = texturecraft_engine::execute(&mut app.session, "export.plan", &p).map_err(|e| e.to_string())?; - let mut names = vec![None; preset.maps.len()]; - for f in plan.as_array().into_iter().flatten() { - let map = f.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - if let (Some(slot), Some(file)) = (map.and_then(|i| names.get_mut(i)), f.get("file").and_then(Value::as_str)) { - *slot = Some(file.to_string()); - } - } - Ok(names) + + params["preset"] = serde_json::to_value(preset).map_err(|error| error.to_string())?; + Ok(params) } -/// One output map row: drag grip, file name, "$", the channel swatches, then file type, bit depth, -/// duplicate and remove. `planned` is the file it writes for the current texture set. -fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: &str, edit: &mut RowEdit) -> bool { - let tokens = Tokens::get(ui.ctx()); - let mut changed = false; - let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); +/// The file each map of `params`' template writes for the texture set (None: no sources), via `export.plan`; a PSD's maps each get the file and their layer +fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result>, String> { + let plan = texturecraft_engine::execute(&mut app.session, "export.plan", params).map_err(|e| e.to_string())?; + let map_count = params.pointer("/preset/maps").and_then(Value::as_array).map_or(0, Vec::len); + let index = |value: &Value| value.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - // The name field gives way in a narrow window, so the swatches and lists stay in the row - let swatches = swatch_targets(map, *split).len() as f32; - let spacing = ui.spacing().item_spacing.x; - let others = GRIP_WIDTH_POINTS + DOLLAR_BUTTON_WIDTH_POINTS + swatches * (SWATCH_SIZE_POINTS + spacing) + ROW_LISTS_WIDTH_POINTS; - let name_width = (ui.available_width() - others - ROW_GAPS * spacing).clamp(MIN_NAME_FIELD_WIDTH_POINTS, NAME_FIELD_WIDTH_POINTS); + let mut outputs: Vec> = vec![None; map_count]; + let tile_files = tr("UV tile files"); + for file in plan.as_array().into_iter().flatten() { + let Some(name) = file.get("file").and_then(Value::as_str) else { continue }; - grip(ui, index, count, edit); - let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { - ui.label(tr("File name without extension; variables insert names")); - ui.label(planned); + let tiled = file["tile"].is_number(); + let display_name = if tiled { file["udimPattern"].as_str().unwrap_or(tile_files) } else { name }; + let mut remember = |entry: &Value, layer_name: Option<&str>| { + let Some(slot) = index(entry).and_then(|index| outputs.get_mut(index)) else { return }; + + if let Some(previous) = slot { + // Some disambiguated or truncated paths have no common tile pattern + if tiled && previous.file != display_name && previous.file != tile_files { + previous.file = tile_files.into(); + } + return; + } + + *slot = Some(PlannedOutput { + file: match layer_name { + Some(layer_name) if !tiled => format!("{name} › {layer_name}"), + _ => display_name.to_owned(), + }, + tiled, + size: file.get("size").and_then(Value::as_u64).unwrap_or(0), + format: file.get("format").and_then(Value::as_str).and_then(FileFormat::from_extension), + bit_depth: file.get("bitDepth").and_then(Value::as_u64).and_then(|depth| u8::try_from(depth).ok()).unwrap_or(0), + dithering: file.get("dithering").and_then(Value::as_bool).unwrap_or(false), }); - changed |= name.changed(); - changed |= token_menu(ui, &mut map.file); - changed |= channel_swatches(ui, index, map, split, edit); - - // The lists and icons at the row's right end: file format and duplicate, bit depth and remove - ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); - ui.vertical(|ui| { - ui.horizontal(|ui| { - changed |= format_menu(ui, map); - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Duplicate(index)); - } - }); - ui.horizontal(|ui| { - changed |= depth_menu(ui, map); - if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Remove(index)); - } - }); - }); - }); - }); - - // Another row's grip dropped here moves that row here (the type check keeps a map list drop) - let row = frame.response; - let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); - if row_dragged_over { - drop_highlight(ui, row.rect, &tokens); + }; + match file.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()) { + Some(layers) => { + for layer in layers { + remember(layer, layer.get("name").and_then(Value::as_str)); + } + } + None => remember(file, None), + } } - if row_dragged_over && let Some(from) = row.dnd_release_payload::() { + + Ok(outputs) +} + +/// One output map card: grip, file name, "$", swatches, then file type over bit depth beside duplicate and remove +fn output_row(ui: &mut Ui, card: Rect, row: &OutputCard, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { + let look = ExportLook::get(ui.ctx()); + let index = row.index; + + // The card takes a dragged row before its controls, which sit above it + let card_response = ui.interact(card, ui.scope_id().with(("exp_card", index)), egui::Sense::hover()); + ui.painter().rect_filled(card, CARD_RADIUS, look.control); + let mid = card.center().y; + let mut changed = false; + grip(ui, Rect::from_center_size(pos2(card.left() + GRIP_X, mid), vec2(GRIP_WIDTH, card.height())), index, row.count, edit); + + // The name field gives way in a narrow window, so the swatches and lists keep their room + let swatches_width = swatch_targets(map, *split).len() as f32 * (SWATCH_WIDTH + SWATCH_GAP); + let lists_width = CARD_ICON_FROM_RIGHT + CARD_CHEVRON_STEP + CARD_VALUE_GAP + row.value_width + SWATCHES_GAP; + let room = card.width() - NAME_FIELD_LEFT - DOLLAR_GAP - DOLLAR_WIDTH - SWATCHES_GAP - swatches_width - lists_width; + let name_width = room.clamp(MIN_NAME_FIELD_WIDTH, NAME_FIELD_WIDTH); + let name_rect = drawn::control_rect(card.left() + NAME_FIELD_LEFT, card.left() + NAME_FIELD_LEFT + name_width, mid); + changed |= name_field(ui, name_rect, index, &mut map.file, planned); + let dollar = drawn::control_rect(name_rect.right() + DOLLAR_GAP, name_rect.right() + DOLLAR_GAP + DOLLAR_WIDTH, mid); + changed |= token_menu(ui, dollar, index, &mut map.file); + let swatches = Rect::from_min_max(pos2(dollar.right() + SWATCHES_GAP, card.top() + CARD_INSET), pos2(card.right(), card.bottom() - CARD_INSET)); + changed |= channel_swatches(ui, swatches, index, map, split, planned, edit); + + // The right block: file type over bit depth on one column, duplicate over remove beside them + let icon_x = card.right() - CARD_ICON_FROM_RIGHT; + let chevron_x = icon_x - CARD_CHEVRON_STEP; + let value_left = chevron_x - CARD_VALUE_GAP - row.value_width; + let (upper, lower) = (mid - CARD_ROW_OFFSET, mid + CARD_ROW_OFFSET); + changed |= format_menu(ui, (value_left, chevron_x, upper), index, map); + changed |= depth_menu(ui, (value_left, chevron_x, lower), index, map); + let duplicate = trf("Duplicate output {number}", &[("number", &(index + 1))]); + if drawn::icon_button(ui, pos2(icon_x, upper), ic::COPY, CARD_ICON_SIZE, &duplicate, ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Duplicate(index)); + } + let remove = trf("Remove output {number}", &[("number", &(index + 1))]); + if drawn::icon_button(ui, pos2(icon_x, lower), ic::X, CARD_ICON_SIZE, &remove, ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Remove(index)); + } + + // Another card's grip dropped here moves that card here (the type check keeps a map list drop) + let row_dragged_over = card_response.dnd_hover_payload::().is_some_and(|from| from.0 != index); + if row_dragged_over { + drop_highlight(ui, card); + } + if row_dragged_over && let Some(from) = card_response.dnd_release_payload::() { edit.action = Some(MapAction::Move { from: from.0, to: index }); } changed } -/// The grip at a row's left: drag it onto another row to move the map there; the arrow keys and -/// its right-click menu move it one place -fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { - let tokens = Tokens::get(ui.ctx()); +/// The file name field; until it is typed in it shows the name's end, cut with "…"; true when it changed +fn name_field(ui: &mut Ui, rect: Rect, index: usize, file: &mut String, planned: Option<&PlannedOutput>) -> bool { + let look = ExportLook::get(ui.ctx()); + let id = ui.scope_id().with(("exp_map_name", index)); + let typing = ui.memory(|memory| memory.has_focus(id)); + let text_color = if typing { look.text } else { Color32::TRANSPARENT }; + let field = egui::TextEdit::singleline(file).id(id).margin(vec2(drawn::VALUE_INSET, 0.0)).background_color(look.control).text_color(text_color); + let response = ui.put(rect, field).on_hover_ui(|ui| { + ui.label(tr("File name without extension; variables insert names")); + ui.label(planned_text(planned)); + }); + if !typing { + let shown = drawn::fitted(ui, file, rect.width() - 2.0 * drawn::VALUE_INSET, true, false); + let color = if drawn::looks_disabled(ui, ui.is_enabled()) { look.text_dim } else { look.text }; + drawn::text_at(ui, rect.left() + drawn::VALUE_INSET, rect.center().y, &shown, color, false); + } + response.changed() +} + +/// A card's grip: drag it onto another card, or use the arrow keys or its menu, to move the map +fn grip(ui: &mut Ui, rect: Rect, index: usize, count: usize, edit: &mut RowEdit) { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click_and_drag()); + let response = ui.interact(rect, ui.scope_id().with(("exp_grip", index)), if enabled { egui::Sense::click_and_drag() } else { egui::Sense::hover() }); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); - let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; - ui.painter().rect_filled(rect, 1.0, color); + let color = if enabled && (response.hovered() || response.dragged()) { look.text } else { look.text_dim }; + drawn::glyph(ui, rect.center(), ic::DOTS_SIX_VERTICAL, GRIP_SIZE, color); + drawn::paint_focus(ui, &response); let response = response.on_hover_cursor(egui::CursorIcon::Grab); response.dnd_set_drag_payload(MapDrag(index)); @@ -1030,10 +1245,12 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the file name variables in the reference's order, then $channel -fn token_menu(ui: &mut Ui, file: &mut String) -> bool { +/// The "$" button in `rect`: the file name variables in the reference's order, then $channel +fn token_menu(ui: &mut Ui, rect: Rect, index: usize, file: &mut String) -> bool { let mut changed = false; - let menu = ui.menu_button("$", |ui| { + let id = ui.scope_id().with(("exp_tokens", index)); + let button = drawn::button_with_id(ui, id, rect, "$", "$", false, ui.is_enabled()).on_hover_text(tr("Insert a variable")); + egui::Popup::menu(&button).show(|ui| { let mut add = |ui: &mut Ui, token: &str| { if ui.button(RichText::new(token).monospace()).clicked() { file.push_str(token); @@ -1052,14 +1269,15 @@ fn token_menu(ui: &mut Ui, file: &mut String) -> bool { add(ui, token); } }); - menu.response.on_hover_text(tr("Insert a variable")); changed } -/// The file type menu of an output map ("png˅") -fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The file type menu of an output map ("png ⌄") at `place`: (value's left, chevron's centre, middle) +fn format_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let mut changed = false; - let menu = ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_format", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, map.format.extension()).on_hover_text(tr("File format")); + egui::Popup::menu(&menu).show(|ui| { for extension in MAP_FILE_TYPES { let Some(format) = FileFormat::from_extension(extension) else { ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); @@ -1077,16 +1295,17 @@ fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("File format")); changed } -/// The bit depth menu of an output map ("8 bits˅"); templates do not keep dithering yet -fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The bit depth menu of an output map ("8 bits ⌄"); templates do not keep dithering yet +fn depth_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let format = map.format; let mut changed = false; let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); - let menu = ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_depth", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, &shown).on_hover_text(tr("Bit depth")); + egui::Popup::menu(&menu).show(|ui| { for (depth, dithering) in crate::export_window::depth_options(format) { let label = crate::export_window::depth_label(Some(format), depth, dithering); if dithering { @@ -1098,7 +1317,6 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("Bit depth")); changed } @@ -1239,8 +1457,8 @@ fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget, inve } } -/// The colour of a map on swatches and list markers (None for constants) -fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { +/// A map's colour on swatches and list markers (None for constants) +fn source_color(source: &SourceRef) -> Option { let channels = Channel::ALL.len(); let converted = VirtualMap::ALL.len(); let index = match source { @@ -1249,28 +1467,88 @@ fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { SourceRef::Baked { map, .. } => channels + converted + BakedMap::ALL.iter().position(|m| m == map)?, SourceRef::Constant(_) => return None, }; + let hue = (index as f32 * HUE_STEP).fract(); - let value = if tokens.dark { SWATCH_VALUE_DARK } else { SWATCH_VALUE_LIGHT }; - Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) + Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, SWATCH_VALUE, 1.0).into()) } -/// The bars under a swatch's letters: red, green and blue for a colour map's RGB, else the one -/// channel read (white for gray) -fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { - match source { - SourceRef::Constant(_) => Vec::new(), - _ if source.components() == 3 && target == ChannelTarget::Rgb && rgb_spread(map) => COMPONENT_COLORS.to_vec(), - _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), - _ => vec![tokens.text_strong], +/// The underline of a swatch: the colour of the channel its letters name (white for RGB and gray) +fn swatch_bar(target: ChannelTarget) -> Color32 { + match target { + ChannelTarget::One(Dest::R) => BAR_RED, + ChannelTarget::One(Dest::G) => BAR_GREEN, + ChannelTarget::One(Dest::B) => BAR_BLUE, + ChannelTarget::One(Dest::A) => BAR_ALPHA, + ChannelTarget::Rgb | ChannelTarget::One(Dest::L) => BAR_WHOLE, } } -/// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. -fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { +/// "→ ", or why the output writes nothing +fn planned_text(planned: Option<&PlannedOutput>) -> String { + match planned { + Some(planned) => format!("{} {}", ic::ARROW_RIGHT, planned.file), + None => tr("Not exported: no source in this texture set").to_string(), + } +} + +/// Below a swatch's tooltip: the file its output writes, each channel with its source, then the file's size and type (built-in templates' swatches show it too) +fn output_preview(ui: &mut Ui, index: usize, map: &MapSpec, planned: Option<&PlannedOutput>) { let tokens = Tokens::get(ui.ctx()); + ui.separator(); + let Some(planned) = planned else { + ui.label(RichText::new(planned_text(None)).color(tokens.text_dim)); + return; + }; + + let title = if planned.tiled { trf("Atlas preview: {file}", &[("file", &planned.file)]) } else { planned.file.clone() }; + ui.label(RichText::new(title).color(tokens.text_strong)); + if let Some(Some(pictures)) = MapPreviewCache::get(ui.ctx(), index) { + preview_pictures(ui, map, &pictures); + } + + let file_type = planned.format.map_or("", FileFormat::extension); + let depth = crate::export_window::depth_label(planned.format, planned.bit_depth, planned.dithering); + let details = if planned.tiled { format!("{file_type} {depth}") } else { format!("{size} x {size} · {file_type} {depth}", size = planned.size) }; + ui.label(RichText::new(details).color(tokens.text_dim)); +} + +/// The file's picture with each channel's grey picture, letter and source beside it +fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { + let tokens = Tokens::get(ui.ctx()); + let picture = |texture, width: f32| egui::Image::new(texture).fit_to_exact_size(vec2(width, width * pictures.aspect)).corner_radius(tokens.radius); + ui.horizontal_top(|ui| { + ui.add(picture(&pictures.file, PREVIEW_FILE_WIDTH_POINTS)); + if pictures.channels.is_empty() { + return; + } + + ui.vertical(|ui| { + for (dest, texture) in &pictures.channels { + let target = ChannelTarget::One(*dest); + let gray = ChannelTarget::One(Dest::L); + let source_target = match dest { + Dest::R | Dest::G | Dest::B if source_of(map, gray).is_some() => gray, + _ => target, + }; + let fallback = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); + let source = source_of(map, source_target).unwrap_or(&fallback); + let inverted = source_target.dests().iter().any(|dest| map.inverted.contains(dest)); + + ui.horizontal(|ui| { + ui.add(picture(texture, PREVIEW_CHANNEL_WIDTH_POINTS)); + ui.label(RichText::new(target_label(target)).color(tokens.text_strong)); + ui.label(RichText::new(swatch_tooltip(map, source, source_target, inverted)).color(tokens.text_dim)); + }); + } + }); + }); +} + +/// A card's channel swatches from `area`'s left: drop targets for the map lists, with click and right-click menus +fn channel_swatches(ui: &mut Ui, area: Rect, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let mut changed = false; let shows_split = *split || !rgb_collapsed(map); + let mut left = area.left(); for (slot, target) in swatch_targets(map, *split).into_iter().enumerate() { let Some(source) = source_of(map, target).cloned() else { continue }; @@ -1281,18 +1559,27 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo if inverted { name = trf("{swatch}, inverted", &[("swatch", &name)]); } - let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; - let response = swatch(ui, label, &name, &look).on_hover_ui(|ui| { + let constant = matches!(source, SourceRef::Constant(_)); + let look = SwatchLook { fill: source_color(&source), bar: (!constant).then(|| swatch_bar(target)), inverted }; + let rect = Rect::from_min_max(pos2(left, area.top()), pos2(left + SWATCH_WIDTH, area.bottom())); + left += SWATCH_WIDTH + SWATCH_GAP; + let response = swatch(ui, ui.scope_id().with(("exp_swatch", index, slot)), rect, label, &name, &look); + if response.contains_pointer() { + edit.hovered_output = Some(index); + } + let hover = |ui: &mut Ui| { ui.label(&tooltip); if inverted { ui.label(tr("Inverted")); } - }); + output_preview(ui, index, map, planned); + }; + let response = response.on_hover_ui(hover).on_disabled_hover_ui(hover); // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); if map_dragged_over { - drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS), &tokens); + drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS)); } if map_dragged_over && let Some(input) = response.dnd_release_payload::() { edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); @@ -1372,35 +1659,41 @@ fn set_constant(map: &mut MapSpec, target: ChannelTarget, value: f32) { } } -/// The accent frame around a drop target under a dragged map or row -fn drop_highlight(ui: &Ui, rect: egui::Rect, tokens: &Tokens) { - ui.painter().rect_stroke(rect, tokens.radius, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, tokens.accent), egui::StrokeKind::Outside); +/// The frame round a drop target, in the text colour: the accent is Export's alone +fn drop_highlight(ui: &Ui, rect: Rect) { + let look = ExportLook::get(ui.ctx()); + ui.painter().rect_stroke(rect, CARD_RADIUS, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, look.text), egui::StrokeKind::Outside); } -/// One channel swatch: `label` on top, filled with the source's colour, bars below for the -/// channels it reads, a corner mark when inverted -fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); +/// One channel swatch `id`: its letters, the source's colour, its channel's underline, a corner mark when inverted +fn swatch(ui: &mut Ui, id: egui::Id, rect: Rect, label: &str, name: &str, swatch_look: &SwatchLook) -> egui::Response { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click()); + let response = ui.interact(rect, id, egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); let painter = ui.painter(); - let border = if response.hovered() { tokens.accent } else { tokens.button_border }; - painter.rect(rect, tokens.radius, look.fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE_POINTS); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP_POINTS), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); - let bar_width = SWATCH_BAR_WIDTH_POINTS / look.bars.len().max(1) as f32; - let left = rect.center().x - SWATCH_BAR_WIDTH_POINTS / 2.0; - for (k, color) in look.bars.iter().enumerate() { - let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM_POINTS); - painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT_POINTS)), 0.0, *color); + let fill = swatch_look.fill.unwrap_or(look.raised); + painter.rect_filled(rect, 0.0, fill); + if response.hovered() { + painter.rect_stroke(rect, 0.0, egui::Stroke::new(1.0, look.text_dim), egui::StrokeKind::Inside); } - if look.inverted { + let lettering = look.lettering_on(fill); + painter.text(pos2(rect.center().x, rect.top() + SWATCH_LABEL_Y), egui::Align2::CENTER_CENTER, label, drawn::font(false), lettering); + if let Some(bar) = swatch_look.bar { + let bottom = rect.bottom() - SWATCH_BAR_BOTTOM; + painter.rect_filled( + Rect::from_min_max(pos2(rect.left() + SWATCH_BAR_INSET, bottom), pos2(rect.right() - SWATCH_BAR_INSET, bottom + SWATCH_BAR_HEIGHT)), + 0.0, + bar, + ); + } + if swatch_look.inverted { let corner = rect.right_top(); let mark = vec![corner, corner - vec2(INVERTED_MARK_POINTS, 0.0), corner + vec2(0.0, INVERTED_MARK_POINTS)]; - painter.add(egui::Shape::convex_polygon(mark, tokens.text_strong, egui::Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(mark, lettering, egui::Stroke::NONE)); } + drawn::paint_focus(ui, &response); response } @@ -1488,79 +1781,92 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } /// The maps the selected template's outputs read, with their colours, for the panes' markers -fn marked_sources(app: &TextureCraftApp, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { +fn marked_sources(app: &TextureCraftApp) -> Vec<(SourceRef, Color32)> { let Some(preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { return Vec::new() }; let sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); - sources.filter_map(|source| source_color(source, tokens).map(|color| (source.clone(), color))).collect() + sources.filter_map(|source| source_color(source).map(|color| (source.clone(), color))).collect() } -/// The Input maps pane: the input maps in their groups -fn input_maps(ui: &mut Ui, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Input maps"))); - egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { +/// A pane's title at `left`, on the column titles' line +fn pane_title(ui: &mut Ui, left: f32, y: f32, title: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, left + GROUP_INDENT, y, title, look.text, true); +} + +/// A pane's entries scrolling in `area`, the scroll bar in its strip at the right +fn pane_list(ui: &mut Ui, area: Rect, id: &str, add: impl FnOnce(&mut Ui, f32)) { + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(id).auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + add(ui, area.width() - GUTTER); + }); + }); +} + +/// The Input maps pane in `pane`: the input maps in their groups +fn input_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + let look = ExportLook::get(ui.ctx()); + pane_title(ui, pane.left(), top + HEADER_Y, tr("Input maps")); + let list = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pane.max); + pane_list(ui, list, "exp_inputs", |ui, width| { for (group, entries) in INPUT_MAPS.iter() { - ui.label(RichText::new(tr(group)).italics()); - map_entries(ui, entries, marked, false); + let (rect, _) = ui.allocate_exact_size(vec2(width, GROUP_HEIGHT), egui::Sense::hover()); + drawn::label_at(ui, rect.left() + GROUP_INDENT, rect.center().y, tr(group), look.text_dim, false); + map_entries(ui, width, entries, marked); } }); } -/// The side pane: Mesh maps above Converted maps (in the highlight colour, as in the reference) -fn mesh_and_converted_maps(ui: &mut Ui, height: f32, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Mesh maps"))); - egui::ScrollArea::vertical() - .id_salt("exp_mesh_maps") - .auto_shrink([false; 2]) - .max_height(height * MESH_MAPS_SHARE) - .show(ui, |ui| map_entries(ui, &MESH_MAPS, marked, false)); - ui.separator(); - ui.label(caption(tr("Converted maps"))); - egui::ScrollArea::vertical().id_salt("exp_converted_maps").auto_shrink([false; 2]).show(ui, |ui| map_entries(ui, &CONVERTED_MAPS, marked, true)); +/// The side pane in `pane`: Mesh maps above Converted maps, a divider between them +fn mesh_and_converted_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + pane_title(ui, pane.left(), top + HEADER_Y, tr("Mesh maps")); + let split = pane.center().y + SIDE_SPLIT_BELOW_MIDDLE; + let mesh = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pos2(pane.right(), split - MESH_BOTTOM_GAP)); + pane_list(ui, mesh, "exp_mesh_maps", |ui, width| map_entries(ui, width, &MESH_MAPS, marked)); + drawn::divider(ui, Rect::from_min_max(pos2(pane.left() - 1.0, split), pos2(pane.right(), split + 1.0))); + pane_title(ui, pane.left(), split + CONVERTED_TITLE_Y, tr("Converted maps")); + let converted = Rect::from_min_max(pos2(pane.left(), split + CONVERTED_ROWS_TOP), pane.max); + pane_list(ui, converted, "exp_converted_maps", |ui, width| map_entries(ui, width, &CONVERTED_MAPS, marked)); } -fn map_entries(ui: &mut Ui, entries: &[MapEntry], marked: &[(SourceRef, Color32)], converted: bool) { - let tokens = Tokens::get(ui.ctx()); - let text_color = if converted { tokens.warning } else { tokens.text }; +fn map_entries(ui: &mut Ui, width: f32, entries: &[MapEntry], marked: &[(SourceRef, Color32)]) { for (name, source) in entries { let marker = source.as_ref().and_then(|source| marked.iter().find(|(used, _)| same_source(used, source)).map(|(_, color)| *color)); - map_entry(ui, tr(name), source.as_ref(), text_color, marker); + map_entry(ui, width, tr(name), source.as_ref(), marker); } } -/// A map list entry to drag onto an output channel, with the colour marker of an output map that -/// reads it; a map TextureCraft does not have yet is greyed and cannot be dragged -fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Color32, marker: Option) { - let tokens = Tokens::get(ui.ctx()); +/// A map list entry to drag onto a channel; a used map shows a square of its colour, a missing one is greyed +fn map_entry(ui: &mut Ui, width: f32, name: &str, source: Option<&SourceRef>, marker: Option) { + let look = ExportLook::get(ui.ctx()); let available = source.is_some(); let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT_POINTS), sense); + let (rect, response) = ui.allocate_exact_size(vec2(width, ENTRY_PITCH), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); + let row = Rect::from_min_max(pos2(rect.left() + ENTRY_INSET, rect.top()), pos2(rect.right(), rect.top() + ENTRY_HEIGHT)); let painter = ui.painter(); - let row = rect.shrink2(vec2(0.0, ENTRY_GAP_POINTS / 2.0)); - painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); + painter.rect_filled(row, 0.0, if available && response.hovered() { look.raised } else { look.control }); if let Some(color) = marker { - painter.rect_filled( - egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT_POINTS, 0.0), egui::Vec2::splat(MARKER_SIZE_POINTS)), - 1.0, - color, + let square = Rect::from_min_size(pos2(rect.left() + MARKER_LEFT, row.center().y - MARKER_SIZE / 2.0), vec2(MARKER_SIZE, MARKER_SIZE)); + let edge = Color32::from_rgb( + color.r().saturating_add(MARKER_EDGE_LIGHTEN), + color.g().saturating_add(MARKER_EDGE_LIGHTEN), + color.b().saturating_add(MARKER_EDGE_LIGHTEN), ); + painter.rect(square, MARKER_RADIUS, color, egui::Stroke::new(1.0, edge), egui::StrokeKind::Inside); } - let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; - painter.text( - row.left_center() + vec2(ENTRY_TEXT_INDENT_POINTS, 0.0), - egui::Align2::LEFT_CENTER, - name, - egui::FontId::proportional(ENTRY_TEXT_SIZE_POINTS), - color, - ); + let color = if available { look.text } else { look.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; + let shown = drawn::fitted(ui, name, row.right() - rect.left() - ENTRY_NAME_LEFT, false, false); + drawn::text_at(ui, rect.left() + ENTRY_NAME_LEFT, row.center().y, &shown, color, false); let Some(source) = source else { response.on_hover_text(tr(NOT_AVAILABLE)); return; }; - let response = response.on_hover_cursor(egui::CursorIcon::Grab); + // How to use the entry is its tooltip, not a line under the cards + let response = response.on_hover_cursor(egui::CursorIcon::Grab).on_hover_text(tr("Drop an input map onto a channel to assign it to that output.")); response.dnd_set_drag_payload(source.clone()); if response.dragged() && let Some(at) = response.interact_pointer_pos() @@ -1579,6 +1885,74 @@ mod tests { SourceRef::Channel { channel, component } } + #[test] + fn feedback_preview_follows_draft_maps_to_their_saved_overrides() { + use crate::state::{MapExport, SetExport}; + use egui_kittest::Harness; + + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let ts = app.session.ts(); + let saved = app.session.export_preset("Unreal Engine (Packed)").unwrap(); + let mut draft = saved.clone(); + draft.maps = vec![saved.maps[1].clone(), new_map(Layout::Gray, "New"), saved.maps[0].clone()]; + let resized = MapExport { size: Some(128), ..MapExport::default() }; + let disabled = MapExport { enabled: false, ..MapExport::default() }; + app.ui.export.preset = saved.name.clone(); + app.ui.export.sets.insert( + ts, + SetExport { + maps_template: saved.name, + maps: [(0, resized), (1, disabled), (2, MapExport { size: Some(512), ..MapExport::default() })].into(), + ..SetExport::default() + }, + ); + app.ui.export.draft = Some(draft.clone()); + app.ui.export.draft_maps = vec![Some(1), None, Some(0)]; + + let params = plan_params(app, &draft).unwrap(); + let outputs = planned_outputs(app, ¶ms).unwrap(); + + assert!(outputs[0].is_none(), "the disabled map stays disabled in its new position"); + assert_eq!(outputs[2].as_ref().unwrap().size, 128); + assert_eq!(params["maps"].as_array().unwrap().len(), 2, "the new map and the removed map get no override"); + } + + #[test] + fn tiled_raster_and_psd_previews_describe_the_whole_atlas() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives::udim_plane; + + let session = Session::new_project("Tiles", udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let mut preset = app.session.export_preset("Separate maps").unwrap(); + preset.maps.truncate(2); + preset.maps[0].file = "Raster".into(); + preset.maps[0].format = FileFormat::Png; + preset.maps[1].file = "Group/Layer.$udim".into(); + preset.maps[1].format = FileFormat::Psd; + let mut ambiguous = preset.maps[0].clone(); + ambiguous.file = "Literal_UDIMTOKEN.$udim".into(); + preset.maps.push(ambiguous); + let params = json!({"ts": 0, "preset": preset}); + + let outputs = planned_outputs(app, ¶ms).unwrap(); + let preview = Harness::builder().with_context_setup(crate::framework::install_headless).build_ui(|ui| { + for (index, map) in preset.maps.iter().enumerate() { + output_preview(ui, index, map, outputs[index].as_ref()); + } + }); + + assert!(preview.query_by_label("Atlas preview: Raster..png").is_some()); + assert!(preview.query_by_label_contains(".psd").is_some()); + assert!(preview.query_by_label("Atlas preview: UV tile files").is_some()); + assert!(preview.query_by_label_contains("128 x 128").is_none(), "the tile size must not describe the whole atlas"); + } + #[test] fn layouts_keep_sources_and_drops_fill_rgb() { let mut map = new_map(Layout::Rgb, "t"); diff --git a/crates/ui-egui/src/export_templates/map_preview_cache.rs b/crates/ui-egui/src/export_templates/map_preview_cache.rs new file mode 100644 index 00000000..4858114c --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_cache.rs @@ -0,0 +1,84 @@ +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use egui::util::id_type_map::RawKey; +use serde_json::Value; + +use super::map_preview_pictures::MapPreviewPictures; +use super::{PlannedOutput, planned_outputs}; +use crate::TextureCraftApp; + +/// Pixels across an output map's hover preview: enough to read the packing, cheap to sample +const PREVIEW_SIDE_PIXELS: u32 = 150; + +/// The current template plan and its hover pictures, invalidated together on edits. +#[derive(Clone)] +pub(super) struct MapPreviewCache { + key: u64, + plan: Result]>, String>, + pictures: HashMap>>, +} + +impl MapPreviewCache { + fn id() -> egui::Id { + egui::Id::unique("export_map_preview_cache") + } + + fn key(app: &TextureCraftApp, params: &Value) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + params.hash(&mut hasher); + (app.session.project_id, app.session.revision).hash(&mut hasher); + hasher.finish() + } + + /// Output map `index`'s pictures once made; None until then + pub(super) fn get(ctx: &egui::Context, index: usize) -> Option>> { + ctx.data(|data| { + let cache = data.get_temp_raw(RawKey::new::(Self::id()))?.downcast_ref::()?; + cache.pictures.get(&index).cloned() + }) + } + + /// Release the plan and its pictures when their tab is dismissed. + pub(super) fn clear(ctx: &egui::Context) { + ctx.data_mut(|data| data.remove::(Self::id())); + } + + /// Keep one descriptor per map until the settings or document change. + pub(super) fn plan(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value) -> Result]>, String> { + let key = Self::key(app, params); + let cached = ctx.data_mut(|data| { + let cache = data.get_temp_raw(RawKey::new::(Self::id()))?.downcast_ref::()?; + if cache.key == key { + return Some(cache.plan.clone()); + } + + data.remove::(Self::id()); + None + }); + if let Some(plan) = cached { + return plan; + } + + let plan = planned_outputs(app, params).map(Arc::from); + ctx.data_mut(|data| data.insert_temp(Self::id(), Self { key, plan: plan.clone(), pictures: HashMap::new() })); + plan + } + + /// Make output map `index`'s pictures for `params` unless they are made, and draw again to show them + pub(super) fn fill(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value, index: usize) { + if Self::get(ctx, index).is_some() { + return; + } + + let preview = app.session.export_preview(params, index, PREVIEW_SIDE_PIXELS).ok().flatten(); + let pictures = preview.map(|preview| Arc::new(MapPreviewPictures::new(ctx, &preview, index))); + ctx.data_mut(|data| { + if let Some(cache) = data.get_temp_raw_mut(RawKey::new::(Self::id())).and_then(|entry| entry.downcast_mut::()) { + cache.pictures.insert(index, pictures); + } + }); + ctx.request_repaint(); + } +} diff --git a/crates/ui-egui/src/export_templates/map_preview_pictures.rs b/crates/ui-egui/src/export_templates/map_preview_pictures.rs new file mode 100644 index 00000000..633f4125 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_pictures.rs @@ -0,0 +1,47 @@ +use egui::{Color32, ColorImage, TextureHandle, TextureOptions}; +use texturecraft_engine::formats::{Dest, MapPreview}; + +/// An output map's file, small, then each of its channels in grey, as textures to draw +pub(super) struct MapPreviewPictures { + pub(super) file: TextureHandle, + /// Empty for a one-channel file, whose picture is its channel + pub(super) channels: Vec<(Dest, TextureHandle)>, + /// Height over width + pub(super) aspect: f32, +} + +impl MapPreviewPictures { + /// The pictures of `preview`, the preview of output map `index` + pub(super) fn new(ctx: &egui::Context, preview: &MapPreview, index: usize) -> MapPreviewPictures { + let size = [preview.width as usize, preview.height as usize]; + let pixel_count = size[0] * size[1]; + let count = preview.channels.len().max(1); + let value = |pixel: usize, channel: usize| preview.pixels.get(pixel * count + channel).copied().unwrap_or(0); + let load = |name: String, image: ColorImage| ctx.load_texture(name, image, TextureOptions::LINEAR); + + // Keep alpha separate so the file preview shows the stored colour + let color = preview.channels.starts_with(&[Dest::R, Dest::G, Dest::B]); + let pixels: Vec<_> = (0..pixel_count) + .map(|pixel| if color { Color32::from_rgb(value(pixel, 0), value(pixel, 1), value(pixel, 2)) } else { Color32::from_gray(value(pixel, 0)) }) + .collect(); + let grayscale = !color || pixels.iter().all(|pixel| pixel.r() == pixel.g() && pixel.g() == pixel.b()); + let file = load(format!("export_map_preview_{index}"), ColorImage::new(size, pixels)); + + // A gray file texture can also draw each of its colour channels + let channels = if preview.channels.len() > 1 { + let channel = |(channel_index, dest): (usize, &Dest)| { + if grayscale && *dest != Dest::A { + return (*dest, file.clone()); + } + + let image = ColorImage::from_gray_iter(size, (0..pixel_count).map(|pixel| value(pixel, channel_index))); + (*dest, load(format!("export_map_preview_{index}_{channel_index}"), image)) + }; + preview.channels.iter().enumerate().map(channel).collect() + } else { + Vec::new() + }; + + MapPreviewPictures { file, channels, aspect: preview.height as f32 / preview.width.max(1) as f32 } + } +} diff --git a/crates/ui-egui/src/export_templates/output_card.rs b/crates/ui-egui/src/export_templates/output_card.rs new file mode 100644 index 00000000..a7f1eddc --- /dev/null +++ b/crates/ui-egui/src/export_templates/output_card.rs @@ -0,0 +1,6 @@ +/// An output map card's index, the card count (for the grip's moves) and the width its lists' values line up on +pub(super) struct OutputCard { + pub(super) index: usize, + pub(super) count: usize, + pub(super) value_width: f32, +} diff --git a/crates/ui-egui/src/export_templates/planned_output.rs b/crates/ui-egui/src/export_templates/planned_output.rs new file mode 100644 index 00000000..6c5bcf37 --- /dev/null +++ b/crates/ui-egui/src/export_templates/planned_output.rs @@ -0,0 +1,14 @@ +use texturecraft_engine::formats::FileFormat; + +/// A file an output map writes for the current texture set, as `export.plan` lists it +#[derive(Clone)] +pub(super) struct PlannedOutput { + pub(super) file: String, + /// The picture shows the full atlas while export writes individual tiles + pub(super) tiled: bool, + /// Pixels per side (export.plan never plans an atlas, so every file is square) + pub(super) size: u64, + pub(super) format: Option, + pub(super) bit_depth: u8, + pub(super) dithering: bool, +} diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs index 6568dac9..2143edfb 100644 --- a/crates/ui-egui/src/export_templates/row_edit.rs +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -6,4 +6,6 @@ pub(super) struct RowEdit { pub(super) action: Option, /// A map dropped on a channel swatch, to ask which of its channels to use. pub(super) pending: Option, + /// The output map whose channel swatch the pointer is on, for its file preview + pub(super) hovered_output: Option, } diff --git a/crates/ui-egui/src/export_templates/swatch_look.rs b/crates/ui-egui/src/export_templates/swatch_look.rs index 99d81b19..f33e86d8 100644 --- a/crates/ui-egui/src/export_templates/swatch_look.rs +++ b/crates/ui-egui/src/export_templates/swatch_look.rs @@ -4,7 +4,7 @@ use egui::Color32; pub(super) struct SwatchLook { /// The source map's colour (None: empty or a constant). pub(super) fill: Option, - /// One bar per channel of the source the swatch reads. - pub(super) bars: Vec, + /// The underline in the colour of the channel the swatch's letters name (None: a constant) + pub(super) bar: Option, pub(super) inverted: bool, } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 6a46f757..c346d033 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -12,44 +12,192 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; -use crate::theme::{Tokens, caption, semibold}; +use crate::theme::{Tokens, semibold}; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::icon_button; +pub(crate) mod drawn; +pub(crate) mod export_look; mod inherited_settings; mod map_row; +mod page_place; +mod tree_file; +pub(crate) use export_look::ExportLook; use inherited_settings::InheritedSettings; use map_row::MapRow; +use page_place::PagePlace; +use tree_file::TreeFile; /// The reference window's size; a smaller screen gets a smaller window const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); /// Space kept free around the content on a small screen: the title bar, the frame and a gap const WINDOW_VIEWPORT_MARGIN_POINTS: f32 = 72.0; -/// Width of the texture set list -const LIST_WIDTH: f32 = 250.0; -const ICON: f32 = 20.0; -/// Width of the label column of the parameter rows, as in the reference -const LABEL_COLUMN_WIDTH: f32 = 200.0; -/// Width of the value column of the parameter rows -const VALUE_WIDTH: f32 = 360.0; -/// Width of the first File type list; the bit depth list fills the rest of the row -const FILE_TYPE_WIDTH: f32 = 166.0; -/// Width of the dilation button, with room for its drop-down arrow -const DILATION_BUTTON_WIDTH: f32 = 60.0; -/// Size of a drop-down arrow, and its distance from the button's right edge -const CARET_SIZE: f32 = 10.0; -const CARET_INSET: f32 = 6.0; -/// A tab: padding around its name, the accent line on top of the open one, the name's size -const TAB_PADDING: egui::Vec2 = egui::vec2(10.0, 6.0); -const TAB_ACCENT_HEIGHT: f32 = 2.0; -const TAB_TEXT_SIZE: f32 = 12.5; -/// Height of a full-width row of the texture set list and where its text starts -const LIST_ROW_HEIGHT: f32 = 24.0; -const LIST_ROW_INDENT: f32 = 16.0; +/// The content runs nearly to the window's frame: one point inside its edge +const CONTENT_INSET: i8 = 1; +/// The widest dilation the slider offers, the cap `export.run` puts on its `dilation` +const MAX_DILATION_PIXELS: u32 = 256; + +// Layout in points from the window content's top left corner, measured on the locked mocks + +/// The tab row's height, down to the divider under it +pub(crate) const TAB_ROW_HEIGHT: f32 = 42.0; +/// The tabs' top edge +const TAB_TOP: f32 = 16.0; +/// The first tab's left edge +const TABS_LEFT: f32 = 7.5; +/// Middle of the controls at the tab row's right end, 9 points of air above the divider +const TAB_ROW_CONTROLS_Y: f32 = 19.5; +/// From the window's left edge to the buttons there +const LEFT_MARGIN: f32 = 7.5; +/// From the window's right edge to the buttons there +const RIGHT_MARGIN: f32 = 10.5; +/// The bottom bar's height under its divider +const FOOTER_HEIGHT: f32 = 46.0; +/// Middle of the bottom bar's buttons, from the window's bottom +const FOOTER_MIDDLE_FROM_BOTTOM: f32 = 22.5; /// Width of the bottom bar's buttons, the same for all as in the reference -const FOOTER_BUTTON_WIDTH: f32 = 126.0; -/// Width of the keyboard focus outline on the window's drawn controls -const FOCUS_OUTLINE_WIDTH: f32 = 2.0; +const FOOTER_BUTTON_WIDTH: f32 = 117.5; +/// Gap between the bottom bar's buttons +const FOOTER_BUTTON_GAP: f32 = 6.5; +/// Air between the texture count and Cancel +const COUNT_GAP: f32 = 14.5; +/// Open output directory: the air around its name +const OPEN_DIRECTORY_PADDING: f32 = 24.0; +/// Open output directory: its distance from the window's right edge +const OPEN_DIRECTORY_FROM_RIGHT: f32 = 12.0; +/// The strip at a list's right edge that holds its scroll bar +pub(crate) const GUTTER: f32 = 12.0; +/// Size of the menu (≡) and reset glyphs of the lists and pages +const MENU_ICON_SIZE: f32 = 14.0; + +/// Width of the texture set list +const SET_LIST_WIDTH: f32 = 240.7; +/// Centre of the set list's menu, x +const SET_MENU_X: f32 = 227.5; +/// Centre of the set list's menu, y +const SET_MENU_Y: f32 = 57.0; +/// Top of the set list's first row, Global settings +const SET_ROWS_TOP: f32 = 70.0; +/// Height of a set list row +const SET_ROW_HEIGHT: f32 = 25.0; +/// Where a set row's check box starts +const SET_CHECK_LEFT: f32 = 18.8; +/// Where a set row's name starts +const SET_NAME_LEFT: f32 = 36.7; +/// Where Global settings starts, having no check box +const GLOBAL_NAME_LEFT: f32 = 16.0; +/// The override mark's distance from its row's end +const OVERRIDE_MARK_FROM_RIGHT: f32 = 14.0; +/// Side of a check box's click area +const CHECK_HIT_SIZE: f32 = 20.0; +/// How far a check box's click area reaches past its box on each side +const CHECK_HIT_OVERHANG: f32 = 3.5; + +/// A page's label column +const LABEL_LEFT: f32 = 257.6; +/// Where a page's controls start +const CONTROLS_LEFT: f32 = 455.0; +/// Where a page's controls end, from the window's right edge +const CONTROLS_RIGHT_MARGIN: f32 = 112.8; +/// A page header's glyph, from the window's right edge +const PAGE_ICON_FROM_RIGHT: f32 = 22.6; +/// Middle of the Global settings page's header +const GLOBAL_HEADER_Y: f32 = 71.0; +/// Middle of its reset glyph +const GLOBAL_ICON_Y: f32 = 70.0; +/// Middle of its first parameter row +const GLOBAL_FIRST_ROW_Y: f32 = 115.0; +/// Pitch of its parameter rows +const GLOBAL_ROW_PITCH: f32 = 35.5; +/// From the last parameter row to the first tick +const CHECKS_GAP: f32 = 30.0; +/// Pitch of the ticks +const CHECK_PITCH: f32 = 24.0; +/// The page's least width before it scrolls +const MIN_PAGE_WIDTH: f32 = 640.0; +/// The Global settings page's height under the tab row +const GLOBAL_PAGE_HEIGHT: f32 = 376.0; +/// The ticks sit a point in from the labels +const CHECK_INDENT: f32 = 1.0; +/// A tick's label starts after its box and the gap +const CHECK_LABEL_ROOM: f32 = 18.0; +/// Width of the output directory's "…" and reset buttons +#[cfg(not(target_arch = "wasm32"))] +const BROWSE_WIDTH: f32 = 22.0; +/// Gap before them +#[cfg(not(target_arch = "wasm32"))] +const BROWSE_GAP: f32 = 4.0; +/// Room the file type list keeps for its chevron past its longest entry +const FILE_TYPE_ROOM: f32 = 36.0; +/// Gap between two controls on one row +const PAIR_GAP: f32 = 6.6; +/// Width of the dilation width's dropdown +const DILATION_WIDTH: f32 = 56.4; + +/// Middle of a texture set page's header +const SET_HEADER_Y: f32 = 74.0; +/// Middle of its first override row +const SET_FIRST_ROW_Y: f32 = 121.0; +/// Pitch of its override rows +const SET_ROW_PITCH: f32 = 36.0; +/// Centre of the override pens +const PEN_CENTRE: f32 = 464.4; +/// Where an inherited value's text starts +const VALUE_LEFT: f32 = 479.4; +/// Where an override's control starts +const OVERRIDE_LEFT: f32 = 480.3; +/// The divider above Output maps +const SET_DIVIDER_Y: f32 = 257.0; +/// Middle of the Output maps header +const MAPS_HEADER_Y: f32 = 288.0; +/// Top of the first Output maps row +const MAPS_TOP: f32 = 318.0; +/// Pitch of the Output maps rows +const MAP_ROW_PITCH: f32 = 34.0; +/// Leave room for two map rows when the texture-set page scrolls vertically. +const MIN_SET_PAGE_HEIGHT: f32 = MAPS_TOP - TAB_ROW_HEIGHT + 2.0 * MAP_ROW_PITCH; +/// Where an Output maps row's tick starts +const MAP_CHECK_LEFT: f32 = 258.6; +/// Where its file name starts +const MAP_NAME_LEFT: f32 = 280.1; +/// The inherited bit depth's text, after the file type's +const BITS_TEXT_OFFSET: f32 = 32.0; +/// Width of a map's file type list +const MAP_FORMAT_WIDTH: f32 = 61.2; +/// Width of a map's own size list +const MAP_SIZE_WIDTH: f32 = 100.0; + +/// The console's least width: the reference's 300 at TextureCraft's narrower window +pub(crate) const CONSOLE_WIDTH: f32 = 284.0; +/// The file tree's least width +const MIN_TREE_WIDTH: f32 = 300.0; +/// Width of the strip that folds the console +const STRIP_WIDTH: f32 = 17.9; +/// Gap between the file tree and the strip +const STRIP_GAP: f32 = 1.9; +/// Size of the strip's glyph +const STRIP_GLYPH_SIZE: f32 = 13.0; +/// The console text's indent +const CONSOLE_TEXT_INDENT: f32 = 18.0; +/// Middle of the console's header +const CONSOLE_HEADER_Y: f32 = 66.0; +/// Where the console's lines start +const CONSOLE_BODY_TOP: f32 = 89.0; +/// Air above and below the console's lines +const CONSOLE_PADDING: f32 = 6.0; +/// Air above the file tree's first row +const TREE_TOP_PADDING: f32 = 3.0; +/// Height of a file tree row +const TREE_ROW_HEIGHT: f32 = 21.0; +/// Centre of a set's chevron +const TREE_CHEVRON_X: f32 = 13.2; +/// Where a set's name starts +const TREE_NAME_INDENT: f32 = 26.3; +/// Where its files start +const TREE_FILE_INDENT: f32 = 45.1; +/// Gap after the name and size columns +const TREE_COLUMN_GAP: f32 = 28.0; +/// Gap after the file type column +const TREE_BITS_GAP: f32 = 14.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -104,9 +252,16 @@ pub(crate) fn depth_label(format: Option, bit_depth: u8, dithering: } } -/// A file type list and its bit depth list; `from_template` adds "Based on output template" -/// (an empty `format`), which leaves the bit depth to the template. -fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, format: &mut String, bit_depth: &mut u8, dithering: &mut bool) { +/// A file type list and its bit depth list in `rects`; `from_template` adds "Based on output template" (an empty `format`) +fn file_type_lists( + ui: &mut Ui, + id: (&str, usize, usize), + from_template: bool, + rects: [egui::Rect; 2], + format: &mut String, + bit_depth: &mut u8, + dithering: &mut bool, +) { let parsed = FileFormat::from_extension(format); // A depth the type does not have (or none) becomes its default @@ -116,10 +271,7 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f (*bit_depth, *dithering) = (f.default_depth(), false); } let shown = if format.is_empty() { tr("Based on output template").to_string() } else { file_type_name(format) }; - - // Tall enough for the whole list - let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { FILE_TYPE_WIDTH } else { 90.0 }).height(f32::INFINITY); - list.selected_text(shown).show_ui(ui, |ui| { + drawn::combo(ui, rects[0], ("type", id), shown, |ui| { if from_template { if ui.selectable_label(format.is_empty(), tr("Based on output template")).clicked() { format.clear(); @@ -141,18 +293,21 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f } } }); + + // A file type with one bit depth (or none) shows its bit depth list greyed let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; - ui.add_enabled_ui(options.len() > 1, |ui| { - // On the global page the bit depth list fills the row - let width = if from_template { VALUE_WIDTH - FILE_TYPE_WIDTH - ui.spacing().item_spacing.x } else { 120.0 }; - egui::ComboBox::from_id_salt(("bits", id)).width(width).selected_text(shown).show_ui(ui, |ui| { - for (d, dither) in options { - if ui.selectable_label((*bit_depth, *dithering) == (d, dither), depth_label(parsed, d, dither)).clicked() { - (*bit_depth, *dithering) = (d, dither); - } + if options.len() < 2 { + drawn::disabled_combo(ui, rects[1], ("bits", id), &shown, tr("Bit depth")); + return; + } + + drawn::combo(ui, rects[1], ("bits", id), shown, |ui| { + for (depth, dither) in options { + if ui.selectable_label((*bit_depth, *dithering) == (depth, dither), depth_label(parsed, depth, dither)).clicked() { + (*bit_depth, *dithering) = (depth, dither); } - }); + } }); } @@ -179,21 +334,48 @@ fn file_type_name(format: &str) -> String { FileFormat::from_extension(format).map_or_else(|| format.to_string(), |f| f.name().to_string()) } +/// The label shown for a stored template name. Custom template names pass through unchanged. +pub(super) fn template_label<'a>(session: &texturecraft_engine::Session, name: &'a str) -> &'a str { + use texturecraft_engine::preset_cmds::unqualified_preset_name; + + let label = match unqualified_preset_name(name) { + "Unreal Engine Subsurface Profile (Packed)" => tr("Packed maps with a scattering mask"), + "Redshift Standard Material (separate maps)" => tr("Separate coat, sheen and scattering maps"), + "Roblox SurfaceAppearance (separate maps)" => tr("Four maps with opacity in color"), + "Sketchfab Metalness (separate maps)" => tr("Six maps with a negative-Y normal"), + _ => return name, + }; + + if session.has_user_export_preset(name) { name } else { label } +} + /// The template list: the first group (name, whether TextureCraft has it), then the others /// (built-in and user templates) sorted by name. pub(crate) fn template_groups(app: &TextureCraftApp, builtins: &[ExportPreset]) -> (Vec<(&'static str, bool)>, Vec) { let first = FIRST_GROUP.iter().map(|name| (*name, builtins.iter().any(|p| p.name == *name))).collect(); - let mut rest: Vec = builtins.iter().map(|p| p.name.clone()).filter(|n| !FIRST_GROUP.contains(&n.as_str())).collect(); + let mut rest: Vec = builtins + .iter() + .filter(|preset| !FIRST_GROUP.contains(&preset.name.as_str())) + .map(|preset| app.session.builtin_export_preset_id(&preset.name).into_owned()) + .collect(); rest.extend(app.session.export_presets.list.iter().map(|p| p.name.clone())); - rest.sort(); + rest.sort_by(|left, right| template_label(&app.session, left).cmp(template_label(&app.session, right)).then_with(|| left.cmp(right))); rest.dedup(); (first, rest) } -/// A template dropdown over `first` and `rest`; true when `current` changed -fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { +/// A template dropdown in `rect` over `first` and `rest`; true when `current` changed +fn template_combo( + session: &texturecraft_engine::Session, + ui: &mut Ui, + rect: egui::Rect, + id: &str, + current: &mut String, + first: &[(&str, bool)], + rest: &[String], +) -> bool { let mut changed = false; - egui::ComboBox::from_id_salt(id).width(VALUE_WIDTH).selected_text(current.clone()).show_ui(ui, |ui| { + drawn::combo(ui, rect, id, template_label(session, current).to_owned(), |ui| { for (name, have) in first { if *have { changed |= ui.selectable_value(current, (*name).to_string(), *name).on_hover_text(*name).changed(); @@ -203,7 +385,7 @@ fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, b } ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); for name in rest { - changed |= ui.selectable_value(current, name.clone(), name).on_hover_text(name).changed(); + changed |= ui.selectable_value(current, name.clone(), template_label(session, name)).on_hover_text(name).changed(); } }); changed @@ -261,7 +443,10 @@ fn start_export(app: &mut TextureCraftApp) { .collect(); let preview: Vec<_> = pending.iter().filter_map(|(index, params)| plan_set(app, *index, params)).collect(); - let error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)); + let error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)).or_else(|| { + let paths = preview.iter().filter_map(|plan| plan.files.as_ref().ok()).flat_map(planned_names); + texturecraft_engine::formats::export::validate_export_paths(paths).err().map(|error| trf("Export stopped: {error}", &[("error", &error)])) + }); let e = &mut app.ui.export; e.tab = 2; @@ -272,7 +457,15 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, usd_asset: e.usd_asset, ..Default::default() }); + e.job = Some(crate::state::ExportJob { + total: pending.len(), + pending, + preview, + directory: dir, + usd_asset: e.usd_asset, + shader_parameters: e.shader_parameters, + ..Default::default() + }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -373,6 +566,11 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } } + // The last command writes the shader parameters, listing every texture set of the export + if let Some(job) = app.ui.export.job.as_ref().filter(|job| job.shader_parameters && job.pending.is_empty()) { + params["shaderParameters"] = job.preview.iter().filter_map(|plan| plan.index).collect(); + } + let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; @@ -394,8 +592,9 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { }; let files: Vec = response_strings(&response, "files").map(relative).collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; - // The USD asset is no texture: it stays in the list of written files only - for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { + + // The USD asset and the shader parameters are no textures: they stay in the list of written files only + for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd") && !file.to_ascii_lowercase().ends_with(".json")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); @@ -507,6 +706,9 @@ pub(crate) fn set_params(app: &TextureCraftApp, set_index: usize) -> serde_json: settings["bitDepth"] = json!(file_type.bit_depth); settings["dithering"] = json!(file_type.dithering); } + if let Some(size) = map.size { + settings["size"] = json!(size); + } settings }) .collect(); @@ -519,103 +721,165 @@ fn set_template(app: &TextureCraftApp, ts: usize) -> String { app.ui.export.sets.get(&ts).and_then(|o| o.preset.clone()).unwrap_or_else(|| app.ui.export.preset.clone()) } -/// Shorten a long file name pattern at the front, as the reference's Output maps rows do -fn elide_front(text: &str) -> String { - const SHOWN: usize = 26; - let n = text.chars().count(); - if n <= SHOWN { text.to_string() } else { format!("…{}", text.chars().skip(n - (SHOWN - 1)).collect::()) } +/// A file type and bit depth as an Output maps row shows them ("png 8 bits"), and the two apart +fn file_type_text(t: &FileType) -> String { + let (format, bits) = file_type_parts(t); + format!("{format} {bits}") } -/// A file type and bit depth as an Output maps row shows them ("png 8 bits") -fn file_type_text(t: &FileType) -> String { - format!("{} {}", file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) +fn file_type_parts(t: &FileType) -> (String, String) { + (file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) } /// The rows of texture set `ts`'s Output maps: the template's maps the set has sources for -fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { - let mut p = set_params(app, ts); - if let Some(o) = p.as_object_mut() { - o.remove("maps"); - } - let preset = app.session.export_preset(&set_template(app, ts)); - let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", &p) else { return Vec::new() }; - let mut rows: Vec = Vec::new(); - for f in plan.as_array().into_iter().flatten() { - let Some(map) = f.get("map").and_then(serde_json::Value::as_u64).map(|m| m as usize) else { continue }; - if rows.iter().any(|r| r.map == map) { - continue; - } +fn map_rows(app: &TextureCraftApp, ts: usize) -> Vec { + let mut params = set_params(app, ts); - let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); - let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; - let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset - .as_ref() - .and_then(|p| p.maps.get(map)) - .map(|m| m.file.replace("$channel", texturecraft_engine::formats::export::channel_label(m))) - .unwrap_or_default(); - rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); + // Discover maps from their sources so invalid output sizes cannot hide the controls that fix them + if let Some(object) = params.as_object_mut() { + object.remove("maps"); + object.remove("size"); } + + let Ok(options) = texturecraft_engine::file_cmds::export_options(&app.session, ¶ms, "export.plan") else { return Vec::new() }; + let Ok(set) = app.session.doc.project.texture_set(ts) else { return Vec::new() }; + + let mut rows = Vec::new(); + let mut psd_rows = Vec::new(); + let mut psd_depth = 8; + let mut psd_dithering = false; + for (map, spec) in options.preset.maps.iter().enumerate().filter(|(_, spec)| spec.is_available_for(set)) { + let (format, bit_depth, dithering) = options.map_file_type(map, spec); + let pattern = spec.file.replace("$channel", texturecraft_engine::formats::export::channel_label(spec)); + let row = MapRow { map, pattern, inherited: FileType { format: format.name().to_owned(), bit_depth, dithering } }; + if format == FileFormat::Psd { + psd_depth = psd_depth.max(bit_depth); + psd_dithering |= dithering; + psd_rows.push(row); + } else { + rows.push(row); + } + } + + // All PSD rows inherit the document's file type and follow the standalone maps + for mut row in psd_rows { + row.inherited.bit_depth = psd_depth; + row.inherited.dithering = psd_depth == 8 && psd_dithering; + rows.push(row); + } + rows } -/// The Output maps section of texture set `ts`'s page -fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { +/// The Output maps section of texture set `ts`'s page: its header, then its rows scrolling in `area` +fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, area: egui::Rect) { + let look = ExportLook::get(ui.ctx()); let rows = map_rows(app, ts); let template = set_template(app, ts); - let o = app.ui.export.sets.entry(ts).or_default(); - if o.maps_template != template { - o.maps.clear(); - o.maps_template = template; + let overrides = app.ui.export.sets.entry(ts).or_default(); + if overrides.maps_template != template { + overrides.maps.clear(); + overrides.maps_template = template; } + let mut menu = None; - header(ui, tr("Output maps"), |ui| { - list_menu(ui, |ui| { - for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(i); - } + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(MAPS_HEADER_Y), tr("Output maps"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, MAPS_HEADER_Y), tr("Output maps menu"), |ui| { + for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(i); } - ui.separator(); - for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(3 + i); - } + } + ui.separator(); + for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(3 + i); + } + } + ui.separator(); + }); + + // The rows scroll under the header, the scroll bar in its strip at the window's right edge + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(("exp_maps_scroll", ts)).auto_shrink([false; 2]).show(ui, |ui| { + let height = rows.len() as f32 * MAP_ROW_PITCH; + let (rows_rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); + for (index, row) in rows.iter().enumerate() { + let y = rows_rect.top() + (index as f32 + 0.5) * MAP_ROW_PITCH; + map_row(ui, place, y, ts, row, overrides.maps.entry(row.map).or_default()); } - ui.separator(); }); }); - egui::Grid::new(("exp_maps", ts)).num_columns(3).spacing(vec2(8.0, 6.0)).show(ui, |ui| { - for row in &rows { - let m = o.maps.entry(row.map).or_default(); - ui.checkbox(&mut m.enabled, ""); - ui.add(egui::Label::new(elide_front(&row.pattern)).selectable(false)).on_hover_text(&row.pattern); - ui.horizontal(|ui| { - if icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), m.file_type.is_some(), ICON).clicked() { - m.file_type = if m.file_type.is_some() { None } else { Some(row.inherited.clone()) }; - } - match &mut m.file_type { - Some(t) => file_type_combo(ui, ("exp_map", ts, row.map), t), - None => { - ui.label(file_type_text(&row.inherited)); - } - } - }); - ui.end_row(); - } - }); + for row in &rows { - let m = o.maps.entry(row.map).or_default(); + let map_export = overrides.maps.entry(row.map).or_default(); match menu { - Some(0) => m.enabled = true, - Some(1) => m.enabled = false, - Some(2) => m.enabled = !m.enabled, - Some(3) if m.file_type.is_none() => m.file_type = Some(row.inherited.clone()), - Some(4) => m.file_type = None, + Some(0) => map_export.enabled = true, + Some(1) => map_export.enabled = false, + Some(2) => map_export.enabled = !map_export.enabled, + Some(3) if map_export.file_type.is_none() => map_export.file_type = Some(row.inherited.clone()), + Some(4) => (map_export.file_type, map_export.size) = (None, None), _ => {} } } - o.maps.retain(|_, m| *m != MapExport::default()); + overrides.maps.retain(|_, map_export| *map_export != MapExport::default()); +} + +/// One Output maps row at `y`: tick, file name cut at the front, override pen, file type, the map's own size +fn map_row(ui: &mut Ui, place: PagePlace, y: f32, ts: usize, row: &MapRow, map_export: &mut MapExport) { + let look = ExportLook::get(ui.ctx()); + let check_left = place.x(MAP_CHECK_LEFT); + let hit = egui::Rect::from_center_size(egui::pos2(check_left + CHECK_HIT_SIZE / 2.0 - CHECK_HIT_OVERHANG, y), vec2(CHECK_HIT_SIZE, CHECK_HIT_SIZE)); + let name_left = place.x(MAP_NAME_LEFT); + let shown = drawn::fitted(ui, &row.pattern, place.x(CONTROLS_LEFT) - name_left, true, false); + drawn::check(ui, ui.scope_id().with(("exp_map_tick", ts, row.map)), hit, egui::pos2(check_left, y), &mut map_export.enabled, None, &shown); + let color = if map_export.enabled { look.text } else { look.text_dim }; + drawn::label_at(ui, name_left, y, &shown, color, false).on_hover_text(&row.pattern); + + let pen = egui::pos2(place.x(PEN_CENTRE), y); + let name = trf("Enable override for map {number} ({pattern})", &[("number", &(row.map + 1)), ("pattern", &row.pattern)]); + if drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, &name, true, map_export.file_type.is_some()).clicked() { + map_export.file_type = if map_export.file_type.is_some() { None } else { Some(row.inherited.clone()) }; + } + + // The map's size list keeps the row's right end; the file type and bit depth come before it + let right = place.right - CONTROLS_RIGHT_MARGIN; + let size_rect = drawn::control_rect(right - MAP_SIZE_WIDTH, right, y); + match &mut map_export.file_type { + Some(FileType { format, bit_depth, dithering }) => { + let format_rect = drawn::control_rect(place.x(OVERRIDE_LEFT), place.x(OVERRIDE_LEFT) + MAP_FORMAT_WIDTH, y); + let bits_rect = drawn::control_rect(format_rect.right() + PAIR_GAP, size_rect.left() - PAIR_GAP, y); + file_type_lists(ui, ("exp_map", ts, row.map), false, [format_rect, bits_rect], format, bit_depth, dithering); + } + None => inherited_file_type(ui, place, y, &row.inherited), + } + map_size_combo(ui, size_rect, ("exp_map_size", ts, row.map), &mut map_export.size); +} + +/// A map's inherited file type: "png" and "8 bits" in their columns, one text to assistive technology +fn inherited_file_type(ui: &mut Ui, place: PagePlace, y: f32, inherited: &FileType) { + let look = ExportLook::get(ui.ctx()); + let (format, bits) = file_type_parts(inherited); + let format_rect = drawn::text_at(ui, place.x(VALUE_LEFT), y, &format, look.text, false); + let bits_rect = drawn::text_at(ui, place.x(VALUE_LEFT + BITS_TEXT_OFFSET), y, &bits, look.text, false); + let text = file_type_text(inherited); + let response = + ui.interact(format_rect.union(bits_rect), ui.scope_id().with(("exp_map_inherited", place.y(0.0).to_bits(), y.to_bits())), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &text)); +} + +/// An output map's size in `rect`: the export's, or its own, which wins over it +fn map_size_combo(ui: &mut Ui, rect: egui::Rect, id: (&str, usize, usize), size: &mut Option) { + let shown = size.map_or_else(|| tr("Export size").to_string(), |side| format!("{side}x{side}")); + drawn::combo(ui, rect, id, shown, |ui| { + ui.selectable_value(size, None, tr("Export size")); + ui.separator(); + for side in SIZES { + ui.selectable_value(size, Some(side), format!("{side}x{side}")); + } + }) + .response + .on_hover_text(tr("This map's own size, which wins over the export size")); } /// Count the files planned across all selected texture sets. @@ -629,54 +893,10 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } -/// The keyboard focus outline of a drawn control: inside `response`'s rect, in the strong text -/// colour, so it differs from the accent of the selected one and the fill of the hovered one -fn paint_focus(ui: &Ui, response: &egui::Response) { - if response.has_focus() { - let stroke = egui::Stroke::new(FOCUS_OUTLINE_WIDTH, Tokens::get(ui.ctx()).text_strong); - ui.painter().rect_stroke(response.rect, 0.0, stroke, egui::StrokeKind::Inside); - } -} - -/// A window tab: a box, lighter and with an accent line on top when open -fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let color = if selected { tokens.text_strong } else { tokens.text }; - let galley = ui.painter().layout_no_wrap(label.to_string(), semibold(TAB_TEXT_SIZE), color); - let (rect, response) = ui.allocate_exact_size(galley.size() + 2.0 * TAB_PADDING, egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, selected, label)); - - let painter = ui.painter(); - let fill = match (selected, response.hovered()) { - (true, _) => tokens.panel, - (false, true) => tokens.row_hover, - (false, false) => tokens.row, - }; - painter.rect(rect, 0.0, fill, egui::Stroke::new(1.0, tokens.separator), egui::StrokeKind::Inside); - if selected { - painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); - } - painter.galley(rect.min + TAB_PADDING, galley, color); - paint_focus(ui, &response); - response -} - -/// A bottom bar button, as wide as the others -fn footer_button(text: &str) -> egui::Button<'_> { - egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) -} - -/// A header with a menu or tool at its right end -fn header(ui: &mut Ui, title: &str, right: impl FnOnce(&mut Ui)) { - ui.horizontal(|ui| { - ui.label(caption(title)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), right); - }); -} - -/// The menu button of a list header -fn list_menu(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { - ui.menu_button(RichText::new(ic::LIST_CHECKS).size(15.0), add); +/// The menu button (≡) of a list or page header centred on `centre`, called `name` for assistive technology; its menu holds `add` +fn list_menu(ui: &mut Ui, centre: egui::Pos2, name: &str, add: impl FnOnce(&mut Ui)) { + let response = drawn::icon_button(ui, centre, ic::LIST, MENU_ICON_SIZE, name, true, false); + egui::Popup::menu(&response).show(add); } /// Check all, Uncheck all, Invert all over the texture sets @@ -695,55 +915,57 @@ fn set_checks_menu(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); } -/// Output directory: the path as a button that opens the folder picker, and a reset -#[cfg(not(target_arch = "wasm32"))] -fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("Output directory")); - ui.horizontal(|ui| { - let dir = app.ui.export.dir.clone(); - let button = egui::Button::new(dir.as_str()).truncate(); - if ui.add_sized(vec2(VALUE_WIDTH - 24.0, 20.0), button).on_hover_text(dir.as_str()).clicked() { - app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { - if let Some(d) = paths.first() { - app.ui.export.dir = d.display().to_string(); - } - }); - } - if ui.small_button("R").on_hover_text(tr("Reset to default")).clicked() { - app.ui.export.dir = ExportUi::default().dir; - } - }); - ui.end_row(); +/// A parameter's name at the label column, its middle at `y` +fn row_label(ui: &mut Ui, place: PagePlace, y: f32, text: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), y, text, look.text, false); } -/// The dilation width: a button showing it, with a slider in its menu (only for paddings that -/// have a width) -fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { - let enabled = has_width(padding); - - // The menu stays open while the slider is used - let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); - let r = ui.add_enabled_ui(enabled, |ui| { - let button = egui::Button::new(dilation.to_string()).min_size(vec2(DILATION_BUTTON_WIDTH, 0.0)); - egui::containers::menu::MenuButton::from_button(button).config(config).ui(ui, |ui| { - ui.label(tr("Dilation (pixels)")); - ui.add(egui::Slider::new(dilation, 0..=256).step_by(1.0)); - }) - }); - - // The drop-down arrow is drawn apart, so the button's name stays the number - let tokens = Tokens::get(ui.ctx()); - let arrow_color = if enabled { tokens.text } else { tokens.text_dim }; - let arrow_at = r.response.rect.right_center() - vec2(CARET_INSET, 0.0); - ui.painter().text(arrow_at, egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_SIZE), arrow_color); - if enabled { - r.response.on_hover_text(tr("Dilation in pixels")); - } else { - r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); +/// Output directory at `y`: the path as a field that opens the folder picker, "…" and a reset +#[cfg(not(target_arch = "wasm32"))] +fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, y: f32) { + row_label(ui, place, y, tr("Output directory")); + let right = place.right - CONTROLS_RIGHT_MARGIN; + let dir = app.ui.export.dir.clone(); + let field = drawn::control_rect(place.x(CONTROLS_LEFT), right - BROWSE_WIDTH - BROWSE_GAP, y); + let path = drawn::field_button(ui, field, ui.scope_id().with("exp_dir"), &dir).on_hover_text(dir.as_str()); + let browse_rect = drawn::control_rect(right - BROWSE_WIDTH, right, y); + let browse_name = tr("Choose the output folder"); + let browse = drawn::button_with_id(ui, ui.scope_id().with("exp_dir_browse"), browse_rect, "…", browse_name, false, true).on_hover_text(browse_name); + if path.clicked() || browse.clicked() { + app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { + if let Some(directory) = paths.first() { + app.ui.export.dir = directory.display().to_string(); + } + }); + } + let reset = drawn::control_rect(right + BROWSE_GAP, right + BROWSE_GAP + BROWSE_WIDTH, y); + let reset_id = ui.scope_id().with("exp_dir_reset"); + let reset_name = tr("Reset to default"); + if drawn::button_with_id(ui, reset_id, reset, ic::ARROW_COUNTER_CLOCKWISE, reset_name, false, true).on_hover_text(reset_name).clicked() { + app.ui.export.dir = ExportUi::default().dir; } } +/// The dilation width in `rect`: a dropdown with a slider in its menu, greyed for paddings without a width +fn dilation_button(ui: &mut Ui, rect: egui::Rect, id_salt: &str, padding: &str, dilation: &mut u32) { + let enabled = has_width(padding); + let response = drawn::combo_button(ui, rect, ui.scope_id().with(("exp_dilation", id_salt)), &dilation.to_string(), enabled); + if !enabled { + response.on_hover_text(tr("This padding mode does not use a dilation width")); + return; + } + + // The menu stays open while the slider is used + let response = response.on_hover_text(tr("Dilation in pixels")); + egui::Popup::menu(&response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.label(tr("Dilation (pixels)")); + ui.add(egui::Slider::new(dilation, 0..=MAX_DILATION_PIXELS).step_by(1.0)); + }); +} + /// A greyed checkbox with its tooltip and the "not available" hint +#[cfg(target_arch = "wasm32")] fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { let mut off = false; ui.add_enabled(false, egui::Checkbox::new(&mut off, label)).on_disabled_hover_ui(|ui| { @@ -752,13 +974,21 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { }); } -/// The Global settings page -fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { - let mut reset = false; - header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); - }); - if reset { +/// A tick of the global page at `y` with its label after it +fn page_check(ui: &mut Ui, place: PagePlace, y: f32, on: &mut bool, label: &str) -> egui::Response { + let left = place.x(LABEL_LEFT + CHECK_INDENT); + let width = CHECK_LABEL_ROOM + drawn::text_width(ui, label, false); + let hit = egui::Rect::from_min_max(egui::pos2(left, y - CHECK_HIT_SIZE / 2.0), egui::pos2(left + width, y + CHECK_HIT_SIZE / 2.0)); + drawn::check(ui, ui.scope_id().with(("exp_check", label)), hit, egui::pos2(left, y), on, Some(label), label) +} + +/// The Global settings page, laid out from `place` +fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, builtins: &[ExportPreset]) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(GLOBAL_HEADER_Y), tr("General Export Parameters"), look.text, true); + let reset_at = place.right_inset(PAGE_ICON_FROM_RIGHT, GLOBAL_ICON_Y); + let reset_tip = tr("Restore the default export parameters"); + if drawn::icon_button(ui, reset_at, ic::ARROW_COUNTER_CLOCKWISE, MENU_ICON_SIZE, reset_tip, true, false).on_hover_text(reset_tip).clicked() { let defaults = ExportUi::default(); let settings = &mut app.ui.export; ( @@ -773,6 +1003,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] settings.color_space, settings.usd_asset, settings.materialx, + settings.shader_parameters, ) = ( defaults.dir, defaults.format, @@ -785,170 +1016,191 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] defaults.color_space, defaults.usd_asset, defaults.materialx, + defaults.shader_parameters, ); crate::export_templates::select(app, defaults.preset); } + + // One row per parameter at the reference's pitch; the browser has no output directory + let mut rows = (0..).map(|k| place.y(GLOBAL_FIRST_ROW_Y + k as f32 * GLOBAL_ROW_PITCH)); + let mut next_row = || rows.next().unwrap_or_default(); + let (left, right) = (place.x(CONTROLS_LEFT), place.right - CONTROLS_RIGHT_MARGIN); + #[cfg(not(target_arch = "wasm32"))] + output_directory(app, ui, place, next_row()); + + let y = next_row(); + row_label(ui, place, y, tr("Output template")); let (first, rest) = template_groups(app, builtins); - egui::Grid::new("exp_grid").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - // The browser downloads the files instead - #[cfg(not(target_arch = "wasm32"))] - output_directory(app, ui); - ui.label(tr("Output template")); - let mut picked = app.ui.export.preset.clone(); - if template_combo(ui, "exp_preset", &mut picked, &first, &rest) { - crate::export_templates::select(app, picked); + let mut picked = app.ui.export.preset.clone(); + if template_combo(&app.session, ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { + crate::export_templates::select(app, picked); + } + + // The file type list fits its longest entry, the bit depth list fills the rest + let y = next_row(); + row_label(ui, place, y, tr("File type")); + let type_right = left + drawn::text_width(ui, tr("Based on output template"), false) + FILE_TYPE_ROOM; + let rects = [drawn::control_rect(left, type_right, y), drawn::control_rect(type_right + PAIR_GAP, right, y)]; + let settings = &mut app.ui.export; + file_type_lists(ui, ("exp_global", 0, 0), true, rects, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); + + let y = next_row(); + row_label(ui, place, y, tr("Size")); + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_size", size_label(settings.size), |ui| { + ui.selectable_value(&mut settings.size, 0, size_label(0)); + ui.separator(); + ui.selectable_value(&mut settings.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); + for size in SIZES { + ui.selectable_value(&mut settings.size, size, size_label(size)); } - ui.end_row(); - ui.label(tr("File type")); - ui.horizontal(|ui| { - let settings = &mut app.ui.export; - file_type_lists(ui, ("exp_global", 0, 0), true, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); - }); - ui.end_row(); - ui.label(tr("Size")); - let settings = &mut app.ui.export; - egui::ComboBox::from_id_salt("exp_size").width(VALUE_WIDTH).selected_text(size_label(settings.size)).show_ui(ui, |ui| { - ui.selectable_value(&mut settings.size, 0, size_label(0)); - ui.separator(); - ui.selectable_value(&mut settings.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); - for size in SIZES { - ui.selectable_value(&mut settings.size, size, size_label(size)); - } - }); - ui.end_row(); - ui.label(tr("Padding")); - ui.horizontal(|ui| { - let width = VALUE_WIDTH - DILATION_BUTTON_WIDTH - ui.spacing().item_spacing.x; - egui::ComboBox::from_id_salt("exp_pad").width(width).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { - for (value, label) in PADDINGS { - ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); - } - }); - dilation_button(ui, &settings.padding, &mut settings.dilation); - }); - ui.end_row(); }); - // The browser downloads the textures only, so it has no USD asset to add - #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")) - .on_hover_text(tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures")); - #[cfg(target_arch = "wasm32")] - unavailable_checkbox( - ui, - tr("Export USD asset"), - tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"), - ); + let y = next_row(); + row_label(ui, place, y, tr("Padding")); + let padding_rect = drawn::control_rect(left, right - DILATION_WIDTH - PAIR_GAP, y); + drawn::combo(ui, padding_rect, "exp_pad", tr(padding_label(&settings.padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, drawn::control_rect(right - DILATION_WIDTH, right, y), "global", &settings.padding, &mut settings.dilation); - // The MaterialX export sits below the USD one; the browser downloads the textures only - #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.materialx, tr("Export MaterialX")); - #[cfg(target_arch = "wasm32")] - crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); + let y = next_row(); + row_label(ui, place, y, tr("Normal map format")); + let normal_label = match settings.normal_format.as_str() { + "openGl" => "OpenGL", + "directX" => "DirectX", + _ => tr("From template / project"), + }; + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_nf", normal_label, |ui| { + for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { + ui.selectable_value(&mut settings.normal_format, value.to_string(), label); + } + }); - // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); - ui.add_space(8.0); - egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let settings = &mut app.ui.export; - ui.label(tr("Normal map format")); - let normal_label = match settings.normal_format.as_str() { - "openGl" => "OpenGL", - "directX" => "DirectX", - _ => tr("From template / project"), + let y = next_row(); + row_label(ui, place, y, tr("Color space")); + let shown = if settings.color_space.is_empty() { tr("Default").to_string() } else { settings.color_space.clone() }; + let color_space = drawn::combo(ui, drawn::control_rect(left, right, y), "exp_cs", shown, |ui| { + ui.selectable_value(&mut settings.color_space, String::new(), tr("Default")); + for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { + ui.selectable_value(&mut settings.color_space, name.to_string(), name); + } + }); + color_space.response.on_hover_text(tr("Color maps only: normal, roughness, metallic and other data maps stay linear")); + + // The extra files, ticked under the parameters + let mut checks = (0..).map(|k| y + CHECKS_GAP + k as f32 * CHECK_PITCH); + let mut next_check = || checks.next().unwrap_or_default(); + let usd_tip = tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.usd_asset, tr("Export USD asset")).on_hover_text(usd_tip); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.materialx, tr("Export MaterialX")); + #[cfg(target_arch = "wasm32")] + { + let at = |y: f32| { + egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::pos2(place.x(LABEL_LEFT), y - CHECK_HIT_SIZE / 2.0), vec2(right, CHECK_HIT_SIZE))) }; - egui::ComboBox::from_id_salt("exp_nf").selected_text(normal_label).show_ui(ui, |ui| { - for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { - ui.selectable_value(&mut settings.normal_format, value.to_string(), label); - } - }); - ui.end_row(); - ui.label(tr("Color space")); - let shown = if settings.color_space.is_empty() { tr("Default") } else { settings.color_space.as_str() }; - egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| { - ui.selectable_value(&mut settings.color_space, String::new(), tr("Default")); - for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { - ui.selectable_value(&mut settings.color_space, name.to_string(), name); - } - }); - ui.end_row(); - }); + ui.scope_builder(at(next_check()), |ui| unavailable_checkbox(ui, tr("Export USD asset"), usd_tip)); + ui.scope_builder(at(next_check()), |ui| crate::unavailable::checkbox(ui, false, tr("Export MaterialX"))); + } + page_check(ui, place, next_check(), &mut settings.shader_parameters, tr("Export shader settings")) + .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); } -/// The left column: Global settings, then a row per texture set with its export tick; a click -/// on a row shows the set's page, "*" marks a set with overrides -fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); - }); - let header = list_row(ui, tr("Global settings"), app.ui.export.page.is_none()); - if header.clicked() { +/// The texture set list in `area`: Global settings, then a tick and a page per texture set, "*" on one with overrides +fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::Rect) { + let top = area.top() - TAB_ROW_HEIGHT; + list_menu(ui, egui::pos2(area.left() + SET_MENU_X, top + SET_MENU_Y), tr("Texture set list menu"), |ui| set_checks_menu(app, ui)); + let rows_right = area.right() - GUTTER; + let header = egui::Rect::from_min_max(egui::pos2(area.left(), top + SET_ROWS_TOP), egui::pos2(rows_right, top + SET_ROWS_TOP + SET_ROW_HEIGHT)); + if list_row(ui, header, tr("Global settings"), app.ui.export.page.is_none()).clicked() { app.ui.export.page = None; } - // Many texture sets scroll inside the list; the footer stays in view - let list_height = ui.available_height(); - egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); + // Many texture sets scroll under Global settings, the scroll bar in its strip at the list's right + let rows = egui::Rect::from_min_max(egui::pos2(area.left(), header.bottom()), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("export_texture_sets").auto_shrink([false; 2]).show(ui, |ui| set_rows(app, ui, rows.width() - GUTTER)); + }); } -/// A row across the whole list, its name in bold; the selected one framed -fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), LIST_ROW_HEIGHT), egui::Sense::click()); +/// A list row across `rect`, its name in bold +fn list_row(ui: &mut Ui, rect: egui::Rect, text: &str, selected: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_list_row", text)), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, text)); - - let painter = ui.painter(); - if selected { - painter.rect(rect, 0.0, tokens.row_selected, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); - } else if response.hovered() { - painter.rect_filled(rect, 0.0, tokens.row_hover); - } - let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); - painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); - paint_focus(ui, &response); + paint_row(ui, rect, selected, response.hovered()); + drawn::text_at(ui, rect.left() + GLOBAL_NAME_LEFT, rect.center().y, text, look.text, true); + drawn::paint_focus(ui, &response); response } -/// A row per texture set: its export tick, its name and the override mark -fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { +/// A list row's face: the selected one in the frame colour with a light edge; a hairline under every row +fn paint_row(ui: &Ui, rect: egui::Rect, selected: bool, hovered: bool) { + let look = ExportLook::get(ui.ctx()); + let painter = ui.painter(); + if selected { + painter.rect(rect, 0.0, look.chrome, egui::Stroke::new(1.0, look.outline), egui::StrokeKind::Inside); + } else if hovered { + painter.rect_filled(rect, 0.0, look.raised); + } + painter.rect_filled(egui::Rect::from_min_max(rect.left_bottom(), rect.right_bottom() + vec2(0.0, 1.0)), 0.0, look.chrome); +} + +/// A row per texture set, `width` wide: its export tick, its name and the override mark +fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32) { + let look = ExportLook::get(ui.ctx()); + ui.spacing_mut().item_spacing.y = 0.0; for i in 0..app.session.set_count() { let name = app.session.doc.project.texture_sets.get(i).map(|t| t.name.clone()).unwrap_or_default(); + let (row, _) = ui.allocate_exact_size(vec2(width, SET_ROW_HEIGHT), egui::Sense::hover()); + let y = row.center().y; + + // The tick leaves the set in or out, the name after it opens the set's page + let name_area = egui::Rect::from_min_max(egui::pos2(row.left() + SET_NAME_LEFT - drawn::CHECK_LABEL_GAP, row.top()), row.max); + let selected = app.ui.export.page == Some(i); + paint_row(ui, row, selected, ui.rect_contains_pointer(name_area)); let mut on = !app.ui.export.skip.contains(&i); - ui.horizontal(|ui| { - if ui.checkbox(&mut on, "").changed() { - if on { - app.ui.export.skip.retain(|x| *x != i); - } else { - app.ui.export.skip.push(i); - } + let tick_area = egui::Rect::from_min_max(row.min, egui::pos2(name_area.left(), row.bottom())); + let tick_name = trf("Include {set}", &[("set", &name)]); + if drawn::check(ui, ui.scope_id().with(("exp_set_tick", i)), tick_area, egui::pos2(row.left() + SET_CHECK_LEFT, y), &mut on, None, &tick_name).changed() + { + if on { + app.ui.export.skip.retain(|x| *x != i); + } else { + app.ui.export.skip.push(i); } - if ui.selectable_label(app.ui.export.page == Some(i), name).clicked() { - app.ui.export.page = Some(i); - } - if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label("*").on_hover_text(tr("Override(s) active")); - }); - } - }); - ui.separator(); + } + + let page = ui.interact(name_area, ui.scope_id().with(("exp_set_row", i)), egui::Sense::click()); + page.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &name)); + if page.clicked() { + app.ui.export.page = Some(i); + } + + let color = if on { look.text } else { look.text_dim }; + drawn::text_at(ui, row.left() + SET_NAME_LEFT, y, &name, color, true); + drawn::paint_focus(ui, &page); + if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { + drawn::label_at(ui, row.right() - OVERRIDE_MARK_FROM_RIGHT, y, "*", look.text_dim, true).on_hover_text(tr("Override(s) active")); + } } } -/// A texture set page row: the label, the override toggle, then the inherited value as text or, -/// overridden, `edit`; true when the toggle was clicked -fn override_row(ui: &mut Ui, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui)) -> bool { - ui.label(label); - let mut toggled = false; - ui.horizontal(|ui| { - toggled = icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), on, ICON).clicked(); - if on { - edit(ui); - } else { - ui.label(inherited); - } - }); - ui.end_row(); +/// A texture set page row at `y`: label, pen, then the inherited value or `edit`; true when the pen was clicked +fn override_row(ui: &mut Ui, place: PagePlace, y: f32, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui, egui::Rect)) -> bool { + let look = ExportLook::get(ui.ctx()); + row_label(ui, place, y, label); + let pen = egui::pos2(place.x(PEN_CENTRE), y); + let name = trf("Enable override for {setting}", &[("setting", &label)]); + let toggled = drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, &name, true, on).clicked(); + if on { + edit(ui, drawn::control_rect(place.x(OVERRIDE_LEFT), place.right - CONTROLS_RIGHT_MARGIN, y)); + } else { + drawn::label_at(ui, place.x(VALUE_LEFT), y, inherited, look.text, false); + } toggled } @@ -972,23 +1224,14 @@ fn toggle(o: &mut SetExport, row: usize, from: &InheritedSettings) { } } -/// A file type dropdown (without "Based on output template") and its bit depth -fn file_type_combo(ui: &mut Ui, id: (&str, usize, usize), t: &mut FileType) { - file_type_lists(ui, id, false, &mut t.format, &mut t.bit_depth, &mut t.dithering); -} - -/// A texture set's page: its overrides of the global settings -fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[ExportPreset]) { +/// A texture set's page from `place`: its overrides, then its output maps scrolling down to `bottom` +fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, bottom: f32, builtins: &[ExportPreset]) { let Some(set) = app.session.doc.project.texture_sets.get(ts) else { return }; let own = set.block_resolution(); let mut from = InheritedSettings::for_texture_set(app, own); - // "Based on output template": the override starts from what the template writes - if app.ui.export.format.is_empty() && app.ui.export.sets.get(&ts).is_none_or(|o| o.file_type.is_none()) { - from.file_type = template_file_type(app, ts); - } let (first, rest) = template_groups(app, builtins); - let first: Vec<(&str, bool)> = first.into_iter().filter(|(n, _)| !NOT_PER_SET.contains(n)).collect(); + let first: Vec<(&str, bool)> = first.into_iter().filter(|(name, _)| !NOT_PER_SET.contains(name)).collect(); let global = &app.ui.export; let inherited_file_type = if global.format.is_empty() { tr("Based on output template").to_string() } else { file_type_text(&from.file_type) }; let inherited_size = match global.size { @@ -997,135 +1240,131 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor }; let inherited_padding = tr(padding_label(&global.padding)).to_string(); - let o = app.ui.export.sets.entry(ts).or_default(); + let look = ExportLook::get(ui.ctx()); + let overrides = app.ui.export.sets.entry(ts).or_default(); let mut all = None; - header(ui, tr("General Export Parameters"), |ui| { - list_menu(ui, |ui| { - if ui.button(tr("Override every item")).clicked() { - all = Some(true); - } - if ui.button(tr("Clear all overrides")).clicked() { - all = Some(false); - } - ui.separator(); - }); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(SET_HEADER_Y), tr("General Export Parameters"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, SET_HEADER_Y), tr("General Export Parameters menu"), |ui| { + if ui.button(tr("Override every item")).clicked() { + all = Some(true); + } + if ui.button(tr("Clear all overrides")).clicked() { + all = Some(false); + } + ui.separator(); }); + + let row_y = |row: usize| place.y(SET_FIRST_ROW_Y + row as f32 * SET_ROW_PITCH); let mut toggled = None; - egui::Grid::new(("exp_set_grid", ts)).num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let on = o.preset.is_some(); - if override_row(ui, tr("Output template"), on, &from.preset, |ui| { - if let Some(p) = &mut o.preset { - template_combo(ui, "exp_set_preset", p, &first, &rest); - } - }) { - toggled = Some(0); + if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), template_label(&app.session, &from.preset), |ui, rect| { + if let Some(preset) = &mut overrides.preset { + template_combo(&app.session, ui, rect, "exp_set_preset", preset, &first, &rest); } - let on = o.file_type.is_some(); - if override_row(ui, tr("File type"), on, &inherited_file_type, |ui| { - if let Some(t) = &mut o.file_type { - file_type_combo(ui, ("exp_set", ts, usize::MAX), t); - } - }) { - toggled = Some(1); - } - let on = o.size.is_some(); - if override_row(ui, tr("Size"), on, &inherited_size, |ui| { - if let Some(size) = &mut o.size { - egui::ComboBox::from_id_salt("exp_set_size").width(VALUE_WIDTH).selected_text(set_size_label(*size, own)).show_ui(ui, |ui| { - for r in SIZES { - ui.selectable_value(size, r, set_size_label(r, own)); - } - }); - } - }) { - toggled = Some(2); - } - let on = o.padding.is_some(); - if override_row(ui, tr("Padding"), on, &inherited_padding, |ui| { - if let Some((padding, dilation)) = &mut o.padding { - egui::ComboBox::from_id_salt("exp_set_pad").width(260.0).selected_text(tr(padding_label(padding))).show_ui(ui, |ui| { - for (v, l) in PADDINGS { - ui.selectable_value(padding, v.to_string(), tr(l)); - } - }); - dilation_button(ui, padding, dilation); - } - }) { - toggled = Some(3); - } - }); - if let Some(row) = toggled { - toggle(o, row, &from); + }) { + toggled = Some(0); } - match all { - Some(true) => { - for row in 0..4 { - let on = [o.preset.is_some(), o.file_type.is_some(), o.size.is_some(), o.padding.is_some()]; - if !on.get(row).copied().unwrap_or(true) { - toggle(o, row, &from); + if override_row(ui, place, row_y(1), tr("File type"), overrides.file_type.is_some(), &inherited_file_type, |ui, rect| { + if let Some(file_type) = &mut overrides.file_type { + let type_rect = rect.with_max_x(rect.left() + MAP_FORMAT_WIDTH); + let rects = [type_rect, rect.with_min_x(type_rect.right() + PAIR_GAP)]; + file_type_lists(ui, ("exp_set", ts, usize::MAX), false, rects, &mut file_type.format, &mut file_type.bit_depth, &mut file_type.dithering); + } + }) { + toggled = Some(1); + } + if override_row(ui, place, row_y(2), tr("Size"), overrides.size.is_some(), &inherited_size, |ui, rect| { + if let Some(size) = &mut overrides.size { + drawn::combo(ui, rect, "exp_set_size", set_size_label(*size, own), |ui| { + for side in SIZES { + ui.selectable_value(size, side, set_size_label(side, own)); + } + }); + } + }) { + toggled = Some(2); + } + if override_row(ui, place, row_y(3), tr("Padding"), overrides.padding.is_some(), &inherited_padding, |ui, rect| { + if let Some((padding, dilation)) = &mut overrides.padding { + drawn::combo(ui, rect.with_max_x(rect.right() - DILATION_WIDTH - PAIR_GAP), "exp_set_pad", tr(padding_label(padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, rect.with_min_x(rect.right() - DILATION_WIDTH), "set", padding, dilation); + } + }) { + toggled = Some(3); + } + if toggled.is_some() || all.is_some() { + // A new file-type override inherits the effective formats of the current template + if (toggled == Some(1) || all == Some(true)) && overrides.file_type.is_none() && app.ui.export.format.is_empty() { + from.file_type = template_file_type(app, ts); + } + + let overrides = app.ui.export.sets.entry(ts).or_default(); + if let Some(row) = toggled { + toggle(overrides, row, &from); + } + match all { + Some(true) => { + for row in 0..4 { + let on = [overrides.preset.is_some(), overrides.file_type.is_some(), overrides.size.is_some(), overrides.padding.is_some()]; + if !on.get(row).copied().unwrap_or(true) { + toggle(overrides, row, &from); + } } } + Some(false) => { + overrides.preset = None; + overrides.file_type = None; + overrides.size = None; + overrides.padding = None; + } + None => {} } - Some(false) => { - o.preset = None; - o.file_type = None; - o.size = None; - o.padding = None; - } - None => {} } - ui.add_space(8.0); - ui.separator(); - egui::ScrollArea::vertical().id_salt("exp_maps_scroll").auto_shrink([false; 2]).show(ui, |ui| output_maps(app, ui, ts)); + + // A divider across the page, then the output maps + let page_left = place.x(SET_LIST_WIDTH + 1.0); + drawn::divider(ui, egui::Rect::from_min_max(egui::pos2(page_left, place.y(SET_DIVIDER_Y)), egui::pos2(place.right, place.y(SET_DIVIDER_Y) + 1.0))); + let maps_area = egui::Rect::from_min_max(egui::pos2(page_left, place.y(MAPS_TOP)), egui::pos2(place.right, bottom)); + output_maps(app, ui, ts, place, maps_area); if app.ui.export.sets.get(&ts).is_some_and(SetExport::is_default) { app.ui.export.sets.remove(&ts); } } -/// The LIST OF EXPORTS console's and file tree's least width, as in the reference -const CONSOLE_WIDTH: f32 = 300.0; -const MIN_TREE_WIDTH: f32 = 300.0; -/// Width of the strip between the file tree and the console -const SPLITTER_WIDTH: f32 = 14.0; -/// Padding of the CONSOLE header band, about 45 points high as in the reference -const CONSOLE_HEADER_MARGIN_X: i8 = 12; -const CONSOLE_HEADER_MARGIN_Y: i8 = 14; -/// The file tree: indent of the file rows under their texture set, and the row height -const TREE_INDENT: f32 = 35.0; -const TREE_ROW_HEIGHT: f32 = 17.0; -/// Half the width of the tree's chevron -const CHEVRON_HALF_WIDTH: f32 = 4.0; - /// Green of the console's success lines fn success(tk: &Tokens) -> egui::Color32 { if tk.dark { egui::Color32::from_rgb(110, 200, 120) } else { egui::Color32::from_rgb(30, 130, 50) } } -/// The LIST OF EXPORTS tab: a tree of the files each ticked texture set exports (file, size, -/// file type, bit depth; the full path as tooltip), and the console -fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The LIST OF EXPORTS tab in `body`: the file tree with each file's path as tooltip, the fold strip and the console +fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { + let look = ExportLook::get(ui.ctx()); let tk = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; - // Tree and console keep at least their reference width - let spacing = ui.spacing().item_spacing.x; - let room = ui.available_width() - SPLITTER_WIDTH - 2.0 * spacing; + // The console keeps at least its least width, the tree at least its own + let room = body.width() - STRIP_WIDTH - STRIP_GAP - 1.0; let console_width = app.ui.export.console_width.min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); - let tree_width = if hidden { room } else { room - console_width }; - ui.vertical(|ui| { - ui.set_width(tree_width); - egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); + let console_left = if hidden { body.right() + 1.0 } else { body.right() - console_width }; + let strip = egui::Rect::from_min_max(egui::pos2(console_left - 1.0 - STRIP_WIDTH, body.top() + 1.0), egui::pos2(console_left - 1.0, body.bottom())); + let tree = egui::Rect::from_min_max(egui::pos2(body.left(), body.top() + 1.0), egui::pos2(strip.left() - STRIP_GAP, body.bottom())); + ui.painter().rect_filled(tree, 0.0, look.chrome); + ui.scope_builder(egui::UiBuilder::new().max_rect(tree), |ui| { + egui::ScrollArea::both().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it - let (strip, response) = ui.allocate_exact_size(vec2(SPLITTER_WIDTH, ui.available_height()), egui::Sense::click_and_drag()); + drawn::divider(ui, egui::Rect::from_min_max(strip.right_top(), egui::pos2(strip.right() + 1.0, strip.bottom()))); + let response = ui.interact(strip, ui.scope_id().with("exp_console_strip"), egui::Sense::click_and_drag()); let tooltip = if hidden { tr("Show Console") } else { tr("Hide Console") }; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip)); let glyph = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; - ui.painter().rect_filled(strip, 0.0, tk.chrome); - ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); - paint_focus(ui, &response); + let glyph_color = if response.hovered() { look.text } else { look.text_dim }; + drawn::glyph(ui, strip.center(), glyph, STRIP_GLYPH_SIZE, glyph_color); + drawn::paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); @@ -1135,31 +1374,33 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } else if response.clicked() { app.ui.export.console_hidden = !hidden; } - if !hidden { - ui.vertical(|ui| { - ui.set_width(console_width); - egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(caption(&tr("Console").to_uppercase()).strong()); - }); - let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); - console.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show(ui, |ui| { - for line in &app.ui.export.console { - match line { - ConsoleLine::Step(t) => { - ui.label(t); - } - ConsoleLine::Done(t) => { - ui.label(RichText::new(t).color(success(&tk))); - } - ConsoleLine::Set(name) => { - ui.label(set_line(ui, name, &tk)); - } - } - } - }); - }); + if hidden { + return; } + + // The console: its header on the window colour, its lines on the frame colour below + let top = body.top() - TAB_ROW_HEIGHT; + let console = egui::Rect::from_min_max(egui::pos2(console_left, body.top() + 1.0), body.max); + drawn::label_at(ui, console.left() + CONSOLE_TEXT_INDENT, top + CONSOLE_HEADER_Y, tr("Console"), look.text, true); + let lines = egui::Rect::from_min_max(egui::pos2(console.left(), top + CONSOLE_BODY_TOP), console.max); + ui.painter().rect_filled(lines, 0.0, look.chrome); + let inner = lines.shrink2(vec2(0.0, CONSOLE_PADDING)).with_min_x(lines.left() + CONSOLE_TEXT_INDENT); + ui.scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| { + let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); + console.show(ui, |ui| { + for (index, line) in app.ui.export.console.iter().enumerate() { + let response = match line { + ConsoleLine::Step(text) => ui.label(text), + ConsoleLine::Done(text) => ui.label(RichText::new(text).color(success(&tk))), + ConsoleLine::Set(name) => ui.label(set_line(ui, name, &tk)), + }; + + if index + 1 == app.ui.export.console.len() { + ui.ctx().accesskit_node_builder(response.id, |node| node.set_live(egui::accesskit::Live::Polite)); + } + } + }); + }); } /// "Texture set " with the name in bold @@ -1175,22 +1416,56 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { job } -/// One expandable node per ticked texture set, a row per file +/// One foldable node per ticked texture set, a row per file; the columns start after the longest file name fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { - if let Some(job) = &app.ui.export.job - && !job.preview.is_empty() - { - for (index, set) in job.preview.iter().enumerate() { - export_tree_set(ui, index, set, &job.directory, tk); + let (sets, directory): (Vec<(usize, ExportSetPlan)>, String) = match &app.ui.export.job { + Some(job) if !job.preview.is_empty() => (job.preview.iter().cloned().enumerate().collect(), job.directory.clone()), + _ => { + let planned = export_selection(app).into_iter().filter_map(|ts| { + let params = set_params(app, ts); + plan_set(app, ts, ¶ms).map(|set| (ts, set)) + }); + (planned.collect(), app.ui.export.dir.clone()) } - return; - } + }; + let rows: Vec> = sets.iter().map(|(_, set)| tree_files(set, &directory)).collect(); + let longest = |text: fn(&TreeFile) -> &str| rows.iter().flatten().map(|file| drawn::text_width(ui, text(file), false)).fold(0.0, f32::max); + let columns = { + let size = TREE_FILE_INDENT + longest(|f| &f.name) + TREE_COLUMN_GAP; + let format = size + longest(|f| &f.size) + TREE_COLUMN_GAP; + [size, format, format + longest(|f| &f.format) + TREE_BITS_GAP] + }; - for ts in export_selection(app) { - let params = set_params(app, ts); - if let Some(set) = plan_set(app, ts, ¶ms) { - export_tree_set(ui, ts, &set, &app.ui.export.dir, tk); + // Each set takes its header row, its files when open and a blank row + let open: Vec = sets.iter().map(|(index, _)| ui.data(|d| d.get_temp::(tree_id(ui, *index))).unwrap_or(true)).collect(); + let row_count: usize = sets + .iter() + .zip(&rows) + .zip(&open) + .map(|(((_, set), files), open)| 1 + 1 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) + .sum(); + let width = ui.available_width().max(columns[2] + longest(|file| &file.bits) + TREE_BITS_GAP); + let height = TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT; + let (area, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); + + let mut y = area.top() + TREE_TOP_PADDING; + for (((index, set), files), open) in sets.iter().zip(&rows).zip(open) { + let header = egui::Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + TREE_ROW_HEIGHT)); + if tree_header(ui, header, &set.name, open, tree_id(ui, *index)) { + ui.data_mut(|d| d.insert_temp(tree_id(ui, *index), !open)); } + y += TREE_ROW_HEIGHT; + if open { + if let Err(error) = &set.files { + drawn::label_at(ui, area.left() + TREE_FILE_INDENT, y + TREE_ROW_HEIGHT / 2.0, error, tk.danger, false); + y += TREE_ROW_HEIGHT; + } + for file in files { + tree_file(ui, area.left(), y + TREE_ROW_HEIGHT / 2.0, columns, file); + y += TREE_ROW_HEIGHT; + } + } + y += TREE_ROW_HEIGHT; } } @@ -1202,47 +1477,75 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) Some(ExportSetPlan { index: Some(index), name, files }) } -fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &str, tokens: &Tokens) { - ui.spacing_mut().indent = TREE_INDENT; - let header = egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).icon(chevron); - header.show(ui, |ui| match &set.files { - Ok(files) => { - egui::Grid::new(("exp_tree_grid", index)).num_columns(4).min_row_height(TREE_ROW_HEIGHT).spacing(vec2(12.0, 4.0)).show(ui, |ui| { - for output in files.as_array().into_iter().flatten() { - let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); - let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); - let depth = output.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; - let dithering = output.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let size = output["size"].as_u64().unwrap_or_default() as u32; - let source_size = output["sourceSize"].as_u64().unwrap_or_default() as u32; - let path = std::path::Path::new(directory).join(file).display().to_string(); - ui.label(file).on_hover_text(&path); - ui.label(set_size_label(size, source_size)).on_hover_text(&path); - ui.label(format.map_or("", FileFormat::name)).on_hover_text(&path); - ui.label(depth_label(format, depth, dithering)).on_hover_text(&path); - ui.end_row(); - } - }); - } - Err(error) => { - ui.label(RichText::new(error).color(tokens.danger)); - } - }); +/// Where a texture set's node keeps whether it is open +fn tree_id(ui: &Ui, index: usize) -> egui::Id { + ui.scope_id().with(("exp_tree", index)) } -/// The tree's outline chevron: pointing down when open, right (left in right-to-left) when closed -fn chevron(ui: &mut Ui, openness: f32, response: &egui::Response) { - let color = Tokens::get(ui.ctx()).text; - let center = response.rect.center(); - let half = CHEVRON_HALF_WIDTH; - let points = if openness > 0.5 { - [center + vec2(-half, -half / 2.0), center + vec2(0.0, half / 2.0), center + vec2(half, -half / 2.0)] - } else if ui.style().right_to_left { - [center + vec2(half / 2.0, -half), center + vec2(-half / 2.0, 0.0), center + vec2(half / 2.0, half)] - } else { - [center + vec2(-half / 2.0, -half), center + vec2(half / 2.0, 0.0), center + vec2(-half / 2.0, half)] +/// The texts of each file `set` plans: name, size, file type, bit depth and its whole path +fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { + let Ok(files) = &set.files else { return Vec::new() }; + + let to_text = |output: &serde_json::Value| { + let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); + let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); + let depth = output.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; + let dithering = output.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); + let size = output["size"].as_u64().unwrap_or_default() as u32; + let source_size = output["sourceSize"].as_u64().unwrap_or_default() as u32; + TreeFile { + name: file.to_string(), + size: set_size_label(size, source_size), + format: format.map_or("", FileFormat::name).to_string(), + bits: depth_label(format, depth, dithering), + path: std::path::Path::new(directory).join(file).display().to_string(), + } }; - ui.painter().add(egui::Shape::line(points.to_vec(), egui::Stroke::new(1.5, color))); + files.as_array().into_iter().flatten().map(to_text).collect() +} + +/// A texture set's node row: the chevron and its name in bold; true when clicked +fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, egui::Sense::click()); + + // Expose the hand-drawn header as a disclosure control + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); + + let y = rect.center().y; + let chevron = if open { + ic::CARET_DOWN + } else if ui.style().right_to_left { + ic::CARET_LEFT + } else { + ic::CARET_RIGHT + }; + drawn::glyph(ui, egui::pos2(rect.left() + TREE_CHEVRON_X, y), chevron, drawn::CHEVRON_SIZE, look.text); + drawn::text_at(ui, rect.left() + TREE_NAME_INDENT, y, name, look.text, true); + drawn::paint_focus(ui, &response); + + if response.has_focus() && rect.width() > ui.clip_rect().width() { + let direction = ui.input_mut(|input| { + let start = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft); + let end = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight); + i8::from(start) - i8::from(end) + }); + if direction != 0 { + ui.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); + ui.scroll_with_delta(vec2(f32::from(direction) * ui.clip_rect().width() / 2.0, 0.0)); + } + } + + response.clicked() +} + +/// A file's row at `y`: its name, then size, file type and bit depth in `columns`, each with the whole path as tooltip +fn tree_file(ui: &mut Ui, left: f32, y: f32, columns: [f32; 3], file: &TreeFile) { + let look = ExportLook::get(ui.ctx()); + let texts = [(TREE_FILE_INDENT, &file.name), (columns[0], &file.size), (columns[1], &file.format), (columns[2], &file.bits)]; + for (x, text) in texts { + drawn::label_at(ui, left + x, y, text, look.text, false).on_hover_text(&file.path); + } } /// Show the output folder in the system's file manager (created first when missing) @@ -1422,8 +1725,106 @@ fn cancel(app: &mut TextureCraftApp) { app.ui.windows.export = false; } +/// Escape closes the window as Cancel does after shortcut routing checks higher-priority inputs. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { + if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { + app.ui.export.job = None; + cancel(app); + } +} + +/// The bottom bar: Export, Save settings, Cancel and the texture count, Reset all on SETTINGS; while exporting, progress +fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do_export: &mut bool, canceled: &mut bool) { + let slot = |k: f32| { + let right = window.right() - RIGHT_MARGIN - k * (FOOTER_BUTTON_WIDTH + FOOTER_BUTTON_GAP); + drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, y) + }; + if let Some(job) = &app.ui.export.job { + let done = job.total - job.pending.len(); + let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; + if drawn::button(ui, slot(0.0), tr("Cancel Export"), false, true).clicked() { + app.ui.export.job = None; + } + let bar = drawn::control_rect(window.left() + LEFT_MARGIN, slot(0.0).left() - FOOTER_BUTTON_GAP, y); + let look = ExportLook::get(ui.ctx()); + let response = ui.put(bar, egui::ProgressBar::new(progress).fill(look.outline).text(format!("{:.0}%", progress * 100.0))); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_live(egui::accesskit::Live::Polite)); + return; + } + + // OUTPUT TEMPLATES shows no count; a template edit that does not validate holds Save and Export + let templates_tab = app.ui.export.tab == 1; + let draft_valid = app.ui.export.draft.as_ref().is_none_or(|draft| draft.validate().is_ok()); + let any = !export_selection(app).is_empty() && draft_valid; + let export = drawn::button(ui, slot(0.0), tr("Export"), true, any); + if export.on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")).clicked() { + *do_export = true; + } + + // Saving closes the window without starting an export + let save = drawn::button(ui, slot(1.0), tr("Save settings"), false, draft_valid); + if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { + app.ui.windows.export = false; + } + let cancel = drawn::button(ui, slot(2.0), tr("Cancel"), false, true); + if cancel.on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { + *canceled = true; + } + if !templates_tab { + let look = ExportLook::get(ui.ctx()); + let count = trf("{n} textures selected for export", &[("n", &selected_texture_count(app))]); + let left = slot(2.0).left() - COUNT_GAP - drawn::text_width(ui, &count, false); + drawn::label_at(ui, left, y, &count, look.text_dim, false); + } + + let reset_rect = drawn::control_rect(window.left() + LEFT_MARGIN, window.left() + LEFT_MARGIN + FOOTER_BUTTON_WIDTH, y); + if app.ui.export.tab == 0 + && drawn::button(ui, reset_rect, tr("Reset all"), false, true).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() + { + // Keep ownership so Cancel can restore the opening settings + let e = &mut app.ui.export; + let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); + app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; + } +} + +/// The SETTINGS tab in `body`: the texture set list, a divider, then the selected page +fn settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect, presets: &[ExportPreset]) { + let list = body.with_max_x(body.left() + SET_LIST_WIDTH); + set_list(app, ui, list); + drawn::divider(ui, egui::Rect::from_min_max(list.right_top(), list.right_bottom() + vec2(1.0, 0.0))); + let page = body.with_min_x(list.right() + 1.0); + match app.ui.export.page { + Some(ts) if ts < app.session.set_count() => { + ui.scope_builder(egui::UiBuilder::new().max_rect(page), |ui| { + egui::ScrollArea::both().id_salt("export_texture_set_page").auto_shrink([false; 2]).show(ui, |ui| { + let size = vec2(ui.available_width().max(MIN_PAGE_WIDTH), ui.available_height().max(MIN_SET_PAGE_HEIGHT)); + let (content, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + let place = PagePlace { left: content.left() - list.width() - 1.0, top: content.top() - TAB_ROW_HEIGHT, right: content.right() }; + set_page(app, ui, ts, place, content.bottom(), presets); + }); + }); + } + + // A short or narrow window scrolls the page, so every control stays reachable + _ => { + ui.scope_builder(egui::UiBuilder::new().max_rect(page), |ui| { + egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false; 2]).show(ui, |ui| { + let size = vec2(ui.available_width().max(MIN_PAGE_WIDTH), GLOBAL_PAGE_HEIGHT); + let (content, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + let place = PagePlace { left: content.left() - list.width() - 1.0, top: content.top() - TAB_ROW_HEIGHT, right: content.right() }; + global_page(app, ui, place, presets); + }); + }); + } + } +} + pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let showing_templates = app.ui.export.tab == 1; if !app.ui.windows.export { + crate::export_templates::clear_map_previews(ctx); + // The window opens on SETTINGS again; an export stops with it let e = &mut app.ui.export; e.job = None; @@ -1436,7 +1837,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } // Settings saved under the default template's old name - if let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) + if !app.session.has_user_export_preset(&app.ui.export.preset) + && let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) && b.name != app.ui.export.preset { app.ui.export.preset = b.name; @@ -1457,15 +1859,19 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let mut do_export = false; let mut canceled = false; - let presets = texturecraft_engine::formats::builtin_presets(); - // The reference size on a screen that has room for it, smaller on a smaller one; resizable from there. - // The window's size counts its frame and title bar, the reference size only the content + let presets = texturecraft_engine::formats::builtin_preset_catalog(); + let look = ExportLook::get(ctx); + + // The reference size includes the frame and title bar let style = ctx.global_style(); + let title_frame = egui::Frame::window(&style); + let frame = title_frame.inner_margin(CONTENT_INSET); let title_height = ctx.fonts_mut(|fonts| fonts.row_height(&egui::TextStyle::Heading.resolve(&style))) + style.spacing.item_spacing.y; - let chrome = egui::Frame::window(&style).total_margin().sum() + vec2(0.0, title_height); + let chrome = vec2(frame.total_margin().sum().x, title_frame.total_margin().sum().y + title_height); let window_size = (REFERENCE_WINDOW_SIZE_POINTS + chrome).min(ctx.content_rect().size() - vec2(WINDOW_VIEWPORT_MARGIN_POINTS, WINDOW_VIEWPORT_MARGIN_POINTS)); - let dialog = crate::windows::dialog(ctx, "export_textures", tr("Export Textures"), &mut open).default_size(window_size); + let dialog = + crate::windows::dialog(ctx, "export_textures", tr("Export textures"), &mut open).title_frame(title_frame).frame(frame).default_size(window_size); dialog.show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { @@ -1473,140 +1879,69 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - // While exporting: the progress and Cancel Export - if let Some(job) = &app.ui.export.job { - let done = job.total - job.pending.len(); - let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Cancel Export")).clicked() { - app.ui.export.job = None; - } - let percent = format!("{:.0}%", progress * 100.0); - ui.add(egui::ProgressBar::new(progress).text(percent)); - }); - }); - } else { - // OUTPUT TEMPLATES edits the templates only: no count, nothing to reset, save or export there - let templates_tab = app.ui.export.tab == 1; - let selected = if templates_tab { 0 } else { selected_texture_count(app) }; - ui.horizontal(|ui| { - // Only on SETTINGS - if app.ui.export.tab == 0 - && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() - { - // Keep ownership so Cancel can restore the opening settings - let e = &mut app.ui.export; - let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); - app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Nothing to write without a ticked texture set - let any = !export_selection(app).is_empty() && !templates_tab; - if ui - .add_enabled(any, footer_button(tr("Export"))) - .on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")) - .clicked() - { - do_export = true; - } + look.apply(ui.style_mut()); + let window = ui.max_rect(); + ui.allocate_rect(window, egui::Sense::hover()); + let body = + egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_ROW_HEIGHT), egui::pos2(window.right(), window.bottom() - FOOTER_HEIGHT)); - // Saving closes the window without starting an export - let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); - if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { - app.ui.windows.export = false; - } - if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { - canceled = true; - } - if !templates_tab { - ui.label(trf("{n} textures selected for export", &[("n", &selected)])); - } - }); - }); - } - ui.separator(); - ui.add_space(8.0); - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.horizontal(|ui| { - // Boxed tabs side by side - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if tab_button(ui, &t.to_uppercase(), app.ui.export.tab == i as u8).clicked() { - app.ui.export.tab = i as u8; - } - } - }); + // The tabs, and the tab's own control at the row's right end + let tab_strip = egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_TOP), egui::pos2(window.right(), body.top())); + let labels = [tr("Settings"), tr("Output templates"), tr("List of exports")]; + if let Some(tab) = drawn::tabs(ui, tab_strip, window.left() + TABS_LEFT, &labels, usize::from(app.ui.export.tab)) { + app.ui.export.tab = tab as u8; + } + let right = window.right() - RIGHT_MARGIN; + let row_y = window.top() + TAB_ROW_CONTROLS_Y; + match app.ui.export.tab { + 1 => crate::export_templates::naming_pattern(ui, window.right(), row_y), + 2 => { + let width = drawn::text_width(ui, tr("Open output directory"), false) + OPEN_DIRECTORY_PADDING; + let rect = drawn::control_rect(window.right() - OPEN_DIRECTORY_FROM_RIGHT - width, window.right() - OPEN_DIRECTORY_FROM_RIGHT, row_y); - // The file list opens the destination folder - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if app.ui.export.tab == 2 { - // The browser downloads the files instead - #[cfg(target_arch = "wasm32")] - crate::unavailable::greyed(ui, |ui| ui.button(tr("Open output directory"))); - #[cfg(not(target_arch = "wasm32"))] - if ui.button(tr("Open output directory")).clicked() { - open_output_directory(app); - } - } else if app.ui.export.tab == 1 { - crate::export_templates::naming_pattern(ui); - } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { - app.ui.export.skip.clear(); - for o in app.ui.export.sets.values_mut() { - o.maps.values_mut().for_each(|m| m.enabled = true); - } - app.ui.export.sets.retain(|_, o| !o.is_default()); - } - }); - }); - ui.separator(); - let body = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), ui.available_height().max(0.0))); - - // The tabs size their columns from the body's width. A child that cannot widen the - // resizable window holds them, so an overflow is clipped instead of growing the window each frame - let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); - body_ui.shrink_clip_rect(body); - ui.advance_cursor_after_rect(body); - let ui = &mut body_ui; - 'tab: { - ui.set_height(body.height()); - match app.ui.export.tab { - 1 => { - crate::export_templates::tab(app, ui, &presets); - break 'tab; - } - 2 => { - list_tab(app, ui); - break 'tab; - } - _ => {} - } - - ui.vertical(|ui| { - ui.set_width(LIST_WIDTH); - set_list(app, ui); - }); - ui.separator(); - - // A short or narrow window scrolls the settings, so the footer and every control stay reachable - ui.vertical(|ui| { - egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false, false]).min_scrolled_height(0.0).show(ui, |ui| match app - .ui - .export - .page - { - Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), - _ => global_page(app, ui, &presets), - }); - }); + // The browser downloads the files instead + #[cfg(target_arch = "wasm32")] + drawn::button(ui, rect, tr("Open output directory"), false, false).on_hover_text(tr(NOT_AVAILABLE)); + #[cfg(not(target_arch = "wasm32"))] + if drawn::button(ui, rect, tr("Open output directory"), false, true).clicked() { + open_output_directory(app); } - }); - }); + } + _ => { + let rect = drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, row_y); + if drawn::button(ui, rect, tr("Include all"), false, true).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { + app.ui.export.skip.clear(); + for o in app.ui.export.sets.values_mut() { + o.maps.values_mut().for_each(|m| m.enabled = true); + } + app.ui.export.sets.retain(|_, o| !o.is_default()); + } + } + } + + let footer_y = window.bottom() - FOOTER_MIDDLE_FROM_BOTTOM; + drawn::divider(ui, egui::Rect::from_min_max(body.left_bottom(), body.right_bottom() + vec2(0.0, 1.0))); + footer(app, ui, window, footer_y, &mut do_export, &mut canceled); + + // The tabs lay out from the body; a child clips what an overflow would draw past it + let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); + body_ui.shrink_clip_rect(body); + let ui = &mut body_ui; + match app.ui.export.tab { + 1 => crate::export_templates::tab(app, ui, body, presets), + 2 => list_tab(app, ui, body), + _ => settings_tab(app, ui, body, presets), + } }); crate::export_templates::ask(app, ctx); + // Keep text focus before egui clears it on Escape + app.ui.export.field_had_keyboard = ctx.text_edit_focused(); + + if (showing_templates || app.ui.export.tab == 1) && (canceled || !open || !app.ui.windows.export || app.ui.export.tab != 1 || do_export) { + crate::export_templates::clear_map_previews(ctx); + } + // Dismissal must run before the next write if canceled || !open { app.ui.export.job = None; diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs new file mode 100644 index 00000000..9f92508f --- /dev/null +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -0,0 +1,334 @@ +//! The Export textures window's own controls, drawn at the places its layout gives them: tabs, +//! checks, dropdowns, buttons and icon buttons in the window's colours ([`ExportLook`]) + +use egui::{Align2, Color32, CornerRadius, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::export_look::{CONTROL_HEIGHT, CONTROL_RADIUS, ExportLook, TEXT_SIZE}; +use crate::theme::semibold; + +/// Side and corner radius of a check box +const CHECK_SIZE: f32 = 13.0; +const CHECK_RADIUS: u8 = 2; + +/// The tick inside a check box: its three points from the box's left edge and centre, and its width +const TICK_POINTS: [(f32, f32); 3] = [(3.2, 0.2), (5.6, 2.6), (9.8, -2.6)]; +const TICK_WIDTH: f32 = 1.7; + +/// Air between a check box and its label +pub(crate) const CHECK_LABEL_GAP: f32 = 5.0; + +/// From a dropdown's left edge to its value, and from its right edge to its chevron's centre +pub(crate) const VALUE_INSET: f32 = 7.0; +pub(crate) const CHEVRON_INSET: f32 = 11.0; + +/// Size of a chevron and of the window's icons +pub(crate) const CHEVRON_SIZE: f32 = 12.0; + +/// The air on either side of a tab's name +const TAB_PADDING: f32 = 14.0; +/// A tab's corner radius +const TAB_RADIUS: u8 = 4; +/// Gap between tabs +const TAB_GAP: f32 = 3.0; +/// How far a tab reaches under the divider, where the body's colour covers its lower corners +const TAB_OVERLAP: f32 = 4.0; + +/// A quiet dropdown's hover face: its padding round the value and chevron, and half its height +const TEXT_DROPDOWN_PADDING: f32 = 3.0; +const TEXT_DROPDOWN_HALF_HEIGHT: f32 = 9.0; + +/// Hit area of an icon button around its glyph +const ICON_HIT_SIZE: f32 = 20.0; + +/// Width of the keyboard focus outline on the window's drawn controls +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; + +/// Whether a control that cannot be used looks greyed; a built-in template's cards keep their look +pub(crate) fn looks_disabled(ui: &Ui, enabled: bool) -> bool { + !enabled && ui.visuals().disabled_alpha() < 1.0 +} + +/// The window's regular and semibold text +pub(crate) fn font(bold: bool) -> FontId { + if bold { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) } +} + +/// Width of `text` in the window's font +pub(crate) fn text_width(ui: &Ui, text: &str, bold: bool) -> f32 { + ui.painter().layout_no_wrap(text.to_owned(), font(bold), Color32::WHITE).size().x +} + +/// `text` with its left edge at `left` and its middle at `y` +pub(crate) fn text_at(ui: &Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Rect { + ui.painter().text(pos2(left, y), Align2::LEFT_CENTER, text, font(bold), color) +} + +/// `text` cut with "…" at its end (or its start, for file names) to fit `room` +pub(crate) fn fitted(ui: &Ui, text: &str, room: f32, from_start: bool, bold: bool) -> String { + if text_width(ui, text, bold) <= room { + return text.to_owned(); + } + + let mut cuts: Vec<_> = text.char_indices().skip(1).map(|(offset, _)| offset).collect(); + if !from_start { + cuts.reverse(); + } + + let truncate = |cut| if from_start { format!("…{}", &text[cut..]) } else { format!("{}…", &text[..cut]) }; + let first_fit = cuts.partition_point(|&cut| text_width(ui, &truncate(cut), bold) > room); + cuts.get(first_fit).map_or_else(|| "…".to_owned(), |&cut| truncate(cut)) +} + +/// A glyph centred on `centre` +pub(crate) fn glyph(ui: &Ui, centre: Pos2, glyph: &str, size: f32, color: Color32) { + ui.painter().text(centre, Align2::CENTER_CENTER, glyph, FontId::proportional(size), color); +} + +/// The keyboard focus outline of a drawn control, in the text colour +pub(crate) fn paint_focus(ui: &Ui, response: &Response) { + if response.has_focus() { + let stroke = Stroke::new(FOCUS_OUTLINE_WIDTH, ExportLook::get(ui.ctx()).text); + ui.painter().rect_stroke(response.rect, CONTROL_RADIUS, stroke, StrokeKind::Inside); + } +} + +/// A horizontal or vertical divider line, one point thick +pub(crate) fn divider(ui: &Ui, rect: Rect) { + ui.painter().rect_filled(rect, 0.0, ExportLook::get(ui.ctx()).divider); +} + +/// Sentence-case rounded tabs along `strip`'s bottom from `left`, the open one joined to the body; returns the clicked one +pub(crate) fn tabs(ui: &mut Ui, strip: Rect, left: f32, labels: &[&str], open: usize) -> Option { + let look = ExportLook::get(ui.ctx()); + let bottom = strip.bottom(); + divider(ui, Rect::from_min_max(pos2(strip.left(), bottom - 1.0), pos2(strip.right(), bottom))); + let mut clicked = None; + let mut x = left; + for (index, label) in labels.iter().enumerate() { + let selected = index == open; + let width = text_width(ui, label, selected) + 2.0 * TAB_PADDING; + let rect = Rect::from_min_max(pos2(x, strip.top()), pos2(x + width, bottom)); + let response = ui.interact(rect, ui.scope_id().with(("export_tab", index)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, selected, *label)); + + // The tab's lower corners reach under the divider and are covered by the body's colour + let painter = ui.painter(); + let face = Rect::from_min_max(rect.min, pos2(rect.right(), bottom + TAB_OVERLAP)); + let below = Rect::from_min_max(pos2(rect.left(), bottom - 1.0), pos2(rect.right(), bottom + TAB_OVERLAP + 1.0)); + if selected { + painter.rect(face, TAB_RADIUS, look.window, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.rect_filled(below.shrink2(vec2(1.0, 0.0)), 0.0, look.window); + } else { + let fill = if response.hovered() { look.raised } else { look.chrome }; + painter.rect_filled(face.with_min_y(face.top() + 1.0), TAB_RADIUS, fill); + painter.rect_filled(below, 0.0, look.window); + painter.rect_filled(below.with_max_y(bottom), 0.0, look.divider); + } + let color = if selected || response.hovered() { look.text } else { look.text_dim }; + painter.text(rect.center() + vec2(0.0, 1.0), Align2::CENTER_CENTER, *label, font(selected), color); + paint_focus(ui, &response); + if response.clicked() { + clicked = Some(index); + } + x += width + TAB_GAP; + } + clicked +} + +/// A check box from `left` with its middle at `y`: dim and ticked when on, dark with a light edge when off +pub(crate) fn paint_check(ui: &Ui, left: f32, y: f32, on: bool) { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_min_size(pos2(left, y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + let painter = ui.painter(); + if on { + painter.rect_filled(rect, CHECK_RADIUS, look.text_dim); + let points = TICK_POINTS.iter().map(|(dx, dy)| pos2(left + dx, y + dy)).collect(); + painter.add(egui::Shape::line(points, Stroke::new(TICK_WIDTH, look.window))); + } else { + painter.rect(rect, CHECK_RADIUS, look.control, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } +} + +/// A check box at `at` (its left edge's middle) with `label` after it, toggled by a click in `hit` +pub(crate) fn check(ui: &mut Ui, id: Id, hit: Rect, at: Pos2, on: &mut bool, label: Option<&str>, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let mut response = ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + response.mark_changed(); + } + let checked = *on; + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, checked, name)); + paint_check(ui, at.x, at.y, checked); + if let Some(label) = label { + text_at(ui, at.x + CHECK_SIZE + CHECK_LABEL_GAP, at.y, label, look.text, false); + } + paint_focus(ui, &response); + response +} + +/// The rect of a control `left`..`right` with its middle at `y` +pub(crate) fn control_rect(left: f32, right: f32, y: f32) -> Rect { + Rect::from_min_max(pos2(left, y - CONTROL_HEIGHT / 2.0), pos2(right, y + CONTROL_HEIGHT / 2.0)) +} + +/// A dropdown's chevron, pointing up while its list is open, drawn just inside the right edge of the button `rect` +pub(crate) fn chevron_icon(ui: &Ui, rect: Rect, visuals: &egui::style::WidgetVisuals, open: bool) { + let centre = pos2(rect.right() + VALUE_INSET - CHEVRON_INSET, rect.center().y); + glyph(ui, centre, if open { ic::CARET_UP } else { ic::CARET_DOWN }, CHEVRON_SIZE, visuals.fg_stroke.color); +} + +/// A dropdown filling `rect`, showing `shown`, its list as wide as it and flush under it +pub(crate) fn combo( + ui: &mut Ui, + rect: Rect, + id: impl std::hash::Hash + std::fmt::Debug, + shown: impl Into, + list: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse> { + let look = ExportLook::get(ui.ctx()); + let shown: String = shown.into(); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + egui::ComboBox::from_id_salt(id) + .width(rect.width()) + .height(f32::INFINITY) + .selected_text(shown) + .wrap_mode(egui::TextWrapMode::Truncate) + .icon(chevron_icon) + .popup_style(look.list_style()) + .show_ui(ui, list) + }) + .inner +} + +/// A button drawn as a dropdown showing `shown`, for a menu that is no option list; lighter when it cannot be used +pub(crate) fn combo_button(ui: &mut Ui, rect: Rect, id: Id, shown: &str, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, shown)); + let (fill, color) = match (enabled, response.hovered()) { + (false, _) => (look.raised, look.text_dim), + (true, true) => (look.raised, look.text), + (true, false) => (look.control, look.text), + }; + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, fill, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), color); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} + +/// A field showing `text` cut with "…" at its end that acts as a button, as the output directory does +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn field_button(ui: &mut Ui, rect: Rect, id: Id, text: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, text)); + let border = if response.hovered() { look.outline } else { look.control_border }; + ui.painter().rect(rect, CONTROL_RADIUS, look.control, Stroke::new(1.0, border), StrokeKind::Inside); + let shown = fitted(ui, text, rect.width() - 2.0 * VALUE_INSET, false, false); + text_at(ui, rect.left() + VALUE_INSET, rect.center().y, &shown, look.text, false); + paint_focus(ui, &response); + response +} + +/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim; `id` tells it from the rows' other ones +pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", id)), Sense::hover()); + response.widget_info(|| { + let mut info = WidgetInfo::labeled(Role::ComboBox, false, name); + info.current_text_value = Some(shown.to_owned()); + info + }); + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), look.text_dim); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, look.text_dim); + response +} + +/// Text that reads as a label to assistive technology and tests: `text` from `left`, its middle at `y`; its response takes a tooltip +pub(crate) fn label_at(ui: &mut Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Response { + let rect = text_at(ui, left, y, text, color, bold); + let response = ui.interact(rect, ui.scope_id().with(("export_label", text, left.to_bits(), y.to_bits())), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, text)); + response +} + +/// A button filling `rect`: a step darker than the window with a light edge, or the accent for the one primary action +pub(crate) fn button(ui: &mut Ui, rect: Rect, label: &str, primary: bool, enabled: bool) -> Response { + let id = ui.scope_id().with(("export_button", label)); + button_with_id(ui, id, rect, label, label, primary, enabled) +} + +/// [`button`] for one of several buttons with the same label (each output map card's "$") +pub(crate) fn button_with_id(ui: &mut Ui, id: Id, rect: Rect, label: &str, name: &str, primary: bool, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, name)); + let (fill, border) = match (primary, enabled && response.hovered()) { + (true, _) => (look.accent, look.accent), + (false, true) => (look.raised, look.outline), + (false, false) => (look.control, look.control_border), + }; + let painter = ui.painter(); + let fade = if enabled { 1.0 } else { ui.visuals().disabled_alpha() }; + painter.rect(rect, CONTROL_RADIUS, fill.gamma_multiply(fade), Stroke::new(1.0, border.gamma_multiply(fade)), StrokeKind::Inside); + let color = if looks_disabled(ui, enabled) { + look.text_dim + } else if primary { + look.lettering_on(fill) + } else { + look.text + }; + painter.text(rect.center(), Align2::CENTER_CENTER, label, font(primary), color); + paint_focus(ui, &response); + response +} + +/// A glyph that acts as a button, centred on `centre`; `lit` frames it as switched on +pub(crate) fn icon_button(ui: &mut Ui, centre: Pos2, icon: &str, size: f32, name: &str, enabled: bool, lit: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_center_size(centre, vec2(ICON_HIT_SIZE, ICON_HIT_SIZE)); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, ui.scope_id().with(("export_icon", name)), sense); + response.widget_info(|| WidgetInfo::selected(Role::Button, enabled, lit, name)); + if lit { + ui.painter().rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } + let color = match (enabled, lit || response.hovered()) { + (false, _) if looks_disabled(ui, enabled) => look.control_border, + (false, _) => look.text_dim, + (true, true) => look.text, + (true, false) => look.text_dim, + }; + glyph(ui, centre, icon, size, color); + paint_focus(ui, &response); + response +} + +/// A card's quiet dropdown: its value from `value_left` and a chevron at `chevron_x`, no box +pub(crate) fn text_dropdown(ui: &mut Ui, id: Id, value_left: f32, chevron_x: f32, y: f32, value: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let enabled = ui.is_enabled(); + let rect = Rect::from_min_max( + pos2(value_left - TEXT_DROPDOWN_PADDING, y - TEXT_DROPDOWN_HALF_HEIGHT), + pos2(chevron_x + CHEVRON_SIZE / 2.0 + TEXT_DROPDOWN_PADDING, y + TEXT_DROPDOWN_HALF_HEIGHT), + ); + let response = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() }); + let name = format!("{value} {}", ic::CARET_DOWN); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &name)); + if response.hovered() && enabled { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), look.raised); + } + let color = if looks_disabled(ui, enabled) { look.text_dim } else { look.text }; + text_at(ui, value_left, y, value, color, false); + glyph(ui, pos2(chevron_x, y), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} diff --git a/crates/ui-egui/src/export_window/export_look.rs b/crates/ui-egui/src/export_window/export_look.rs new file mode 100644 index 00000000..0d8c862b --- /dev/null +++ b/crates/ui-egui/src/export_window/export_look.rs @@ -0,0 +1,160 @@ +use egui::{Color32, CornerRadius, Stroke, Style, TextStyle, style::StyleModifier}; + +use crate::theme::{Tokens, contrast_ratio, lerp_color}; + +/// Text size of the whole window, labels and values alike +pub(crate) const TEXT_SIZE: f32 = 12.0; + +/// Height and corner radius of the window's controls: dropdowns, fields and buttons +pub(crate) const CONTROL_HEIGHT: f32 = 25.0; +pub(crate) const CONTROL_RADIUS: u8 = 3; + +/// Height of an option in an open list +const OPTION_HEIGHT: f32 = 22.0; +/// An open list's margin round its options +const LIST_MARGIN: i8 = 3; +/// An option's text inset, lining up with the dropdown's value above it +const OPTION_INSET: f32 = 3.0; + +/// A scroll bar's strip beside its list: the bar and the air on either side of it +const SCROLL_BAR_WIDTH: f32 = 4.0; +const SCROLL_BAR_MARGIN: f32 = 4.0; + +/// How far the dividers sit below the frame colour, so they read on it +const DIVIDER_DARKENING: f32 = 0.26; + +/// Split the difference between the field outline and text so control edges read against the panel +const BORDER_TEXT_MIX: f32 = 0.5; + +/// How far the Presets list's names sit from the text colour towards the dim one +const LIST_TEXT_DIMMING: f32 = 0.37; + +/// The Export textures window's colours from the theme: controls a step darker than the window, raised faces a step lighter +#[derive(Clone, Copy)] +pub(crate) struct ExportLook { + pub(crate) window: Color32, + pub(crate) control: Color32, + pub(crate) control_border: Color32, + /// A step lighter than controls: hover, lit and unusable faces + pub(crate) raised: Color32, + pub(crate) chrome: Color32, + pub(crate) divider: Color32, + pub(crate) outline: Color32, + pub(crate) text: Color32, + pub(crate) text_dim: Color32, + pub(crate) list_text: Color32, + pub(crate) accent: Color32, +} + +impl ExportLook { + pub(crate) fn get(ctx: &egui::Context) -> Self { + let tokens = Tokens::get(ctx); + Self { + window: tokens.panel, + control: tokens.row, + control_border: lerp_color(tokens.field_border, tokens.text, BORDER_TEXT_MIX), + raised: tokens.separator, + chrome: tokens.chrome, + divider: lerp_color(tokens.chrome, Color32::BLACK, DIVIDER_DARKENING), + outline: lerp_color(tokens.button_border, tokens.text, BORDER_TEXT_MIX), + text: tokens.text, + text_dim: tokens.text_dim, + list_text: lerp_color(tokens.text, tokens.text_dim, LIST_TEXT_DIMMING), + accent: tokens.accent, + } + } + + /// Prefer the theme lettering when it meets the normal-text contrast threshold. + pub(crate) fn lettering_on(&self, fill: Color32) -> Color32 { + const MIN_TEXT_CONTRAST: f32 = 4.5; + if contrast_ratio(self.text, fill) >= MIN_TEXT_CONTRAST { + return self.text; + } + + if contrast_ratio(Color32::WHITE, fill) >= MIN_TEXT_CONTRAST { Color32::WHITE } else { Color32::BLACK } + } + + /// 12 point text, the window's control colours, scroll bars in their own strip beside the list + pub(crate) fn apply(&self, style: &mut Style) { + for text_style in [TextStyle::Body, TextStyle::Button] { + if let Some(font) = style.text_styles.get_mut(&text_style) { + font.size = TEXT_SIZE; + } + } + style.spacing.interact_size.y = CONTROL_HEIGHT; + style.spacing.button_padding.x = super::drawn::VALUE_INSET; + style.spacing.scroll = egui::style::ScrollStyle { + bar_width: SCROLL_BAR_WIDTH, + bar_inner_margin: SCROLL_BAR_MARGIN, + bar_outer_margin: SCROLL_BAR_MARGIN, + ..egui::style::ScrollStyle::solid() + }; + + // The scroll strip shows no track, only the bar + style.visuals.extreme_bg_color = Color32::TRANSPARENT; + let widgets = &mut style.visuals.widgets; + for (state, fill, border) in [ + (&mut widgets.inactive, self.control, self.control_border), + (&mut widgets.hovered, self.raised, self.outline), + (&mut widgets.active, self.raised, self.outline), + (&mut widgets.open, self.control, self.control_border), + ] { + state.weak_bg_fill = fill; + state.bg_stroke = Stroke::new(1.0, border); + state.corner_radius = CornerRadius::same(CONTROL_RADIUS); + state.expansion = 0.0; + } + + // Scroll bars and checks use the strong fill: the raised grey + widgets.inactive.bg_fill = self.raised; + widgets.hovered.bg_fill = self.outline; + widgets.active.bg_fill = self.outline; + widgets.inactive.fg_stroke.color = self.text; + widgets.open.fg_stroke.color = self.text; + style.visuals.selection.bg_fill = self.chrome; + style.visuals.selection.stroke = Stroke::new(1.0, self.text); + } + + /// An open list: flush under its button, one light edge, the chosen option in the frame colour + pub(crate) fn list_style(&self) -> StyleModifier { + let look = *self; + StyleModifier::new(move |style: &mut Style| { + look.apply(style); + style.spacing.interact_size.y = OPTION_HEIGHT; + style.spacing.menu_margin = egui::Margin::same(LIST_MARGIN); + style.spacing.button_padding.x = OPTION_INSET; + style.spacing.item_spacing.y = 0.0; + style.visuals.window_fill = look.control; + style.visuals.window_stroke = Stroke::new(1.0, look.control_border); + style.visuals.menu_corner_radius = CornerRadius::same(CONTROL_RADIUS); + style.visuals.widgets.hovered.weak_bg_fill = look.raised; + style.visuals.widgets.hovered.bg_stroke = Stroke::NONE; + style.visuals.widgets.inactive.bg_stroke = Stroke::NONE; + style.visuals.widgets.active.bg_stroke = Stroke::NONE; + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::{Accent, Brightness, apply}; + + #[test] + fn export_button_and_empty_swatch_text_and_control_edges_read_in_each_theme() { + let context = egui::Context::default(); + for brightness in Brightness::ALL { + for accent in Accent::ALL { + apply(&context, brightness, accent); + let look = ExportLook::get(&context); + + for fill in [look.accent, look.raised] { + assert!(contrast_ratio(look.lettering_on(fill), fill) >= 4.5, "{brightness:?} {accent:?}"); + } + for background in [look.window, look.control] { + assert!(contrast_ratio(look.control_border, background) >= 3.0, "{brightness:?}"); + } + } + } + } +} diff --git a/crates/ui-egui/src/export_window/page_place.rs b/crates/ui-egui/src/export_window/page_place.rs new file mode 100644 index 00000000..7a8c8269 --- /dev/null +++ b/crates/ui-egui/src/export_window/page_place.rs @@ -0,0 +1,26 @@ +use egui::{Pos2, pos2}; + +/// Where a Settings page lays out from: the window's left edge, the tab row's top and the page's right edge +#[derive(Clone, Copy)] +pub(super) struct PagePlace { + pub(super) left: f32, + pub(super) top: f32, + pub(super) right: f32, +} + +impl PagePlace { + /// `x` from the window's left edge + pub(super) fn x(&self, x: f32) -> f32 { + self.left + x + } + + /// `y` from the top of the tab row + pub(super) fn y(&self, y: f32) -> f32 { + self.top + y + } + + /// A point `from_right` in from the page's right edge, at `y` from the tab row's top + pub(super) fn right_inset(&self, from_right: f32, y: f32) -> Pos2 { + pos2(self.right - from_right, self.top + y) + } +} diff --git a/crates/ui-egui/src/export_window/tree_file.rs b/crates/ui-egui/src/export_window/tree_file.rs new file mode 100644 index 00000000..8b3f64fb --- /dev/null +++ b/crates/ui-egui/src/export_window/tree_file.rs @@ -0,0 +1,8 @@ +/// A file row of LIST OF EXPORTS: the texts of its columns and its whole path +pub(super) struct TreeFile { + pub(super) name: String, + pub(super) size: String, + pub(super) format: String, + pub(super) bits: String, + pub(super) path: String, +} diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 95080619..2bf2dba0 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -278,9 +278,11 @@ mod tests { assert_eq!(Script::of_language("ko"), Some(Script::Korean)); assert_eq!(Script::of_language("ar"), Some(Script::Arabic)); assert_eq!(Script::of_language("de"), None); + assert_eq!(Script::of_language("ru"), None); for l in &crate::i18n::LANGUAGES { - // Past the Latin blocks and their diacritics. - let other_script = l.name.chars().any(|c| c > '\u{036F}'); + // Past the Latin blocks and their diacritics. Cyrillic needs no fallback: the UI fonts + // themselves carry it (egui's Ubuntu and craft-fonts' Inter). + let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } } diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs index 042f4f39..6bb7d226 100644 --- a/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs @@ -253,7 +253,10 @@ mod tests { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mesh = texturecraft_engine::geom::primitives::material_ball(); let session = texturecraft_engine::Session::new_project("Warp placement", mesh, "builtin:material_ball", None, 128).unwrap(); - let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(vec2(1600.0, 960.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "projection": "warp"})).unwrap(); harness.run_steps(2); diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 187d0de6..22c87109 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -48,14 +48,15 @@ fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc Result<(), String> { - let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env()); +pub fn install(ctx: &egui::Context, frame: Decision, backend: craft_host::target::Backend) -> Result<(), String> { + let shell = ShellInfo::default().backend(backend); install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows), Some(frame)) } diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 95d3fcd7..745d93fd 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -18,6 +18,8 @@ use crate::property_sheet::PropertySheet; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +mod bake_note; + /// The outline on the preview while it can open enlarged under the pointer, or is open, in points const ENLARGE_OUTLINE_WIDTH: f32 = 1.0; @@ -35,6 +37,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, PropertySheet::show(ui, ("generator_sheet", id), |sheet| { sheet.section(tr("Generator"), false); slot_card(app, sheet, id, generator); + bake_note::bake_notes(app, sheet, generator); let band = sheet.band(tr("Parameters"), true, Some(differs_from_defaults(generator)), None); if band.reset { @@ -68,9 +71,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, if sheet.band(tr("Attributes"), false, None, None).open { attributes(sheet, generator.kind); } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - sheet.caption(tr("Bake mesh maps for curvature, AO and thickness based generators.")); - } }); } diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs new file mode 100644 index 00000000..d152d5ea --- /dev/null +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -0,0 +1,104 @@ +//! One quiet line under a generator's kind when a mesh map it reads is not baked or out of date, with a Bake button + +use egui::{Align, Layout, RichText, Stroke, Ui, UiBuilder, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeChange, BakedMap, Generator}; + +use crate::TextureCraftApp; +use crate::i18n::{bake_change_reason, baked_map_label, tr, trf}; +use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS}; +use crate::theme::{Tokens, semibold}; + +/// Height of the note's line, in points (the mock's 28 px row) +const NOTE_HEIGHT: f32 = 28.0; + +/// Height of the Bake button, in points (the panels' 24 px controls) +const BUTTON_HEIGHT: f32 = 24.0; + +/// Size of the tooltip's title and reasons, in points +const TOOLTIP_TEXT_SIZE: f32 = 12.0; + +/// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date +pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) { + let texture_set = app.session.ts(); + for map in generator.baked_maps_read() { + if generator.inputs.contains_key(map) { + continue; + } + + let baked = app.session.baked(texture_set).is_some_and(|baked| baked.maps.contains_key(map)); + let changes = if baked { app.session.bake_changes(texture_set, *map) } else { Vec::new() }; + if baked && changes.is_empty() { + continue; + } + + // A full-width line inside the sheet's side padding + let (line, _) = sheet.ui.allocate_exact_size(vec2(sheet.ui.available_width(), NOTE_HEIGHT), egui::Sense::hover()); + let builder = UiBuilder::new().id_salt(map).max_rect(line.shrink2(vec2(SIDE_PADDING_POINTS, 0.0))).layout(Layout::left_to_right(Align::Center)); + sheet.ui.scope_builder(builder, |ui| note(app, ui, (texture_set, *map), &changes)); + } +} + +/// The line for `map` of `texture_set`: not baked when `changes` is empty, else out of date because of them +fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, BakedMap), changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let name = tr(baked_map_label(map)); + + let (glyph, text, title) = match changes.is_empty() { + true => (ic::WARNING, trf("{map} map not baked", &[("map", &name)]), tr("Not baked")), + false => (ic::CLOCK, trf("{map} map out of date", &[("map", &name)]), tr("Out of date")), + }; + let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map)); + + ui.label(RichText::new(glyph).color(tokens.warning)); + let reasons = reasons(changes, checked); + let line = ui.add(egui::Label::new(&text).truncate()); + ui.ctx().accesskit_node_builder(line.id, |node| node.set_description(reasons.join(" "))); + line.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for reason in reasons { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); + + let bake = ui + .with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = egui::Button::new(tr("Bake")).stroke(Stroke::new(1.0, tokens.button_border)).min_size(vec2(0.0, BUTTON_HEIGHT)); + ui.add_enabled(app.bake.is_none(), button) + .on_hover_text(tr("Bake this texture set's mesh maps in the background")) + .on_disabled_hover_text(tr("A bake is already running")) + }) + .inner; + + if bake.clicked() { + bake_map(app, texture_set, map); + } +} + +/// Why the line shows: what changed since the bake, or what a missing map does to the generator +fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> { + if changes.is_empty() { + let mut reasons = vec![tr("The generator reads a flat value until this map is baked.")]; + if !checked { + reasons.push(tr("Bake turns this map on in the bake settings first.")); + } + return reasons; + } + + changes.iter().map(|change| tr(bake_change_reason(*change))).collect() +} + +/// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off +fn bake_map(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + let Some(before) = app.session.doc.project.texture_sets.get(texture_set).map(|set| set.bake.clone()) else { return }; + + if !before.maps.is_enabled(map) { + let mut after = before.clone(); + after.maps.set_enabled(map, true); + app.run("bake.settings", json!({ "ts": texture_set, "patch": settings_patch(&before, &after) })); + } + + app.start_bake(vec![texture_set]); +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 235ebc5e..e9cc27f4 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,8 +1,8 @@ //! UI text lookup over the optional shared craft-i18n catalogs. //! Missing translations and builds without catalogs use the English source text. +use std::cell::Cell; use std::fmt::Display; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{LazyLock, OnceLock}; include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); @@ -37,7 +37,7 @@ pub struct Language { pub english: &'static str, } -const COUNT: usize = 10; +const COUNT: usize = 11; pub static LANGUAGES: [Language; COUNT] = [ Language { code: "en", name: "English", english: "English" }, @@ -46,13 +46,17 @@ pub static LANGUAGES: [Language; COUNT] = [ 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: "ru", name: "Русский", english: "Russian" }, 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 CURRENT: AtomicUsize = AtomicUsize::new(0); +// Rendering and preferences use the UI thread, including independent test harnesses. +thread_local! { + static CURRENT: Cell = const { Cell::new(0) }; +} /// How a fill reads its images, as the Filtering combo names it pub(crate) fn filtering_label(filtering: texturecraft_engine::core::Filtering) -> &'static str { @@ -93,23 +97,36 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta } } +/// Why a baked map is out of date: one sentence for what changed after its bake +pub(crate) fn bake_change_reason(change: texturecraft_engine::core::BakeChange) -> &'static str { + use texturecraft_engine::core::BakeChange; + + match change { + BakeChange::LowPoly => n_("The mesh changed after this bake."), + BakeChange::HighPoly => n_("The high poly files changed after this bake."), + BakeChange::Cage => n_("The cage changed after this bake."), + BakeChange::Settings => n_("The common bake settings changed after this bake."), + BakeChange::MapSettings => n_("This map's bake settings changed after this bake."), + } +} + /// The saved language that follows the operating system's (Settings > Language > Default (System Language)). pub const SYSTEM_LANGUAGE: &str = ""; -/// Switch the UI language ([`SYSTEM_LANGUAGE`] follows the system; unknown codes fall back to English). +/// Switch the calling UI thread's language. [`SYSTEM_LANGUAGE`] follows the system. pub fn set_language(code: &str) { let code = if code == SYSTEM_LANGUAGE { system_language() } else { code }; - CURRENT.store(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0), Ordering::Relaxed); + CURRENT.set(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0)); } /// The current UI language. pub fn current() -> &'static Language { - LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0]) + LANGUAGES.get(CURRENT.get()).unwrap_or(&LANGUAGES[0]) } /// `text` in the current language (unchanged when it has no translation). pub fn tr(text: &str) -> &str { - let lang = shared_languages().get(CURRENT.load(Ordering::Relaxed)).copied().unwrap_or(craft_i18n::Lang::EN); + let lang = shared_languages().get(CURRENT.get()).copied().unwrap_or(craft_i18n::Lang::EN); I18N.t(lang, text) } @@ -182,7 +199,7 @@ fn system_language() -> &'static str { SYSTEM.get_or_init(os_language) } -/// Tests that switch the global UI language, or draw the UI under it, run one at a time. +/// Shared guard used by language fixture tests. #[cfg(test)] pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -192,6 +209,27 @@ mod tests { use super::*; use std::collections::{BTreeSet, HashMap}; + #[test] + fn a_parallel_ui_language_context_keeps_its_own_language() { + set_language("en"); + let french = LANGUAGES.iter().position(|language| language.code == "fr").unwrap(); + let barrier = std::sync::Barrier::new(2); + let (first, second) = std::thread::scope(|scope| { + let other = scope.spawn(|| { + // Exercise the resolved language selection even when the French catalog is absent. + CURRENT.set(french); + barrier.wait(); + barrier.wait(); + current().code + }); + barrier.wait(); + let first = current().code; + barrier.wait(); + (first, other.join().unwrap()) + }); + assert_eq!((first, second), ("en", "fr")); + } + /// 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 { @@ -237,6 +275,9 @@ mod tests { 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(texturecraft_engine::ResourceStatus::ALL.iter().map(|status| status.label())); + let notice = crate::toast_action::ToastAction::UpdateResources { project: 0 }; + keys.extend([notice.label(), notice.accessible_name()]); keys.extend(texturecraft_engine::HISTORY_TEMPLATES); keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); @@ -410,9 +451,18 @@ mod tests", assert_eq!(trf("Saved {path}", &[("path", &"a.tcraft")]), "Saved a.tcraft"); assert_eq!(trf("{a} of {b} {c}", &[("a", &1), ("b", &2)]), "1 of 2 {c}"); assert_eq!(trf("{unclosed", &[]), "{unclosed"); - for (locale, code) in - [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("nl-NL", "en"), ("", "en")] - { + for (locale, code) in [ + ("de-AT", "de"), + ("pt_PT.UTF-8", "pt-BR"), + ("zh-Hant-TW", "zh-Hans"), + ("ja", "ja"), + ("ko_KR", "ko"), + ("ar-EG", "ar"), + ("ru-SK", "ru"), + ("ru_RU.UTF-8", "ru"), + ("nl-NL", "en"), + ("", "en"), + ] { assert_eq!(language_for_locale(locale), code, "{locale}"); } set_language("de"); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 47d6548d..7d9be266 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -3,6 +3,7 @@ //! the shortcut editor window (Help ▸ Shortcuts list) and the Edit ▸ Settings ▸ Shortcuts page. use std::collections::BTreeMap; +use std::sync::OnceLock; use crate::shortcut_dispatch::Dispatcher; use craft_keymap::{Active, Chord, CommandDef, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes}; @@ -41,6 +42,22 @@ pub static NOT_AVAILABLE_ACTIONS: [(&str, Binding); 2] = [ ("viewport.frame", Binding { id: "ui.toggleAnimation", group: "Viewport", label: "Toggle animation", default: Some("Space") }), ]; +/// Shortcut reference rows shown before Reimport mesh. Their example keys stay available to bind. +pub const REFERENCE_ACTIONS: [Binding; 7] = [ + Binding { id: "ui.manipulator.toggle", group: "Viewport", label: "Toggle transform handles", default: Some("Q") }, + Binding { id: "ui.manipulator.grow", group: "Viewport", label: "Enlarge transform handles", default: None }, + Binding { id: "ui.manipulator.shrink", group: "Viewport", label: "Shrink transform handles", default: Some("-") }, + Binding { id: "ui.manipulator.space", group: "Viewport", label: "Switch transform coordinate space", default: Some("T") }, + Binding { id: "ui.warpEdit", group: "Viewport", label: "Toggle warp editing", default: Some("Shift+V") }, + Binding { id: "ui.manipulator.translate", group: "Viewport", label: "Move with transform handles", default: Some("W") }, + Binding { id: "ui.manipulator.rotate", group: "Viewport", label: "Rotate with transform handles", default: Some("E") }, +]; + +fn unavailable_before(id: &str) -> impl Iterator + '_ { + let reference = if id == "file.reimportMesh" { REFERENCE_ACTIONS.as_slice() } else { &[] }; + reference.iter().chain(NOT_AVAILABLE_ACTIONS.iter().filter(move |(before, _)| *before == id).map(|(_, row)| row)) +} + /// The shortcut list's first rows, in the reference's order. The `>` and `<` of the reference are /// the shifted Period and Comma keys. const LISTED_SHORTCUTS: &[ShortcutListEntry] = &[ @@ -222,14 +239,15 @@ pub struct Bindings { stored: Keymap, map: craft_keymap::Keymap, dispatcher: Dispatcher, + conflicts: OnceLock>, } 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::default() } + + Bindings { stored, map, dispatcher: Dispatcher::default(), conflicts: OnceLock::new() } } } @@ -239,6 +257,7 @@ impl Bindings { if self.stored != *keymap || self.map.platform() != platform { self.stored = keymap.clone(); self.map = resolved(keymap, platform); + self.conflicts.take(); } } @@ -275,14 +294,22 @@ impl Bindings { 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> { + /// The first conflicting action for each shortcut, computed only when an editor needs it. + fn conflicts(&self) -> &BTreeMap<&'static str, &'static Binding> { + self.conflicts.get_or_init(|| bindings().iter().filter_map(|binding| self.find_conflict(binding).map(|other| (binding.id, other))).collect()) + } + + fn conflict(&self, binding: &Binding) -> Option<&'static Binding> { + self.conflicts().get(binding.id).copied() + } + + fn find_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); if let Some(clash) = clash { return bindings().iter().find(|x| x.id == clash.b.0.id); } - // The rows the reference lists and TextureCraft cannot run yet still own their keys + // Keep the existing reserved shortcuts for paused computation and animation let mine = parse(shortcut(&self.stored, b)?)?; NOT_AVAILABLE_ACTIONS.iter().map(|(_, row)| row).find(|row| row.default.and_then(parse) == Some(mine)) } @@ -369,7 +396,7 @@ pub fn shown(text: &str) -> &str { /// Whether the shortcuts in `edited` (kept in step with the working copy) have an item that /// shares its shortcut with another. pub(crate) fn has_conflict(edited: &Bindings) -> bool { - bindings().iter().any(|b| edited.conflict(b).is_some()) + !edited.conflicts().is_empty() } /// Follow `keymap` with the checker of the Settings window. @@ -399,6 +426,7 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi } capture = None; } + follow(edited, keymap, &ctx); let cell = |ui: &mut egui::Ui, width: f32, add: &mut dyn FnMut(&mut egui::Ui)| { @@ -408,7 +436,6 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi }); }; - // A pencil that cannot be used yet let locked_pencil = |ui: &mut egui::Ui, action: &str| { let edit = trf("Edit the shortcut of {item}", &[("item", &tr(action))]); ui.add_enabled_ui(false, |ui| icon_button(ui, ic::PENCIL_SIMPLE, &edit, false, 20.0)).inner.on_disabled_hover_text(tr(NOT_AVAILABLE)); @@ -428,9 +455,10 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi ui.label(caption(tr("Actions"))); ui.add_space(4.0); for (i, b) in bindings().iter().enumerate() { - for (_, row) in NOT_AVAILABLE_ACTIONS.iter().filter(|(before, _)| *before == b.id) { + for row in unavailable_before(b.id) { locked_row(ui, row.label, row.default.unwrap_or("")); } + let waiting = capture == Some(i); ui.horizontal(|ui| { cell(ui, 300.0, &mut |ui| { @@ -485,8 +513,8 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi }); } -/// The first key press this frame as a shortcut. A plain Escape while none of TextureCraft's widgets has the keyboard -/// is the window's cancel, which the recorder takes as the Escape that cancels it. +/// The first key press this frame as a shortcut, including Escape routed to the window's cancel. +/// Keep the press's modifiers so only plain Escape cancels recording. fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option { let platform = craft_keymap::egui::platform(ctx); let press = ctx.input(|i| { @@ -495,7 +523,14 @@ fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option _ => None, }) }); - press.or_else(|| crate::framework::take_window_cancel(ctx).then(|| KeyboardShortcut::new(Modifiers::NONE, Key::Escape))) + + press.or_else(|| { + crate::framework::take_window_cancel(ctx).then(|| { + let modifiers = craft_ui::runtime::keys::escape_mods(ctx).unwrap_or(Mods::NONE); + + Chord::new(modifiers, craft_keymap::Key::Escape).to_egui_shortcut() + }) + }) } /// The shortcut editor window. @@ -519,6 +554,7 @@ 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; @@ -532,7 +568,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); }); - let clashes = bindings().iter().filter(|b| app.bindings.conflict(b).is_some()).count(); + let clashes = app.bindings.conflicts().len(); if clashes > 0 { ui.label( RichText::new(format!("{} {}", ic::WARNING, trf("{n} items share a shortcut; the first one listed wins.", &[("n", &clashes)]))) @@ -544,7 +580,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { egui::ScrollArea::vertical().max_height(420.0).auto_shrink([false, true]).show(ui, |ui| { egui::Grid::new("keymap_grid").num_columns(3).striped(true).spacing(vec2(10.0, 4.0)).show(ui, |ui| { for (i, b) in bindings().iter().enumerate() { - for (_, row) in NOT_AVAILABLE_ACTIONS.iter().filter(|(before, _)| *before == b.id) { + for row in unavailable_before(b.id) { let key = row.default.unwrap_or(""); if !needle.is_empty() && ![row.label, row.group, tr(row.label), tr(row.group), key].iter().any(|t| t.to_lowercase().contains(&needle)) { continue; @@ -558,6 +594,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add_enabled(false, button).on_disabled_hover_text(tr(NOT_AVAILABLE)); ui.end_row(); } + let current = shortcut(&app.ui.keymap, b); let current_text = current.map(shown); if !needle.is_empty() diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index d5390546..554161f3 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -1,12 +1,13 @@ //! 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. +//! which effect stack is open, and the one place the preview size is decided. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::time::Duration; use egui::{Context, TextureHandle, TextureId, TextureOptions}; use texturecraft_engine::Session; use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::LayerId; use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; use crate::TextureCraftApp; @@ -42,20 +43,23 @@ pub struct LayerPanel { frame: u64, /// Whether this frame's pictures are begun and not yet finished by [`LayerPanel::end`] pictures_begun: bool, - /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. - pub(crate) folded: HashSet<(u64, bool)>, + /// The open stack, with `true` for a layer's mask. This belongs to the panel view. + pub(crate) expanded_effects: Option<(LayerId, bool)>, } /// How soon to look again for pictures still rendering (milliseconds) const POLL_INTERVAL_MS: u64 = 40; impl LayerPanel { + pub(crate) fn toggle_effects(&mut self, stack: Option<(LayerId, bool)>) { + self.expanded_effects = stack.filter(|stack| Some(*stack) != self.expanded_effects); + } + /// Start drawing the panel for this frame. pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.begin_pictures(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))); + self.expanded_effects = self.expanded_effects.filter(|(layer, _)| session.doc.project.layers.contains_key(layer)); } /// Advance the picture frame once, whether the panel or a picture outside it asks first @@ -115,22 +119,22 @@ impl LayerPanel { #[cfg(test)] mod tests { use super::*; - use texturecraft_engine::core::{Channel, LayerId}; + use texturecraft_engine::core::Channel; use texturecraft_engine::geom::primitives; #[test] - fn deleted_layers_release_their_fold_state() { + fn deleted_layers_close_their_effect_stack() { 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.expanded_effects = Some((layer, false)); panel.begin(&session, 0.0); - assert_eq!(panel.folded.len(), 2, "existing layers keep their view settings"); + assert_eq!(panel.expanded_effects, Some((layer, false)), "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"); + assert_eq!(panel.expanded_effects, None, "the deleted layer leaves no open stack"); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 401581e8..568a70bf 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,12 +10,16 @@ mod anchor_properties; mod angle_dial; mod ask; +mod auto_rebake; +#[cfg(not(target_arch = "wasm32"))] +mod autosave_name; mod bake_job; pub mod bake_mode; mod bake_preset; pub mod bake_presets; mod bake_report; mod bake_scene; +pub mod baking_log; mod color_management; mod color_picker; mod color_selection_editor; @@ -78,6 +82,8 @@ mod levels_properties; mod line_snap; mod list_action; pub mod log_panel; +#[cfg(not(target_arch = "wasm32"))] +mod manual_save; mod mask_fill_panel; mod mask_paint_panel; mod mask_preview_image; @@ -117,6 +123,7 @@ mod placed_fill_slot; mod placement; mod pointer_lock; mod popup_drag; +mod press_edit; mod preview_dots; mod preview_image; mod preview_request; @@ -139,6 +146,8 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; +#[cfg(not(target_arch = "wasm32"))] +mod resources_updater; mod round_gizmo; mod running_bake; #[cfg(not(target_arch = "wasm32"))] @@ -152,12 +161,21 @@ mod session_log_file; pub mod settings_window; pub mod shader_settings; pub mod shelf; +pub mod shelf_custom_preview; +pub mod shelf_drag_ghost; +pub mod shelf_drag_ghost_shown; +pub mod shelf_drag_verdict; mod shelf_entry; +pub mod shelf_favorite; mod shelf_folders; +mod shelf_menu; pub mod shelf_panes; pub mod shelf_preview; +pub mod shelf_query; +pub mod shelf_second; mod shelf_tabs; mod shelf_toolbar; +pub mod shelf_updates; pub mod shelf_view; mod shortcut_dispatch; mod slot_thumbnail; @@ -174,6 +192,7 @@ pub mod thumbs; mod tile_edits; mod tile_picture; pub mod titlebar; +pub mod toast_action; pub mod toolbar; pub mod ui_state_store; pub mod unavailable; @@ -255,6 +274,9 @@ pub struct Toast { pub error: bool, pub until: f64, pub show_log: bool, + /// A button after the text that acts on the notice + pub action: Option, + announce: bool, } pub struct TextureCraftApp { @@ -284,6 +306,8 @@ pub struct TextureCraftApp { pub bake: Option, /// What the bake running now has done so far, for the summary when it ends pub bake_report: bake_report::BakeReport, + /// When the out-of-date auto-rebake maps are rebaked + auto_rebake: auto_rebake::AutoRebake, /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, @@ -306,6 +330,8 @@ pub struct TextureCraftApp { hovered_texture_set: Option<(u64, usize)>, /// The set under the pointer in this pass, independent of dock drawing order. next_hovered_texture_set: Option<(u64, usize)>, + /// Project identity of the current inline rename buffer. + rename_project_id: u64, pub fps: f32, /// User smart materials found in the library folder (refreshed on demand). pub library: Option>, @@ -357,20 +383,41 @@ pub struct TextureCraftApp { /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, + /// The unsaved project (its id) and the stable filename of its autosave copy. + #[cfg(not(target_arch = "wasm32"))] + unsaved_autosave_file: Option<(u64, String)>, + /// The dialog opening that owns the Project name widget's undo state. + #[cfg(not(target_arch = "wasm32"))] + project_name_editor_opening: Option, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. focused: bool, + /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_notified: std::collections::BTreeSet, + /// The project the Resources Updater last checked on opening (see `resources_updater::follow_project`) + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_project: Option, /// 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. + /// Project whose unsaved-changes dialog can still answer. + prompt_project_id: u64, + /// A manual save running on the desktop archive writer. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) save_job: Option, + /// The unsaved-changes dialog's Save is waiting for a path or a save result. #[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. + /// A close the finished save left waiting for an open stroke, with the id of the project it + /// belongs to; decided once the stroke ends, dropped when another project replaced that one. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) quit_after_stroke: Option, + /// The requested save completed; 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. @@ -386,11 +433,8 @@ pub(crate) fn start_ui(saved: Option, session: &mut Session) -> UiState ui.tool_settings.apply(&mut session.tool); ui } - None => { - let mut ui = UiState::default(); - ui.prefs.language = i18n::SYSTEM_LANGUAGE.into(); - ui - } + // The default language follows the operating system + None => UiState::default(), } } @@ -449,6 +493,7 @@ impl TextureCraftApp { gpu_memory: (Vec::new(), None), bake: None, bake_report: Default::default(), + auto_rebake: Default::default(), pbr_import: None, resize: None, #[cfg(not(target_arch = "wasm32"))] @@ -463,6 +508,7 @@ impl TextureCraftApp { viewport_rect: egui::Rect::NOTHING, hovered_texture_set: None, next_hovered_texture_set: None, + rename_project_id: project_id, fps: 0.0, ui_ms: 0.0, profiler: profile::Profiler::default(), @@ -493,15 +539,28 @@ impl TextureCraftApp { fired_clipboard: Vec::new(), last_time: 0.0, next_autosave, + #[cfg(not(target_arch = "wasm32"))] + unsaved_autosave_file: None, + #[cfg(not(target_arch = "wasm32"))] + project_name_editor_opening: None, styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] + resources_notified: std::collections::BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] + resources_project: None, + #[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()), + prompt_project_id: project_id, + #[cfg(not(target_arch = "wasm32"))] + save_job: None, #[cfg(not(target_arch = "wasm32"))] saving_for_prompt: false, #[cfg(not(target_arch = "wasm32"))] + quit_after_stroke: None, + #[cfg(not(target_arch = "wasm32"))] prompt_saved: false, bindings: keymap::Bindings::default(), settings_bindings: keymap::Bindings::default(), @@ -648,13 +707,24 @@ impl TextureCraftApp { } 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 }, show_log: false }); + const ERROR_SECONDS: f64 = 6.0; + const NOTICE_SECONDS: f64 = 3.0; + let until = self.last_time + if error { ERROR_SECONDS } else { NOTICE_SECONDS }; + + self.toasts.push(Toast { text: text.into(), error, until, show_log: false, action: None, announce: false }); + } + + #[cfg(not(target_arch = "wasm32"))] + fn announce_latest_toast(&mut self) { + if let Some(toast) = self.toasts.last_mut() { + toast.announce = true; + } } /// An error toast that stays until the user dismisses it (for a problem that persists and /// is reported once, like a texture set the GPU could not hold). pub fn toast_sticky(&mut self, text: impl Into) { - self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); + self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, action: None, announce: false }); } /// Bake texture sets in the background, one after another; invalid set indices show an error without starting anything @@ -682,8 +752,12 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); + match only { + Some(map) => self.session.begin_map_bake_log(&sets, &[map]), + None => self.session.begin_bake_log(&sets), + } self.bake_report = bake_report::BakeReport::started(self.last_time); - self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only, rebake: None }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -800,17 +874,21 @@ impl TextureCraftApp { if let Some(running) = &job.current { running.progress.cancel.store(true, Ordering::Relaxed); } + self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); self.bake = None; return; } ctx.request_repaint_after(BAKE_POLL_INTERVAL); - if let Some(running) = &job.current { + if let Some(running) = &mut job.current { let set_index = running.set_index; // Wait for the sender to close so the last map also gets a preview frame match running.maps.try_recv() { Ok(map) => { + running.finished.resolution = map.resolution; + running.finished.maps.insert(map.map, map.data.clone()); + self.session.bake_log.map_baked(set_index, map.map); self.session.bake_preview_map(set_index, map); return; } @@ -824,22 +902,21 @@ impl TextureCraftApp { job.current = None; match self.session.apply_streamed_bake(set_index, output) { - Ok(()) => self.bake_report.map_count += maps_baked, + Ok(()) => { + self.session.bake_log.set_finished(set_index); + self.bake_report.map_count += maps_baked; + } Err(error) => self.bake_failed(set_index, &error.to_string()), } } Ok(Err(error)) => { // The worker's error ends the whole bake; the maps of the sets before it stay - self.bake_failed(set_index, &error.to_string()); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, &error.to_string()); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.bake_failed(set_index, i18n::tr("The bake worker stopped")); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, i18n::tr("The bake worker stopped")); return; } } @@ -856,17 +933,23 @@ impl TextureCraftApp { let set_index = job.queue.remove(0); let only = job.only; + let rebake = job.rebake.as_ref().map(|(_, map, _, stroke)| (*map, stroke.is_some())); self.session.bake_preview_set_current(set_index); - let task = match only { - Some(map) => self.session.bake_task_only(set_index, map), - None => self.session.bake_task(set_index), + self.session.bake_log.set_started(set_index); + let task = match (rebake, only) { + (Some((map, true)), _) => self.session.bake_painted_task(set_index, map), + (Some((map, false)), _) => self.session.bake_task_for(set_index, &self.session.auto_rebake_maps(set_index, map)), + (None, Some(map)) => self.session.bake_task_only(set_index, map), + (None, None) => self.session.bake_task(set_index), }; match task { Ok(task) => { + self.session.bake_log.high_polys_loaded(set_index); let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); + let (sources, painted_stroke) = (task.sources.clone(), task.painted_stroke); let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let worker_done = maps_done.clone(); let (sender, maps) = std::sync::mpsc::channel(); @@ -880,16 +963,29 @@ impl TextureCraftApp { }); if let Some(job) = self.bake.as_mut() { - job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); + job.current = + Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total, finished: Default::default(), sources, painted_stroke }); } } Err(error) => self.bake_failed(set_index, &error.to_string()), } } + /// End the bake at texture set `set_index`, whose worker failed: none of its maps are kept, the queued sets are canceled + fn end_failed_bake(&mut self, set_index: usize, error: &str) { + if let Some(job) = &mut self.bake { + job.current = None; + } + + self.bake_failed(set_index, error); + self.cancel_bake(); + self.finish_bake_report(); + } + /// Note a texture set whose bake failed: one Log line, counted in the summary fn bake_failed(&mut self, set_index: usize, error: &str) { self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}")); + self.session.bake_log.set_failed(set_index, error); self.bake_report.failed_set_count += 1; } @@ -902,23 +998,66 @@ impl TextureCraftApp { self.session.log.info("Baker", line); } + if self.bake_report.auto_rebake && !failed { + return; + } + self.toast(text, failed); if let Some(toast) = self.toasts.last_mut() { toast.show_log = failed; } } - /// 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. + /// Cancel the bake and restore the view. Keep applied sets and any eligible maps from the running set. pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - if let Some(running) = job.current { - running.progress.cancel.store(true, Ordering::Relaxed); + let mut discarded = None; + let mut worker_failed = false; + + if let Some(mut running) = job.current { + running.progress.cancel(); + let set_index = running.set_index; + + if job.mesh_id != self.session.mesh_id { + discarded = Some(set_index); + } else { + // Collect every map the worker sent, including those the preview never took + while let Ok(map) = running.maps.try_recv() { + running.finished.resolution = map.resolution; + running.finished.maps.insert(map.map, map.data); + self.session.bake_log.map_baked(set_index, map.map); + } + + let failure = match running.receiver.try_recv() { + Ok(Ok(_) | Err(texturecraft_engine::EngineError::BakeCancelled)) | Err(std::sync::mpsc::TryRecvError::Empty) => None, + Ok(Err(error)) => Some(error.to_string()), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(i18n::tr("The bake worker stopped").to_owned()), + }; + + if let Some(error) = failure { + self.bake_failed(set_index, &error); + worker_failed = true; + } else { + let kept = self.session.keep_canceled_bake(set_index, running.finished, &running.sources, running.painted_stroke); + match kept { + Ok(maps) if !maps.is_empty() => {} + Ok(_) => discarded = Some(set_index), + Err(error) => { + self.toast(error.to_string(), true); + discarded = Some(set_index); + } + } + } + } } - // Only the current set is uncommitted; completed sets remain applied + self.session.bake_log.cancel(discarded); self.session.bake_preview_end(); + + if worker_failed { + self.finish_bake_report(); + } } /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when @@ -1034,6 +1173,10 @@ impl TextureCraftApp { /// and written on a worker thread; the project data is shared copy-on-write). #[cfg(not(target_arch = "wasm32"))] fn autosave(&mut self, now: f64) { + if self.save_job.is_some() { + return; + } + let period = autosave_period_seconds(self.ui.prefs.autosave_minutes); // The clock starts at the first unsaved change @@ -1052,11 +1195,7 @@ impl TextureCraftApp { self.next_autosave = now + period; let dir = user_dir("autosave"); - let path = dir.join(format!( - "{}.{}", - texturecraft_engine::formats::export::sanitize_file_stem(&self.session.doc.project.name), - texturecraft_engine::core::PROJECT_EXT - )); + let path = self.autosave_path(&dir); let snapshot = self.session.project_snapshot(); let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || { let result = @@ -1096,7 +1235,7 @@ const BAKE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis /// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames) const FRAME_AVERAGE_KEEP: f32 = 0.9; -/// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason +/// The interface scale applied (`prefs.ui_scale`, set through `ui.set`; Settings has no control for it), clamped to a usable range const UI_SCALE_APPLIED: std::ops::RangeInclusive = 0.5..=3.0; /// Zoom factors closer than this are the same zoom (float noise), so the zoom is not set again each frame const SAME_ZOOM_TOLERANCE: f32 = 1e-3; @@ -1165,6 +1304,7 @@ impl eframe::App for TextureCraftApp { self.ui.prefs.apply_resource_limits(); control::poll(self, ctx); + shelf_updates::tick(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.run_file_dialog_answers(); web_files::poll(self); @@ -1188,6 +1328,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.bake_map_thumbnails.retain_mesh(self.session.mesh_id); bake_mode::poll_live_preview(self, ctx); + auto_rebake::poll(self, ctx); self.poll_resize(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_high_poly_job(ctx); @@ -1205,15 +1346,24 @@ impl eframe::App for TextureCraftApp { let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; + + // Files may have been edited in another app meanwhile + #[cfg(not(target_arch = "wasm32"))] + resources_updater::check_files(self); } self.focused = focused; + #[cfg(not(target_arch = "wasm32"))] + resources_updater::follow_project(self); let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end()); if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] - self.autosave(now); + { + self.poll_save(ctx); + self.autosave(now); + } i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] { @@ -1251,6 +1401,8 @@ impl eframe::App for TextureCraftApp { self.profiler.logic_ms = (now_ms() - logic_start_ms) as f32; // Last, so it sees every close request this frame's work made + #[cfg(not(target_arch = "wasm32"))] + self.resume_close_after_stroke(ctx); self.close_path(ctx); } @@ -1278,6 +1430,12 @@ impl eframe::App for TextureCraftApp { let hide_ui = self.ui.hide_ui; let tokens = theme::Tokens::get(&ctx); + // Layer and effect IDs can repeat in a replacement project + if self.rename_project_id != self.session.project_id { + self.ui.rename = None; + self.rename_project_id = self.session.project_id; + } + // The dock keeps the cards' gutter from the bars and rails around it let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) }; egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| { @@ -1287,6 +1445,7 @@ impl eframe::App for TextureCraftApp { docking::show(self, ui); } }); + dock::finish_hidden_effect_rename(self); let hovered_texture_set = self.next_hovered_texture_set.take(); if self.hovered_texture_set != hovered_texture_set { @@ -1296,6 +1455,9 @@ impl eframe::App for TextureCraftApp { windows::show(self, &ctx); + // After every drop target has said whether it takes the dragged asset + shelf_drag_ghost::show(&ctx); + // Finish after the dock and windows have requested their thumbnails self.layer_panel.end(&ctx, &self.session); @@ -1355,7 +1517,23 @@ pub fn data_folder(pref: &str) -> std::path::PathBuf { std::path::Path::new(&home).join("Documents").join("TextureCraft") } -/// The data folder in use: the Nightly profile when this is one, else Settings › Folders › Data folder. +/// An absolute preview cache override, or the app's default under the user's cache directory. +#[cfg(not(target_arch = "wasm32"))] +pub fn local_cache_folder(pref: &str) -> std::path::PathBuf { + let chosen = std::path::Path::new(pref.trim()); + if chosen.is_absolute() { + return chosen.to_path_buf(); + } + + let cache = if has_data_root() { + data_dir().join("cache") + } else { + craft_update::Paths::per_user(UPDATE_APP.id).map_or_else(|_| data_dir().join("cache"), |paths| paths.cache) + }; + cache.join("previews") +} + +/// The Nightly profile's data folder, or the folder chosen in Settings › Files. #[cfg(not(target_arch = "wasm32"))] pub fn data_dir() -> std::path::PathBuf { if let Some(root) = DATA_ROOT.get() { @@ -1364,7 +1542,7 @@ pub fn data_dir() -> std::path::PathBuf { DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder("")) } -/// `` in the data folder in use (Settings › Folders › Data folder). +/// `` in the data folder in use (Settings › Files › Data folder). #[cfg(not(target_arch = "wasm32"))] pub fn user_dir(sub: &str) -> std::path::PathBuf { data_dir().join(sub) @@ -1419,14 +1597,17 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.toasts.iter().any(|t| t.until.is_finite()) { ctx.request_repaint_after(std::time::Duration::from_millis(250)); } + let tk = theme::Tokens::get(ctx); let mut dismissed = None; let mut show_log = false; + let mut clicked_action = None; // Limit toast dimensions so the dismiss button stays visible let screen = ctx.content_rect().size(); let max_width = (screen.x - 52.0).clamp(120.0, 360.0); let max_text_height = (screen.y * 0.35).clamp(48.0, 220.0); + egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| { for (i, t) in app.toasts.iter().enumerate() { egui::Frame::NONE @@ -1444,12 +1625,23 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| { ui.set_max_width(width); - ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + let message = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + if t.announce || t.action.is_some() { + ui.ctx().accesskit_node_builder(message.id, |node| node.set_live(egui::accesskit::Live::Polite)); + } }); if t.show_log && ui.link(i18n::tr("Open Log")).clicked() { show_log = true; dismissed = Some(i); } + if let Some(action) = t.action { + let button = ui.button(i18n::tr(action.label())); + button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, i18n::tr(action.accessible_name()))); + if button.clicked() { + clicked_action = Some(action); + dismissed = Some(i); + } + } }); if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { dismissed = Some(i); @@ -1459,6 +1651,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add_space(4.0); } }); + if let Some(i) = dismissed.filter(|i| *i < app.toasts.len()) { app.toasts.remove(i); } @@ -1467,4 +1660,8 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.log_channel = log_panel::LogChannel::General; crate::rail_popup::open(app, crate::docking::Panel::Log); } + + if let Some(action) = clicked_action { + action.run(app); + } } diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs new file mode 100644 index 00000000..aee62dc9 --- /dev/null +++ b/crates/ui-egui/src/manual_save.rs @@ -0,0 +1,467 @@ +//! Manual desktop saves share the atomic archive writer with autosave and headless saves. + +use std::sync::{Arc, mpsc}; +use std::time::Duration; + +use texturecraft_engine::formats::project_file::SaveProgress; + +use crate::{ + TextureCraftApp, + i18n::{tr, trf}, + state::Unsaved, +}; + +mod save_job; + +pub(crate) use save_job::SaveJob; + +const SAVE_POLL_INTERVAL: Duration = Duration::from_millis(80); + +pub(crate) fn is_save(id: &str) -> bool { + matches!(id, "file.save" | "file.saveAs" | "file.saveCopy") +} + +impl TextureCraftApp { + pub(crate) fn start_save(&mut self, path: &str, adopt: bool, for_prompt: bool, remember: bool) -> bool { + if self.save_job.is_some() { + self.toast(tr("A project save is already running"), true); + return false; + } + + if let Err(error) = self.session.end_stroke() { + self.toast(error.to_string(), true); + return false; + } + + let task = self.session.save_task(path, adopt); + let progress = Arc::new(SaveProgress::default()); + let worker_progress = progress.clone(); + let output = crate::spawn_worker("texturecraft-save", move || task.run(Some(&worker_progress))); + self.save_job = Some(SaveJob { progress, output, project_id: self.session.project_id, for_prompt, remember, quit_requested_by: None }); + true + } + + pub(crate) fn hold_close_for_save(&mut self) -> bool { + let Some(job) = &mut self.save_job else { return false }; + + // A close on a replacement project still waits for the outstanding archive + job.quit_requested_by = Some(self.session.project_id); + true + } + + pub(crate) fn cancel_close_after_save(&mut self) { + self.quit_after_stroke = None; + if let Some(job) = &mut self.save_job { + job.quit_requested_by = None; + } + } + + pub(crate) fn resume_close_after_stroke(&mut self, ctx: &egui::Context) { + let Some(project_id) = self.quit_after_stroke else { return }; + + if project_id == self.session.project_id && self.session.stroke_active() { + return; + } + + self.quit_after_stroke = None; + if project_id == self.session.project_id && !crate::windows::ask_to_save(self, Unsaved::Quit) { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + + pub(crate) fn save_progress(&self) -> Option { + self.save_job.as_ref().map(|job| job.progress.fraction()) + } + + pub(crate) fn poll_save(&mut self, ctx: &egui::Context) { + let Some(job) = &self.save_job else { return }; + + let result = match job.output.try_recv() { + Ok(result) => result.map_err(|error| error.to_string()), + Err(mpsc::TryRecvError::Empty) => { + ctx.request_repaint_after(SAVE_POLL_INTERVAL); + return; + } + Err(mpsc::TryRecvError::Disconnected) => Err(tr("The project save worker stopped").into()), + }; + + let Some(job) = self.save_job.take() else { return }; + let same_project = job.project_id == self.session.project_id; + let quit_requested = job.quit_requested_by == Some(self.session.project_id); + let continue_prompt = same_project && job.for_prompt && self.saving_for_prompt; + if continue_prompt { + self.saving_for_prompt = false; + } + + let save_succeeded = result.is_ok(); + match result { + Ok(output) => { + output.apply(&mut self.session); + if job.remember { + crate::windows::remember(self, &output.path); + } + + if continue_prompt { + self.prompt_saved = !self.session.modified && !self.session.stroke_active() && !quit_requested; + } + + self.toast(trf("Saved {path}", &[("path", &output.path)]), false); + } + Err(error) => { + let message = trf("Could not save project: {error}", &[("error", &error)]); + self.session.log.warn("Project", message.clone()); + self.toast(message, true); + } + } + + if quit_requested { + if self.session.stroke_active() { + self.quit_after_stroke = Some(self.session.project_id); + } else if !self.session.modified && (save_succeeded || !same_project) { + // A replacement project's own close only needs the previous writer to finish + self.ui.windows.unsaved = None; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } else { + crate::windows::ask_to_save(self, Unsaved::Quit); + } + } + + self.announce_latest_toast(); + } +} + +#[cfg(test)] +mod tests { + use egui::{ViewportCommand, ViewportEvent, ViewportId}; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT as _, Queryable as _}; + use texturecraft_engine::{ + Result, + file_cmds::{SaveOutput, SaveTask}, + }; + + use super::*; + + fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.modified = true; + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // Match English labels independently of the system locale + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(2); + h + } + + fn temp_file(test: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("tc-manual-save-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir.join("project.tcraft") + } + + /// A save the test finishes by hand, so the close lands while it is still running + fn start_held_save(h: &mut Harness<'_, TextureCraftApp>, path: &std::path::Path, adopt: bool) -> (SaveTask, mpsc::Sender>) { + let app = h.state_mut(); + let task = app.session.save_task(&path.display().to_string(), adopt); + let (sender, output) = mpsc::channel(); + app.save_job = + Some(SaveJob { progress: Arc::default(), output, project_id: app.session.project_id, for_prompt: false, remember: false, quit_requested_by: None }); + (task, sender) + } + + 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); + } + + /// Hands the worker's result over and reports whether the app asked to close in the next frames + fn finish(h: &mut Harness<'_, TextureCraftApp>, task: SaveTask, sender: &mpsc::Sender>) -> bool { + sender.send(task.run(None)).unwrap(); + sends_close(h) + } + + /// Whether the app asks to close in the next frames + fn sends_close(h: &mut Harness<'_, TextureCraftApp>) -> bool { + (0..3).any(|_| { + h.step(); + h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close)) + }) + } + + fn prompt_is_usable(h: &Harness<'_, TextureCraftApp>) -> bool { + ["Save", "Don't save", "Cancel"].iter().all(|label| !h.get_by_label(label).accesskit_node().is_disabled()) + } + + #[test] + fn closing_during_a_regular_save_quits_once_it_has_saved() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-saved"); + let mut h = harness(); + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + + request_close(&mut h); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the changes are not written yet"); + assert!(h.get_by_label("Save").accesskit_node().is_disabled(), "the prompt waits for the running save"); + let closed = finish(&mut h, task, &sender); + + assert!(closed, "the close goes on after the save"); + assert!(file.exists()); + assert!(!h.state().session.modified); + assert!(h.state().ui.windows.unsaved.is_none(), "no question is left once the changes are saved"); + } + + #[test] + fn closing_during_a_failed_save_keeps_a_usable_prompt() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-failed").with_file_name("missing").join("project.tcraft"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, true); + + request_close(&mut h); + let closed = finish(&mut h, task, &sender); + + assert!(!closed); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); + assert!(prompt_is_usable(&h), "the prompt answers again after the failed write"); + + let message = &h.state().toasts.iter().find(|toast| toast.error).expect("the failed write shows an error").text; + let announced = h.get_all_by_label(message).any(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite); + assert!(announced, "the save error is announced away from focus"); + } + + #[test] + fn closing_during_a_save_a_copy_keeps_the_prompt() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-copied"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, false); + + request_close(&mut h); + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "a copy leaves the project's own changes unsaved"); + assert!(file.exists()); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); + assert!(prompt_is_usable(&h)); + } + + #[test] + fn closing_during_a_save_keeps_the_prompt_for_later_edits() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-edited"); + let mut h = harness(); + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"})); + assert!(rename.is_some()); + + request_close(&mut h); + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "the edit made after the snapshot is not in the file"); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); + assert!(prompt_is_usable(&h)); + } + + #[test] + fn an_edit_after_a_clean_close_asks_once_the_save_returns() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("clean-close-then-edited"); + let mut h = harness(); + h.state_mut().session.modified = false; + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + + request_close(&mut h); + assert!(h.state().ui.windows.unsaved.is_none(), "nothing to ask while the project is clean"); + let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"})); + assert!(rename.is_some()); + let closed = finish(&mut h, task, &sender); + + assert!(!closed); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the edit instead of being dropped"); + assert!(prompt_is_usable(&h)); + } + + /// A clean project closed during its save, with paint still held down when the save returns + fn stroke_open_when_the_save_returns(test: &str) -> Harness<'static, TextureCraftApp> { + let file = temp_file(test); + let mut h = harness(); + h.state_mut().session.modified = false; + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + request_close(&mut h); + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "the open stroke may still change the project"); + assert!(h.state().session.stroke_active()); + assert!(h.state().ui.windows.unsaved.is_none()); + h + } + + #[test] + fn a_stroke_open_when_the_save_returns_asks_once_it_is_painted() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = stroke_open_when_the_save_returns("stroke-painted"); + + h.state_mut().session.end_stroke().unwrap(); + let closed = sends_close(&mut h); + + assert!(!closed); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the painted stroke"); + } + + #[test] + fn a_stroke_open_when_the_save_returns_quits_once_it_is_canceled() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = stroke_open_when_the_save_returns("stroke-canceled"); + + h.state_mut().session.cancel_stroke(); + let closed = sends_close(&mut h); + + assert!(closed, "nothing is left to save, so the close goes on"); + assert!(h.state().ui.windows.unsaved.is_none()); + } + + #[test] + fn opening_another_project_drops_the_close_that_waited_for_a_stroke() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = stroke_open_when_the_save_returns("stroke-replaced"); + + h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + let closed = sends_close(&mut h); + + assert!(!closed, "the old project's close does not quit the new one"); + assert!(h.state().ui.windows.unsaved.is_none()); + assert!(h.state().quit_after_stroke.is_none()); + } + + #[test] + fn replacing_the_project_during_a_save_drops_its_pending_close() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for stroke_active in [false, true] { + let test = if stroke_active { "replace-saving-stroke" } else { "replace-saving-dirty" }; + let file = temp_file(test); + let mut h = harness(); + h.state_mut().session.modified = false; + let (task, sender) = start_held_save(&mut h, &file, true); + + request_close(&mut h); + assert_eq!(h.state().save_job.as_ref().unwrap().quit_requested_by, Some(h.state().session.project_id)); + h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + if stroke_active { + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + } else { + assert!(h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Replacement edit"})).is_some()); + } + + assert!(!finish(&mut h, task, &sender)); + assert!(file.exists(), "the old archive still finished"); + assert!(h.state().session.path.is_none(), "the replacement does not adopt the old archive"); + assert!(h.state().ui.windows.unsaved.is_none(), "the old close does not prompt about the replacement"); + if stroke_active { + h.state_mut().session.cancel_stroke(); + assert!(!sends_close(&mut h), "the old close does not survive the replacement's stroke"); + } + } + } + + #[test] + fn replacing_a_project_with_an_open_quit_prompt_discards_its_answer() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("replace-prompt"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, true); + request_close(&mut h); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); + + let ctx = h.ctx.clone(); + let result = crate::control::handle(h.state_mut(), &ctx, "command.run", &serde_json::json!({ "id": "file.close" })); + assert_eq!(result["ok"], true); + assert!(!finish(&mut h, task, &sender)); + + assert!(h.state().ui.windows.unsaved.is_none(), "the discarded project's prompt cannot act on the replacement"); + } + + #[test] + fn closing_the_replacement_waits_for_the_original_archive() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-replacement"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, true); + let replacement = texturecraft_engine::sample_session(256, 64).unwrap(); + h.state_mut().session.switch_to(replacement); + + assert!(crate::windows::close_requested(h.state_mut()), "the new close must hold the process open for the pending write"); + let closed = finish(&mut h, task, &sender); + + assert!(file.exists()); + assert!(closed, "the replacement's own close resumes once the writer finishes"); + assert!(h.state().session.path.is_none()); + assert!(h.state().ui.windows.unsaved.is_none()); + } + + #[test] + fn closing_the_replacement_resumes_after_the_original_save_fails() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-replacement-after-failure").with_file_name("missing").join("project.tcraft"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, true); + let replacement = texturecraft_engine::sample_session(256, 64).unwrap(); + h.state_mut().session.switch_to(replacement); + + request_close(&mut h); + assert!(!sends_close(&mut h), "the replacement waits for the original save"); + let result = task.run(None); + assert!(result.is_err(), "the original write fails"); + sender.send(result).unwrap(); + + assert!(sends_close(&mut h), "the replacement's own close resumes after the failed write"); + assert!(h.state().ui.windows.unsaved.is_none()); + } + + #[test] + fn canceling_a_stroke_after_a_successful_save_leaves_the_saved_edits_clean() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("saved-then-cancel-stroke"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, true); + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + + assert!(!finish(&mut h, task, &sender)); + h.state_mut().session.cancel_stroke(); + + assert!(!crate::windows::close_requested(h.state_mut()), "the saved edits and canceled stroke need no second save"); + } + + #[test] + fn dismissing_the_prompt_during_a_save_cancels_the_quit() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-dismissed"); + let mut h = harness(); + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + request_close(&mut h); + h.get_by_label("Close window").click(); + h.run_steps(2); + assert!(h.state().ui.windows.unsaved.is_none(), "the prompt is dismissed while the save runs"); + + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "a dismissed prompt keeps the app open"); + assert!(!h.state().session.modified); + } +} diff --git a/crates/ui-egui/src/manual_save/save_job.rs b/crates/ui-egui/src/manual_save/save_job.rs new file mode 100644 index 00000000..4834b1b8 --- /dev/null +++ b/crates/ui-egui/src/manual_save/save_job.rs @@ -0,0 +1,12 @@ +use std::sync::{Arc, mpsc}; + +use texturecraft_engine::{Result, file_cmds::SaveOutput, formats::project_file::SaveProgress}; + +pub(crate) struct SaveJob { + pub(super) progress: Arc, + pub(super) output: mpsc::Receiver>, + pub(super) project_id: u64, + pub(super) for_prompt: bool, + pub(super) remember: bool, + pub(super) quit_requested_by: Option, +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 32062a06..5e5ced92 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -148,6 +148,11 @@ fn tooltip_of(id: &str) -> Option<&'static str> { /// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if app.save_job.is_some() && crate::manual_save::is_save(id) { + return false; + } + if UNAVAILABLE.contains(&id) { return false; } @@ -478,7 +483,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } // 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 + // Unbound Shift+Delete and Shift+Insert use the standard cut and paste shortcuts ctx.input_mut(|input| { let held = input.modifiers; let aliases: Vec<_> = input @@ -532,11 +537,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - // The open list or the picker window closes on this Escape itself + let export = &app.ui.export; let escape_is_free = !popup_open && !picker_open; + + // Local export inputs handle Escape during drawing + let export_input_active = app.ui.windows.export && (export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some()); if confirming_reset { // Its keys were handled before the shortcuts ran - } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { // The Output templates question: Escape answers it with the safe choice app.ui.export.ask = None; } else if app.ui.windows.project_config.is_some() { @@ -546,19 +554,25 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if popup_open || export_input_active { + // The open list or export input handles the key + } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; - } else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; - } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if !escape_is_free { + // The picker window handles the key + } else if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; - } else if escape_is_free && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); - } else if escape_is_free && app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_symmetry_plane = false; - } else if escape_is_free && app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.ui.windows.export { + crate::export_window::keys_in(app, input); + } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.cancel_path(); } diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 8458db61..7d5cb5c2 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -31,6 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut export, mut cancel) = (false, false); + let mut triangulated = true; crate::windows::dialog(ctx, "mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { ui.set_width(DIALOG_WIDTH); @@ -38,24 +39,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); option( ui, - true, + &mut triangulated, + false, tr("Apply triangulation"), &[ tr("Splits every face with more than three corners into triangles; triangles stay as they are."), tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."), ], ); - ui.add_space(GROUP_GAP); - unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); option( ui, + &mut app.ui.mesh_recompute_normals, true, tr("Recompute vertex normals"), &[ tr("Replaces the mesh's vertex normals with newly computed ones in the exported file."), - tr("TextureCraft cannot do this yet: it writes the vertex normals the mesh has in the project."), + tr("On: smooth area-weighted normals from the exported geometry. Off: the project's stored normals. The project itself is not changed."), ], ); + ui.add_space(GROUP_GAP); + unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); ui.add_space(8.0); // One row keeps the window to its contents; a bare right-to-left layout fills the screen height @@ -76,12 +79,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// A greyed option under a choice, ticked as the reference shows it, with an info icon at the -/// row's right end whose tooltip has the paragraphs `info` -fn option(ui: &mut Ui, checked: bool, label: &str, info: &[&str]) { +/// An option under a choice, greyed when `enabled` is false, with an info icon at the row's right +/// end whose tooltip has the paragraphs `info`. +fn option(ui: &mut Ui, checked: &mut bool, enabled: bool, label: &str, info: &[&str]) { ui.horizontal(|ui| { ui.add_space(OPTION_INDENT); - unavailable::checkbox(ui, checked, label); + if enabled { + ui.checkbox(checked, label); + } else { + unavailable::checkbox(ui, *checked, label); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let icon = ui.label(egui::RichText::new(egui_phosphor::regular::INFO).color(Tokens::get(ui.ctx()).text_dim)); icon.on_hover_ui(|ui| { diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs index 50b51a55..2ad606b1 100644 --- a/crates/ui-egui/src/parity.rs +++ b/crates/ui-egui/src/parity.rs @@ -6,6 +6,83 @@ use crate::menus::{CATALOG, implemented}; /// Live menu items must never drop below this (raise it when parity rises). pub const FLOOR: usize = 51; +/// RFC-0052 hand marks for catalog ids that aren't engine commands: `(id, headless, reach, why)`. +/// +/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer), +/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine +/// command, isn't one yet). `yes` is never written here: an item is `yes` only when its id is an +/// engine command (`texturecraft_engine::find`), the registry `texturecraft-cli` and the MCP server +/// load. A `ui.*` id is live in the desktop app only. An unmarked id is `unknown`. +pub const HEADLESS: &[(&str, &str, &str, &str)] = &[ + ("ui.newProject", "partial", "window", "the dialog is desktop-only; `project.new` creates the project"), + ("ui.saveAsTemplate", "partial", "window", "the dialog is desktop-only; `project.template.save` saves it"), + ("ui.export", "partial", "window", "the dialog is desktop-only; `file.exportTextures` exports"), + ("ui.saveReduced", "no", "engine-gap", "a smaller save could be a command"), + ("ui.projectConfig", "partial", "window", "the dialog is desktop-only; `project.rename` sets the project name"), + ("ui.recent.clear", "no", "window", "the desktop recent-projects list"), + ("ui.quit", "no", "window", "quits the desktop app"), + ("ui.settings", "no", "window", "the desktop settings window"), + ("ui.mode.bake", "no", "window", "switches the desktop workspace; `bake.run` bakes"), + ("ui.mode.paint", "no", "window", "switches the desktop workspace"), + ("ui.mode.render", "no", "window", "switches the desktop workspace"), + ("ui.layout.save.painting", "no", "window", "desktop window layout"), + ("ui.layout.save.rendering", "no", "window", "desktop window layout"), + ("ui.layout.save.baking", "no", "window", "desktop window layout"), + ("ui.layout.load", "no", "window", "desktop window layout"), + ("ui.hideUi", "no", "window", "desktop window layout"), + ("ui.resetUi", "no", "window", "desktop window layout"), + ("ui.help.releaseNotes", "no", "os", "opens a web page in the browser"), + ("ui.help.docs", "no", "os", "opens a web page in the browser"), + ("ui.help.discord", "no", "os", "opens a web page in the browser"), + ("ui.help.bug", "no", "os", "opens a web page in the browser"), + ("ui.help.checkForUpdates", "no", "os", "an online update check"), + ("ui.help.shortcuts", "no", "window", "a desktop window"), + ("ui.help.showLog", "no", "window", "a desktop window"), + ("ui.help.exportLog", "no", "window", "saves the desktop app's log"), + ("ui.about", "no", "window", "a desktop window"), +]; + +/// Prefixes whose every id opens or arranges a desktop panel (`no`, `window`). +const WINDOW_PREFIXES: [&str; 2] = ["ui.view.", "ui.toolbar."]; + +/// An item's RFC-0052 `(headless, reach, why)`: `yes` for an engine command, else its mark, else +/// `unknown`. +pub fn headless_of(id: &str, in_engine: bool) -> (&'static str, Option<&'static str>, &'static str) { + if in_engine { + return ("yes", None, ""); + } + if let Some(m) = HEADLESS.iter().find(|m| m.0 == id) { + return (m.1, Some(m.2), m.3); + } + if WINDOW_PREFIXES.iter().any(|p| id.starts_with(p)) { + return ("no", Some("window"), "a desktop panel or toolbar"); + } + ("unknown", None, "") +} + +/// Problems with `marks` against `ids` (`(id, is an engine command)`): bad values, repeats, ids +/// not in the catalog, and marks on engine commands (they would hide a `yes`). +pub fn headless_errors(marks: &[(&str, &str, &str, &str)], ids: &[(&str, bool)]) -> Vec { + let mut errs = Vec::new(); + for (i, (id, value, reach, _)) in marks.iter().enumerate() { + if !matches!(*value, "no" | "partial") { + errs.push(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)")); + } + if !matches!(*reach, "window" | "os" | "engine-gap") { + errs.push(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap")); + } + if marks[..i].iter().any(|m| m.0 == *id) { + errs.push(format!("headless mark `{id}` is written twice")); + } + match ids.iter().find(|x| x.0 == *id) { + None => errs.push(format!("headless mark `{id}` is not a catalog id")), + Some((_, true)) => errs.push(format!("headless mark `{id}` is stale: it is an engine command, so it is `yes`")), + Some(_) => {} + } + } + errs +} + /// (live, total) over the catalog, separators excluded. pub fn counts() -> (usize, usize) { let items: Vec<_> = CATALOG.iter().filter(|i| i.label != "-").collect(); @@ -20,15 +97,32 @@ pub fn report() -> String { out.push_str("Each row is a menu item of the target menu layout with TextureCraft's command id; "); out.push_str("**live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md).\n\n"); out.push_str(&format!("**{live} of {total} menu items live ({:.0}%).**\n\n", live as f32 * 100.0 / total.max(1) as f32)); + let values: Vec<_> = CATALOG.iter().filter(|i| i.label != "-").map(|i| headless_of(i.id, texturecraft_engine::find(i.id).is_some())).collect(); + let count = |v: &str| values.iter().filter(|h| h.0 == v).count(); + let no = |r: &str| values.iter().filter(|h| h.0 == "no" && h.1 == Some(r)).count(); + out.push_str(&format!( + "**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** ", + count("yes"), + count("no"), + no("window"), + no("os"), + no("engine-gap"), + count("partial"), + count("unknown") + )); + out.push_str("An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. "); + out.push_str("A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`).\n\n"); for top in crate::menus::TOP { - out.push_str(&format!("## {top}\n\n| Item | Id | Shortcut | Status |\n|---|---|---|---|\n")); + out.push_str(&format!("## {top}\n\n| Item | Id | Shortcut | Status | Headless |\n|---|---|---|---|---|\n")); for i in CATALOG.iter().filter(|i| i.menu == top && i.label != "-") { let label = match i.sub { Some(s) => format!("{s} ▸ {}", i.label), None => i.label.to_string(), }; let status = if implemented(i.id) { "live" } else { "missing" }; - out.push_str(&format!("| {label} | `{}` | {} | {status} |\n", i.id, i.shortcut.unwrap_or(""))); + let (value, reach, why) = headless_of(i.id, texturecraft_engine::find(i.id).is_some()); + let headless = reach.map_or_else(|| value.to_string(), |r| format!("{value}, reach: {r} ({why})")); + out.push_str(&format!("| {label} | `{}` | {} | {status} | {headless} |\n", i.id, i.shortcut.unwrap_or(""))); } out.push('\n'); } @@ -39,6 +133,38 @@ pub fn report() -> String { mod tests { use super::*; + #[test] + fn headless_marks_are_current() { + let ids: Vec<(&str, bool)> = CATALOG.iter().filter(|i| i.label != "-").map(|i| (i.id, texturecraft_engine::find(i.id).is_some())).collect(); + let errs = headless_errors(HEADLESS, &ids); + assert!(errs.is_empty(), "{errs:?}"); + } + + #[test] + fn a_desktop_only_id_is_live_but_not_headless() { + assert!(implemented("ui.export"), "live in the desktop app"); + assert_eq!(headless_of("ui.export", false).0, "partial"); + assert_eq!(headless_of("ui.view.layers", false), ("no", Some("window"), "a desktop panel or toolbar")); + assert_eq!(headless_of("file.save", true).0, "yes"); + assert_eq!(headless_of("ui.unheardOf", false).0, "unknown"); + let r = report(); + assert!(r.contains("| `file.save` | Ctrl+S | live | yes |"), "{r}"); + let (live, _) = counts(); + let yes = CATALOG.iter().filter(|i| i.label != "-" && texturecraft_engine::find(i.id).is_some()).count(); + assert!(yes < live, "the ui.* ids are live but not headless"); + assert!(r.contains(&format!("{yes} yes,")), "{r}"); + } + + #[test] + fn bad_headless_marks_are_refused() { + let ids = [("a.b", true), ("c.d", false)]; + let marks = [("c.d", "yes", "os", ""), ("c.d", "no", "desk", ""), ("a.b", "no", "os", ""), ("z.z", "no", "os", "")]; + let errs = headless_errors(&marks, &ids); + for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`a.b` is stale", "`z.z` is not a catalog id"] { + assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}"); + } + } + #[test] fn parity_floor_and_report() { let (live, total) = counts(); diff --git a/crates/ui-egui/src/press_edit.rs b/crates/ui-egui/src/press_edit.rs new file mode 100644 index 00000000..22376088 --- /dev/null +++ b/crates/ui-egui/src/press_edit.rs @@ -0,0 +1,8 @@ +//! What [`crate::widgets::press_edit`] keeps of an editor's last change + +/// The press an editor's last change belonged to, and the frame it was seen in +#[derive(Clone, Copy)] +pub(crate) struct PressEdit { + pub(crate) press: u64, + pub(crate) frame: u64, +} diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index cb887ca1..e88413f2 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -1,14 +1,15 @@ //! Edit > Project Configuration...: the project's settings in sections. 3D MESH picks another mesh -//! file for the project or reads the current one again; PROJECT SETTINGS sets the normal map format -//! and shows the UV tiles. Settings TextureCraft does not have yet (tangent space per fragment, -//! physical size, OpenColorIO, import options other than stroke preservation) are shown disabled. +//! file for the project or reads the current one again; PROJECT SETTINGS sets the project name and +//! normal map format and shows the UV tiles. Unsupported options such as tangent space per fragment, +//! physical size and OpenColorIO are shown disabled. +use std::borrow::Cow; use std::sync::atomic::{AtomicU64, Ordering}; use egui::{Key, Modifiers}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; -use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; +use texturecraft_engine::project_cmds::{MAX_PROJECT_NAME_CHARS, validate_project_name}; use crate::TextureCraftApp; use crate::dock::info_icon; @@ -34,6 +35,7 @@ const MIN_FIELD_WIDTH_POINTS: f32 = 60.0; const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 560.0; /// Leave space around the centered dialog on short viewports. const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; +const PROJECT_NAME_FIELD_ID: &str = "project_config_name"; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { @@ -45,7 +47,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) { mesh: None, reimport: false, preserve: true, - name: None, + draft_name: None, normal_format: None, color_management: crate::project_form::ColorManagement::Legacy, confirm: false, @@ -117,14 +119,23 @@ fn format_name(format: NormalFormat) -> &'static str { } } -pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - let Some(mut config) = app.ui.windows.project_config.take() else { return }; - - // Choices for another project cannot be applied here - if config.project != app.session.project_id { +fn sync_name_editor(app: &mut TextureCraftApp, ctx: &egui::Context, opening: Option) { + if app.project_name_editor_opening == opening { return; } + // Egui keeps widget undo data after the dialog closes + app.project_name_editor_opening = opening; + ctx.data_mut(|data| data.remove::(egui::Id::unique(PROJECT_NAME_FIELD_ID))); +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + // Choices for another project cannot be applied here + let config = app.ui.windows.project_config.take().filter(|config| config.project == app.session.project_id); + sync_name_editor(app, ctx, config.as_ref().map(|config| config.opening_id)); + + let Some(mut config) = config else { return }; + let project = &app.session.doc.project; let current_mesh_path = &project.mesh_path; @@ -139,7 +150,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - // Start with a form that fits the viewport; subsequent sizes follow the user's resize + // Fit the first frame to the viewport and follow the user's resize after that let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); let dialog = crate::windows::dialog(ctx, "project_config", tr("Project Configuration"), &mut open) @@ -218,13 +229,15 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let label = ui.label(tr("Project name")).id; ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { info_icon(ui, tr("The name $project stands for in export file names. The project file keeps its own name.")); - let mut name = config.name.clone().unwrap_or_else(|| project.name.clone()); - let field = egui::TextEdit::singleline(&mut name).char_limit(MAX_PROJECT_NAME_CHARS).desired_width(FIELD_WIDTH_POINTS); - if ui.add(field).labelled_by(label).changed() { - config.name = Some(name); + let was_edited = config.draft_name.is_some(); + let mut name = config.draft_name.take().map_or(Cow::Borrowed(project.name.as_str()), Cow::Owned); + let field = egui::TextEdit::singleline(&mut name).id(egui::Id::unique(PROJECT_NAME_FIELD_ID)).desired_width(FIELD_WIDTH_POINTS); + if ui.add(field).labelled_by(label).changed() || was_edited { + config.draft_name = Some(name.into_owned()); } }); }); + let shown_format = config.normal_format.unwrap_or(current_normal_format); row( ui, @@ -298,7 +311,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { physical_size(ui, "project_config_physical_size", false); color_management(ui, "project_config_color_management", &mut config.color_management); }); - }); }); }); @@ -317,9 +329,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); } - // Apply the mesh first so a failed mesh change leaves the format untouched + let confirming = ok && !cancel && open; + + // Reject invalid drafts before applying mesh or format changes + if confirming && config.draft_name.as_deref().is_some_and(|name| validate_project_name(name).is_err()) { + app.toast(trf("Project name must be 1 to {max} characters after trimming, without control characters.", &[("max", &MAX_PROJECT_NAME_CHARS)]), true); + app.announce_latest_toast(); + app.ui.windows.project_config = Some(config); + return; + } + + // Apply the mesh first so a failed mesh change leaves the remaining settings untouched let mut mesh_applied = false; - let done = ok && !cancel && open && { + let done = confirming && { let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() { // Drop a stale reimport tick so the user can retry the remaining settings @@ -342,20 +364,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } None => true, } - // An untouched name is left alone, even one longer than a typed name may be - && match config.name.as_deref() { + && match config.draft_name.as_deref() { Some(name) => app.run("project.rename", json!({"name": name})).is_some(), None => true, } }; if !done && !cancel && open { - // A format retry must not reimport an already changed mesh + // A retry must not reimport an already changed mesh if ok && mesh_applied { (config.mesh, config.reimport) = (None, false); } app.ui.windows.project_config = Some(config); + } else { + sync_name_editor(app, ctx, None); } } diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs index a8cbee52..dc866982 100644 --- a/crates/ui-egui/src/property_sheet/info_icon.rs +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -1,7 +1,7 @@ use egui::{Align2, CornerRadius, FontId, Frame, Margin, Rect, RectAlign, RichText, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; -use super::{PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE}; +use super::{PropertySheet, ROW_HEIGHT, SIDE_PADDING_POINTS, SMALL_TEXT_SIZE}; use crate::theme::HARD_SHADOW; /// The i's slot at the panel edge; a row with an i at its left starts this much further right @@ -16,6 +16,9 @@ const INFO_ICON_SIZE: f32 = 13.0; /// Room the tooltip leaves at the panel's right edge, so it covers no number, dial or switch const TIP_VALUE_ROOM: f32 = 70.0; +/// Width of a tooltip beside its window +const BESIDE_TIP_WIDTH: f32 = 320.0; + /// How far the tooltip reaches up into its row const TIP_OVERLAP: f32 = 2.0; @@ -47,6 +50,48 @@ impl<'u> PropertySheet<'u> { self.paint_info_in(self.right - INFO_SLOT, self.right - INFO_ICON_SIZE / 2.0, center_y); } + /// Paints an i for the row just laid out in the `column` right of the sheet, its tooltip beside the window the sheet is in + pub(crate) fn beside_info(&mut self, column: f32, tip: &str) { + let center_y = self.cursor_y() - ROW_HEIGHT / 2.0; + let row_top = center_y - ROW_HEIGHT / 2.0; + let edge = self.right + SIDE_PADDING_POINTS + column; + let slot = Rect::from_min_max(pos2(edge - SIDE_PADDING_POINTS - INFO_SLOT, row_top), pos2(edge - SIDE_PADDING_POINTS, row_top + ROW_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(slot, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tip)); + + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + self.ui.painter().text(slot.center(), Align2::CENTER_CENTER, ic::INFO, FontId::proportional(INFO_ICON_SIZE), color); + + // Beside the window, from this row down, so it covers none of the rows under it + let layer = self.ui.layer_id().id; + let window = self.ui.ctx().memory(|memory| memory.area_rect(layer)).unwrap_or(self.ui.clip_rect()); + let anchor = Rect::from_min_max(pos2(window.left(), row_top), pos2(window.right(), row_top + ROW_HEIGHT)); + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip + .popup + .anchor(anchor) + .align(RectAlign::RIGHT_START) + .align_alternatives(&[RectAlign::LEFT_START]) + .frame(self.tip_frame()) + .width(BESIDE_TIP_WIDTH); + tooltip.show(|ui| { + ui.set_width(BESIDE_TIP_WIDTH); + ui.label(RichText::new(tip).size(SMALL_TEXT_SIZE).color(tokens.text).line_height(Some(TIP_LINE_HEIGHT))); + }); + } + + /// The tooltips' box: the chrome, a hairline, rounded, with a hard shadow + fn tip_frame(&self) -> Frame { + Frame::NONE + .fill(self.tokens.chrome) + .stroke(Stroke::new(1.0, self.tokens.field_border)) + .corner_radius(CornerRadius::same(TIP_ROUNDING)) + .inner_margin(TIP_MARGIN) + .shadow(TIP_SHADOW) + } + /// Paints the pending i at `glyph_x` in its slot from `slot_left` fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { let Some(tip) = self.info.take() else { return }; @@ -63,12 +108,7 @@ impl<'u> PropertySheet<'u> { // Under the row from the i, ending before the value column; above it where the window ends first let anchor = Rect::from_min_max(pos2(self.left, row_top), pos2(self.right - TIP_VALUE_ROOM, row_top + ROW_HEIGHT)); - let frame = Frame::NONE - .fill(tokens.chrome) - .stroke(Stroke::new(1.0, tokens.field_border)) - .corner_radius(CornerRadius::same(TIP_ROUNDING)) - .inner_margin(TIP_MARGIN) - .shadow(TIP_SHADOW); + let frame = self.tip_frame(); let text_width = anchor.width() - TIP_MARGIN.sum().x; let mut tooltip = egui::Tooltip::for_enabled(&response); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 51c6ecfb..acd1f2dd 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -75,13 +75,14 @@ pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection}; pub(crate) use row_lead::RowLead; pub(crate) use section_tabs::{ SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, in_scope, - room_past_end, section_tabs, + room_past_end, section_tabs, shown_tab_box, }; pub(crate) use sheet::PropertySheet; pub(crate) use size_columns_response::SizeColumnsResponse; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; pub(crate) use stacked_rows::{CHECK_SIZE, paint_check}; +pub(crate) use switch_control::{TOGGLE_ROOM, paint_focus_outline}; pub(crate) fn paint_keyboard_focus(ui: &egui::Ui, response: &egui::Response, tokens: &crate::theme::Tokens) { if response.has_focus() { @@ -123,7 +124,7 @@ const VALUE_MIN_WIDTH: f32 = 26.0; const TRACK_TO_VALUE: f32 = 14.0; /// Size of regular labels and SemiBold values -const TEXT_SIZE: f32 = 12.0; +pub(crate) const TEXT_SIZE: f32 = 12.0; /// Size of captions, pill names and the switch's words const SMALL_TEXT_SIZE: f32 = 11.0; diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 595116ca..754c3fd2 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -110,7 +110,7 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { } /// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip -fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { +pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); } diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs index 5fe48e1f..bc17fa4f 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs @@ -5,4 +5,6 @@ pub(crate) enum SectionScope { Docked, /// The right-click Properties popup over a view Popup, + /// The Assets panel's refresh popup, which has no strip + Shelf, } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 8f700a6d..fa355eff 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -38,6 +38,9 @@ const TOGGLE_LABEL_AIR: f32 = 10.0; /// From that column to the pill's centre: the pill starts on the column const TOGGLE_CENTER_OFFSET: f32 = PILL_SIZE.x / 2.0; +/// Room a toggle takes right of its label: the air and the switch +pub(crate) const TOGGLE_ROOM: f32 = TOGGLE_LABEL_AIR + PILL_SIZE.x; + /// From one of a pair's toggles to the next, and from its name to its pill's centre const PAIR_PITCH: f32 = 76.0; const PAIR_NAME_TO_PILL: f32 = 32.0; @@ -63,7 +66,7 @@ pub(super) fn untinted(_index: usize) -> &'static [Color32] { &[] } -pub(super) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { +pub(crate) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(FOCUS_OUTLINE_WIDTH, color), StrokeKind::Inside); } @@ -191,6 +194,15 @@ impl PropertySheet<'_> { /// An on/off beside its label; every toggle in a panel lines up past the longest toggle label pub(crate) fn toggle(&mut self, label: &str, on: &mut bool) -> bool { + self.toggle_in(label, on, true) + } + + /// A [`Self::toggle`] greyed out and off: a setting this app can't act on yet, said in its row's i + pub(crate) fn unavailable_toggle(&mut self, label: &str) { + self.toggle_in(label, &mut false, false); + } + + fn toggle_in(&mut self, label: &str, on: &mut bool, enabled: bool) -> bool { let rect = self.take(ROW_HEIGHT); let center_y = rect.center().y; let label_x = self.left + self.lead_shift(); @@ -201,11 +213,19 @@ impl PropertySheet<'_> { let column = (self.column() - self.left).max(self.used.toggle_label_end).max(label_end); let pill = Rect::from_center_size(pos2(self.left + column + TOGGLE_CENTER_OFFSET, center_y), PILL_SIZE); - let clicked = self.toggle_hit(Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + let hit = Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())); + let clicked = if enabled { + self.toggle_hit(hit, label, on) + } else { + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::hover()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, false, false, label)); + false + }; - let text = self.tokens.text; + let text = if enabled { self.tokens.text } else { self.tokens.text_dim }; self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, label, font, text); - self.pill(pill.center(), *on, true); + self.pill(pill.center(), *on, enabled); self.drawn(center_y + PILL_SIZE.y / 2.0); clicked } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 10c7ecfd..28b126c4 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1042,6 +1042,48 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening"); } +/// Editing one editor after another, a press at a time, keeps the record of the latest press only (it kept one per editor ever dragged) +#[test] +fn the_editors_of_earlier_presses_are_forgotten() { + const EDITOR_COUNT: usize = 12; + let context = egui::Context::default(); + let button = + |pressed| egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + + for editor in 0..EDITOR_COUNT { + let owner = egui::Id::unique(("distinct editor", editor)); + for pressed in [true, false] { + let input = egui::RawInput { events: vec![button(pressed)], ..Default::default() }; + context.run_ui(input, |ui| _ = crate::widgets::press_edit(ui, owner, pressed)).textures_delta.clear(); + } + } + + let kept = context.data(|data| data.count::()); + assert!(kept < 2, "{kept} editor records kept after {EDITOR_COUNT} presses"); +} + +/// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step +#[test] +fn a_drag_stays_one_undo_step_while_another_window_draws() { + let context = egui::Context::default(); + let owner = egui::Id::unique("held editor"); + let edit = |events| { + let mut result = None; + let mut output = context.run_ui(egui::RawInput { events, ..Default::default() }, |ui| result = crate::widgets::press_edit(ui, owner, true)); + output.textures_delta.clear(); + result + }; + let press = egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + + assert_eq!(edit(vec![press]), Some(false), "the press starts an undo step"); + let viewport = egui::ViewportId::from_hash_of("floating History"); + let floating = + egui::RawInput { viewport_id: viewport, viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), ..Default::default() }; + context.run_ui(floating, |_| {}).textures_delta.clear(); + + assert_eq!(edit(Vec::new()), Some(true), "the held press continues its undo step"); +} + #[test] fn section_tabs_show_focus_before_a_keyboard_jump() { let mut harness = builder(Brightness::MediumDark).build_ui(|ui| { diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs new file mode 100644 index 00000000..a4bed5c9 --- /dev/null +++ b/crates/ui-egui/src/resources_updater.rs @@ -0,0 +1,442 @@ +//! The Resources Updater: the project's image resources and whether the files they were imported +//! from changed on disk. Update reads a changed file again, Select new resource points a resource +//! at another file, and a notice offers to update when the app gets the focus back after files +//! changed. Everything runs through `resource.status`, `resource.update` and `resource.relink`. + +mod row_request; + +use std::collections::BTreeSet; + +use serde_json::json; +use texturecraft_engine::{ResourceState, ResourceStatus}; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::ResourcesUpdater; +use crate::theme::Tokens; +use crate::toast_action::ToastAction; +use crate::web_files::IMAGE_EXTS; +use row_request::RowRequest; + +/// Width of the window +const WINDOW_WIDTH_POINTS: f32 = 640.0; +/// Height of the resource list +const LIST_HEIGHT_POINTS: f32 = 360.0; +/// Initial space for the header, tabs, filters and footer +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0; +/// Side of a row's thumbnail +const THUMBNAIL_POINTS: f32 = 40.0; +/// Width of the name filter field +const NAME_FILTER_WIDTH_POINTS: f32 = 160.0; +/// Width of the status dropdown +const STATUS_WIDTH_POINTS: f32 = 120.0; +/// Space inside a row's frame +const ROW_MARGIN: egui::Margin = egui::Margin::same(4); +/// Strength of the danger tint behind an outdated row (the status text says it too) +const OUTDATED_TINT: f32 = 0.18; +/// How long the "changed on disk" notice stays, in seconds: long enough to reach its button +const NOTICE_SECONDS: f64 = 12.0; +/// Time between two checks while the window is open, in seconds (each check looks at every file; an unchanged one is not read) +const RECHECK_SECONDS: f64 = 0.5; + +/// Opens the window, or closes it when it is open (the shelf button) +pub(crate) fn toggle(app: &mut TextureCraftApp) { + if app.ui.windows.resources_updater.take().is_none() { + open(app); + } +} + +/// Opens the window with the resources checked now (an open window is checked again) +pub(crate) fn open(app: &mut TextureCraftApp) { + let window = app.ui.windows.resources_updater.take().unwrap_or_default(); + app.ui.windows.resources_updater = + Some(ResourcesUpdater { rows: app.session.resource_states(), project: app.session.project_id, checked_at: app.last_time, ..window }); +} + +/// Check once when another project is open (files may have changed while it was closed), and +/// forget what was announced for the last one +pub(crate) fn follow_project(app: &mut TextureCraftApp) { + if !app.session.project_open || app.resources_project == Some(app.session.project_id) { + return; + } + + app.resources_project = Some(app.session.project_id); + app.resources_notified.clear(); + check_files(app); +} + +/// Check the files again (the app has the focus back, or a project opened) and, when other +/// resources than last time are outdated, show a notice whose button updates them +pub(crate) fn check_files(app: &mut TextureCraftApp) { + if !app.session.project_open { + return; + } + + let rows = app.session.resource_states(); + let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect(); + if let Some(window) = app.ui.windows.resources_updater.as_mut() { + window.rows = rows; + window.checked_at = app.last_time; + } + + if !outdated.is_empty() && outdated != app.resources_notified { + let text = if outdated.len() == 1 { + tr("1 resource changed on disk").to_string() + } else { + trf("{count} resources changed on disk", &[("count", &outdated.len())]) + }; + app.toast(text, false); + if let Some(toast) = app.toasts.last_mut() { + toast.until = app.last_time + NOTICE_SECONDS; + toast.action = Some(ToastAction::UpdateResources { project: app.session.project_id }); + } + } + app.resources_notified = outdated; +} + +/// Read the files of `names` again (every outdated resource when None), one undo step, and say +/// what happened +pub(crate) fn update(app: &mut TextureCraftApp, names: Option>) { + let params = match names { + Some(names) => json!({ "names": names }), + None => json!({}), + }; + let Some(result) = app.run("resource.update", params) else { + app.announce_latest_toast(); + return; + }; + + let updated = result["updated"].as_array().map_or(0, Vec::len); + let failed: Vec = result["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failure| format!("{}: {}", failure["name"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default())) + .collect(); + if failed.is_empty() { + app.toast(trf("Updated {count} resources", &[("count", &updated)]), false); + } else { + app.toast(trf("Updated {count} resources; could not update {failed}", &[("count", &updated), ("failed", &failed.join("; "))]), true); + } + app.announce_latest_toast(); + + // What was announced is handled; a later change is announced again + app.resources_notified.clear(); +} + +/// Ask for another file for resource `name`; the resource takes its pixels and follows it +fn select_new_resource(app: &mut TextureCraftApp, name: String) { + let dialog = FileDialog::open().filter(tr("Images"), IMAGE_EXTS); + app.ask_file(dialog, Bound::Project, move |app, paths| { + let Some(path) = paths.first() else { return }; + let Some(path) = path.to_str() else { + app.toast(trf("Could not use a path that is not UTF-8: {path}", &[("path", &path.display())]), true); + app.announce_latest_toast(); + return; + }; + + if app.run("resource.relink", json!({ "name": name, "path": path })).is_some() { + app.toast(trf("{name} now reads {path}", &[("name", &name), ("path", &path)]), false); + } + app.announce_latest_toast(); + }); +} + +/// Show the folder holding `path` in the system's file manager +fn show_in_folder(app: &mut TextureCraftApp, path: &str) { + let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default(); + if let Err(error) = app.file_dialogs.show_folder(&folder) { + app.toast(trf("Could not show {folder}: {error}", &[("folder", &folder.display()), ("error", &error)]), true); + app.announce_latest_toast(); + } +} + +/// Whether `row` passes the window's status and name filters +fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool { + let name_filter = window.name_filter.trim().to_lowercase(); + window.status_filter.is_none_or(|status| row.status == status) && (name_filter.is_empty() || row.name.to_lowercase().contains(&name_filter)) +} + +/// "(N resources, M outdated)" +fn summary(rows: &[ResourceState]) -> String { + let outdated = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).count(); + trf("({count} resources, {outdated} outdated)", &[("count", &rows.len()), ("outdated", &outdated)]) +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut window) = app.ui.windows.resources_updater.take() else { return }; + + // Drop the window state when its project closes or changes + if window.project != app.session.project_id || !app.session.project_open { + return; + } + + // Files changed on disk and document changes (undo, a removed resource) show while the window stays open + let wait = window.checked_at + RECHECK_SECONDS - app.last_time; + if wait <= 0.0 { + window.rows = app.session.resource_states(); + window.checked_at = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK_SECONDS)); + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } + + // Only close on Escape when the window owned keyboard focus + // Read raw input because egui consumes Escape when it clears focus + let escape = ctx.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if window.had_keyboard && escape && !egui::Popup::is_any_open(ctx) { + return; + } + + let tokens = Tokens::get(ctx); + let mut window_open = true; + let (mut refresh, mut update_all) = (false, false); + let mut request = None; + + let shown = crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut window_open) + .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) + .show(ctx, |ui| { + ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name)); + + let tab = ui.add(egui::Button::selectable(true, tr("Resources"))); + tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, true, tr("Resources"))); + ui.separator(); + + ui.horizontal(|ui| { + let status_label = ui.label(tr("Status:")); + let selected = window.status_filter.map_or(tr("All"), |status| tr(status.label())); + egui::ComboBox::from_id_salt("resources_updater_status") + .width(STATUS_WIDTH_POINTS) + .selected_text(selected) + .show_ui(ui, |ui| { + ui.selectable_value(&mut window.status_filter, None, tr("All")); + for status in ResourceStatus::ALL { + ui.selectable_value(&mut window.status_filter, Some(status), tr(status.label())); + } + }) + .response + .labelled_by(status_label.id); + + let name_label = ui.label(tr("Name filter:")); + ui.add(egui::TextEdit::singleline(&mut window.name_filter).desired_width(NAME_FILTER_WIDTH_POINTS)).labelled_by(name_label.id); + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Bottom")).clicked() { + window.jump = Some(egui::Align::Max); + } + if ui.button(tr("Top")).clicked() { + window.jump = Some(egui::Align::Min); + } + }); + }); + ui.add_space(4.0); + + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + let refresh_button = ui.button(tr("Refresh")); + refresh_button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Refresh resources"))); + refresh = refresh_button.clicked(); + let count = ui.label(summary(&window.rows)); + ui.ctx().accesskit_node_builder(count.id, |node| node.set_live(egui::accesskit::Live::Polite)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated); + let label = egui::RichText::new(tr("Update All")).color(tokens.text_strong); + let action = egui::Button::new(label).fill(tokens.accent_dim).stroke(egui::Stroke::new(1.0, tokens.text_dim)); + let button = ui.add_enabled(outdated, action); + update_all = button.on_disabled_hover_text(tr("No resource is outdated")).clicked(); + }); + }); + ui.separator(); + + let list_height = ui.available_height().max(0.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, false]).show(ui, |ui| { + let jump = window.jump.take(); + if jump == Some(egui::Align::Min) { + ui.scroll_to_cursor(Some(egui::Align::Min)); + } + + let visible: Vec<&ResourceState> = window.rows.iter().filter(|row| shown(&window, row)).collect(); + if visible.is_empty() { + ui.label(tr("No resources match the filters")); + } + for (index, row) in visible.into_iter().enumerate() { + // Keep keyboard focus with the resource when rows move + let row_scope = egui::UiBuilder::new().scope_id(ui.scope_id().with(("resources_updater_row", &row.name))); + let asked = ui.scope_builder(row_scope, |ui| row_ui(app, ui, &tokens, index + 1, row)).inner; + if let Some(asked) = asked { + request = Some(asked); + } + } + + if jump == Some(egui::Align::Max) { + ui.scroll_to_cursor(Some(egui::Align::Max)); + } + }); + }); + }); + }); + + let focused = ctx.memory(|memory| memory.focused()).and_then(|id| ctx.read_response(id)); + window.had_keyboard = shown.as_ref().zip(focused.as_ref()).is_some_and(|(shown, focused)| focused.layer_id == shown.response.layer_id); + if !window_open { + return; + } + + app.ui.windows.resources_updater = Some(window); + + // Its own changes and Refresh show at once + let check_now = refresh || update_all || matches!(request, Some(RowRequest::Update(_))); + if update_all { + update(app, None); + } + match request { + Some(RowRequest::Update(name)) => update(app, Some(vec![name])), + Some(RowRequest::SelectNew(name)) => select_new_resource(app, name), + Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path), + None => {} + } + + if check_now { + open(app); + } +} + +/// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are +/// tinted, and their status says so in words too. +fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: usize, row: &ResourceState) -> Option { + let outdated = row.status == ResourceStatus::Outdated; + let (fill, stroke) = if outdated { + (tokens.danger.gamma_multiply(OUTDATED_TINT), egui::Stroke::new(1.0, tokens.danger)) + } else { + (egui::Color32::TRANSPARENT, egui::Stroke::NONE) + }; + let mut request = None; + + egui::Frame::NONE.fill(fill).stroke(stroke).inner_margin(ROW_MARGIN).corner_radius(crate::theme::CARD_RADIUS).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + match app.session.images.get(&row.name) { + Some(image) => { + let (rect, preview) = ui.allocate_exact_size(egui::Vec2::splat(THUMBNAIL_POINTS), egui::Sense::hover()); + preview.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, &row.name)); + if ui.is_rect_visible(rect) { + let texture = app.thumbs.image(ui.ctx(), &row.name, image); + egui::Image::new(&texture).paint_at(ui, rect); + } + } + + // Reserve thumbnail space for images that failed to decode + None => ui.add_space(THUMBNAIL_POINTS), + } + ui.label(number.to_string()); + + // Reserve space for the buttons before truncating the labels + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let update = ui.add_enabled(outdated, egui::Button::new(tr("Update"))); + let update_name = format!("{} {}", tr("Update"), row.name); + update.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, outdated, &update_name)); + if update.clicked() { + request = Some(RowRequest::Update(row.name.clone())); + } + + // Only images can be relinked to disk + let material = row.status == ResourceStatus::Material; + if !material { + let select = ui.button(tr("Select new resource")); + let select_name = format!("{} {}", tr("Select new resource"), row.name); + select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); + if select.clicked() { + request = Some(RowRequest::SelectNew(row.name.clone())); + } + } + + if let Some(path) = &row.path { + let folder = ui.button(tr("Show in folder")); + let folder_name = format!("{} {}", tr("Show in folder"), row.name); + folder.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &folder_name)); + if folder.clicked() { + request = Some(RowRequest::ShowFolder(path.clone())); + } + } + + ui.vertical(|ui| { + ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate()); + ui.label(format!("{} {}", tr("Shelf :"), tr("project"))); + let file = row.path.as_deref().unwrap_or(tr("No source file")); + ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file); + let status = ui.label(tr(row.status.label())); + let detail = row + .error + .as_deref() + .or_else(|| material.then(|| tr("This MaterialCraft package is stored in the project. Its cooked maps are separate image resources."))); + if let Some(detail) = detail { + ui.ctx().accesskit_node_builder(status.id, |node| node.set_description(detail)); + status.on_hover_text(detail); + } + }); + }); + }); + }); + + request +} + +#[cfg(test)] +mod tests { + use std::sync::PoisonError; + + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT as _, Queryable as _}; + use texturecraft_engine::Session; + + use super::*; + + fn write_png(path: &std::path::Path, size: u32) { + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap(); + } + + fn notices(app: &TextureCraftApp) -> Vec { + app.toasts.iter().filter_map(|toast| toast.action).collect() + } + + #[test] + fn a_changed_file_is_announced_once_and_the_notice_updates_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("notice.png"); + write_png(&path, 4); + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(2); + let app = harness.state_mut(); + let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); + + check_files(app); + assert!(notices(app).is_empty(), "nothing changed yet"); + + write_png(&path, 8); + check_files(app); + check_files(app); + let announced = notices(app); + assert_eq!(announced, [ToastAction::UpdateResources { project: app.session.project_id }], "the same change is announced once"); + + // A notice about another project does nothing + ToastAction::UpdateResources { project: app.session.project_id + 1 }.run(app); + assert_eq!(app.session.images[&name].width, 4); + + harness.run_steps(2); + let message = harness.get_by_label("1 resource changed on disk"); + assert_eq!(message.accesskit_node().live(), egui::accesskit::Live::Polite, "the notice is announced away from focus"); + harness.get_by_role_and_label(egui::Role::Button, "Update resources").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); + + let app = harness.state(); + assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource"); + assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources")); + } +} diff --git a/crates/ui-egui/src/resources_updater/row_request.rs b/crates/ui-egui/src/resources_updater/row_request.rs new file mode 100644 index 00000000..75f0626c --- /dev/null +++ b/crates/ui-egui/src/resources_updater/row_request.rs @@ -0,0 +1,9 @@ +/// What a Resources Updater row's buttons asked for, run after the window is drawn +pub(super) enum RowRequest { + /// Update: read the resource's file again + Update(String), + /// Select new resource: ask for another file for the resource + SelectNew(String), + /// Show in folder: the folder holding this file + ShowFolder(String), +} diff --git a/crates/ui-egui/src/running_bake.rs b/crates/ui-egui/src/running_bake.rs index 512af28a..76427ad4 100644 --- a/crates/ui-egui/src/running_bake.rs +++ b/crates/ui-egui/src/running_bake.rs @@ -12,4 +12,9 @@ pub struct RunningBake { /// Maps finished so far, and how many the set makes. pub maps_done: Arc, pub maps_total: usize, + /// The maps received so far, kept when the bake is canceled even if the preview has closed + pub finished: texturecraft_engine::compose::BakedMaps, + /// What the task bakes from and the newest stroke it saw, recorded with the finished maps a cancel keeps + pub sources: std::collections::BTreeMap, + pub painted_stroke: u64, } diff --git a/crates/ui-egui/src/saved_search.rs b/crates/ui-egui/src/saved_search.rs index ec6181b8..b4d4c562 100644 --- a/crates/ui-egui/src/saved_search.rs +++ b/crates/ui-egui/src/saved_search.rs @@ -2,11 +2,14 @@ use serde::{Deserialize, Serialize}; -/// The search text, tab and library folder of a saved shelf query, under the name it lists as +/// The search text, tab, library folder and Favorites choice 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, + /// Only favorites show; searches saved before favorites show everything + #[serde(default)] + pub favorites_only: bool, } diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index 88d73912..f1bf6713 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -9,7 +9,7 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{LANGUAGES, SYSTEM_LANGUAGE, n_, tr, trf}; use crate::state::{CAMERA_SPEED_RANGE, LibraryLocation, MAX_RECENT_PROJECTS, Prefs}; -use crate::theme::{Accent, Brightness, Tokens, caption}; +use crate::theme::{Tokens, caption}; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; @@ -59,7 +59,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] let mut pick = None; let project_open = app.session.project_open; - let gpu = app.render_state.as_ref().map(|render_state| render_state.adapter.get_info().name); // 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))); @@ -80,16 +79,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { .show(ctx, |ui| { // Measure the footer through layout, then let the pages use only what remains ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - // Recheck after drawing the page as well, before accepting any edits - let conflict = crate::keymap::has_conflict(&app.settings_bindings); ui.horizontal(|ui| { - if conflict { + if shortcut_conflict { let danger = Tokens::get(ui.ctx()).danger; ui.label(RichText::new(format!("{} {}", ic::WARNING, tr(SHORTCUT_ERRORS))).color(danger)); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(100.0, 0.0))).clicked(); - ok = ui.add_enabled(!conflict, egui::Button::new(tr("OK")).min_size(vec2(100.0, 0.0))).clicked(); + ok = ui.add_enabled(!shortcut_conflict, egui::Button::new(tr("OK")).min_size(vec2(100.0, 0.0))).clicked(); }); }); ui.separator(); @@ -125,7 +122,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui, &mut draft.prefs, &drawable, - gpu.as_deref(), #[cfg(not(target_arch = "wasm32"))] resources, #[cfg(not(target_arch = "wasm32"))] @@ -152,7 +148,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); - ok &= !crate::keymap::has_conflict(&app.settings_bindings); + // The Shortcuts page can introduce a conflict after the footer was drawn + let ok = ok && !crate::keymap::has_conflict(&app.settings_bindings); app.ui.windows.settings_page = draft.page; if draft.page != SettingsPage::Shortcuts || ok || cancel || !open { crate::keymap::stop_settings_capture(ctx); @@ -175,7 +172,8 @@ fn apply(app: &mut TextureCraftApp, draft: SettingsDraft) { let libraries_changed = draft.prefs.libraries != app.ui.prefs.libraries; let previous_autosave_minutes = app.ui.prefs.autosave_minutes; - app.ui.prefs = draft.prefs; + // Display Settings can change the texture resolution while this draft is open + app.ui.prefs = Prefs { viewport_texture: app.ui.prefs.viewport_texture, ..draft.prefs }; app.ui.trim_recent(); app.reschedule_autosave_if_changed(previous_autosave_minutes); @@ -274,9 +272,17 @@ fn section(ui: &mut Ui, title: &str) { ui.add_space(2.0); } -/// A disabled check box in the right column of a row labelled `label`. -fn disabled_check(ui: &mut Ui, label: egui::Id, mut checked: bool) { - not_available(ui.add_enabled(false, egui::Checkbox::without_text(&mut checked)).labelled_by(label)); +/// A check box in the right column of a row labelled `label`. +fn check(ui: &mut Ui, label: egui::Id, checked: &mut bool) { + ui.add(egui::Checkbox::without_text(checked)).labelled_by(label); +} + +/// A check box with its text. +fn text_check(ui: &mut Ui, text: &str, checked: &mut bool) { + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.checkbox(checked, tr(text)); + }); } /// A disabled check box with its text. @@ -301,71 +307,97 @@ fn speed_slider(ui: &mut Ui, label: &str, value: &mut f32, width: f32) -> Respon .inner } -/// Whether the Baking options say there is no GPU to trace rays on: no adapter, or the browser. +/// Whether the platform or a missing adapter name rules out GPU baking. +/// The Settings control also checks the bake adapter's compute capabilities. pub fn gpu_note_shown(adapter: Option<&str>) -> bool { adapter.is_none() || cfg!(target_arch = "wasm32") } +/// The Enable GPU raytracing check box for the hardware and the stored choice: whether it can be +/// changed and whether it shows ticked. Without a GPU to trace on it is off and disabled; the +/// stored choice is kept for a machine that has one. +pub fn gpu_raytracing_check(adapter_supports_raytracing: bool, stored: bool) -> (bool, bool) { + let supported = adapter_supports_raytracing && !cfg!(target_arch = "wasm32"); + (supported, supported && stored) +} + +/// The Max CPU threads slider's position for a stored `work_threads`: 0 (every thread) is the +/// slider's end, the core count. +#[cfg(not(target_arch = "wasm32"))] +fn work_threads_shown(work_threads: u32, cores: u32) -> u32 { + if work_threads == 0 { cores } else { work_threads.min(cores).max(1) } +} + +/// The stored `work_threads` for the slider at `threads`: its end keeps 0, so every thread works +/// on any machine. +#[cfg(not(target_arch = "wasm32"))] +fn work_threads_stored(threads: u32, cores: u32) -> u32 { + if threads >= cores { 0 } else { threads } +} + +/// The note right of a core slider: how many cores this machine has. +#[cfg(not(target_arch = "wasm32"))] +fn cores_in_total(ui: &mut Ui, cores: u32) { + let tk = Tokens::get(ui.ctx()); + ui.label(RichText::new(trf("{count} cores in total", &[("count", &cores)])).color(tk.text_dim)); +} + /// The General page. fn general( ui: &mut Ui, - p: &mut Prefs, + prefs: &mut Prefs, drawable: &[bool], - gpu: Option<&str>, #[cfg(not(target_arch = "wasm32"))] (available_cores, available_ram_bytes): (u32, u64), #[cfg(not(target_arch = "wasm32"))] pick: &mut Option, ) { let tk = Tokens::get(ui.ctx()); section(ui, n_("INTERFACE OPTIONS")); row(ui, tr("Language"), |ui, label| { - let selected = if p.language == SYSTEM_LANGUAGE { + let selected = if prefs.language == SYSTEM_LANGUAGE { tr("Default (System Language)") } else { - LANGUAGES.iter().find(|l| l.code == p.language).map_or(tr("Default (System Language)"), |l| l.name) + LANGUAGES.iter().find(|l| l.code == prefs.language).map_or(tr("Default (System Language)"), |l| l.name) }; egui::ComboBox::from_id_salt("settings_language") .width(CONTROL_WIDTH) .height(320.0) .selected_text(selected) .show_ui(ui, |ui| { - ui.selectable_value(&mut p.language, SYSTEM_LANGUAGE.to_owned(), tr("Default (System Language)")); + ui.selectable_value(&mut prefs.language, SYSTEM_LANGUAGE.to_owned(), tr("Default (System Language)")); for (l, ok) in LANGUAGES.iter().zip(drawable).filter(|(l, _)| crate::i18n::available(l.code)) { - let item = egui::Button::selectable(l.code == p.language, if *ok { l.name } else { l.english }); + let item = egui::Button::selectable(l.code == prefs.language, 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(); + prefs.language = l.code.to_owned(); } } }) .response .labelled_by(label); }); - row(ui, tr("Show keyboard helper"), |ui, label| disabled_check(ui, label, true)); - row(ui, tr("Show world axes"), |ui, label| disabled_check(ui, label, true)); + row(ui, tr("Show keyboard helper"), |ui, label| check(ui, label, &mut prefs.show_keyboard_helper)); + row(ui, tr("Show world axes"), |ui, label| check(ui, label, &mut prefs.show_world_axes)); row(ui, tr("Background color"), |ui, _| { for (index, side, name) in [(0, "top", "Top background"), (1, "bottom", "Bottom background")] { let id = format!("settings_background_{side}"); - crate::widgets::color_swatch(ui, &id, &mut p.background[index], 38.0); + crate::widgets::color_swatch(ui, &id, &mut prefs.background[index], 38.0); - // The reference shows no tooltip here; the name is only for screen readers + // Give the eyedropper an accessible name without adding a tooltip let label = trf("Pick the {overlay} Color from the Screen", &[("overlay", &name)]); - crate::screen_color_pick::eyedropper_without_tooltip(ui, ui.make_persistent_id(&id), &mut p.background[index], &label, 18.0); + crate::screen_color_pick::eyedropper_without_tooltip(ui, ui.make_persistent_id(&id), &mut prefs.background[index], &label, 18.0); ui.add_space(10.0); } }); - row(ui, tr("Only display the selected material when painting"), |ui, label| disabled_check(ui, label, false)); + row(ui, tr("Only display the selected material when painting"), |ui, label| check(ui, label, &mut prefs.only_selected_material_when_painting)); + ui.small(tr("The keyboard helper and selected-material view preferences are saved for future use.")); row(ui, tr("Viewport Scaling"), |ui, label| { - ui.add_enabled_ui(false, |ui| { - not_available( - egui::ComboBox::from_id_salt("settings_viewport_scaling").width(CONTROL_WIDTH).selected_text(tr("Auto")).show_ui(ui, |_| {}).response, - ) + egui::ComboBox::from_id_salt("settings_viewport_scaling") + .width(CONTROL_WIDTH) + .selected_text(tr("Auto")) + .show_ui(ui, |ui| { + ui.add(egui::Button::selectable(true, tr("Auto"))); + }) + .response .labelled_by(label); - }); - }); - - row(ui, tr("Recent projects limit"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.recent_projects_limit).range(0..=MAX_RECENT_PROJECTS)) - .labelled_by(label) - .on_hover_text(tr("Number of recent projects to remember. 0 disables recent-project history.")); }); section(ui, n_("LAYER STACK OPTIONS")); @@ -385,9 +417,11 @@ fn general( let speed_width = CONTROL_WIDTH + 12.0; ui.horizontal(|ui| { ui.add_space(12.0); - speed_slider(ui, tr("Rotation speed"), &mut p.rotation_speed, speed_width); + speed_slider(ui, tr("Rotation speed"), &mut prefs.rotation_speed, speed_width); }); - for (label, speed, inverse) in [(tr("Zoom speed"), &mut p.zoom_speed, &mut p.zoom_inverse), (tr("Wheel speed"), &mut p.wheel_speed, &mut p.wheel_inverse)] { + for (label, speed, inverse) in + [(tr("Zoom speed"), &mut prefs.zoom_speed, &mut prefs.zoom_inverse), (tr("Wheel speed"), &mut prefs.wheel_speed, &mut prefs.wheel_inverse)] + { ui.horizontal(|ui| { ui.add_space(12.0); speed_slider(ui, label, speed, speed_width); @@ -397,14 +431,25 @@ fn general( } section(ui, n_("BAKING OPTIONS")); - disabled_text_check(ui, n_("Save preprocessed scene files"), true); - disabled_text_check(ui, n_("Enable live preview baking process"), true); + text_check(ui, n_("Save preprocessed scene files"), &mut prefs.save_preprocessed_scene_files); + ui.small(tr("The preprocessed scene file preference is saved for future use.")); + text_check(ui, n_("Enable live preview baking process"), &mut prefs.live_preview_baking); + + #[cfg(not(target_arch = "wasm32"))] + let gpu_bake_supported = texturecraft_render::gpu_bake::raytracing_available(); + #[cfg(target_arch = "wasm32")] + let gpu_bake_supported = false; + let (gpu_raytracing_enabled, mut gpu_raytracing_ticked) = gpu_raytracing_check(gpu_bake_supported, prefs.gpu_raytracing); ui.horizontal(|ui| { ui.add_space(12.0); - ui.checkbox(&mut p.gpu_raytracing, tr("Enable GPU raytracing")) + let gpu_raytracing = ui + .add_enabled(gpu_raytracing_enabled, egui::Checkbox::new(&mut gpu_raytracing_ticked, tr("Enable GPU raytracing"))) .on_hover_text(tr("Bakes cast their rays on the graphics card when one is available. Off, they run on the CPU.")); + if gpu_raytracing.changed() { + prefs.gpu_raytracing = gpu_raytracing_ticked; + } }); - if gpu_note_shown(gpu) { + if !gpu_raytracing_enabled { ui.horizontal(|ui| { ui.add_space(12.0); ui.label(RichText::new(tr(GPU_RAYTRACING_UNAVAILABLE)).color(tk.danger)); @@ -413,12 +458,32 @@ fn general( section(ui, n_("PREVIEW OPTIONS")); row(ui, tr("Local cache directory"), |ui, label| { + #[cfg(not(target_arch = "wasm32"))] + { + let default = crate::local_cache_folder("").display().to_string(); + ui.add(egui::TextEdit::singleline(&mut prefs.local_cache_directory).hint_text(default).desired_width(CONTROL_WIDTH - 24.0)).labelled_by(label); + let reset = ui.add(egui::Button::new("R").frame(false)).on_hover_text(tr("Reset to the default folder")); + + // Screen readers hear what the single letter does + let name = format!("R, {}", tr("Reset to the default folder")); + reset.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + if reset.clicked() { + prefs.local_cache_directory.clear(); + } + } + + // The browser has no folders + #[cfg(target_arch = "wasm32")] ui.add_enabled_ui(false, |ui| { let mut path = String::new(); not_available(ui.add(egui::TextEdit::singleline(&mut path).desired_width(CONTROL_WIDTH - 24.0))).labelled_by(label); not_available(ui.add(egui::Button::new("R").frame(false))); }); }); + + #[cfg(not(target_arch = "wasm32"))] + ui.small(tr("The local cache directory is saved for future use.")); + row(ui, tr("Local cache budget (in MB)"), |ui, label| { let mut budget = 4000_u32; ui.spacing_mut().item_spacing.x = 2.0; @@ -431,7 +496,7 @@ fn general( not_available(ui.add_enabled(false, egui::Button::new(text).min_size(vec2(CONTROL_WIDTH, 40.0)))); }); - section(ui, n_("TEMPORARY FILES")); + section(ui, n_("FILES")); row(ui, tr("Cache directory"), |ui, label| { #[cfg(not(target_arch = "wasm32"))] let mut path = std::env::temp_dir().display().to_string(); @@ -442,145 +507,74 @@ fn general( not_available(ui.add(egui::Button::new("R").frame(false))); }); }); + #[cfg(not(target_arch = "wasm32"))] + row(ui, tr("Data folder"), |ui, label| { + // The launcher fixes the Nightly data folder before the app starts + if crate::has_data_root() { + ui.label(RichText::new(crate::data_dir().display().to_string()).small().color(tk.text_dim)) + .labelled_by(label) + .on_hover_text(tr("TextureCraft Nightly keeps its data in its own profile.")); + return; + } + + let default = crate::data_folder("").display().to_string(); + ui.add(egui::TextEdit::singleline(&mut prefs.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)) + .labelled_by(label) + .on_hover_text(tr("Applies on restart.")); + if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() { + *pick = Some(SettingsFolder::DataFolder); + } + }); section(ui, n_("SPARSE VIRTUAL TEXTURE")); disabled_text_check(ui, n_("Hardware support acceleration"), true); - section(ui, n_("IRAY HARDWARE")); - disabled_text_check(ui, gpu.unwrap_or(n_("no GPU")), true); - disabled_text_check(ui, n_("CPU"), false); - - // TextureCraft's own settings, after the reference sections - section(ui, n_("APPEARANCE")); - row(ui, tr("Interface scale"), |ui, label| { - ui.add(egui::Slider::new(&mut p.ui_scale, 0.75..=2.0).fixed_decimals(2)).labelled_by(label); - }); - row(ui, tr("Brightness"), |ui, label| { - egui::ComboBox::from_id_salt("settings_brightness") - .width(140.0) - .selected_text(tr(p.brightness.label())) - .show_ui(ui, |ui| { - for b in Brightness::ALL { - ui.selectable_value(&mut p.brightness, b, tr(b.label())); - } - }) - .response - .labelled_by(label); - }); - row(ui, tr("Accent color"), |ui, _| { - for a in Accent::ALL { - let (rect, resp) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, p.accent == a, tr(a.label()))); - let ring = if p.accent == a { - tk.text_strong - } else if resp.hovered() { - tk.text_dim - } else { - Color32::TRANSPARENT - }; - ui.painter().circle(rect.center(), 6.5, a.colors(tk.dark).0, egui::Stroke::NONE); - ui.painter().circle_stroke(rect.center(), 9.0, egui::Stroke::new(1.5, ring)); - if resp.on_hover_text(tr(a.label())).clicked() { - p.accent = a; - } - } - }); - #[cfg(not(target_arch = "wasm32"))] - { - row(ui, tr("Title bar"), |ui, _| { - ui.checkbox(&mut p.system_title_bar, tr("System title bar (applies on restart)")) - .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); - }); - } - - section(ui, n_("VIEWPORT")); - row(ui, tr("Texture resolution"), |ui, _| { - ui.horizontal(|ui| { - for (v, l) in [(0u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] { - ui.selectable_value(&mut p.viewport_texture, v, l); - } - }) - .response - .on_hover_text(tr( - "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", - )); - }); - section(ui, n_("RESOURCES")); #[cfg(not(target_arch = "wasm32"))] { row(ui, tr("Max CPU threads for work"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.work_threads).range(0..=available_cores)) + let mut threads = work_threads_shown(prefs.work_threads, available_cores); + let slider = ui + .add(egui::Slider::new(&mut threads, 1..=available_cores.max(1)).step_by(1.0)) .labelled_by(label) - .on_hover_text(tr("Threads that paint, bake and export. 0 uses every CPU thread. Applies on restart.")); + .on_hover_text(tr("Threads that paint, bake and export. Applies on restart.")); + if slider.changed() { + prefs.work_threads = work_threads_stored(threads, available_cores); + } + cores_in_total(ui, available_cores); }); row(ui, tr("Cores kept for the UI"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label); + ui.add(egui::Slider::new(&mut prefs.reserved_cores, 0..=available_cores).step_by(1.0)).labelled_by(label); + cores_in_total(ui, available_cores); }); row(ui, tr("Max RAM while saving"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label); - let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); + ui.add(egui::Slider::new(&mut prefs.save_ram_percent, 0..=100).step_by(1.0).suffix(" %")) + .labelled_by(label) + .on_hover_text(tr("0 % uses at least 1 %")); + let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, prefs.save_ram_percent); ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); }); } row(ui, tr("Max project size on open"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.project_open_limit_gib).range(1..=u32::MAX).suffix(" GiB")) + ui.add(egui::DragValue::new(&mut prefs.project_open_limit_gib).range(1..=u32::MAX).suffix(" GiB")) .labelled_by(label) .on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects.")); }); - #[cfg(not(target_arch = "wasm32"))] - { - note(ui, tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")); - } + row(ui, tr("Recent projects limit"), |ui, label| { + ui.add(egui::DragValue::new(&mut prefs.recent_projects_limit).range(0..=MAX_RECENT_PROJECTS)) + .labelled_by(label) + .on_hover_text(tr("Number of recent projects to remember. 0 disables recent-project history.")); + }); #[cfg(not(target_arch = "wasm32"))] { section(ui, n_("AUTOSAVE")); row(ui, tr("Autosave every"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))).labelled_by(label); + ui.add(egui::DragValue::new(&mut prefs.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))).labelled_by(label); }); - note(ui, &trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])); - - section(ui, n_("FOLDERS")); - row(ui, tr("Data folder"), |ui, label| { - // A Nightly install keeps every folder inside its own profile (the Launcher picks it), - // so the Setting would be ignored: show where they are instead of editing it. - if crate::has_data_root() { - ui.label(RichText::new(crate::data_dir().display().to_string()).small().color(tk.text_dim)); - return; - } - let default = crate::data_folder("").display().to_string(); - ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)).labelled_by(label); - if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() { - *pick = Some(SettingsFolder::DataFolder); - } - }); - for (label, dir) in [(tr("Smart materials"), crate::library_dir()), (tr("UI layouts"), crate::user_dir("layouts"))] { - row(ui, label, |ui, _| ui.label(RichText::new(dir.display().to_string()).small().color(tk.text_dim))); - } - note( - ui, - if crate::has_data_root() { - tr("TextureCraft Nightly keeps its autosaves, smart materials, presets, templates and UI layouts in its own profile, beside its settings.") - } else { - tr( - "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.", - ) - }, - ); } } -/// A small dim note under a section's rows. -#[cfg(not(target_arch = "wasm32"))] -fn note(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.add_space(12.0); - ui.add(egui::Label::new(RichText::new(text).small().color(tk.text_dim)).wrap()); - }); -} - /// The built-in library locations as (name, path): the user's assets in the data folder, the /// assets built into TextureCraft, and the font folders text alphas read. pub fn built_in_locations() -> Vec<(String, String)> { @@ -807,6 +801,16 @@ mod tests { assert_eq!(app.next_autosave, 70.0, "an unchanged interval keeps the deadline"); } + #[test] + fn max_cpu_threads_shows_every_thread_at_the_slider_end_and_keeps_it_as_every_thread() { + let cores = 8; + + assert_eq!(work_threads_shown(0, cores), cores, "every thread is the slider's end"); + assert_eq!(work_threads_shown(64, cores), cores, "a larger machine's choice stays inside this one"); + assert_eq!(work_threads_stored(cores, cores), 0, "the end follows any machine's core count"); + assert_eq!(work_threads_stored(work_threads_shown(3, cores), cores), 3); + } + #[test] fn a_folder_answer_cannot_edit_a_reopened_settings_window() { let session = texturecraft_engine::Session::closed().unwrap(); diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index ba00a046..1e7cd39e 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -2,7 +2,7 @@ use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as ic; -use texturecraft_engine::core::project::DisplaySettings; +use texturecraft_engine::core::project::{DisplaySettings, MAX_INDEX_OF_REFRACTION, MIN_INDEX_OF_REFRACTION}; use crate::TextureCraftApp; use crate::i18n::tr; @@ -52,7 +52,7 @@ const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; 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; +const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = MIN_INDEX_OF_REFRACTION..=MAX_INDEX_OF_REFRACTION; /// Values the reference's panel shows for controls TextureCraft lacks const SCATTER_ANISOTROPY_SHOWN: f32 = 0.1; @@ -70,15 +70,19 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { header(ui); let mut display = app.session.doc.project.display.clone(); + let mut ior_specular = display.ior_specular; section_page::show(ui, "shader_settings", &SECTIONS, |ui, index| match index { - 0 => shader_parameters(ui, &mut display), + 0 => shader_parameters(ui, &mut display, &mut ior_specular), _ => displacement(ui, &mut display), }); if display != app.session.doc.project.display { app.session.doc.project.display = display; - app.session.modified = true; - app.session.revision = app.session.revision.wrapping_add(1); + app.session.mark_modified(); + } + + if ior_specular != app.session.doc.project.display.ior_specular { + app.run("display.set", serde_json::json!({"iorSpecular": ior_specular})); } } @@ -139,7 +143,7 @@ pub fn matches_query(name: &str, query: &str) -> bool { } /// Base Surface, Specular, Transmission and Subsurface -fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) { +fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings, ior_specular: &mut bool) { let tokens = Tokens::get(ui.ctx()); section(ui, "shader_base_surface", tr("Base Surface"), true, |ui| { shader_model(ui, display); @@ -148,8 +152,22 @@ fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) { section(ui, "shader_specular", tr("Specular"), true, |ui| { unavailable::checkbox(ui, false, tr("Enable anisotropy")); 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", + "Controls how strongly transmissive surfaces bend light. When the checkbox below is on, it also controls dielectric reflectance.", )); + + ui.add_enabled_ui(!display.spec_gloss, |ui| { + let widgets = &mut ui.visuals_mut().widgets; + widgets.inactive.bg_stroke.color = tokens.text_dim; + widgets.hovered.bg_stroke.color = tokens.text; + widgets.active.bg_stroke.color = tokens.text_strong; + + ui.checkbox(ior_specular, tr("Use IOR for specular reflection")) + .on_hover_text(tr( + "Uses the index of refraction for dielectric reflectance at normal incidence. Specular level adjusts the surface reflection.", + )) + .on_disabled_hover_text(tr("Specular Glossiness uses the Specular color channel for reflectance.")); + }); + unavailable::checkbox(ui, false, tr("Enable specular color")); }); section(ui, "shader_transmission", tr("Transmission"), true, |ui| { diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2fa13ce5..830a10ff 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -108,10 +108,12 @@ impl Asset { } /// The drag-and-drop payload of a shelf tile. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct ShelfDrag { pub asset: Asset, pub label: String, + /// The tile's thumbnail, shown at the pointer while dragging (the name when there is none) + pub thumb: Option, } /// Apply `asset` the way a shelf click does: a simple material becomes the brush's material (no @@ -209,7 +211,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response 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, @@ -217,8 +218,13 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::SmartMask(_) | Asset::SavedMask(_) | Asset::Filter(_) => false, }; 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); + if let Some(drag) = response.dnd_hover_payload::().filter(|drag| accepts(drag)) { + // The 3D view outlines the set under the pointer itself; its background takes nothing + if !onto_set(&drag.asset) { + crate::shelf_drag_ghost::outline_target(ui, response.rect); + } else if set_under_pointer(app, ui, response).is_some() { + crate::shelf_drag_ghost::accept(ui.ctx()); + } } let pointer = ui.input(|input| input.pointer.interact_pos()); @@ -252,7 +258,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response /// The Assets panel body (a dock tab) pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let ctx = ui.ctx().clone(); let filter = app.ui.shelf_filter.to_lowercase(); scan_library(app); let all_entries = ShelfEntry::all(app); @@ -266,6 +271,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; let mut matching: Vec = all_entries.into_iter().filter(|entry| entry.matches(&filter)).collect(); + if app.ui.shelf_favorites_only { + matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); + } + let path_pane_open = app.ui.shelf_panes.filter_by_path; let mut applicable = if path_pane_open { crate::shelf_folders::paths(matching.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))) @@ -280,15 +289,16 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); - // Saved smart materials and masks count toward their tabs even without tiles - let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + // Saved smart materials and masks count toward their tabs even without tiles; they can't be favorites yet + let favorites_only = app.ui.shelf_favorites_only; + let in_user_library = !favorites_only && folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); let saved_materials_matching = saved_matching(app, &filter, false); let saved_masks_matching = saved_matching(app, &filter, true); for (tab, saved) in [(Tab::Smart, saved_materials_matching), (Tab::Masks, saved_masks_matching)] { if in_user_library && let Some(count) = TABS.iter().position(|(shown, _, _)| *shown == tab).and_then(|position| counts.get_mut(position)) { *count += saved; } - if path_pane_open && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) { + if path_pane_open && !favorites_only && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) { applicable.push(vec![crate::shelf_entry::USER.to_string()]); } } @@ -300,11 +310,14 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tab = app.ui.shelf_tab; let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); - let show_user_brushes = crate::shelf_tabs::shows(tab, Tab::Brushes) + let show_user_brushes = !favorites_only + && crate::shelf_tabs::shows(tab, Tab::Brushes) && folder.len() <= 2 && folder.iter().zip([crate::shelf_entry::USER, "Brushes"]).all(|(selected, part)| selected == part); 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()); + // Favorites first, the most recently added first, then by name + let favorites = &app.ui.shelf_favorites; + entries.sort_by_cached_key(|entry| (crate::shelf_favorite::rank(favorites, entry).unwrap_or(usize::MAX), 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(); @@ -317,7 +330,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.set_min_size(vec2(width, grid_rect.height())); crate::shelf_panes::column(app, ui, &paths, &applicable); }); - ui.separator(); + crate::shelf_panes::edge(app, ui, width, grid_rect.width()); } // Saved smart materials are files in the user's library, without folders of their own @@ -326,7 +339,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { grid(app, ui, &entries, grid_rect.height(), [saved_materials, saved_masks], show_user_brushes, &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 user brushes, saved smart materials and saved smart masks when selected @@ -383,18 +395,6 @@ fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -/// The dragged asset's name next to the pointer. -fn drag_preview(ctx: &egui::Context) { - let tk = Tokens::get(ctx); - let (Some(d), Some(pos)) = (egui::DragAndDrop::payload::(ctx), ctx.input(|i| i.pointer.hover_pos())) else { return }; - let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("shelf_drag"))); - let galley = p.layout_no_wrap(d.label.clone(), egui::FontId::proportional(11.0), tk.text_strong); - let rect = egui::Rect::from_min_size(pos + vec2(14.0, 12.0), galley.size() + vec2(12.0, 6.0)); - p.rect_filled(rect, 3.0, tk.row_selected); - p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); -} - pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -493,7 +493,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { let location = path.display().to_string(); let asset = if masks { Asset::SavedMask(location) } else { Asset::Library(location) }; if response.drag_started() { - response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned() }); + response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned(), thumb: None }); } else { selected.push(asset); } @@ -514,7 +514,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {} -/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu +/// The tile of `entry`, outlined when `selected`: a click applies it, a right-click opens its 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 @@ -523,13 +523,15 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry return; } - let texture = entry.thumbnail(app, ctx); + // A picture the user picked replaces the thumbnail, unless its file is gone; it is read only once its tile shows + let thumbnail = entry.thumbnail(app, ctx); + let custom_file = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry); let asset = entry.asset(); let session = &app.session; let response = tile_in_view( ui, &mut app.thumbs, - |_, _| texture, + |ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or(thumbnail), |thumbs| match entry { ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)), _ => entry.preview(session), @@ -548,6 +550,10 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry if entry.includes_randomness() { randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); } + if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { + crate::shelf_favorite::star(ui.painter(), view.thumbnail_rect(response.rect), Tokens::get(ctx).warning); + ctx.accesskit_node_builder(response.id, |node| node.set_description(tr("Favorite"))); + } if response.clicked() || response.secondary_clicked() { let (kind, id) = entry.identity(); @@ -557,18 +563,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry 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(); - } - }); - } + crate::shelf_menu::show(app, &response, entry); } /// Asset tile with optional dragging and a larger hover preview, at the medium size @@ -601,7 +596,7 @@ fn tile_in_view( if let Some(asset) = drag && response.drag_started() { - response.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(), thumb: texture.clone() }); } let painter = ui.painter(); diff --git a/crates/ui-egui/src/shelf_custom_preview.rs b/crates/ui-egui/src/shelf_custom_preview.rs new file mode 100644 index 00000000..6fbe2ca1 --- /dev/null +++ b/crates/ui-egui/src/shelf_custom_preview.rs @@ -0,0 +1,67 @@ +//! A picture the user picked to show on an asset's tile instead of its rendered thumbnail ("Set custom preview..." in the asset menu) + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::shelf_entry::ShelfEntry; + +/// The custom preview's size in pixels: the largest tile's thumbnail on a high-density screen +pub(crate) const CUSTOM_PREVIEW_PX: u32 = 164; + +/// The image file shown on the tile of the asset with [`ShelfEntry::identity`] `kind` and `id` +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfCustomPreview { + pub kind: String, + pub id: String, + pub file: PathBuf, +} + +impl ShelfCustomPreview { + fn is(&self, entry: &ShelfEntry) -> bool { + let (kind, id) = entry.identity(); + self.kind == kind && self.id == id + } +} + +/// The image file `entry` shows instead of its thumbnail, if the user picked one +pub(crate) fn file_for<'a>(previews: &'a [ShelfCustomPreview], entry: &ShelfEntry) -> Option<&'a Path> { + previews.iter().find(|preview| preview.is(entry)).map(|preview| preview.file.as_path()) +} + +/// Shows `file` on the tile of the asset with identity `kind` and `id`, replacing an earlier pick +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn set(previews: &mut Vec, kind: String, id: String, file: PathBuf) { + previews.retain(|preview| preview.kind != kind || preview.id != id); + previews.push(ShelfCustomPreview { kind, id, file }); +} + +/// Shows `entry`'s own thumbnail again +pub(crate) fn remove(previews: &mut Vec, entry: &ShelfEntry) { + previews.retain(|preview| !preview.is(entry)); +} + +/// The largest centred square of `image`, scaled to [`CUSTOM_PREVIEW_PX`] (smaller images keep their size) +pub(crate) fn square(image: &image::DynamicImage) -> image::RgbaImage { + let side = image.width().min(image.height()); + let cropped = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side); + let size = side.min(CUSTOM_PREVIEW_PX); + cropped.resize_exact(size, size, image::imageops::FilterType::Triangle).to_rgba8() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_wide_picture_keeps_its_middle() { + let red = image::Rgba([255, 0, 0, 255]); + let blue = image::Rgba([0, 0, 255, 255]); + let wide = image::RgbaImage::from_fn(6, 2, |x, _| if (2..4).contains(&x) { blue } else { red }); + + let square = square(&image::DynamicImage::ImageRgba8(wide)); + + assert_eq!(square.width(), square.height(), "the preview is square"); + assert!(square.pixels().all(|pixel| *pixel == blue), "only the middle of a wide picture shows"); + } +} diff --git a/crates/ui-egui/src/shelf_drag_ghost.rs b/crates/ui-egui/src/shelf_drag_ghost.rs new file mode 100644 index 00000000..2c11a2a1 --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_ghost.rs @@ -0,0 +1,154 @@ +//! The picture that follows a dragged asset or layer, with a badge saying whether the place under it takes it + +use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, TextureId, Vec2, vec2}; + +use crate::shelf::ShelfDrag; +pub use crate::shelf_drag_ghost_shown::ShelfDragGhostShown; +pub use crate::shelf_drag_verdict::ShelfDragVerdict; +use crate::theme::Tokens; + +/// Side of the dragged asset's thumbnail +const GHOST_SIZE: f32 = 48.0; + +/// The thumbnail's top-left corner from the pointer: just under its tip +const GHOST_OFFSET: Vec2 = vec2(4.0, 4.0); + +/// How opaque the thumbnail is, so the target shows through it +const GHOST_OPACITY: f32 = 0.6; + +/// Corner rounding of the name chip +const CHIP_ROUNDING: f32 = 3.0; + +/// Side of the badge +const BADGE_SIZE: f32 = 9.0; + +/// The badge's centre from the pointer: past the pointer arrow's tail, on the thumbnail's corner +const BADGE_OFFSET: Vec2 = vec2(14.0, 22.0); + +/// Size of the badge's icon +const BADGE_ICON_SIZE: f32 = 7.5; + +/// Corner rounding of the square badge +const BADGE_ROUNDING: f32 = 2.0; + +/// Fill of the square badge and colour of the icon on the red one +const BADGE_LIGHT: Color32 = Color32::from_gray(245); + +/// Colour of the icon on the square badge +const BADGE_DARK: Color32 = Color32::from_gray(35); + +/// Opacity of the thin dark outline that keeps the badge apart from whatever is under it +const BADGE_OUTLINE_ALPHA: u8 = 140; + +/// Padding of the name chip shown when the asset has no thumbnail +const CHIP_PADDING: Vec2 = vec2(6.0, 3.0); + +/// Text size of the name chip +const CHIP_TEXT_SIZE: f32 = 11.0; + +/// Width of the outline around a drop target that takes the dragged asset +const TARGET_OUTLINE_WIDTH: f32 = 2.0; + +/// How far the outline sits inside the target's edge, so a neighbouring panel doesn't cut it +const TARGET_OUTLINE_INSET: f32 = 1.0; + +/// Corner rounding of the outline +const TARGET_OUTLINE_ROUNDING: f32 = 3.0; + +/// Pass number of the last drop target that took the dragged asset (ctx temp data) +const ACCEPTED: &str = "shelf_drag_accepted"; + +/// What the last pass painted (ctx temp data) +const SHOWN: &str = "shelf_drag_shown"; + +/// The name of the layer being dragged in the layer stack, whose payload is only its id (ctx temp data) +const LAYER: &str = "shelf_drag_layer"; + +/// Note that the drop target being drawn takes the dragged asset or layer, where it paints its drop highlight +pub(crate) fn accept(ctx: &Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(Id::unique(ACCEPTED), pass)); +} + +/// Outlines drop target `rect` while the dragged asset hovers it, and notes that it takes the asset +pub(crate) fn outline_target(ui: &egui::Ui, rect: Rect) { + let stroke = Stroke::new(TARGET_OUTLINE_WIDTH, Tokens::get(ui.ctx()).accent); + ui.painter().rect_stroke(rect.shrink(TARGET_OUTLINE_INSET), TARGET_OUTLINE_ROUNDING, stroke, egui::StrokeKind::Inside); + accept(ui.ctx()); +} + +/// Note the name of the layer whose drag starts: a chip with it follows the pointer, since an empty layer's thumbnail shows nothing +pub(crate) fn start_layer(ctx: &Context, label: &str) { + ctx.data_mut(|data| data.insert_temp(Id::unique(LAYER), label.to_owned())); +} + +/// The picture and name of what is being dragged: an asset, or a layer (its name only) +fn dragged(ctx: &Context) -> Option<(Option, String)> { + if let Some(drag) = egui::DragAndDrop::payload::(ctx) { + return Some((drag.thumb.as_ref().map(egui::TextureHandle::id), drag.label.clone())); + } + if !egui::DragAndDrop::has_payload_of_type::(ctx) { + return None; + } + ctx.data(|data| data.get_temp::(Id::unique(LAYER))).map(|label| (None, label)) +} + +/// The ghost painted this pass, if an asset or a layer is being dragged +pub fn shown(ctx: &Context) -> Option { + ctx.data(|data| data.get_temp(Id::unique(SHOWN))) +} + +/// Paint the dragged asset and its badge at the pointer, once a pass after every drop target +pub(crate) fn show(ctx: &Context) { + let (Some((thumb, label)), Some(pointer)) = (dragged(ctx), ctx.input(|input| input.pointer.hover_pos())) else { + ctx.data_mut(|data| data.remove::(Id::unique(SHOWN))); + return; + }; + + let pass = ctx.cumulative_pass_nr(); + let accepted = ctx.data(|data| data.get_temp::(Id::unique(ACCEPTED))) == Some(pass); + let verdict = if accepted { ShelfDragVerdict::Valid } else { ShelfDragVerdict::NotValid }; + let painter = ctx.layer_painter(LayerId::new(Order::Tooltip, Id::unique("shelf_drag_ghost"))); + let tokens = Tokens::get(ctx); + + let ghost = match thumb { + Some(thumb) => { + let rect = Rect::from_min_size(pointer + GHOST_OFFSET, Vec2::splat(GHOST_SIZE)); + let uv = Rect::from_min_max(Pos2::ZERO, egui::pos2(1.0, 1.0)); + painter.image(thumb, rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY)); + rect + } + None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &label), + }; + let badge = badge(&painter, &tokens, pointer + BADGE_OFFSET, verdict); + ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), ShelfDragGhostShown { verdict, ghost, badge })); +} + +/// The name in a chip at `top_left`, for what has no thumbnail (saved smart materials and masks, layers) +fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &str) -> Rect { + let galley = painter.layout_no_wrap(label.to_owned(), egui::FontId::proportional(CHIP_TEXT_SIZE), tokens.text_strong); + let rect = Rect::from_min_size(top_left, galley.size() + CHIP_PADDING * 2.0); + painter.rect_filled(rect, CHIP_ROUNDING, tokens.row_selected); + painter.rect_stroke(rect, CHIP_ROUNDING, Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + painter.galley(rect.min + CHIP_PADDING, galley, tokens.text_strong); + rect +} + +/// The badge at `centre`: a crosshair on a light square where a drop works, else a no-entry sign +fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: ShelfDragVerdict) -> Rect { + let rect = Rect::from_center_size(centre, Vec2::splat(BADGE_SIZE)); + let outline = Stroke::new(1.0, Color32::from_black_alpha(BADGE_OUTLINE_ALPHA)); + let (icon, color) = match verdict { + ShelfDragVerdict::Valid => { + painter.rect(rect, BADGE_ROUNDING, BADGE_LIGHT, outline, egui::StrokeKind::Outside); + (egui_phosphor::regular::CROSSHAIR_SIMPLE, BADGE_DARK) + } + ShelfDragVerdict::NotValid => { + painter.circle(centre, BADGE_SIZE / 2.0, tokens.danger, outline); + (egui_phosphor::regular::PROHIBIT, BADGE_LIGHT) + } + }; + let glyph = painter.layout_no_wrap(icon.to_owned(), egui::FontId::proportional(BADGE_ICON_SIZE), color); + painter.galley(centre - glyph.mesh_bounds.center().to_vec2(), glyph, color); + rect.expand(outline.width) +} diff --git a/crates/ui-egui/src/shelf_drag_ghost_shown.rs b/crates/ui-egui/src/shelf_drag_ghost_shown.rs new file mode 100644 index 00000000..2e961053 --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_ghost_shown.rs @@ -0,0 +1,16 @@ +//! Where the drag ghost and its badge were painted, and what the badge said + +use egui::Rect; + +use crate::shelf_drag_verdict::ShelfDragVerdict; + +/// The ghost as the last pass painted it +#[derive(Clone, Copy, Debug)] +pub struct ShelfDragGhostShown { + /// What the badge says + pub verdict: ShelfDragVerdict, + /// Where the thumbnail (or the name chip) is + pub ghost: Rect, + /// Where the badge is + pub badge: Rect, +} diff --git a/crates/ui-egui/src/shelf_drag_verdict.rs b/crates/ui-egui/src/shelf_drag_verdict.rs new file mode 100644 index 00000000..2af311da --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_verdict.rs @@ -0,0 +1,10 @@ +//! What the drag badge says about the place under the pointer + +/// Whether the place under the pointer takes the dragged asset +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShelfDragVerdict { + /// A drop here does something: a crosshair on a light square + Valid, + /// A drop here does nothing: a no-entry sign on red + NotValid, +} diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 66774efc..32669e7f 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -13,7 +13,7 @@ use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask}; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{n_, tr}; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; @@ -124,6 +124,21 @@ impl ShelfEntry { path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have) } + /// What the asset is used as, lowercase (English, shown through `tr`): the menu's Usages row + pub(crate) fn usage(&self) -> &'static str { + match self { + ShelfEntry::Material(material) if material.smart => n_("smart material"), + ShelfEntry::Material(_) => n_("material"), + ShelfEntry::SmartMask(_) => n_("smart mask"), + ShelfEntry::Filter(_) => n_("filter"), + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush { .. } => n_("brush"), + ShelfEntry::Alpha(_) => n_("alpha"), + ShelfEntry::Procedural(_) => n_("procedural"), + ShelfEntry::Environment(_) => n_("environment"), + ShelfEntry::Image(_) => n_("texture"), + } + } + /// The name under the tile, translated where the asset's name is pub(crate) fn label(&self) -> &str { match self { diff --git a/crates/ui-egui/src/shelf_favorite.rs b/crates/ui-egui/src/shelf_favorite.rs new file mode 100644 index 00000000..c3ef0674 --- /dev/null +++ b/crates/ui-egui/src/shelf_favorite.rs @@ -0,0 +1,78 @@ +//! An asset the user marked as a favorite in the Assets panel: it shows a star and comes first in its type + +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, epaint::Mesh, vec2}; +use serde::{Deserialize, Serialize}; + +use crate::shelf_entry::ShelfEntry; + +/// The star's outer and inner radius and its centre's inset from the thumbnail's top-right corner, in points +const STAR_OUTER_RADIUS: f32 = 5.5; +const STAR_INNER_RADIUS: f32 = 2.4; +const STAR_INSET: f32 = 4.0; +/// The offset and colour of the star's shadow, which keeps it readable on light thumbnails +const STAR_SHADOW_OFFSET: f32 = 1.0; +const STAR_SHADOW: Color32 = Color32::from_black_alpha(170); +const STAR_POINTS: usize = 5; +/// The width of the outline that smooths the star's edges (a mesh has no anti-aliasing), in points +const STAR_EDGE_WIDTH: f32 = 0.6; + +/// A favorite asset by its [`ShelfEntry::identity`] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfFavorite { + pub kind: String, + pub id: String, +} + +impl ShelfFavorite { + fn is(&self, entry: &ShelfEntry) -> bool { + let (kind, id) = entry.identity(); + self.kind == kind && self.id == id + } +} + +/// Where `entry` is in `favorites` (most recently added first), or None if it isn't one +pub(crate) fn rank(favorites: &[ShelfFavorite], entry: &ShelfEntry) -> Option { + favorites.iter().position(|favorite| favorite.is(entry)) +} + +/// Adds `entry` in front of `favorites`, or removes it if it is one +pub(crate) fn toggle(favorites: &mut Vec, entry: &ShelfEntry) { + if let Some(index) = rank(favorites, entry) { + favorites.remove(index); + return; + } + + let (kind, id) = entry.identity(); + favorites.insert(0, ShelfFavorite { kind: kind.to_owned(), id: id.to_owned() }); +} + +/// A filled star in `color` at the thumbnail's top-right corner, over a dark shadow +pub(crate) fn star(painter: &Painter, thumbnail: Rect, color: Color32) { + let center = thumbnail.right_top() + vec2(-STAR_INSET, STAR_INSET); + star_shape(painter, center + vec2(STAR_SHADOW_OFFSET, STAR_SHADOW_OFFSET), STAR_SHADOW); + star_shape(painter, center, color); +} + +/// A five-pointed star around `center`, point up: a triangle fan from the centre, outlined in its colour +fn star_shape(painter: &Painter, center: Pos2, color: Color32) { + let corner_count = STAR_POINTS * 2; + let corners: Vec = (0..corner_count) + .map(|corner| { + let radius = if corner % 2 == 0 { STAR_OUTER_RADIUS } else { STAR_INNER_RADIUS }; + let angle = corner as f32 * std::f32::consts::TAU / corner_count as f32 - std::f32::consts::FRAC_PI_2; + center + radius * vec2(angle.cos(), angle.sin()) + }) + .collect(); + + let mut mesh = Mesh::default(); + mesh.colored_vertex(center, color); + for corner in &corners { + mesh.colored_vertex(*corner, color); + } + let last = corner_count as u32; + for corner in 1..=last { + mesh.add_triangle(0, corner, corner % last + 1); + } + painter.add(Shape::mesh(mesh)); + painter.add(Shape::closed_line(corners, Stroke::new(STAR_EDGE_WIDTH, color))); +} diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs new file mode 100644 index 00000000..e098ef5f --- /dev/null +++ b/crates/ui-egui/src/shelf_menu.rs @@ -0,0 +1,477 @@ +//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it; the Name of an asset the user owns is a field that renames it + +use egui::{Align2, Color32, CornerRadius, FontId, Id, Response, Sense, Ui, pos2, vec2}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::{n_, tr}; +use crate::shelf_entry::{LIBRARIES, ShelfEntry}; +use crate::theme::Tokens; + +/// A menu row's height and the inset of its hover face from the menu's sides, in points +const ROW_HEIGHT: f32 = 24.0; +const HOVER_INSET: f32 = 3.0; +const HOVER_ROUNDING: u8 = 3; +/// Where a row's text starts, from the menu's left edge, in points +const TEXT_X: f32 = 10.0; +/// The space after the text of the widest row, in points +const RIGHT_PADDING: f32 = 24.0; +/// The air between the info block's label column and its values, in points +const LABEL_GAP: f32 = 12.0; +/// The widest the info block's values get before the path is cut in the middle, in points +const MAX_VALUE_WIDTH: f32 = 220.0; +/// The menu's text size, in points +const TEXT_SIZE: f32 = 12.0; +/// The Name field's row and field heights, and the air before its text, in points +const FIELD_ROW_HEIGHT: f32 = 28.0; +const FIELD_HEIGHT: f32 = 24.0; +const FIELD_TEXT_INSET: f32 = 8.0; +/// The air above and below the separators, in points +const SEPARATOR_SPACE: f32 = 3.0; + +/// The category's place in an asset's path: after the library and the type's folder +const CATEGORY_PART: usize = 2; + +/// A menu just opened from the keyboard gives the focus to its first row that can be picked (ctx temp data) +const FOCUS_FIRST_ROW: &str = "shelf_menu_focus_first_row"; + +/// The right-click menu on the tile whose response is `response` +pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { + // Clicks inside keep the menu open, so the Name field can be typed in; its rows close it themselves + let mut menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + response.ctx.accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu)); + + // The keyboard opens it on the focused tile, and Escape gives the focus back to the tile + let keyboard_id = response.id.with("menu_from_keyboard"); + let return_focus = menu.is_open() && response.ctx.input(|input| input.key_pressed(egui::Key::Escape)); + if response.has_focus() + && response + .ctx + .input_mut(|input| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu)) + { + menu = menu.open_memory(Some(egui::SetOpenCommand::Bool(true))); + response.ctx.data_mut(|data| { + data.insert_temp(keyboard_id, true); + data.insert_temp(Id::unique(FOCUS_FIRST_ROW), true); + }); + } else if response.secondary_clicked() { + response.ctx.data_mut(|data| data.remove::(keyboard_id)); + } + + // A menu opened from the keyboard has no pointer position to open at: it opens at the tile + if response.ctx.data(|data| data.get_temp::(keyboard_id)).unwrap_or_default() { + menu = menu.anchor(response); + } + menu.show(|ui| { + let tokens = Tokens::get(ui.ctx()); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let info = info_rows(entry); + let width = menu_width(ui, &info, &row_labels(entry)); + ui.set_width(width); + let column = label_column(ui, &info); + + // A saved brush or a project image is the user's own: its Name row is a field that renames it + let mut shown_info = info.as_slice(); + let rename = match entry { + ShelfEntry::SavedBrush { name, .. } => Some((name.as_str(), "brush.preset.rename")), + ShelfEntry::Image(name) => Some((name.as_str(), "resource.rename")), + _ => None, + }; + if let Some((name, command)) = rename + && let Some((_, rest)) = info.split_first() + { + shown_info = rest; + let field_id = ui.make_persistent_id(("asset_name", entry.identity())); + if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) + && let Some(result) = app.run(command, json!({"name": name, "to": renamed})) + && let Some(new_name) = result["name"].as_str() + { + // The rows below would act on the old name: the menu draws again under the new one next frame + keep_star_and_preview(app, entry, new_name); + return; + } + } + info_block(ui, width, column, shown_info, &tokens); + separator(ui, &tokens); + + match entry { + ShelfEntry::Image(name) => { + let reloadable = app.session.doc.project.resource_sources.contains_key(name); + let reload = row(ui, width, tr("Reload"), reloadable, &tokens); + if reload.clicked() { + crate::shelf_updates::update_from_files(app, Some(vec![name.clone()])); + ui.close(); + } + if !reloadable { + reload.on_hover_text(tr("Not imported from a file: no file to reload from")); + } + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_image(app, name); + ui.close(); + } + } + ShelfEntry::SavedBrush { name, .. } => { + if row(ui, width, tr("Replace with the current brush"), true, &tokens).clicked() { + app.run("brush.preset.store", json!({"name": name, "overwrite": true})); + ui.close(); + } + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("brush.preset.delete", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_brush(app, name); + ui.close(); + } + } + _ => { + row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); + } + } + custom_preview_rows(app, ui, width, entry, &tokens); + show_in(app, ui, width, entry, &tokens); + if row(ui, width, favorite_label(app, entry), true, &tokens).clicked() { + crate::shelf_favorite::toggle(&mut app.ui.shelf_favorites, entry); + ui.close(); + } + if let ShelfEntry::Image(name) = entry { + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } + } + + separator(ui, &tokens); + if row(ui, width, tr("Close"), true, &tokens).clicked() { + ui.close(); + } + }); + if return_focus { + response.request_focus(); + } +} + +/// Moves the favorite star and custom preview of `entry`, just renamed to `new_name`, to its new identity +fn keep_star_and_preview(app: &mut TextureCraftApp, entry: &ShelfEntry, new_name: &str) { + let (kind, old_id) = entry.identity(); + let new_id = match entry { + ShelfEntry::SavedBrush { .. } => app + .session + .brush_presets + .list + .iter() + .find(|preset| preset.name == new_name) + .map(|preset| preset.file.as_ref().and_then(|file| file.to_str()).unwrap_or(&preset.name).to_owned()), + _ => Some(new_name.to_owned()), + }; + let Some(new_id) = new_id else { return }; + + let ui = &mut app.ui; + let favorites = ui.shelf_favorites.iter_mut().map(|favorite| (&favorite.kind, &mut favorite.id)); + let previews = ui.shelf_custom_previews.iter_mut().map(|preview| (&preview.kind, &mut preview.id)); + for (_, id) in favorites.chain(previews).filter(|(stored_kind, id)| *stored_kind == kind && *id == old_id) { + id.clone_from(&new_id); + } +} + +/// The info block's label and value rows: rows only where the asset has the data +fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { + let path = entry.path(); + let shown_path: Vec<&str> = path.iter().map(|part| LIBRARIES.iter().find(|(id, _)| id == part).map_or_else(|| tr(part), |(_, name)| tr(name))).collect(); + let mut rows = + vec![(tr("Name"), entry.label().to_string()), (tr("Usages"), tr(entry.usage()).to_string()), (tr("Path"), format!("/{}/", shown_path.join("/")))]; + if let Some(category) = path.get(CATEGORY_PART) { + rows.push((tr("Category"), tr(category).to_string())); + } + rows +} + +/// The labels of the rows under the info block, for the menu's width +fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { + let mut labels = vec![ + tr("Export resource..."), + tr("Set custom preview..."), + tr("Remove custom preview"), + tr("Show in"), + tr("Add to favorites"), + tr("Remove from favorites"), + tr("Close"), + ]; + match entry { + ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), + ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), + _ => {} + } + labels +} + +/// Set custom preview... picks a picture to show on the tile; Remove custom preview, once one is set, shows the asset's own thumbnail again +fn custom_preview_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) { + if row(ui, width, tr("Set custom preview..."), true, tokens).clicked() { + pick_custom_preview(app, entry); + ui.close(); + } + if crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).is_some() + && row(ui, width, tr("Remove custom preview"), true, tokens).clicked() + { + crate::shelf_custom_preview::remove(&mut app.ui.shelf_custom_previews, entry); + ui.close(); + } +} + +/// Asks for a picture, then shows it on `entry`'s tile +#[cfg(not(target_arch = "wasm32"))] +fn pick_custom_preview(app: &mut TextureCraftApp, entry: &ShelfEntry) { + use crate::file_dialogs::{Bound, FileDialog}; + + let (kind, id) = entry.identity(); + let (kind, id) = (kind.to_owned(), id.to_owned()); + let dialog = FileDialog::open().filter(tr("Images"), crate::web_files::IMAGE_EXTS); + app.ask_file(dialog, Bound::App, move |app, paths| { + let Some(file) = paths.into_iter().next() else { return }; + if image::image_dimensions(&file).is_err() { + app.toast(crate::i18n::trf("Could not read {file} as a picture", &[("file", &file.display())]), true); + return; + } + + app.thumbs.forget_custom_preview(&file); + crate::shelf_custom_preview::set(&mut app.ui.shelf_custom_previews, kind, id, file); + }); +} + +#[cfg(target_arch = "wasm32")] +fn pick_custom_preview(app: &mut TextureCraftApp, _: &ShelfEntry) { + app.toast(tr("Custom previews need the desktop app"), true); +} + +/// The row that adds the asset to the favorites, or takes a favorite out +fn favorite_label(app: &TextureCraftApp, entry: &ShelfEntry) -> &'static str { + if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { tr("Remove from favorites") } else { tr("Add to favorites") } +} + +fn text_width(ui: &Ui, text: &str) -> f32 { + ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x) +} + +/// The label column's width: the longest label and its gap +fn label_column(ui: &Ui, info: &[(&str, String)]) -> f32 { + info.iter().map(|(label, _)| text_width(ui, label)).fold(0.0, f32::max) + LABEL_GAP +} + +/// The widest row, the info block's values capped at [`MAX_VALUE_WIDTH`] +fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 { + let widest_value = info.iter().map(|(_, value)| text_width(ui, value)).fold(0.0, f32::max).min(MAX_VALUE_WIDTH); + let widest_row = labels.iter().map(|label| text_width(ui, label)).fold(0.0, f32::max); + TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING +} + +/// The label (dim) and value rows, values `column` points after the labels; a value too wide is cut in the middle with "…" +fn info_block(ui: &mut Ui, width: f32, column: f32, info: &[(&str, String)], tokens: &Tokens) { + let value_width = width - TEXT_X - column - RIGHT_PADDING; + for (label, value) in info { + let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); + let shown = cut_middle(ui, value, value_width); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label} {value}"))); + let painter = ui.painter(); + painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, *label, FontId::proportional(TEXT_SIZE), tokens.text_dim); + painter.text(pos2(rect.left() + TEXT_X + column, rect.center().y), Align2::LEFT_CENTER, shown, FontId::proportional(TEXT_SIZE), tokens.text); + } +} + +/// The Name row of an asset the user owns: a field in the value column that returns the new name once typing ends (Enter or a click elsewhere) with a changed, non-blank name. Escape keeps the old one +fn name_field(ui: &mut Ui, width: f32, column: f32, field_id: egui::Id, name: &str, tokens: &Tokens) -> Option { + let (rect, _) = ui.allocate_exact_size(vec2(width, FIELD_ROW_HEIGHT), Sense::hover()); + let label = tr("Name"); + ui.painter().text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text_dim); + + // Check raw Escape even if the menu consumed it + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if escaped { + ui.data_mut(|data| data.remove::(field_id)); + } + let mut text = ui.data(|data| data.get_temp::(field_id)).unwrap_or_else(|| name.to_owned()); + + // The field's text lines up with the values below it + let field = egui::Rect::from_min_max( + pos2(rect.left() + TEXT_X + column - FIELD_TEXT_INSET, rect.center().y - FIELD_HEIGHT / 2.0), + pos2(rect.right() - TEXT_X, rect.center().y + FIELD_HEIGHT / 2.0), + ); + ui.painter().rect(field, CornerRadius::same(HOVER_ROUNDING), tokens.field, egui::Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let edit = egui::TextEdit::singleline(&mut text) + .id(field_id) + .font(FontId::proportional(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET as i8, 0))) + .align(Align2::LEFT_CENTER); + let response = ui.new_child(egui::UiBuilder::new().max_rect(field.shrink(1.0))).add_sized(field.shrink(1.0).size(), edit); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, label)); + + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(field_id, text)); + return None; + } + + ui.data_mut(|data| data.remove::(field_id)); + let typed = text.trim(); + (response.lost_focus() && !escaped && !typed.is_empty() && typed != name).then(|| typed.to_owned()) +} + +/// `text`, or its start and end around "…" so it fits `width` points +fn cut_middle(ui: &Ui, text: &str, width: f32) -> String { + if text_width(ui, text) <= width { + return text.to_owned(); + } + + let chars: Vec = text.chars().collect(); + let mut kept = chars.len(); + loop { + let head = kept.div_ceil(2); + let tail = kept / 2; + let cut: String = chars[..head].iter().chain(['…'].iter()).chain(chars[chars.len() - tail..].iter()).collect(); + if kept == 0 || text_width(ui, &cut) <= width { + return cut; + } + + kept -= 1; + } +} + +/// A hairline across the menu between groups of rows +fn separator(ui: &mut Ui, tokens: &Tokens) { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), SEPARATOR_SPACE * 2.0 + 1.0), Sense::hover()); + ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, tokens.separator)); +} + +/// The file manager's own name for showing a file in it +fn show_in_folder_label() -> &'static str { + if cfg!(target_os = "windows") { + tr("Show in Explorer...") + } else if cfg!(target_os = "macos") { + tr("Show in Finder...") + } else { + tr("Show in file manager...") + } +} + +/// The Show in row: a submenu that opens the folder of the asset's file, greyed for an asset with no file on this computer +fn show_in(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) { + let file = match entry { + ShelfEntry::SavedBrush { name, .. } => app.session.brush_presets.file_for(name), + ShelfEntry::Image(name) => app.session.doc.project.resource_sources.get(name).map(|source| std::path::PathBuf::from(&source.path)), + _ => None, + }; + let folder = file.as_deref().and_then(std::path::Path::parent).filter(|folder| folder.is_dir()).map(std::path::Path::to_path_buf); + + // Reserved under the row, so the row stays highlighted while its submenu is open + let open_highlight = ui.painter().add(egui::Shape::Noop); + let response = row(ui, width, tr("Show in"), folder.is_some(), tokens); + let caret_color = if folder.is_some() { tokens.text } else { tokens.text_dim }; + ui.painter().text( + pos2(response.rect.right() - TEXT_X, response.rect.center().y), + Align2::RIGHT_CENTER, + egui_phosphor::regular::CARET_RIGHT, + FontId::proportional(TEXT_SIZE), + caret_color, + ); + let Some(folder) = folder else { + let reason = match (file.is_some(), entry) { + (true, _) => n_("The folder of this asset's file is gone"), + (false, ShelfEntry::Image(_)) => n_("Imported before this session: no file to show"), + (false, ShelfEntry::SavedBrush { .. }) => n_("This brush isn't saved to a file"), + (false, _) => n_("Built-in assets have no file to show"), + }; + + response.on_hover_text(tr(reason)); + return; + }; + + let submenu = egui::containers::menu::SubMenu::new().show(ui, &response, |ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let label = show_in_folder_label(); + let submenu_width = text_width(ui, label) + TEXT_X + RIGHT_PADDING; + if row(ui, submenu_width, label, true, tokens).clicked() { + open_folder(app, &folder); + ui.close(); + } + }); + if submenu.is_some() { + let highlight = egui::Shape::rect_filled(response.rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); + ui.painter().set(open_highlight, highlight); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn open_folder(app: &mut TextureCraftApp, folder: &std::path::Path) { + if let Err(error) = app.file_dialogs.show_folder(folder) { + app.toast(crate::i18n::trf("Could not open the folder: {error}", &[("error", &error)]), true); + } +} + +#[cfg(target_arch = "wasm32")] +fn open_folder(app: &mut TextureCraftApp, _: &std::path::Path) { + app.toast(tr("Showing files needs the desktop app"), true); +} + +/// One menu row: a hover face inset from the sides, its text dim and unclickable when not `enabled` +fn row(ui: &mut Ui, width: f32, label: &str, enabled: bool, tokens: &Tokens) -> Response { + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); + if enabled && ui.data_mut(|data| data.remove_temp::(Id::unique(FOCUS_FIRST_ROW))).unwrap_or_default() { + response.request_focus(); + } + let painter = ui.painter(); + if enabled && (response.hovered() || response.has_focus()) { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); + } + let color = if enabled { tokens.text } else { tokens.text_dim }; + painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color); + if enabled { response } else { response.on_hover_cursor(egui::CursorIcon::NotAllowed) } +} + +/// Asks where to save image resource `name`, then writes it there as imported +#[cfg(not(target_arch = "wasm32"))] +fn export_image(app: &mut TextureCraftApp, name: &str) { + use crate::file_dialogs::{Bound, FileDialog}; + + let extension = std::path::Path::new(name).extension().and_then(|extension| extension.to_str()).unwrap_or_default().to_owned(); + let name = name.to_owned(); + let dialog = FileDialog::save().filter(tr("Image"), &[extension.as_str()]).file_name(&name); + app.ask_file(dialog, Bound::Project, move |app, paths| { + if let Some(path) = paths.first() { + app.run("resource.export", json!({"name": name, "path": path.to_string_lossy()})); + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn export_image(app: &mut TextureCraftApp, _: &str) { + app.toast(tr("Exporting resources needs the desktop app"), true); +} + +/// Asks where to save saved brush `name`, then writes it there as a brush preset file +#[cfg(not(target_arch = "wasm32"))] +fn export_brush(app: &mut TextureCraftApp, name: &str) { + use crate::file_dialogs::{Bound, FileDialog}; + use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + + let name = name.to_owned(); + let dialog = FileDialog::save().filter(tr("Brush preset"), &[BRUSH_EXT]).file_name(format!("{name}.{BRUSH_EXT}")); + app.ask_file(dialog, Bound::App, move |app, paths| { + if let Some(path) = paths.first() { + app.run("brush.preset.export", json!({"name": name, "path": path.to_string_lossy()})); + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn export_brush(app: &mut TextureCraftApp, _: &str) { + app.toast(tr("Exporting resources needs the desktop app"), true); +} diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index 42b8494e..0455ecd5 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -15,12 +15,17 @@ use crate::theme::Tokens; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; -const COLUMN_FRACTION: f32 = 0.45; const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0; +/// Width of the draggable edge between the panes and the grid +const EDGE_WIDTH_POINTS: f32 = 6.0; +/// The grid keeps at least this much width when the edge is dragged right +const GRID_MIN_WIDTH_POINTS: f32 = 80.0; const SPLITTER_HEIGHT_POINTS: f32 = 6.0; const PANE_MIN_HEIGHT_POINTS: f32 = 40.0; -/// The reference's built-in saved searches after "All", shown greyed until they work -const BUILT_IN_SEARCHES: [&str; 3] = [n_("Favorites"), n_("3D Assets"), n_("Flattened layers")]; +/// The built-in saved search after "All" that shows only the favorite assets +const FAVORITES: &str = n_("Favorites"); +/// The reference's other built-in saved searches, shown greyed until they work +const UNAVAILABLE_SEARCHES: [&str; 2] = [n_("3D Assets"), n_("Flattened layers")]; /// The reference's font libraries after the asset libraries, shown greyed until they work const FONT_LIBRARIES: [&str; 2] = [n_("System fonts"), n_("User fonts")]; /// The pane header's caption size in points @@ -49,7 +54,29 @@ pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { /// 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_POINTS).min(width)) + let share = app.ui.shelf_panes_share; + (panes.saved_searches || panes.filter_by_path) + .then(|| (width * share).min(width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS).min(width)) +} + +/// The draggable edge between the panes' column (`column` wide) and the grid in a panel `width` wide +pub(crate) fn edge(app: &mut TextureCraftApp, ui: &mut Ui, column: f32, width: f32) { + let (rect, _) = ui.allocate_exact_size(egui::vec2(EDGE_WIDTH_POINTS, ui.available_height()), egui::Sense::hover()); + let visuals = ui.visuals(); + let line_stroke = visuals.widgets.noninteractive.bg_stroke; + let widest = (width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS); + if width > 0.0 && widest > COLUMN_MIN_WIDTH_POINTS { + let colors = + ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill }; + let delta = ResizeHandle::new(ui.scope_id().with("shelf_panes_edge"), Axis::X, rect, tr("Resize Assets filter panes and grid"), colors) + .hit_margin(0.0) + .value(column.clamp(COLUMN_MIN_WIDTH_POINTS, widest), COLUMN_MIN_WIDTH_POINTS..=widest) + .show(ui); + if delta != 0.0 { + app.ui.shelf_panes_share = (column + delta).clamp(COLUMN_MIN_WIDTH_POINTS, widest) / width; + } + } + ui.painter().vline(rect.center().x, rect.y_range(), line_stroke); } /// Draws the open panes and a divider when both are visible. @@ -193,7 +220,12 @@ fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { }); } -/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one +/// Saved searches' first rows: "All", then Favorites, then the searches that aren't available +const ALL_ROW: usize = 0; +const FAVORITES_ROW: usize = 1; +const FIXED_SEARCH_ROWS: usize = 2; + +/// "All", Favorites, 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; header(ui, tr("Saved searches"), |ui| { @@ -205,8 +237,9 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - let all_selected = app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE; - let first_saved_row = 1 + BUILT_IN_SEARCHES.len(); + let favorites_only = app.ui.shelf_favorites_only; + let all_selected = !favorites_only && app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE; + let first_saved_row = FIXED_SEARCH_ROWS + UNAVAILABLE_SEARCHES.len(); let row_height = ui.spacing().interact_size.y; let total_rows = first_saved_row + app.ui.shelf_saved_searches.len(); let mut deleted_index = None; @@ -218,14 +251,22 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { total_rows, |ui, visible_rows| { for row in visible_rows { - if row == 0 { + if row == ALL_ROW { if ui.selectable_label(all_selected, tr("All")).clicked() { crate::shelf_toolbar::reset_query(app); } continue; } - if let Some(name) = BUILT_IN_SEARCHES.get(row - 1) { + if row == FAVORITES_ROW { + if ui.selectable_label(favorites_only, tr(FAVORITES)).clicked() { + crate::shelf_toolbar::reset_query(app); + app.ui.shelf_favorites_only = true; + } + continue; + } + + if let Some(name) = UNAVAILABLE_SEARCHES.get(row - FIXED_SEARCH_ROWS) { ui.add_enabled(false, egui::Button::selectable(false, tr(name))).on_disabled_hover_text(tr(NOT_AVAILABLE)); continue; } @@ -233,10 +274,14 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { let saved_index = row - first_saved_row; let Some(saved) = app.ui.shelf_saved_searches.get(saved_index) else { continue }; - let selected = saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path; + let selected = saved.favorites_only == favorites_only + && saved.filter == app.ui.shelf_filter + && saved.tab == app.ui.shelf_tab + && saved.path == app.ui.shelf_path; let response = ui.selectable_label(selected, &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()); + app.ui.shelf_favorites_only = saved.favorites_only; } response.context_menu(|ui| { @@ -254,18 +299,21 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// The shelf's query, named after its search text, else its folder, else its tab +/// The shelf's query, named after its search text, else its folder, else Favorites, else its tab fn current_query(app: &TextureCraftApp) -> SavedSearch { let filter = &app.ui.shelf_filter; let tab = app.ui.shelf_tab; let path = &app.ui.shelf_path; + let favorites_only = app.ui.shelf_favorites_only; let name = if !filter.is_empty() { filter.as_str() } else if let Some(folder) = path.last() { crate::shelf_folders::name(path.len() - 1, folder) + } else if favorites_only { + tr(FAVORITES) } else { TABS.get(tab).map_or_else(|| tr("All"), |(_, _, label)| tr(label)) }; - SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone() } + SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone(), favorites_only } } diff --git a/crates/ui-egui/src/shelf_query.rs b/crates/ui-egui/src/shelf_query.rs new file mode 100644 index 00000000..9e9d4b67 --- /dev/null +++ b/crates/ui-egui/src/shelf_query.rs @@ -0,0 +1,24 @@ +//! One Assets panel's query: search, type, folder and favorites only + +use serde::{Deserialize, Serialize}; + +/// One Assets panel's search, type and folder, and whether it shows only favorites +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ShelfQuery { + /// The search text + pub filter: String, + /// The picked type: an index into the shelf's types, or past them for every type + pub tab: usize, + /// The library folder: a library id, then folder names (empty: all libraries) + pub path: Vec, + /// Only favorites (the Favorites saved search) + pub favorites_only: bool, +} + +impl Default for ShelfQuery { + /// Every asset of every type + fn default() -> Self { + Self { filter: String::new(), tab: crate::shelf_tabs::NO_TYPE, path: Vec::new(), favorites_only: false } + } +} diff --git a/crates/ui-egui/src/shelf_second.rs b/crates/ui-egui/src/shelf_second.rs new file mode 100644 index 00000000..4c129816 --- /dev/null +++ b/crates/ui-egui/src/shelf_second.rs @@ -0,0 +1,23 @@ +//! The second Assets panel, opened by the folder button: the same panel with its own query + +use egui::Ui; + +use crate::TextureCraftApp; +use crate::shelf_query::ShelfQuery; + +/// Swap `query` with the first Assets panel's query in `ui` +fn swap_query(ui: &mut crate::state::UiState, query: &mut ShelfQuery) { + std::mem::swap(&mut ui.shelf_filter, &mut query.filter); + std::mem::swap(&mut ui.shelf_tab, &mut query.tab); + std::mem::swap(&mut ui.shelf_path, &mut query.path); + std::mem::swap(&mut ui.shelf_favorites_only, &mut query.favorites_only); +} + +/// The second Assets panel's body: the Assets panel drawn with its own query +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let mut query = std::mem::take(&mut app.ui.shelf_second); + swap_query(&mut app.ui, &mut query); + ui.push_id("assets_second", |ui| crate::shelf::body(app, ui)); + swap_query(&mut app.ui, &mut query); + app.ui.shelf_second = query; +} diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index a8708685..c61d37bc 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -1,4 +1,4 @@ -//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query, new panel and import on the right use egui::Ui; use egui_phosphor::regular as ic; @@ -18,6 +18,7 @@ pub(crate) fn height(ui: &Ui) -> f32 { /// The toolbar pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let size = ui.spacing().interact_size.y; + let panel = ui.max_rect(); ui.add_space(GAP_ABOVE); ui.horizontal(|ui| { crate::shelf_panes::toggles(app, ui, size); @@ -25,12 +26,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut 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::FOLDER, tr("New Assets panel"), false, size).clicked() { + app.ui.dock.focus(crate::docking::Panel::AssetsSecond); + } 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); - } + crate::shelf_updates::button(app, ui, size, panel); }); }); } @@ -40,16 +42,5 @@ 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; - - #[cfg(not(target_arch = "wasm32"))] - for warning in app.session.load_brush_presets(crate::user_dir("brushes")) { - app.toast(warning, true); - } - - app.thumbs.forget_saved_files(); + app.ui.shelf_favorites_only = false; } diff --git a/crates/ui-egui/src/shelf_updates.rs b/crates/ui-egui/src/shelf_updates.rs new file mode 100644 index 00000000..5a53fd27 --- /dev/null +++ b/crates/ui-egui/src/shelf_updates.rs @@ -0,0 +1,231 @@ +//! The shelf's refresh popup: read the Assets panel and the project's images again every few minutes, or now by hand + +use egui::{Context, Id, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::{n_, tr}; +use crate::property_sheet::{NumberField, PropertySheet, SIDE_PADDING_POINTS, SectionScope, in_scope}; +use crate::widgets::icon_dropdown_button; + +/// Least and most minutes between automatic updates +const MIN_MINUTES: u32 = 1; +const MAX_MINUTES: u32 = 24 * 60; + +/// Air between the popup and the toolbar under it +const POPUP_GAP: f32 = 1.0; + +/// Air between the two update buttons and under the last one +const BUTTON_GAP: f32 = 6.0; + +/// Room right of a row's switch for its i +const INFO_COLUMN: f32 = 28.0; + +/// How soon a run that waited for a stroke tries again +const STROKE_RETRY: std::time::Duration = std::time::Duration::from_millis(250); + +/// A drag of 20 points moves the minutes by one +const MINUTES_PER_DRAG_POINT: f32 = 0.05; + +/// How much shorter a manual update button is than a sheet row, so neighbouring buttons don't touch +const BUTTON_INSET: f32 = 4.0; + +const SKIP_MISMATCH: &str = n_("Skip assets when their parameters mismatch"); + +/// Which automatic updates are on and how often they run +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ShelfUpdates { + /// Read the user's saved assets again + pub assets: bool, + /// Read the project's images again from the files they were imported from when a file changed + pub resources: bool, + pub minutes: u32, +} + +impl Default for ShelfUpdates { + fn default() -> Self { + ShelfUpdates { assets: false, resources: false, minutes: MIN_MINUTES } + } +} + +/// When the automatic updates last ran, on egui's clock +fn last_run_id() -> Id { + Id::unique("shelf_updates_last_run") +} + +/// Runs the automatic updates once their minutes have passed since the last run, and wakes the app for the next one +pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) { + let updates = app.ui.shelf_updates; + if !updates.assets && !updates.resources { + ctx.data_mut(|data| data.remove::(last_run_id())); + return; + } + + // An update during a stroke would land in the stroke's undo step: it waits for the stroke to end + if app.session.stroke_active() { + ctx.request_repaint_after(STROKE_RETRY); + return; + } + + let now = ctx.input(|input| input.time); + let every = f64::from(updates.minutes.clamp(MIN_MINUTES, MAX_MINUTES)) * 60.0; + let last = ctx.data_mut(|data| *data.get_temp_mut_or(last_run_id(), now)); + if now - last < every { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(every - (now - last))); + return; + } + + ctx.data_mut(|data| data.insert_temp(last_run_id(), now)); + if updates.assets { + refresh_assets(app); + } + if updates.resources { + update_resources(app, ctx); + } + ctx.request_repaint_after(std::time::Duration::from_secs_f64(every)); +} + +/// Read the user's saved assets from disk again and redraw their thumbnails +pub(crate) fn refresh_assets(app: &mut TextureCraftApp) { + app.library = None; + + #[cfg(not(target_arch = "wasm32"))] + for warning in app.session.load_brush_presets(crate::user_dir("brushes")) { + app.toast(warning, true); + } + + app.thumbs.forget_saved_files(); +} + +/// Reads the project's changed image files again; a file that is gone or can't be read says why once, until it reads again +fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { + let Some(status) = app.run("resource.status", json!({})) else { return }; + let rows = status["resources"].as_array().cloned().unwrap_or_default(); + let mut failures: Vec<(String, String)> = + rows.iter().filter(|row| row["status"] == "missing").map(|row| (text(&row["name"]), text(&row["error"]))).collect(); + if status["outdated"].as_u64().is_some_and(|outdated| outdated > 0) + && let Some(result) = app.run("resource.update", json!({})) + { + failures.extend(result["failed"].as_array().into_iter().flatten().map(|failure| (text(&failure["name"]), text(&failure["error"])))); + } + + let reported_id = reported_failures_id(app.session.project_id); + let mut reported: Vec = ctx.data(|data| data.get_temp(reported_id)).unwrap_or_default(); + reported.retain(|name| failures.iter().any(|(failed, _)| failed == name)); + for (name, error) in failures { + if !reported.contains(&name) { + app.toast(format!("{name}: {error}"), true); + reported.push(name); + } + } + ctx.data_mut(|data| data.insert_temp(reported_id, reported)); +} + +/// Reads the files of `names` (every changed image when None) again through the Resources Updater, which says what happened +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn update_from_files(app: &mut TextureCraftApp, names: Option>) { + crate::resources_updater::update(app, names); +} + +/// The browser reads no files: the command's refusal says so +#[cfg(target_arch = "wasm32")] +pub(crate) fn update_from_files(app: &mut TextureCraftApp, names: Option>) { + app.run("resource.update", names.map_or_else(|| json!({}), |names| json!({ "names": names }))); +} + +/// A string field of a command's result, empty when it has none +fn text(value: &serde_json::Value) -> String { + value.as_str().unwrap_or_default().to_owned() +} + +/// The files of project `project_id` whose failure to read was already shown (ctx temp data) +fn reported_failures_id(project_id: u64) -> Id { + Id::unique(("shelf_updates_reported_failures", project_id)) +} + +/// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's +pub(crate) fn button(app: &mut TextureCraftApp, ui: &mut Ui, size: f32, panel: egui::Rect) { + let label = tr("Refresh"); + let response = icon_dropdown_button(ui, ic::ARROWS_CLOCKWISE, label, false, size).on_hover_text(label); + let width = popup_width(ui, panel.width()); + egui::Popup::from_toggle_button_response(&response) + .anchor(panel) + .align(egui::RectAlign::TOP_START) + .gap(POPUP_GAP) + .width(width) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + ui.set_width(width); + popup(app, ui); + }); +} + +/// The panel's width, or wider to fit the longest row +fn popup_width(ui: &Ui, panel_width: f32) -> f32 { + let font = egui::FontId::proportional(crate::property_sheet::TEXT_SIZE); + let longest = ui.painter().layout_no_wrap(tr(SKIP_MISMATCH).to_owned(), font, egui::Color32::WHITE).size().x; + panel_width.max(longest + crate::property_sheet::TOGGLE_ROOM + INFO_COLUMN + 2.0 * SIDE_PADDING_POINTS) +} + +fn popup(app: &mut TextureCraftApp, ui: &mut Ui) { + let updates = &mut app.ui.shelf_updates; + let full = ui.available_rect_before_wrap(); + let rows = full.with_max_x(full.right() - INFO_COLUMN); + in_scope(ui, SectionScope::Shelf, |ui| { + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + PropertySheet::show(ui, "shelf_updates", |sheet| { + sheet.section(tr("Automatic updates"), false); + sheet.toggle(tr("Assets panel"), &mut updates.assets); + sheet.beside_info(INFO_COLUMN, tr("Reads your saved assets from disk again every few minutes, so new and changed ones show here.")); + sheet.toggle(tr("Resources used in project"), &mut updates.resources); + sheet.beside_info( + INFO_COLUMN, + tr("Every few minutes, reads again the images whose files changed since this project imported them. Each update is one undo step."), + ); + + let mut minutes = [NumberField { + tag: "", + tag_color: None, + value: updates.minutes as f32, + speed: MINUTES_PER_DRAG_POINT, + decimals: 0, + suffix: tr(" min"), + }]; + if sheet.number_fields(tr("Update every"), &mut minutes, None, false).is_some() { + updates.minutes = (minutes[0].value.round() as u32).clamp(MIN_MINUTES, MAX_MINUTES); + } + sheet.beside_info(INFO_COLUMN, tr("How often the automatic updates above run.")); + + sheet.section(tr("Advanced settings"), false); + sheet.unavailable_toggle(tr(SKIP_MISMATCH)); + sheet.beside_info( + INFO_COLUMN, + tr("For assets with parameters: an update whose parameters were renamed or removed would change your texturing, so it is skipped. TextureCraft doesn't update assets with parameters from their files yet, so there is nothing to skip."), + ); + + sheet.section(tr("Manual"), false); + }); + }); + }); + + let button_size = vec2(full.width() - 2.0 * SIDE_PADDING_POINTS, crate::property_sheet::ROW_HEIGHT - BUTTON_INSET); + let add_button = |ui: &mut Ui, label: &str| { + let clicked = ui + .horizontal(|ui| { + ui.add_space(SIDE_PADDING_POINTS); + ui.add_sized(button_size, egui::Button::new(label)).clicked() + }) + .inner; + ui.add_space(BUTTON_GAP); + clicked + }; + if add_button(ui, tr("Update Assets panel")) { + refresh_assets(app); + } + if add_button(ui, tr("Update resources used in project")) { + update_from_files(app, None); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b16d6e66..1ea83ab4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,6 +6,8 @@ use texturecraft_engine::core::{BakedMap, Channel, ChannelBlend, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; use crate::saved_search::SavedSearch; +use crate::shelf_custom_preview::ShelfCustomPreview; +use crate::shelf_favorite::ShelfFavorite; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; @@ -14,11 +16,13 @@ mod import_row; mod library_location; mod project_config; mod resource_usage; +mod resources_updater; pub use import_resources::ImportResources; pub use import_row::ImportRow; pub use library_location::LibraryLocation; pub use project_config::ProjectConfig; pub use resource_usage::ResourceUsage; +pub use resources_updater::ResourcesUpdater; mod console_line; mod export_job; @@ -115,6 +119,9 @@ pub struct Windows { /// File > Import resources: the files added so far, imported by Import. #[serde(skip)] pub import_resources: Option, + /// The Resources Updater: the project's image resources and whether their files changed on disk. + #[serde(skip)] + pub resources_updater: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, @@ -170,7 +177,8 @@ pub struct Prefs { 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). + /// Percentage of free RAM available to a project save on desktop (0 to 100). + /// A stored zero uses the minimum budget of 1%. pub save_ram_percent: u8, /// Worker threads for painting, baking and export (desktop; 0: one per logical CPU). Read at /// startup, before the first parallel job. @@ -190,6 +198,21 @@ pub struct Prefs { /// The plain background of the 3D and 2D views at Environment Opacity 0 (Settings > General > /// Background color): the color at the top and at the bottom, linear RGB. pub background: [[f32; 3]; 2], + /// The 3D view draws the X, Y and Z axes in its corner. + pub show_world_axes: bool, + /// Settings > General > Show keyboard helper. Stored only: TextureCraft has no keyboard helper yet. + pub show_keyboard_helper: bool, + /// Settings > General > Only display the selected material when painting. Stored only: the + /// views always show every texture set. + pub only_selected_material_when_painting: bool, + /// Settings > Baking options > Save preprocessed scene files. Stored only: bakes keep no + /// preprocessed scene files. + pub save_preprocessed_scene_files: bool, + /// Settings > Baking options > Enable live preview baking process. + pub live_preview_baking: bool, + /// Settings > Preview options > Local cache directory (desktop). Empty or relative uses the + /// app's default cache directory. Stored only until TextureCraft has a preview cache. + pub local_cache_directory: String, } /// The orbit speed the built-in navigation runs at. @@ -203,7 +226,7 @@ impl Default for Prefs { ui_scale: 1.0, autosave_minutes: 10, recent_projects_limit: 10, - language: "en".into(), + language: crate::i18n::SYSTEM_LANGUAGE.into(), viewport_texture: 0, brightness: crate::theme::Brightness::default(), accent: crate::theme::Accent::default(), @@ -221,6 +244,12 @@ impl Default for Prefs { gpu_raytracing: true, libraries: Vec::new(), background: texturecraft_render::DEFAULT_BACKGROUND, + show_world_axes: true, + show_keyboard_helper: true, + only_selected_material_when_painting: false, + save_preprocessed_scene_files: true, + live_preview_baking: true, + local_cache_directory: String::new(), } } } @@ -375,6 +404,9 @@ pub struct ExportUi { /// `file.exportTextures`). #[serde(default)] pub materialx: bool, + /// Also write `_shaders.json`: the shader's settings and the texture sets using it (`shaderParameters` of `file.exportTextures`) + #[serde(default)] + pub shader_parameters: bool, /// Texture sets excluded from export. pub skip: Vec, /// Per texture set (by index) overrides of the settings above. @@ -418,6 +450,9 @@ pub struct ExportUi { /// Output templates tab: F2 asked to rename the selected preset. #[serde(skip)] pub rename_key: bool, + /// A text field of the window had the keyboard when the last frame ended + #[serde(skip)] + pub field_had_keyboard: bool, /// Output templates tab: the question waiting for an answer (delete, or drop an unsaved edit). #[serde(skip)] pub ask: Option, @@ -449,6 +484,7 @@ impl Default for ExportUi { color_space: String::new(), usd_asset: false, materialx: false, + shader_parameters: false, skip: Vec::new(), sets: Default::default(), owner: Vec::new(), @@ -463,6 +499,7 @@ impl Default for ExportUi { pending_drop: None, renaming: None, rename_key: false, + field_had_keyboard: false, ask: None, opened_with: None, job: None, @@ -474,7 +511,7 @@ impl Default for ExportUi { /// The LIST OF EXPORTS console's width when the window opens, as in the reference fn default_console_width() -> f32 { - 300.0 + crate::export_window::CONSOLE_WIDTH } fn default_export_dir() -> String { @@ -498,6 +535,18 @@ pub(crate) fn default_shelf_panes_split() -> f32 { 0.45 } +/// The share of the Assets panel's width the filter panes take until their edge is dragged +fn default_shelf_panes_share() -> f32 { + 0.45 +} + +fn deserialize_shelf_panes_share<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + let share = f32::deserialize(deserializer)?; + + // A finite JSON number can overflow f32 and prevent the next settings save + Ok(if share.is_finite() { share } else { default_shelf_panes_share() }) +} + fn deserialize_shelf_panes_split<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { let share = f32::deserialize(deserializer)?; @@ -521,7 +570,7 @@ fn default_true() -> bool { } /// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` -const BAKE_LAYOUT_VERSION: u32 = 2; +const BAKE_LAYOUT_VERSION: u32 = 3; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { @@ -566,6 +615,10 @@ pub struct UiState { /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, + /// Mesh Export Options: compute smooth normals on the exported copy, not the project. + /// Off by default so an export keeps the project's authored normals unless the user opts in. + #[serde(default)] + pub mesh_recompute_normals: bool, pub uv_zoom: f32, pub uv_pan: [f32; 2], /// The 2D view's turn, counter-clockwise on screen in radians (Alt+left drag) @@ -592,9 +645,27 @@ pub struct UiState { /// The asset shelf's saved queries, in the order they were saved #[serde(default)] pub shelf_saved_searches: Vec, + /// The asset shelf's favorite assets, most recently added first + #[serde(default)] + pub shelf_favorites: Vec, + /// The asset shelf shows only favorites (the Favorites saved search) + #[serde(default)] + pub shelf_favorites_only: bool, + /// The second Assets panel's search, type and folder, swapped in while it draws + #[serde(default)] + pub shelf_second: crate::shelf_query::ShelfQuery, + /// The asset shelf's automatic updates (its refresh popup) + #[serde(default)] + pub shelf_updates: crate::shelf_updates::ShelfUpdates, + /// Pictures the user picked to show on asset tiles instead of their thumbnails + #[serde(default)] + pub shelf_custom_previews: Vec, /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, + /// The share of the Assets panel's width the filter panes take + #[serde(default = "default_shelf_panes_share", deserialize_with = "deserialize_shelf_panes_share")] + pub shelf_panes_share: f32, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -655,6 +726,12 @@ pub struct UiState { /// The Log panel's shown channel tab #[serde(default)] pub log_channel: crate::log_panel::LogChannel, + /// The Baking Log panel's shown tab + #[serde(default)] + pub baking_log_tab: crate::baking_log::BakingLogTab, + /// Whether the Baking Log keeps only the rows with an issue + #[serde(default)] + pub baking_log_issues_only: bool, /// The project template the last New project was created from (name or label) #[serde(default)] pub last_template: String, @@ -721,6 +798,12 @@ impl UiState { self.rail_panel = None; } + /// Reset the workspace and return the interface to the system language. + pub(crate) fn reset_ui(&mut self) { + self.adopt_layout(Self::default()); + self.prefs.language.clear(); + } + /// 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); @@ -735,6 +818,7 @@ impl UiState { } self.export = keep.export; + self.mesh_recompute_normals = keep.mesh_recompute_normals; self.recent = keep.recent; self.last_template = keep.last_template; self.prefs = keep.prefs; @@ -752,6 +836,11 @@ impl UiState { self.shelf_tab = keep.shelf_tab; self.shelf_path = keep.shelf_path; self.shelf_saved_searches = keep.shelf_saved_searches; + self.shelf_favorites = keep.shelf_favorites; + self.shelf_favorites_only = keep.shelf_favorites_only; + self.shelf_second = keep.shelf_second; + self.shelf_custom_previews = keep.shelf_custom_previews; + self.shelf_updates = keep.shelf_updates; } } @@ -774,6 +863,7 @@ impl Default for UiState { selected_baked_map: None, hide_ui: false, windows: Windows::default(), + mesh_recompute_normals: false, uv_zoom: 1.0, uv_pan: [0.0, 0.0], uv_rotation: 0.0, @@ -786,7 +876,13 @@ impl Default for UiState { shelf_view: ShelfView::default(), shelf_panes: ShelfPanes::default(), shelf_saved_searches: Vec::new(), + shelf_favorites: Vec::new(), + shelf_favorites_only: false, + shelf_second: crate::shelf_query::ShelfQuery::default(), + shelf_custom_previews: Vec::new(), + shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), + shelf_panes_share: default_shelf_panes_share(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, @@ -810,6 +906,8 @@ impl Default for UiState { bake_preset_name: String::new(), layout_dialog: None, log_channel: crate::log_panel::LogChannel::default(), + baking_log_tab: crate::baking_log::BakingLogTab::default(), + baking_log_issues_only: false, last_template: String::new(), log_selection: Default::default(), log_anchor: None, @@ -856,6 +954,15 @@ mod tests { assert_eq!(crate::start_ui(None, &mut session).prefs.language, crate::i18n::SYSTEM_LANGUAGE); } + #[test] + fn mesh_export_normal_choice_defaults_off_for_older_saved_states() { + assert!(!UiState::default().mesh_recompute_normals); + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + saved.as_object_mut().unwrap().remove("mesh_recompute_normals"); + let loaded: UiState = serde_json::from_value(saved).unwrap(); + assert!(!loaded.mesh_recompute_normals, "older states keep the project's stored normals unless the user opts in"); + } + #[test] fn adopting_a_layout_keeps_recent_files_and_user_settings() { use crate::frame_gizmo::warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings}; @@ -865,7 +972,9 @@ mod tests { ui.warp_toolbar = warp_toolbar; ui.export.preset = "Mine".into(); ui.keymap.insert("file.save".into(), "F5".into()); + ui.mesh_recompute_normals = false; let mut layout = UiState::default(); + layout.mesh_recompute_normals = true; layout.dock.close(crate::docking::Panel::Assets); ui.adopt_layout(layout); @@ -874,6 +983,7 @@ mod tests { 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")); + assert!(!ui.mesh_recompute_normals, "a layout does not change the user's export setting"); assert_eq!(ui.warp_toolbar, warp_toolbar, "loading a layout keeps the user's warp settings"); } @@ -919,15 +1029,26 @@ mod tests { } #[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() }; + fn adopting_a_layout_keeps_the_shelf_query_saved_searches_favorites_and_custom_previews() { + let saved = + crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()], favorites_only: false }; + let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() }; + let mut ui = + UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() }; ui.shelf_saved_searches.push(saved.clone()); + ui.shelf_favorites.push(favorite.clone()); + let preview = crate::shelf_custom_preview::ShelfCustomPreview { kind: "material".into(), id: "gold".into(), file: "gold.png".into() }; + ui.shelf_custom_previews.push(preview.clone()); + ui.shelf_updates.resources = true; 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]); + assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too"); + assert!(ui.shelf_favorites_only, "the Favorites search is part of the query"); + assert_eq!(ui.shelf_custom_previews, [preview], "custom previews are the user's own"); + assert!(ui.shelf_updates.resources, "automatic updates are a setting, not part of a layout"); } #[test] @@ -972,6 +1093,24 @@ mod tests { } } + #[test] + fn a_saved_bake_dock_with_the_log_at_the_bottom_gets_the_baking_log_there() { + use crate::docking::Panel; + + let mut ui = UiState { mode: Mode::Baking, ..UiState::default() }; + ui.sync_mode_dock(); + ui.dock.close(Panel::BakingLog); + ui.dock.focus(Panel::Log); + let mut saved = serde_json::to_value(&ui).unwrap(); + saved["bake_layout_version"] = serde_json::json!(2); + + let mut loaded: UiState = serde_json::from_value(saved).unwrap(); + loaded.sync_mode_dock(); + + assert!(loaded.dock.is_visible(Panel::BakingLog), "the Baking Log takes the bottom of the bake layout"); + assert!(!loaded.dock.is_open(Panel::Log), "the general Log stays in Window > Views"); + } + #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index cf4a87de..853ca813 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -20,6 +20,8 @@ pub struct ExportJob { /// Also write the mesh and materials as a USD asset with the last texture set, as ticked when /// Export was clicked. pub usd_asset: bool, + /// Also write the shader parameters with the last texture set, listing every texture set of the export, as ticked when Export was clicked + pub shader_parameters: bool, /// The params of the texture sets written so far, for the USD asset. pub sent: Vec, /// Warning messages already shown in this export. diff --git a/crates/ui-egui/src/state/map_export.rs b/crates/ui-egui/src/state/map_export.rs index 339ee1bb..2b8a3e37 100644 --- a/crates/ui-egui/src/state/map_export.rs +++ b/crates/ui-egui/src/state/map_export.rs @@ -10,6 +10,9 @@ pub struct MapExport { pub enabled: bool, #[serde(default)] pub file_type: Option, + /// The map's own size in texels per side, which wins over the export size + #[serde(default)] + pub size: Option, } fn enabled_by_default() -> bool { @@ -18,6 +21,6 @@ fn enabled_by_default() -> bool { impl Default for MapExport { fn default() -> Self { - MapExport { enabled: true, file_type: None } + MapExport { enabled: true, file_type: None, size: None } } } diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs index 6c7eb95c..0d848f6e 100644 --- a/crates/ui-egui/src/state/project_config.rs +++ b/crates/ui-egui/src/state/project_config.rs @@ -7,8 +7,8 @@ pub struct ProjectConfig { pub reimport: bool, /// Whether painted strokes follow the surface of a newly imported mesh pub preserve: bool, - /// The project name as typed, when the field was edited - pub name: Option, + /// The name as typed, or None to leave the current name unvalidated and unchanged + pub draft_name: Option, /// The selected normal map format when it differs from the project's pub normal_format: Option, /// Color management as chosen in the window; nothing is applied (the project stays Legacy) diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs new file mode 100644 index 00000000..3b515d32 --- /dev/null +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -0,0 +1,21 @@ +use texturecraft_engine::{ResourceState, ResourceStatus}; + +/// The Resources Updater window: the project's image resources as last checked, and the filters +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ResourcesUpdater { + /// The resources and how they compare with their files, outdated first (checked on opening, + /// Refresh, twice a second while open and when the app gets the focus back) + pub rows: Vec, + /// The status the list is narrowed to (None: all) + pub status_filter: Option, + /// Shows only resources whose name contains this, ignoring case + pub name_filter: String, + /// Top or Bottom asked the list to scroll to that end in the next frame + pub jump: Option, + /// The project that was open when this window opened + pub project: u64, + /// When the rows were checked, in app seconds + pub(crate) checked_at: f64, + /// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it) + pub(crate) had_keyboard: bool, +} diff --git a/crates/ui-egui/src/state/set_export.rs b/crates/ui-egui/src/state/set_export.rs index 0fb05522..7bb10770 100644 --- a/crates/ui-egui/src/state/set_export.rs +++ b/crates/ui-egui/src/state/set_export.rs @@ -26,7 +26,11 @@ pub struct SetExport { impl SetExport { /// Whether anything is overridden (the set is marked "*"). pub fn any(&self) -> bool { - self.preset.is_some() || self.file_type.is_some() || self.size.is_some() || self.padding.is_some() || self.maps.values().any(|m| m.file_type.is_some()) + self.preset.is_some() + || self.file_type.is_some() + || self.size.is_some() + || self.padding.is_some() + || self.maps.values().any(|m| m.file_type.is_some() || m.size.is_some()) } /// Whether the set exports as the global settings say (no override, every map ticked). diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 942f9450..30af4f1e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -449,7 +449,7 @@ pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color3 const WCAG_FLARE: f32 = 0.05; /// The WCAG contrast ratio of two opaque colors (1..21) -fn contrast_ratio(a: Color32, b: Color32) -> f32 { +pub(crate) fn contrast_ratio(a: Color32, b: Color32) -> f32 { let luminance = |color: Color32| { let linear = egui::Rgba::from(color); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 41c20d1f..66925033 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -70,6 +70,8 @@ pub struct Thumbs { big_shown: VecDeque, /// The frame that last took in the worker's results received_in_pass: u64, + /// Pictures the user picked as asset previews, by file; None for a file that doesn't load + custom_previews: HashMap>, /// Per active generator picture size: the current effect, pending key and last finished picture set_pictures: HashMap<(u64, usize), (Option, Option)>, } @@ -314,6 +316,26 @@ impl Thumbs { self.rendered.retain(|key, _| current(key)); self.big_shown.retain(current); self.saved_brush_previews.clear(); + self.custom_previews.clear(); + } + + /// Load the picture at `file` again next time: the user picked it anew, maybe after changing it + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn forget_custom_preview(&mut self, file: &Path) { + self.custom_previews.remove(file); + } + + /// The picture at `file` as an asset's custom preview (its centred square), loaded once; None if it doesn't load + pub(crate) fn custom_preview(&mut self, ctx: &egui::Context, file: &Path) -> Option { + self.custom_previews + .entry(file.to_path_buf()) + .or_insert_with(|| { + let image = crate::shelf_custom_preview::square(&image::open(file).ok()?); + let size = [image.width() as usize, image.height() as usize]; + let pixels = ColorImage::from_rgba_unmultiplied(size, image.as_raw()); + Some(ctx.load_texture(format!("custom_preview_{}", file.display()), pixels, TextureOptions::LINEAR)) + }) + .clone() } /// Smart mask thumbnail; None until the worker returns it diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 024675b1..e910f094 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -68,12 +68,12 @@ const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [ impl TitleBar { /// Decide who draws the title bar; call once at startup, before the window is created, and /// hand the decision to the window ([`viewport`]) and the runtime (`framework::install`). - /// `system` is Settings › Interface › System title bar. - pub fn decide(system: bool) -> Decision { + /// `system` is Settings › Interface › System title bar; `backend` is the one the window opens on. + pub fn decide(system: bool, backend: craft_host::target::Backend) -> Decision { let choice = craft_window::Choice::probe(PREFIX); let wanted = Self::from_choice(choice.frame(), choice.overridden(), system); let pref = if wanted == TitleBar::System { TitleBarPref::System } else { TitleBarPref::Integrated }; - craft_window::policy::decide_for(PREFIX, craft_host::target::Backend::from_env(), pref) + craft_window::policy::decide_for(PREFIX, backend, pref) } /// The bar a decided `frame` gives. @@ -93,6 +93,7 @@ impl TitleBar { if overridden.is_none() && system { return TitleBar::System; } + match frame { Frame::App(layout) => TitleBar::App(layout.clone()), Frame::Desktop if overridden.is_some() => TitleBar::System, @@ -238,15 +239,18 @@ mod tests { #[test] fn the_override_wins_then_the_setting_then_the_platform() { let gnome = Frame::App(Layout::parse("appmenu:close")); - // TEXTURECRAFT_TITLEBAR=app / =system, whatever the setting. + + // The environment override wins regardless of the saved setting for system in [false, true] { assert_eq!(TitleBar::from_choice(&gnome, Some(true), system), TitleBar::App(Layout::parse("appmenu:close"))); assert_eq!(TitleBar::from_choice(&Frame::Desktop, Some(false), system), TitleBar::System); } - // The setting brings the system's frame back. + + // The saved setting selects the system frame without an override assert_eq!(TitleBar::from_choice(&gnome, None, true), TitleBar::System); assert_eq!(TitleBar::from_choice(&Frame::Desktop, None, true), TitleBar::System); - // The platform: a compositor that leaves the frame to the app gets the app's. + + // Otherwise the desktop determines who draws the frame assert_eq!(TitleBar::from_choice(&gnome, None, false), TitleBar::App(Layout::parse("appmenu:close"))); let desktop = TitleBar::from_choice(&Frame::Desktop, None, false); let expected = if cfg!(windows) { diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs new file mode 100644 index 00000000..e7d05308 --- /dev/null +++ b/crates/ui-egui/src/toast_action.rs @@ -0,0 +1,41 @@ +//! A button on a toast that acts on what the toast says + +use crate::TextureCraftApp; + +/// What a toast's button does +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToastAction { + /// "Update": read every outdated resource file of `project` again (the desktop's "changed on disk" notice) + UpdateResources { + /// The project the notice is about; the button does nothing once another one is open + project: u64, + }, +} + +impl ToastAction { + /// The button's text (English; translated where it is drawn) + pub fn label(self) -> &'static str { + match self { + ToastAction::UpdateResources { .. } => "Update", + } + } + + /// The button's accessible name, which says what it acts on (English; translated where it is drawn) + pub fn accessible_name(self) -> &'static str { + match self { + ToastAction::UpdateResources { .. } => "Update resources", + } + } + + pub(crate) fn run(self, app: &mut TextureCraftApp) { + match self { + // Another project's notice is stale + ToastAction::UpdateResources { project } if project != app.session.project_id => {} + #[cfg(not(target_arch = "wasm32"))] + ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None), + // The browser has no files to read again + #[cfg(target_arch = "wasm32")] + ToastAction::UpdateResources { .. } => {} + } + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 21cf3c93..59f56357 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -510,15 +510,33 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add_space(SHELF_GROUP_GAP); } - for (icon, label) in [(ic::HOURGLASS, "Snooze Autosave"), (ic::ARROWS_CLOCKWISE, "Resources Updater")] { - ui.add_enabled_ui(false, |ui| icon_button(ui, icon, tr(label), false, SHELF_BUTTON_SIZE)) - .inner - .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); - } + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::HOURGLASS, tr("Snooze Autosave"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); + resources_updater_button(app, ui); }); }); } +/// The shelf's Resources Updater button: opens or closes its window while a project is open +#[cfg(not(target_arch = "wasm32"))] +fn resources_updater_button(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let open = app.ui.windows.resources_updater.is_some(); + let label = tr("Resources Updater"); + let button = ui.add_enabled_ui(app.session.project_open, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, label, open, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(tr("Open a project to check its resources")).clicked() { + crate::resources_updater::toggle(app); + } +} + +/// The browser reads no files from disk, so there is nothing to update +#[cfg(target_arch = "wasm32")] +fn resources_updater_button(_: &mut TextureCraftApp, ui: &mut egui::Ui) { + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Resources Updater"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); +} + /// Width of the icon rail beside the dock const RAIL_WIDTH: f32 = 38.0; @@ -556,6 +574,10 @@ pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + const PROGRESS_WIDTH_PT: f32 = 160.0; + const PROGRESS_HEIGHT_PT: f32 = 10.0; + const PROGRESS_TEXT_SIZE_PT: f32 = 10.0; + let tk = Tokens::get(ui.ctx()); egui::Panel::bottom("status_bar") .exact_size(22.0) @@ -563,16 +585,36 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { .frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(10, 0))) .show(ui, |ui| { ui.horizontal_centered(|ui| { - if let Some(p) = app.bake_progress() { - ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Baking")).size(10.0))); + #[cfg(not(target_arch = "wasm32"))] + if let Some(progress) = app.save_progress() { + ui.add( + egui::ProgressBar::new(progress) + .desired_width(PROGRESS_WIDTH_PT) + .desired_height(PROGRESS_HEIGHT_PT) + .text(RichText::new(tr("Saving project")).size(PROGRESS_TEXT_SIZE_PT)), + ); + ui.separator(); + } + if let Some(progress) = app.bake_progress() { + ui.add( + egui::ProgressBar::new(progress) + .desired_width(PROGRESS_WIDTH_PT) + .desired_height(PROGRESS_HEIGHT_PT) + .text(RichText::new(tr("Baking")).size(PROGRESS_TEXT_SIZE_PT)), + ); if ui.small_button(tr("Cancel")).clicked() { app.cancel_bake(); } } else if let Some(job) = &app.resize { - let bar = egui::ProgressBar::new(job.progress.fraction()).desired_width(160.0).desired_height(10.0); - ui.add(bar.animate(true).text(RichText::new(tr("Resizing")).size(10.0))); - } else if let Some(p) = app.gpu.as_ref().and_then(|g| g.composite_progress(&app.session)) { - ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Compositing")).size(10.0))); + let bar = egui::ProgressBar::new(job.progress.fraction()).desired_width(PROGRESS_WIDTH_PT).desired_height(PROGRESS_HEIGHT_PT); + ui.add(bar.animate(true).text(RichText::new(tr("Resizing")).size(PROGRESS_TEXT_SIZE_PT))); + } else if let Some(progress) = app.gpu.as_ref().and_then(|g| g.composite_progress(&app.session)) { + ui.add( + egui::ProgressBar::new(progress) + .desired_width(PROGRESS_WIDTH_PT) + .desired_height(PROGRESS_HEIGHT_PT) + .text(RichText::new(tr("Compositing")).size(PROGRESS_TEXT_SIZE_PT)), + ); ui.ctx().request_repaint(); } else if let Some(msg) = app.session.log.last() { ui.label(RichText::new(&msg.message).size(11.0).color(tk.text_dim)); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 4305dd0f..646835f6 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -73,10 +73,9 @@ 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. +/// Whether an update can restart the app with all edits saved and pending work finished. fn safe_to_close(app: &TextureCraftApp) -> bool { - !app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none() && app.high_poly_job.is_none() + !app.session.modified && !app.session.stroke_active() && app.save_job.is_none() && app.bake.is_none() && app.resize.is_none() && app.high_poly_job.is_none() } /// One pass of the update flow, before the dialog host runs: answers the result dialog closed in @@ -298,7 +297,8 @@ mod tests { 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, only: None }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None, rebake: None }); + assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; @@ -318,6 +318,19 @@ mod tests { assert!(!safe_to_close(h.state()), "a stroke"); h.state_mut().session.cancel_stroke(); assert!(safe_to_close(h.state())); + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("project.tcraft"); + assert!(h.state_mut().start_save(path.to_str().unwrap(), true, false, false)); + assert!(!safe_to_close(h.state()), "the accepted archive write must finish before restarting"); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while h.state().save_job.is_some() && std::time::Instant::now() < deadline { + h.step(); + } + + assert!(safe_to_close(h.state())); + assert!(path.exists()); } #[test] diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3ae2bfbd..4c1fe3c7 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -414,9 +414,10 @@ fn set_highlight(ui: &Ui, texture_set: usize) -> SetHighlight { /// 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(); + if !names.is_empty() { - // One sticky notice for every set the GPU could not hold (they are not retried, so the - // notice stays until dismissed); after a dismissal, a new one names only the new sets. + // Failed allocations are not retried, so keep a notice until the user dismisses it + // Start a new list on the first failure after dismissal let (sets, shown) = &mut app.gpu_memory; let current = shown.take().filter(|text| app.toasts.iter().any(|t| &t.text == text)); match ¤t { @@ -430,7 +431,7 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) } let text = match sets.as_slice() { [one] => trf( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the Texture resolution in Display Settings › Render settings. Painting and export are not affected.", &[("name", one)], ), many => { @@ -443,7 +444,7 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) list.push_str(", ..."); } trf( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the Texture resolution in Display Settings › Render settings. Painting and export are not affected.", &[("count", &many.len()), ("names", &list)], ) } @@ -1157,7 +1158,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin solo_notice(app, ui, rect); view_header(app, ui, rect, "v3d"); mask_view_badge(app, ui, rect); - axis_gizmo(ui, rect, app, None); + if app.ui.prefs.show_world_axes { + axis_gizmo(ui, rect, app, None); + } + crate::nav_buttons::show(app, ui, rect, crate::nav_buttons::NavView::Scene); } @@ -2966,8 +2970,9 @@ mod tests { 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()); + // The source effect is a valid inherited target when selection changes to its instance + execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).unwrap(); + assert_eq!(session.target, texturecraft_engine::StackTarget::Effect(effect)); assert_eq!(session.ts(), 1); assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 02a17d8c..19c3bd3a 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -234,12 +234,15 @@ pub fn project_file_name(app: &TextureCraftApp) -> String { fn zip_files(files: Vec) -> Result, String> { let mut zip = craft_zip::Writer::new(); for f in files { - // add_with reserves ZIP64 headers up front, even for small entries. + // Reserve ZIP64 headers up front, even for small entries zip.add_with(&f.name, craft_zip::Compression::Deflated, |out| out.write_all(&f.bytes)).map_err(|e| e.to_string())?; } zip.finish().map_err(|e| e.to_string()) } +#[cfg(any(target_arch = "wasm32", test))] +use texturecraft_engine::shader_parameters::shader_parameters_sidecar; + #[cfg(target_arch = "wasm32")] pub use web::{ download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, open_sample_project, @@ -337,9 +340,9 @@ mod web { pub fn export_mesh(app: &mut TextureCraftApp, ext: &str) { let name = format!("{}.{ext}", sanitize_file_stem(&app.session.doc.project.name)); let bytes = match ext { - "glb" => app.session.mesh_glb_bytes(), - "usdz" => app.session.mesh_usd(texturecraft_engine::formats::UsdFormat::Usdz).map(|u| u.bytes), - _ => app.session.mesh_obj_bytes(), + "glb" => app.session.mesh_glb_bytes_with_normals(app.ui.mesh_recompute_normals), + "usdz" => app.session.mesh_usd_with_normals(texturecraft_engine::formats::UsdFormat::Usdz, app.ui.mesh_recompute_normals).map(|u| u.bytes), + _ => app.session.mesh_obj_bytes_with_normals(app.ui.mesh_recompute_normals), }; match bytes.map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) { Ok(()) => app.toast(trf("Downloaded {name}", &[("name", &name)]), false), @@ -357,14 +360,24 @@ mod web { } fn export(app: &mut TextureCraftApp, jobs: &[(usize, Value)]) -> Result { - let mut files = Vec::new(); - for (set_index, params) in jobs { - let options = texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures").map_err(|e| e.to_string())?; - files.extend(app.session.export_files(&[*set_index], &options).map_err(|e| e.to_string())?); - } + let options = jobs + .iter() + .map(|(_, params)| texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures")) + .collect::, _>>() + .map_err(|error| error.to_string())?; + let jobs_with_options = jobs.iter().zip(&options).map(|((set_index, _), options)| (*set_index, options)); + let mut files = app.session.export_file_jobs(jobs_with_options).map_err(|error| error.to_string())?; - // Keep one file for each case-insensitive name in the download - texturecraft_engine::formats::skip_repeated_names(&mut files); + if app.ui.export.shader_parameters { + let sets: Vec = jobs.iter().map(|(set_index, _)| *set_index).collect(); + match shader_parameters_sidecar(&app.session.doc.project, &sets, &files) { + Ok(sidecar) => files.push(sidecar), + Err(error) => { + app.session.log.warnings("MapExporter", [format!("The shader settings file was not written: {error}")]); + app.toast(trf("The shader settings file was not written: {error}", &[("error", &error)]), true); + } + } + } app.session.log.warnings("MapExporter", files.iter().flat_map(|file| file.warnings.iter().cloned())); let file_count = files.len(); @@ -530,6 +543,28 @@ mod tests { assert!(harness.state().session.doc.bake_meshes.cage.is_some()); } + #[test] + fn shader_sidecar_does_not_take_a_texture_folder_name() { + let project = texturecraft_engine::core::Project::new("Chair", "builtin:sphere"); + let name = "chair_SHADERS.json/Color.png"; + let mut files = vec![ExportedFile { name: name.into(), bytes: vec![1, 2, 3], width: 1, height: 1, warnings: Vec::new() }]; + + let error = shader_parameters_sidecar(&project, &[], &files).unwrap_err(); + + assert!(error.contains("Chair_shaders.json")); + assert_eq!(files.len(), 1); + assert_eq!(files[0].name, name); + + files[0].name = "Chair_shaders.json_backup/Color.png".into(); + files.push(shader_parameters_sidecar(&project, &[], &files).unwrap()); + let bytes = zip_files(files).unwrap(); + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + + assert_eq!(archive.len(), 2); + assert!(archive.by_name("Chair_shaders.json_backup/Color.png").is_ok()); + assert!(archive.by_name("Chair_shaders.json").is_ok()); + } + #[test] fn zip_round_trips_every_export_file() { let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 991585dc..abba3370 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -5,6 +5,7 @@ use egui::{Color32, CornerRadius, Rect, Response, RichText, Sense, Stroke, Strok use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; +use crate::press_edit::PressEdit; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -31,21 +32,28 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { return None; } - ui.memory_mut(|memory| { - let edits = memory.caches.cache::>(); + // Kept in memory, not a frame cache: a floating panel in its own OS window ends a pass of its own inside ours, which would clear it every frame + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|data| { let id = id.with("pointer edit"); - let previous = edits.get(&id).copied(); + let previous = data.get_temp::(id); let merge = match press { Some(start) => { - let continuing = previous == Some(start); + let continuing = previous.is_some_and(|previous| previous.press == start); if changed || continuing { - edits.set(id, start); + // Only the latest press's editors can merge, so its first change forgets every editor of the older ones + let latest_press = egui::Id::unique("pointer edit press"); + if data.get_temp::(latest_press) != Some(start) { + data.remove_by_type::(); + data.insert_temp(latest_press, start); + } + data.insert_temp(id, PressEdit { press: start, frame }); } continuing } // A final movement still belongs to the press that ended - None => release_only && previous.is_some(), + None => release_only && previous.is_some_and(|previous| previous.frame + 1 >= frame), }; changed.then_some(merge) }) diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index ba6c3179..b8eff6e8 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -23,6 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { { crate::project_config::show(app, ctx); crate::import_resources::show(app, ctx); + crate::resources_updater::show(app, ctx); } crate::keymap::window(app, ctx); crate::export_window::show(app, ctx); @@ -41,7 +42,7 @@ pub(crate) fn reset_ui_keys(app: &mut TextureCraftApp, input: &mut egui::InputSt if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { app.ui.windows.confirm_reset_ui = false; } else if nothing_focused && input.consume_key(egui::Modifiers::NONE, egui::Key::Enter) { - app.ui.adopt_layout(crate::UiState::default()); + app.ui.reset_ui(); app.ui.windows.confirm_reset_ui = false; } } @@ -54,7 +55,7 @@ fn reset_ui(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut reset, mut cancel) = (false, false); dialog(ctx, "reset_ui", tr("Reset UI"), &mut open).show(ctx, |ui| { - ui.label(tr("Reset the panels, view layout, zoom and every other view setting to their defaults? Settings and shortcuts stay.")); + ui.label(tr("Reset the panels, view settings and interface language to their defaults? Other preferences and shortcuts stay.")); ui.add_space(8.0); // One row keeps the window to its contents; a bare right-to-left layout fills the screen height @@ -67,19 +68,35 @@ fn reset_ui(app: &mut TextureCraftApp, ctx: &egui::Context) { }); if reset { - app.ui.adopt_layout(crate::UiState::default()); + app.ui.reset_ui(); } if reset || cancel || !open { app.ui.windows.confirm_reset_ui = false; } } +fn discard_replaced_prompt(app: &mut TextureCraftApp) { + if app.prompt_project_id == app.session.project_id { + return; + } + + app.prompt_project_id = app.session.project_id; + app.ui.windows.unsaved = None; + #[cfg(not(target_arch = "wasm32"))] + { + app.saving_for_prompt = false; + app.prompt_saved = false; + } +} + /// Hold `then` (quitting, opening or closing a project) behind the unsaved-changes dialog when /// the project has unsaved changes; false when it can go ahead now. pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved) -> bool { + discard_replaced_prompt(app); if app.session.modified { app.ui.windows.unsaved = Some(then); } + app.session.modified } @@ -88,13 +105,20 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved /// brings the window back so it can be answered. A close nothing holds open goes ahead through the platform's own /// quit. pub(crate) fn close_requested(app: &mut TextureCraftApp) -> bool { - // A stroke still open at the close, or released in this frame, is a change to ask about. + // An open stroke may contain unsaved changes if app.session.stroke_active() && let Err(error) = app.session.end_stroke() { app.toast(error.to_string(), true); } - ask_to_save(app, crate::state::Unsaved::Quit) + + let prompted = ask_to_save(app, crate::state::Unsaved::Quit); + #[cfg(not(target_arch = "wasm32"))] + if app.hold_close_for_save() { + return true; + } + + prompted } /// Quitting, opening or closing a project with unsaved changes asks whether to save them first @@ -102,10 +126,11 @@ pub(crate) fn close_requested(app: &mut TextureCraftApp) -> bool { fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { use crate::state::Unsaved; + discard_replaced_prompt(app); 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)); + let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt || app.save_job.is_some(), std::mem::take(&mut app.prompt_saved)); #[cfg(target_arch = "wasm32")] let (waiting_for_save, saved_by_dialog) = (false, false); @@ -124,7 +149,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { // 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 + // The prompt waits for its path picker or any active save 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() { @@ -145,17 +170,22 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { app.saving_for_prompt = false; + if pending == Unsaved::Quit { + app.cancel_close_after_save(); + } } } let discard_after_create = matches!(pending, Unsaved::CreateProject(_)) && save_first == Some(false) && app.session.modified; 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(); + app.saving_for_prompt = true; + file_action(app, ctx, "file.save"); + return; } + #[cfg(target_arch = "wasm32")] file_action(app, ctx, "file.save"); } // Going ahead anyway: the changes are let go @@ -551,15 +581,16 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> app.ask_file(dialog, Bound::App, open_picked); true } - "file.save" if app.session.path.is_some() => { - if let Some(result) = app.run("file.save", json!({})) { - let saved_path = result["path"].as_str().unwrap_or_default(); - app.toast(trf("Saved {path}", &[("path", &saved_path)]), false); - } - true - } "file.save" | "file.saveAs" => { - ask_save_project(app, "file.saveAs"); + if id == "file.save" + && let Some(path) = app.session.path.clone() + { + if !app.start_save(&path, true, app.saving_for_prompt, false) { + app.saving_for_prompt = false; + } + } else { + ask_save_project(app, "file.saveAs"); + } true } "file.saveCopy" => { @@ -601,7 +632,8 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> .file_name(name); app.ask_file(dialog, Bound::Project, |app, paths| { if let Some(path) = paths.first() - && let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()})) + && let Some(result) = + app.run("file.exportMesh", json!({"path": path.display().to_string(), "recomputeNormals": app.ui.mesh_recompute_normals})) { let saved_path = result["path"].as_str().unwrap_or_default(); app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false); @@ -636,32 +668,28 @@ fn open_picked(app: &mut TextureCraftApp, paths: Vec) { } } -/// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog +/// Asks where to save the project and starts the save 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. + + // Saving a copy cannot satisfy the unsaved-changes prompt let for_prompt = app.saving_for_prompt && cmd == "file.saveAs"; + let project_id = app.session.project_id; 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 { + let for_prompt = for_prompt && app.saving_for_prompt && app.session.project_id == project_id; + let started = paths.first().is_some_and(|p| app.start_save(&p.display().to_string(), cmd != "file.saveCopy", for_prompt, true)); + + // A canceled picker or failed start lets the prompt retry + if for_prompt && !started { 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. + + // Keep the buttons usable if the picker was already queued if for_prompt && !asked { app.saving_for_prompt = false; } @@ -776,7 +804,8 @@ mod tests { 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. + + // A script saved the project while the dialog was open app.session.modified = false; app.saving_for_prompt = true; ask_save_project(app, "file.saveAs"); diff --git a/crates/ui-egui/tests/autosave_files.rs b/crates/ui-egui/tests/autosave_files.rs new file mode 100644 index 00000000..9b8b7548 --- /dev/null +++ b/crates/ui-egui/tests/autosave_files.rs @@ -0,0 +1,68 @@ +//! The desktop autosave writes each project's copy to a file of its own. This is a test binary of its own because it +//! points the process's data folder at a temporary one + +#![cfg(not(target_arch = "wasm32"))] + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// App time each frame advances by, so a few frames pass any autosave interval +const FRAME_SECONDS: f32 = 600.0; + +/// How long the worker thread gets to write a copy +const WRITE_TIMEOUT: Duration = Duration::from_secs(60); + +/// A project named as one made from `hero.fbx` would be, with `layers` paint layers added since it was saved +fn unsaved_hero(layers: usize) -> Session { + let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + for _ in 0..layers { + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + } + session +} + +fn copies(folder: &Path) -> Vec { + let files = std::fs::read_dir(folder).map(|entries| entries.flatten().map(|entry| entry.path()).collect::>()).unwrap_or_default(); + files.into_iter().filter(|path| path.extension().is_some_and(|extension| extension == "tcraft")).collect() +} + +/// Runs an app on `session` until the autosave folder holds `count` copies +fn autosave(session: Session, folder: &Path, count: usize) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder() + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + let started = Instant::now(); + while copies(folder).len() < count { + harness.step(); + assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote {:?}", copies(folder)); + std::thread::sleep(Duration::from_millis(20)); + } + harness +} + +#[test] +fn two_projects_of_one_name_keep_two_autosave_copies() { + let data = std::env::temp_dir().join(format!("tc-autosave-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&data); + texturecraft_ui_egui::set_data_root(data.clone()); + let folder = data.join("autosave"); + + let first = autosave(unsaved_hero(1), &folder, 1); + let second = autosave(unsaved_hero(2), &folder, 2); + drop((first, second)); + + // Each copy opens as the project that wrote it + let mut layers: Vec = + copies(&folder).iter().map(|path| texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap().doc.project.layers.len()).collect(); + layers.sort_unstable(); + assert_eq!(layers[1], layers[0] + 1, "{layers:?}"); + + std::fs::remove_dir_all(&data).unwrap(); +} diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6de467e4..9d99354b 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -71,16 +71,19 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { } #[test] -fn cancelling_restores_the_view_and_leaves_the_document_alone() { +fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() { let mut harness = harness(); let before = harness.state().session.doc.baked.get(&0).cloned(); + // One frame starts the worker; a finished map shows only from the next one harness.state_mut().start_bake(vec![0]); - harness.run_steps(2); + harness.run_steps(1); 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); @@ -134,6 +137,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { total: 1, mesh_id, only: None, + rebake: None, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), @@ -141,6 +145,9 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { maps, maps_done: Arc::new(AtomicUsize::new(MAPS.len())), maps_total: MAPS.len(), + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, }), }); @@ -149,6 +156,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { 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(); } @@ -162,6 +170,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { 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()); diff --git a/crates/ui-egui/tests/i18n_build.rs b/crates/ui-egui/tests/i18n_build.rs index c972cfc7..d2d690de 100644 --- a/crates/ui-egui/tests/i18n_build.rs +++ b/crates/ui-egui/tests/i18n_build.rs @@ -3,6 +3,12 @@ #[allow(dead_code)] // The production build entry point is not invoked by these pure-input tests. mod i18n_build; +/// The catalogs' Rust includes alone, which is what these tests assert on; the build itself asks +/// [`i18n_build::collect`] for the characters its web font cut needs as well. +fn generate(dir: Option<&std::path::Path>, required: bool) -> Result { + i18n_build::collect(dir, required).map(|(source, _)| source) +} + use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -23,23 +29,23 @@ impl Drop for Fixture { #[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()); + assert!(!generate(None, false).unwrap().contains("include_str!")); + assert!(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()); + assert!(generate(Some(&fixture.0.join("missing")), false).is_err()); + assert!(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()); + assert!(!generate(Some(&fixture.0), false).unwrap().contains("include_str!")); + assert!(generate(Some(&fixture.0), true).is_err()); } #[test] @@ -47,26 +53,26 @@ 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(); + let source = 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")); + assert!(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()); + assert!(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 generated = 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\"); }}" ); @@ -93,8 +99,35 @@ fn malformed_utf8_catalogs_and_invalid_rows_fail_during_generation() { 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:?}"); + assert!(generate(Some(&fixture.0), required).is_err(), "accepted {file}: {invalid:?}"); } } } } + +#[test] +fn the_catalog_characters_are_the_ones_the_web_font_keeps() { + 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/common.tsv"), "\tSave\tGuardar\n").unwrap(); + std::fs::create_dir_all(fixture.0.join("locales/ja")).unwrap(); + std::fs::write(fixture.0.join("locales/ja/texturecraft.tsv"), "\tLayers\t\u{30ec}\u{30a4}\u{30e4}\u{30fc}\n").unwrap(); + // A shared-only locale contributes no characters: its catalog is not embedded. + std::fs::create_dir_all(fixture.0.join("locales/de")).unwrap(); + std::fs::write(fixture.0.join("locales/de/common.tsv"), "\tSave\tSpeichern \u{fc}\n").unwrap(); + + let (source, characters) = i18n_build::collect(Some(&fixture.0), true).unwrap(); + assert!(source.contains("texturecraft.tsv")); + for used in ['L', 'a', 'y', 'e', 'r', 's', 'C', 'p', 'G', 'u', 'd', '\u{30ec}', '\u{30a4}', '\u{30e4}', '\u{30fc}'] { + assert!(characters.contains(&used), "missing {used:?}"); + } + assert!(!characters.contains(&'\u{fc}'), "the shared-only de catalog is not embedded"); + let mut sorted = characters.clone(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted, characters, "sorted and distinct"); + + // Nothing to cut with no checkout: the web build then keeps the faces whole. + assert_eq!(i18n_build::collect(None, false).unwrap().1, Vec::::new()); + assert!(i18n_build::collect(None, true).is_err()); +} diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs new file mode 100644 index 00000000..c4cc3ec7 --- /dev/null +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -0,0 +1,200 @@ +//! Auto-rebake in the app: a settings change rebakes the auto-rebake map alone, in the background + +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; + +/// Frames far past the half-second settle wait, at the harness's quarter-second step +const PAST_THE_SETTLE_FRAMES: usize = 60; + +/// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map +fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serde_json::Value) { + execute(&mut harness.state_mut().session, "bake.settings", ¶ms).unwrap(); +} + +#[test] +fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { + let mut harness = harness(64); + let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.doc.project.texture_sets[0].bake_sources.contains_key(&BakedMap::Position), "the rebake records what it read"); + assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position)); + assert!(std::sync::Arc::ptr_eq(&app.session.baked(0).unwrap().maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} + +#[test] +fn the_progress_footer_names_the_map_the_rebake_makes() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + + let stage = harness.state().session.bake_preview.as_ref().and_then(|preview| preview.stage()); + assert_eq!(stage.map(|stage| (stage.map, stage.total)), Some((BakedMap::Position, 1)), "not the set's first checked map, not all its maps"); +} + +#[test] +fn nothing_is_rebaked_outside_bake_mode() { + let mut harness = harness(64); + harness.state_mut().ui.mode = Mode::Painting; + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + harness.run_steps(120); + + assert!(harness.state().bake.is_none()); + assert!(!harness.state().session.bake_changes(0, BakedMap::Position).is_empty()); +} + +#[test] +fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { + let mut harness = harness(64); + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["ambientOcclusion"], "ao": { "rays": 1 } })).unwrap(); + execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": "ambientOcclusion" })).unwrap(); + + // A slow rebake, so the next change lands while it runs + change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } })); + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + change_settings(&mut harness, json!({ "ao": { "rays": 128 } })); + harness.run_steps(1); + + let app = harness.state(); + assert!(app.bake.is_none(), "the outdated rebake stopped"); + let ambient_occlusion = app.session.bake_log.maps.iter().find(|row| row.map == BakedMap::AmbientOcclusion).map(|row| row.state.clone()); + assert_eq!(ambient_occlusion, Some(BakeMapState::Canceled)); +} + +#[test] +fn a_canceled_rebake_holds_back_only_its_own_texture_set() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + for set in [0, 1] { + execute(&mut session, "bake.autoRebake", &json!({ "ts": set, "map": "position" })).unwrap(); + } + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let rebaking = |app: &TextureCraftApp, set: usize| app.bake.as_ref().and_then(|job| job.rebake.as_ref()).is_some_and(|rebake| rebake.0 == set); + + change_settings(&mut harness, json!({ "ts": "all", "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the first set's rebake", |app| rebaking(app, 0)); + harness.state_mut().cancel_bake(); + + super::step_until(&mut harness, "the second set's rebake", |app| rebaking(app, 1)); +} + +#[test] +fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { + let mut harness = harness(64); + let plane = primitives::builtin("plane").unwrap(); + let mut high = String::from("o Part_high\n"); + for position in &plane.positions { + high += &format!("v {} {} {}\n", position.x, position.y + 0.1, position.z); + } + for triangle in plane.indices.as_chunks::<3>().0 { + high += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1); + } + let session = &mut harness.state_mut().session; + session.add_high_poly_bytes("high.obj", high.into_bytes()).unwrap(); + execute(session, "bake.run", &json!({ "maps": ["position"] })).unwrap(); + harness.run_steps(4); + assert!(harness.state().bake.is_none(), "up to date after the bake"); + + execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} + +#[test] +fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() { + use egui_kittest::kittest::Queryable; + + let mut harness = harness(64); + let auto_rebake = |harness: &Harness<'static, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].auto_rebake; + assert_eq!(auto_rebake(&harness), Some(BakedMap::Position)); + + assert!(harness.query_by_label("Auto-rebake Normal").is_none(), "off: shown only on a hovered, focused or selected row"); + harness.get_by_role_and_label(egui::Role::Button, "Normal").hover(); + harness.run_steps(2); + harness.get_by_label("Auto-rebake Normal"); + + // ID is the selected row (the first checked map), which shows its icons + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), Some(BakedMap::Id), "one map per set: ID replaces Position"); + + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), None); +} + +#[test] +fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_step() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + // Held still well past the settle time, as a hand pausing mid-drag, in the window's corner where no control takes the press + let corner = harness.ctx.content_rect().right_bottom() - egui::vec2(10.0, 10.0); + harness.drag_at(corner); + harness.run_steps(120); + assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts"); + + harness.drop_at(corner); + super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some()); +} + +#[test] +fn a_rebake_canceled_in_one_project_still_runs_in_the_next_project_opened() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + harness.state_mut().cancel_bake(); + harness.run_steps(PAST_THE_SETTLE_FRAMES); + assert!(harness.state().bake.is_none(), "a canceled rebake is not tried again in its project"); + + // The same project opened again: its out-of-date map reads what the canceled one read + let mesh = primitives::builtin("plane").unwrap(); + let mut next = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut next, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut next, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut next, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + harness.state_mut().session.switch_to(next); + + super::step_until(&mut harness, "the rebake in the opened project", |app| app.bake.is_some()); +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 309bb67e..84cf4244 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -1,15 +1,27 @@ -//! 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. +//! 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 dropped; a cancel keeps the maps it finished use std::sync::Arc; use std::sync::atomic::Ordering; +use std::sync::mpsc::Sender; use egui_kittest::Harness; +use texturecraft_engine::StreamedMap; use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; -/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id` fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harness<'static, TextureCraftApp>, &Progress)) { + let (mut harness, progress, _senders) = running_job(mesh_id); + harness.step(); + check(&harness, &progress); +} + +/// The ends a test plays the bake worker with: its result (never sent) and its finished maps +type WorkerSenders = (Sender>, Sender); + +/// An app with a running bake job of set 0 started on mesh `mesh_id`, whose worker sends only what the test sends +fn running_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc, WorkerSenders) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder() .with_size(egui::vec2(1600.0, 960.0)) @@ -17,15 +29,23 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); let progress = Arc::new(Progress::new()); - let (_result_sender, receiver) = std::sync::mpsc::channel(); - let (_map_sender, maps) = std::sync::mpsc::channel(); + let (result_sender, receiver) = std::sync::mpsc::channel(); + let (map_sender, maps) = std::sync::mpsc::channel(); let job_mesh_id = mesh_id(harness.state().session.mesh_id); - let running = - RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; - harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None }); - - harness.step(); - check(&harness, &progress); + let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let running = RunningBake { + set_index: 0, + progress: progress.clone(), + receiver, + maps, + maps_done, + maps_total: 1, + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, + }; + harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); + (harness, progress, (result_sender, map_sender)) } #[test] @@ -49,3 +69,38 @@ fn a_job_on_the_current_mesh_keeps_running() { }, ); } + +#[test] +fn a_cancel_keeps_the_maps_the_worker_sent_before_any_frame_took_them() { + let (mut harness, _progress, (result_sender, map_sender)) = running_job(|current| current); + let data = Arc::new(vec![0.5; 64 * 64]); + let normal_before = harness.state().session.baked(0).and_then(|baked| baked.maps.get(&BakedMap::Normal).cloned()); + assert!(normal_before.is_some(), "the sample's Normal map is baked before the job"); + for (index, map) in [BakedMap::Curvature, BakedMap::AmbientOcclusion].into_iter().enumerate() { + map_sender.send(StreamedMap { map, index, total: 2, resolution: 64, height: 64, data: data.clone() }).unwrap(); + } + result_sender.send(Err(texturecraft_engine::EngineError::BakeCancelled)).unwrap(); + + harness.state_mut().cancel_bake(); + let baked = harness.state().session.baked(0).unwrap(); + for map in [BakedMap::Curvature, BakedMap::AmbientOcclusion] { + assert!(baked.maps.get(&map).is_some_and(|kept| Arc::ptr_eq(kept, &data)), "{map:?} is kept"); + } + let normal = baked.maps.get(&BakedMap::Normal); + assert!(normal.zip(normal_before.as_ref()).is_some_and(|(now, before)| Arc::ptr_eq(now, before)), "a map the worker never sent keeps the one baked before"); +} + +#[test] +fn a_cancel_does_not_keep_maps_from_a_worker_that_already_failed() { + let (mut harness, _progress, (result_sender, map_sender)) = running_job(|current| current); + let map = BakedMap::Normal; + let before = harness.state().session.baked(0).unwrap().maps[&map].clone(); + let data = Arc::new(vec![0.5; 64 * 64 * map.components()]); + map_sender.send(StreamedMap { map, index: 0, total: 2, resolution: 64, height: 64, data }).unwrap(); + result_sender.send(Err(texturecraft_engine::EngineError::Other("the second map failed".into()))).unwrap(); + + harness.state_mut().cancel_bake(); + + let after = &harness.state().session.baked(0).unwrap().maps[&map]; + assert!(Arc::ptr_eq(&before, after), "the failed set leaves the previous bake in place"); +} diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs index 4c7d6c7c..839bbc75 100644 --- a/crates/ui-egui/tests/it/bake_live_preview.rs +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -105,6 +105,31 @@ fn switching_the_preview_off_hides_it() { assert!(!harness.state().session.bake_preview_active()); } +#[test] +fn disabling_live_preview_in_preferences_releases_the_picture_and_can_be_reenabled() { + let mut harness = harness(); + + for resolution in [BakeResolution::R256, BakeResolution::R128] { + let state = harness.state_mut(); + state.ui.bake_visualization.map_preview_size = resolution; + state.ui.prefs.live_preview_baking = true; + + assert!(wait_for_preview(&mut harness, |size| size == resolution.pixels()).is_some()); + let pixels = &harness.state().session.bake_preview_baked(0).unwrap().maps[&BakedMap::AmbientOcclusion]; + let picture = std::sync::Arc::downgrade(pixels); + let bytes = pixels.len() * std::mem::size_of::(); + + harness.state_mut().ui.prefs.live_preview_baking = false; + harness.run_steps(3); + + let remaining_owners = picture.strong_count(); + eprintln!("preview resolution: {resolution:?}, published bytes: {bytes}, owners after disabling: {remaining_owners}"); + assert!(!harness.state().session.bake_preview_active()); + assert_eq!(remaining_owners, 0, "disabling the preview releases its image"); + assert_ne!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion)); + } +} + #[test] fn pictures_keep_coming_while_the_slider_is_still_moving() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 1f7253ac..90d8d5a1 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -595,7 +595,7 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { 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.doc.bake_meshes.cage = - Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new(), fingerprint: 0 }); 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); @@ -697,3 +697,73 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() { assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); } + +#[test] +fn a_click_on_the_middle_of_an_out_of_date_row_selects_its_map_and_bakes_nothing() { + use serde_json::json; + use texturecraft_engine::execute; + + // Use two sets so the row shows all hover icons alongside the out-of-date clock + let mut harness = harness(None); + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_label("Out of date: Ambient Occlusion"); + + select_map(&mut harness, "Ambient Occlusion"); + + assert!(harness.state().bake_progress().is_none(), "the click landed on the row, not its Bake Only icon"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings"); + harness.get_by_label("Attenuation"); +} + +#[test] +fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { + use serde_json::json; + use texturecraft_engine::execute; + + let mesh = texturecraft_engine::geom::primitives::builtin("plane").unwrap(); + let mut session = texturecraft_engine::Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + assert!(harness.query_by_label("Out of date: Position").is_none(), "just baked"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + + let description = harness.get_by_label("Out of date: Position").accesskit_node().description(); + assert!(description.is_some_and(|reasons| !reasons.is_empty()), "what changed is read without hovering"); + assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); +} + +#[test] +fn dragging_secondary_rays_is_one_undo_step() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + select_map(&mut harness, "Ambient Occlusion"); + let rays_before = harness.state().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays; + let history_steps = harness.state().session.history_labels().len(); + + let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect(); + let at = |share: f32| egui::pos2(track.left() + track.width() * share, track.center().y); + + harness.drag_at(at(0.2)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + for step in 1..=3 { + harness.hover_at(at(0.2 + 0.15 * step as f32)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + } + + // The release moves too, and that last change still belongs to the drag + harness.drop_at(at(0.8)); + harness.run_steps(crate::SETTLE_FRAMES); + + let session = &harness.state().session; + assert_ne!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays, rays_before, "the drag changed the rays"); + assert_eq!(session.history_labels().len(), history_steps + 1, "{:?}", session.history_labels()); +} diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs new file mode 100644 index 00000000..a4d456aa --- /dev/null +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -0,0 +1,317 @@ +//! The Baking Log panel: the latest bake, map by map + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +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.select([BakedMap::Id, BakedMap::Position]); + } + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +/// Run frames until the bake ends, then a few more for its result to show +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); +} + +/// Bake sets 0 and 1, where set 1 has no tile left to bake, so its bake fails +fn bake_with_set_1_failing(harness: &mut Harness<'static, TextureCraftApp>, failed_set_maps: &[BakedMap]) { + let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; + set.uv_tiles = vec![1001]; + set.bake_excluded_tiles.insert(1001); + set.bake.maps.select(failed_set_maps.iter().copied()); + + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(harness); +} + +#[test] +fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { + let mut harness = harness(); + assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log"); + + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); + + let names: Vec = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + for map in ["ID", "Position"] { + assert!(harness.query_by_label(&format!("{} {map}, Baked", names[0])).is_some(), "set 0's {map} row is ticked"); + } + assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); +} + +#[test] +fn a_failed_rows_reason_is_read_without_hovering() { + let mut harness = harness(); + + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); + + let app = harness.state(); + let row = app.session.bake_log.maps.iter().find(|row| row.texture_set == 1).unwrap(); + let BakeMapState::Failed(reason) = &row.state else { panic!("set 1's bake failed: {:?}", row.state) }; + + let label = format!("{} ID, Not baked", row.set_name); + let node = harness.get_by_label(&label); + assert_eq!(node.accesskit_node().description().as_deref(), Some(reason.as_str()), "the row's node carries its tooltip's reason"); +} + +#[test] +fn a_one_map_bake_lists_only_that_map() { + let mut harness = harness(); + + harness.state_mut().start_bake_of(vec![0], Some(BakedMap::Position)); + run_to_the_end(&mut harness); + + let name = harness.state().session.doc.project.texture_sets[0].name.clone(); + assert!(harness.query_by_label(&format!("{name} Position, Baked")).is_some(), "the baked map is ticked"); + assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row"); +} + +#[test] +fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() { + let mut harness = harness(); + let before = harness.state().session.baked(0).cloned().unwrap_or_default(); + + harness.state_mut().start_bake(vec![0, 1]); + + // Leaving Bake mode closes the preview; the bake and the maps it finishes go on + harness.state_mut().ui.mode = Mode::Painting; + let state = |app: &TextureCraftApp, set: usize, map: BakedMap| { + app.session.bake_log.maps.iter().find(|row| row.texture_set == set && row.map == map).map(|row| row.state.clone()) + }; + super::step_until(&mut harness, "set 0's first map", |app| state(app, 0, BakedMap::Id) == Some(BakeMapState::Baked)); + assert!(!harness.state().session.bake_preview_active()); + + harness.state_mut().cancel_bake(); + + let app = harness.state(); + assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick"); + for map in [BakedMap::Id, BakedMap::Position] { + assert_eq!(state(app, 1, map), Some(BakeMapState::Canceled), "set 1 was still queued, so its {map:?} warns"); + } + + // The worker may have queued Position before cancellation + let row = state(app, 0, BakedMap::Position); + assert!(matches!(row, Some(BakeMapState::Baked | BakeMapState::Canceled)), "set 0's Position is ticked or, unfinished, warns: {row:?}"); + let after = app.session.baked(0).cloned().unwrap_or_default(); + let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) { + (Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new), + (old, new) => old.is_some() != new.is_some(), + }; + for map in [BakedMap::Id, BakedMap::Position] { + let ticked = state(app, 0, map) == Some(BakeMapState::Baked); + assert_eq!(changed(map), ticked, "set 0's {map:?} is in the document exactly when its row is ticked"); + } +} + +#[test] +fn a_failed_maps_arrow_opens_its_settings() { + let mut harness = harness(); + + // Three rows fit the docked log without scrolling + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Id]); + bake_with_set_1_failing(&mut harness, &[BakedMap::Id, BakedMap::Position]); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + + assert_eq!(harness.state().session.ts(), 0); + assert!(harness.query_by_label("Normalization Scale").is_none(), "Position's settings are not shown yet"); + + let set_name = harness.state().session.doc.project.texture_sets[1].name.clone(); + harness.get_by_label(&format!("Open the {set_name} Position settings")).click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.ts(), 1, "the failed map's texture set is the active one"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "the arrow fronts Mesh Map Settings"); + harness.get_by_label("Normalization Scale"); + assert!( + harness.query_by_label(&format!("Open the {} ID settings", harness.state().session.doc.project.texture_sets[0].name)).is_none(), + "a baked map has no arrow" + ); +} + +/// Put a finished bake of set 0's ID and Position maps in the log, the Position map ending as `position` +fn log_a_bake(harness: &mut Harness<'static, TextureCraftApp>, position: BakeMapState) -> String { + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + let row = |map, state| BakeLogMap { texture_set: 0, set_name: set_name.clone(), map, state }; + harness.state_mut().session.bake_log.maps = vec![row(BakedMap::Id, BakeMapState::Baked), row(BakedMap::Position, position)]; + harness.run_steps(3); + set_name +} + +#[test] +fn the_issues_filter_keeps_only_the_maps_with_a_problem() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into())); + harness.get_by_label(&format!("{set_name} ID, Baked")); + + harness.get_by_label("1, Show only rows with an issue").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out"); + harness.get_by_label(&format!("{set_name} Position, Not baked")); + assert!(harness.query_by_label("Turn off the issues filter to see every row.").is_none(), "an issue left: no empty text"); +} + +#[test] +fn the_issues_filter_says_so_when_nothing_went_wrong() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + + harness.get_by_label("Show only rows with an issue").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none()); + harness.get_by_label("Every map so far baked without a problem."); + harness.get_by_label("Turn off the issues filter to see every row."); + + harness.get_by_label("Show only rows with an issue").click(); + harness.run_steps(3); + + harness.get_by_label(&format!("{set_name} ID, Baked")); + assert!(harness.query_by_label("Every map so far baked without a problem.").is_none(), "off again: every row is back"); +} + +#[test] +fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() { + let mut harness = harness(); + harness.state_mut().session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + harness.get_by_label("ball_high.obj, Loaded"); + let set_row = format!("{set_name}, High poly files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(true)); + + harness.get_by_label(&set_row).click(); + harness.run_steps(3); + + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(false), "the row says it is folded"); +} + +#[test] +fn the_high_poly_tab_counts_and_keeps_its_own_issues() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + let row = |file: &str, state| BakeLogHigh { texture_set: 0, set_name: set_name.clone(), file: file.into(), state }; + harness.state_mut().session.bake_log.highs = vec![row("ball_high.obj", BakeHighState::Loaded), row("bolt_high.obj", BakeHighState::Canceled)]; + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + + harness.get_by_label("1, Show only rows with an issue").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out"); + harness.get_by_label("bolt_high.obj, Canceled"); +} + +#[test] +fn the_matching_tab_lists_the_pairs_and_its_filter_keeps_the_parts_with_no_partner() { + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![pair(Some("Barrel_low"), Some("Barrel_high")), pair(Some("Strap_low"), None)], + }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + harness.get_by_label("Barrel_low, Barrel_high"); + + harness.get_by_label("1, Show only rows with an issue").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("Barrel_low, Barrel_high").is_none(), "a pair is filtered out"); + harness.get_by_label("Strap_low, No match"); +} + +#[test] +fn the_matching_tab_says_when_no_set_matched_by_name() { + let mut harness = harness(); + + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("Set Match to By Mesh Name to pair parts by name.").is_none(), "nothing baked yet: nothing to say"); + + log_a_bake(&mut harness, BakeMapState::Baked); + + harness.get_by_label("Set Match to By Mesh Name to pair parts by name."); +} + +#[test] +fn on_a_narrow_dock_the_tabs_scroll_clear_of_the_issues_filter() { + // A window this narrow leaves the docked log less room than its three tabs and the filter take together + const NARROW_WINDOW_WIDTH: f32 = 520.0; + + let mut harness = Harness::builder() + .with_size(egui::vec2(NARROW_WINDOW_WIDTH, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, texturecraft_engine::sample_session(256, 64).unwrap())); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + let filter = harness.get_by_label("Show only rows with an issue").rect(); + let strip_start = harness.get_by_role_and_label(Role::Tab, "Baking Process").rect().left(); + let last_tab = harness.get_by_role_and_label(Role::Tab, "Matching by Name").rect(); + assert!(last_tab.right() > filter.left(), "unscrolled, the tabs {last_tab:?} run past the filter {filter:?}, so they must scroll"); + + // Frames for the strip's scroll to the focused tab to finish + const SCROLL_FRAMES: usize = 30; + + for tab in ["Baking Process", "High Poly Parameters", "Matching by Name"] { + harness.get_by_role_and_label(Role::Tab, tab).focus(); + harness.run_steps(SCROLL_FRAMES); + + let rect = harness.get_by_role_and_label(Role::Tab, tab).rect(); + assert!(rect.right() <= filter.left(), "the focused {tab} tab {rect:?} ends left of the filter {filter:?}"); + assert!(rect.left() >= strip_start, "the focused {tab} tab {rect:?} starts inside the log, where the first tab starts unscrolled"); + } +} + +#[test] +fn a_matching_name_cut_short_shows_in_full_on_hover() { + const LONG_NAME: &str = "Left_shoulder_strap_buckle_with_its_rivets_and_its_stitching_low"; + + // Frames past the tooltip delay + const TOOLTIP_FRAMES: usize = 60; + + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = NamePair { low: Some(LONG_NAME.into()), high: Some("Strap_high".into()) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { low_suffix: "_low".into(), high_suffix: "_high".into(), pairs: vec![pair] }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + + let label = format!("{LONG_NAME}, Strap_high"); + let row = harness.get_by_label(&label).rect(); + assert_eq!(harness.query_all_by_label(&label).count(), 1, "no tooltip before hovering"); + + harness.hover_at(row.center()); + harness.run_steps(TOOLTIP_FRAMES); + + assert_eq!(harness.query_all_by_label(&label).count(), 2, "the tooltip carries both names in full"); +} diff --git a/crates/ui-egui/tests/it/display_environment.rs b/crates/ui-egui/tests/it/display_environment.rs index eab3f207..e00dd9fa 100644 --- a/crates/ui-egui/tests/it/display_environment.rs +++ b/crates/ui-egui/tests/it/display_environment.rs @@ -110,7 +110,7 @@ fn an_image_dropped_on_the_slot_becomes_the_environment() { h.run_steps(SETTLE); let slot = h.get_by_role_and_label(Role::Button, "Studio Soft").rect().center(); - egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); h.hover_at(slot); h.run_steps(2); h.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index debb9ba9..822525f0 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -7,6 +7,8 @@ use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; use texturecraft_ui_egui::TextureCraftApp; +use super::layers_panel::click_selected_content_thumbnail; + fn id(v: Value, key: &str) -> u64 { v[key].as_u64().unwrap() } @@ -42,6 +44,7 @@ fn dragging_an_effect_row_reorders_its_stack() { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); 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]); @@ -74,6 +77,7 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); 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); @@ -123,6 +127,7 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); 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(); @@ -165,6 +170,7 @@ fn an_effect_rows_blending_options_reach_every_channel() { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); assert_eq!(effect_of(&harness).blend_of(Some(Channel::Roughness)).mode, BlendMode::Normal); diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index d7be9973..d2edee62 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -2,15 +2,21 @@ //! name pattern, and its own file type and bit depth. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable as _; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; +use super::temp_dir::TempDir; + /// The Export textures window open on the first texture set's page fn harness() -> Harness<'static, TextureCraftApp> { + harness_at(egui::vec2(1600.0, 960.0)) +} + +fn harness_at(size: egui::Vec2) -> 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)) + .with_size(size) .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); @@ -48,25 +54,57 @@ fn plan(h: &mut Harness<'_, TextureCraftApp>) -> Vec { fn the_rows_show_each_map_with_its_pattern_and_file_type() { let mut h = harness(); let rows = plan(&mut h).len(); + assert!(h.query_by_label("Output maps").is_some()); // Four rows of General Export Parameters, then one per map - assert_eq!(h.get_all_by_label("Enable override").count(), 4 + rows); + assert_eq!(h.get_all_by_label_contains("Enable override for ").count(), 4 + rows); assert!(h.query_all_by_label("png 8 bits").next().is_some()); assert!(h.query_all_by_label("png 16 bits").next().is_some(), "height is 16-bit in the default template"); - // A pattern longer than the column is cut at the front, the whole one is its tooltip + // A pattern longer than the column (the packed template's) is cut at the front, the whole one is its tooltip + h.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + h.run_steps(4); let preset = texturecraft_engine::formats::builtin_preset(&h.state().ui.export.preset).unwrap(); - let long = - plan(&mut h).iter().map(|f| preset.maps[f["map"].as_u64().unwrap() as usize].file.clone()).find(|p| p.chars().count() > 26).expect("a long pattern"); - let cut: String = format!("…{}", long.chars().skip(long.chars().count() - 25).collect::()); + let long = preset.maps.iter().map(|map| map.file.clone()).max_by_key(|file| file.chars().count()).unwrap(); + let cut = h + .query_all_by_label_contains("…") + .find_map(|node| node.accesskit_node().value().filter(|text| long.ends_with(text.trim_start_matches('…')))) + .expect("the pattern's end, cut at the front"); assert!(h.query_by_label(&long).is_none(), "{long} is cut"); - let at = h.get_all_by_label(&cut).next().unwrap().rect().center(); + let at = h.get_all_by_role_and_label(egui::Role::Label, &cut).next().unwrap().rect().center(); h.hover_at(at); h.run_steps(30); + assert!(h.query_by_label(&long).is_some(), "the tooltip has the whole {long}"); } +#[test] +fn feedback_psd_preflight_keeps_map_controls_available() { + let mut h = harness(); + let available = plan(&mut h).len(); + assert!(available >= 3); + let preset = h.state().ui.export.preset.clone(); + let settings = &mut h.state_mut().ui.export; + settings.format = "psd".into(); + settings.bit_depth = 16; + settings.size = 8192; + let params = serde_json::json!({"ts": 0, "preset": preset, "format": "psd", "bitDepth": 16, "size": 8192}); + + let error = texturecraft_engine::execute(&mut h.state_mut().session, "export.plan", ¶ms).unwrap_err(); + assert!(error.to_string().contains("2 GiB"), "{error}"); + h.run_steps(4); + + assert_eq!(h.get_all_by_label_contains("Enable override for map ").count(), available); + let size = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list"); + size.click(); + h.run_steps(4); + click(&mut h, "128x128"); + + assert!(maps(&h).values().any(|map| map.size == Some(128))); + assert_eq!(h.state().ui.export.size, 8192); +} + #[test] fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { let mut h = harness(); @@ -77,21 +115,25 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { let boxes = h.get_all_by_role(egui::Role::CheckBox).count(); h.get_all_by_role(egui::Role::CheckBox).nth(boxes - rows).unwrap().click(); h.run_steps(4); + assert_eq!(selected(&h), before - 1); assert_eq!(maps(&h).values().filter(|m| !m.enabled).count(), 1); assert!(h.query_by_label("*").is_none(), "a left-out map is not an override"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); + assert_eq!(selected(&h), before - rows); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Invert all"); + assert_eq!(selected(&h), before); assert!(!h.state().ui.export.sets.contains_key(&0), "nothing left to remember"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); click(&mut h, "Include all"); + assert_eq!(selected(&h), before, "Include all ticks the output maps too"); } @@ -99,18 +141,21 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { fn a_map_override_sets_its_own_file_type_and_marks_the_set() { let mut h = harness(); let rows = plan(&mut h).len(); - h.get_all_by_label("Enable override").nth(4).unwrap().click(); + h.get_all_by_label_contains("Enable override for ").nth(4).unwrap().click(); h.run_steps(4); let m = maps(&h); let (_, first) = m.iter().next().unwrap(); + assert!(first.file_type.is_some(), "{m:?}"); assert!(h.query_by_label("*").is_some(), "the set is marked"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Override every item"); + assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Clear all overrides"); + assert!(maps(&h).is_empty()); } @@ -118,11 +163,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { fn export_writes_a_map_with_its_own_file_type() { let mut h = harness(); let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; - let dir = std::env::temp_dir().join(format!("tc-export-map-overrides-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = TempDir::new("export-map-overrides"); let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }) }); + o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); let e = &mut h.state_mut().ui.export; e.dir = dir.display().to_string(); e.sets.insert(0, o); @@ -139,9 +183,9 @@ fn export_writes_a_map_with_its_own_file_type() { h.run_steps(1); } h.run_steps(2); - let names: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + let names: Vec = std::fs::read_dir(&*dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.iter().filter(|n| n.ends_with(".tga")).count(), 1, "{names:?}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -150,9 +194,10 @@ fn a_map_the_template_no_longer_has_is_ignored() { let before = selected(&h); let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(999, MapExport { enabled: false, file_type: None }); + o.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); h.state_mut().ui.export.sets.insert(0, o); h.run_steps(3); + assert_eq!(selected(&h), before, "the export still plans every file"); } @@ -166,3 +211,91 @@ fn each_row_names_its_own_map() { assert!(h.query_all_by_label_contains(&format!("_{id}")).next().is_some(), "a row for {id}"); } } + +#[test] +fn texture_set_map_sizes_are_reachable_on_a_narrow_screen() { + let mut h = harness_at(egui::vec2(800.0, 480.0)); + let header = h.get_by_label("General Export Parameters").rect().center(); + let size_rect = |h: &Harness<'_, TextureCraftApp>| { + h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map size list").rect() + }; + let before = size_rect(&h); + + h.hover_at(header); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-500.0, -200.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(12); + + let after = size_rect(&h); + + assert!(after.left() < before.left(), "{before:?} → {after:?}"); + assert!(h.ctx.content_rect().contains_rect(after), "{after:?}"); + h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).unwrap().click(); + h.run_steps(4); + click(&mut h, "128x128"); + + assert!(maps(&h).values().any(|map| map.size == Some(128))); +} + +#[test] +fn a_map_picks_its_own_size_and_the_export_writes_it_at_that_size() { + let mut h = harness(); + let expected = plan(&mut h); + let first = expected[0]["map"].as_u64().unwrap() as usize; + let combo = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list"); + combo.click(); + h.run_steps(4); + click(&mut h, "128x128"); + + assert_eq!(maps(&h).get(&first).and_then(|map| map.size), Some(128), "{:?}", maps(&h)); + assert!(h.query_by_label("*").is_some(), "the set is marked"); + + let dir = TempDir::new("export-map-sizes"); + let set_count = h.state().session.set_count(); + let export = &mut h.state_mut().ui.export; + export.dir = dir.display().to_string(); + export.skip = (1..set_count).collect(); + h.run_steps(3); + click(&mut h, "Export"); + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + + h.run_steps(1); + } + h.run_steps(2); + + assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), expected.len()); + for file in expected { + let path = dir.join(file["file"].as_str().unwrap()); + let side = if file["map"].as_u64().unwrap() as usize == first { 128 } else { 256 }; + + assert_eq!(image::image_dimensions(&path).unwrap(), (side, side), "{}", path.display()); + } +} + +#[test] +fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() { + let mut h = harness(); + let rows: Vec = plan(&mut h).iter().take(2).map(|file| file["map"].as_u64().unwrap() as usize).collect(); + let template = h.state().ui.export.preset.clone(); + let mut o = SetExport { maps_template: template, ..SetExport::default() }; + for map in &rows { + o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None }); + } + h.state_mut().ui.export.sets.insert(0, o); + h.run_steps(4); + + let greyed: Vec<_> = + h.get_all_by_role(egui::Role::ComboBox).filter(|node| node.value().as_deref() == Some("32f bits")).map(|node| node.accesskit_node().id()).collect(); + + assert_eq!(rows.len(), 2); + assert_eq!(greyed.len(), 2, "each row's greyed bit depth list is its own node"); + assert_ne!(greyed[0], greyed[1]); +} diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index c2eee653..3579ece6 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -33,13 +33,13 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { /// Open the General Export Parameters menu fn page_menu(h: &mut Harness<'_, TextureCraftApp>) { - h.get_all_by_label(egui_phosphor::regular::LIST_CHECKS).nth(1).unwrap().click(); + h.get_by_label("General Export Parameters menu").click(); h.run_steps(4); } /// The `row`th "Enable override" button (Output template, File type, Size, Padding) fn toggle(h: &mut Harness<'_, TextureCraftApp>, row: usize) { - h.get_all_by_label("Enable override").nth(row).unwrap().click(); + h.get_all_by_label_contains("Enable override for ").nth(row).unwrap().click(); h.run_steps(4); } @@ -63,8 +63,9 @@ fn png_width(path: &std::path::Path) -> u32 { #[test] fn a_texture_set_page_shows_what_it_inherits() { let h = harness(); + assert_eq!(h.state().ui.export.page, Some(0)); - assert!(h.get_all_by_label("Enable override").count() >= 4, "four rows, then the output maps"); + assert!(h.get_all_by_label_contains("Enable override for ").count() >= 4, "four rows, then the output maps"); let own = h.state().session.doc.project.texture_sets[0].resolution; for text in ["Document channels + Normal + AO (No Alpha)", "Based on output template", &format!("{own}x{own} (Texture Set size)"), "Dilation infinite"] { assert!(h.query_by_label(text).is_some(), "{text}"); @@ -302,3 +303,19 @@ fn an_empty_file_type_override_keeps_the_template_types_under_a_global_one() { h.run_steps(4); assert!(h.query_all_by_label("png 16 bits").next().is_some(), "the set still writes the template's types"); } + +#[test] +fn keyboard_size_override_changes_only_the_size_row() { + let mut harness = harness(); + let size = harness.state().session.doc.project.texture_sets[0].block_resolution(); + + harness.get_by_role_and_label(egui::Role::Button, "Enable override for Size").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Space); + harness.run_steps(4); + + let settings = overrides(&harness); + + assert_eq!(settings.size, Some(size)); + assert!(settings.preset.is_none() && settings.file_type.is_none() && settings.padding.is_none() && settings.maps.is_empty()); +} diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index ddcb5bca..ec4bf518 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -2,6 +2,7 @@ //! progress bar with Cancel Export, and the window staying open. use egui_kittest::Harness; +use egui_kittest::kittest::NodeT; use egui_kittest::kittest::Queryable as _; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; @@ -50,6 +51,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { assert_eq!(h.state().ui.export.tab, 2, "Export switches to LIST OF EXPORTS"); h.run_steps(1); assert!(h.query_by_label("Cancel Export").is_some()); + assert_eq!(h.get_by_role(egui::Role::ProgressIndicator).accesskit_node().live(), egui::accesskit::Live::Polite); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export")); @@ -134,7 +136,7 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some()); assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some()); assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none()); - assert!(h.query_by_label("CONSOLE").is_some()); + assert!(h.query_by_label("Console").is_some()); // A row's tooltip is the full path let preset = h.state().ui.export.preset.clone(); @@ -143,17 +145,50 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { let at = h.get_by_label(&file).rect().center(); h.hover_at(at); h.run_steps(30); + assert!(h.query_by_label(&dir.join(&file).display().to_string()).is_some()); // The strip at the console's edge hides it, then shows it again h.get_by_role_and_label(egui::Role::Button, "Hide Console").click(); h.run_steps(4); - assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none()); + + assert!(h.state().ui.export.console_hidden && h.query_by_label("Console").is_none()); h.get_by_role_and_label(egui::Role::Button, "Show Console").click(); h.run_steps(4); + assert!(!h.state().ui.export.console_hidden); } +#[test] +fn long_filenames_leave_the_export_details_reachable_by_scrolling() { + let (mut h, _) = harness("wide-tree"); + let name = "Wide".repeat(44); + h.state_mut().session.doc.project.texture_sets[0].name.clone_from(&name); + h.state_mut().ui.export.tab = 2; + h.run_steps(4); + let bits_label = "16 bits"; + let bits_fit = |h: &Harness<'_, TextureCraftApp>| { + h.output().shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == bits_label => clipped.clip_rect.contains_rect(text.visual_bounding_rect()), + _ => false, + }) + }; + assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport"); + h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).focus(); + h.run_steps(3); + assert!(h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).is_focused()); + + for _ in 0..12 { + h.key_press(egui::Key::ArrowRight); + h.run_steps(2); + } + h.run_steps(10); + + assert!(bits_fit(&h), "horizontal keyboard scrolling brings bit depth into the viewport"); + assert!(h.query_all_by_label(bits_label).next().is_some(), "bit depth has an accessibility label"); + assert!(h.query_by_label("Console").is_some()); +} + #[test] fn open_output_directory_asks_the_system_to_show_the_folder() { let (mut h, dir) = harness("open"); @@ -220,6 +255,40 @@ fn texture_sets_writing_the_same_file_name_do_not_start_an_export() { let _ = std::fs::remove_dir_all(&library); } +#[test] +fn a_texture_set_cannot_export_into_another_sets_psd_file() { + use texturecraft_ui_egui::state::SetExport; + + let (mut h, _) = harness("psd-folder-clash"); + let scratch = tempfile::tempdir().unwrap(); + let dir = scratch.path().join("textures"); + let library = tempfile::tempdir().unwrap(); + let app = h.state_mut(); + app.ui.export.dir = dir.display().to_string(); + app.session.load_export_presets(library.path().to_path_buf()); + let psd = json!({"name": "Layered", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": psd})).unwrap(); + let plan = app.run("export.plan", json!({"preset": "Layered", "ts": 0})).unwrap(); + let file_name = plan[0]["file"].as_str().unwrap(); + let nested = json!({"name": "Nested", "maps": [ + {"file": format!("{file_name}/detail"), "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": nested})).unwrap(); + app.ui.export.preset = "Layered".into(); + app.ui.export.sets.insert(1, SetExport { preset: Some("Nested".into()), ..Default::default() }); + h.run_steps(4); + + click(&mut h, "Export"); + finish(&mut h); + + assert!(h.state().ui.export.job.is_none()); + assert_eq!(exports(&h), 0, "the full selection must be checked before starting"); + assert!(!dir.exists()); + assert!(console(&h).iter().any(|line| line.contains("folder")), "{:?}", console(&h)); +} + #[test] fn opening_another_project_stops_the_export() { let (mut h, dir) = harness("project"); diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index c33be805..041174fb 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -52,7 +52,7 @@ fn the_window_has_the_reference_size() { let h = harness(egui::vec2(1600.0, 960.0)); let reset = window_button_rect(&h, "Reset all", 1600.0); let export = window_button_rect(&h, "Export", 1600.0); - let tabs = h.get_by_label("SETTINGS").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Settings").rect(); let width = export.max.x - reset.min.x; let height = export.max.y - tabs.min.y; diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 749bab18..d3309e43 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -75,6 +75,47 @@ fn closing_the_window_is_cancel() { assert_eq!(h.state().ui.export.size, 0); } +#[test] +fn escape_is_cancel() { + let mut h = harness(); + h.state_mut().ui.export.size = 2048; + h.run_steps(3); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0, "the opening settings are back"); +} + +#[test] +fn escape_cancels_when_a_button_has_keyboard_focus() { + let mut h = harness(); + h.get_by_role_and_label(egui::Role::Button, "Save settings").focus(); + h.run_steps(4); + + assert!(h.get_by_role_and_label(egui::Role::Button, "Save settings").is_focused()); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); +} + +#[test] +fn escape_in_an_open_dropdown_closes_only_the_dropdown() { + let mut h = harness(); + open_combo(&mut h, "Based on output template"); + + assert!(h.query_by_label("png").is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.query_by_label("png").is_none(), "the dropdown closed"); + assert!(h.state().ui.windows.export, "the window stays open"); +} + #[test] fn the_lists_hold_the_reference_entries() { let mut h = harness(); @@ -122,15 +163,18 @@ fn a_saved_legacy_preset_name_resolves_to_its_current_name() { fn the_set_list_menu_checks_unchecks_and_inverts() { let mut h = harness(); let sets = h.state().session.set_count(); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Uncheck all"); + assert_eq!(h.state().ui.export.skip.len(), sets); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Invert all"); + assert!(h.state().ui.export.skip.is_empty()); h.state_mut().ui.export.skip = vec![0]; - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Check all"); + assert!(h.state().ui.export.skip.is_empty()); } @@ -140,9 +184,8 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { let default = h.state().ui.export.dir.clone(); h.state_mut().ui.export.dir = "/somewhere/else".into(); h.run_steps(3); - hover(&mut h, "R"); - assert!(h.query_by_label("Reset to default").is_some()); - click(&mut h, "R"); + click(&mut h, "Reset to default"); + assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); @@ -152,11 +195,13 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { hover(&mut h, "16"); assert!(h.query_all_by_label("Dilation in pixels").next().is_some()); click(&mut h, "16"); + assert!(h.query_by_label("Dilation (pixels)").is_some()); // A click on the slider sets the width and leaves the menu open h.get_by_role(egui::Role::Slider).click(); h.run_steps(4); + assert_ne!(h.state().ui.export.dilation, 16); assert!(h.query_by_label("Dilation (pixels)").is_some(), "the menu stays open"); } @@ -174,3 +219,24 @@ fn the_page_reset_puts_the_parameters_back() { assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); } + +#[test] +fn feedback_escape_clears_a_pick_before_cancelling_export() { + let mut h = harness(); + let pick = egui::Id::unique("export_escape_screen_color_pick"); + h.state_mut().picking_color = Some(pick); + h.state_mut().ui.export.size = 512; + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().picking_color.is_none(), "the armed pick receives Escape first"); + assert!(h.query_by_role_and_label(egui::Role::Button, "Save settings").is_some()); + assert_eq!(h.state().ui.export.size, 512); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0); +} diff --git a/crates/ui-egui/tests/it/export_shader_parameters.rs b/crates/ui-egui/tests/it/export_shader_parameters.rs new file mode 100644 index 00000000..7480cd63 --- /dev/null +++ b/crates/ui-egui/tests/it/export_shader_parameters.rs @@ -0,0 +1,44 @@ +//! Export textures › SETTINGS: Export shader settings writes `_shaders.json`, the +//! shader's settings and every texture set of the export, with the export's last texture set + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; + +use super::temp_dir::TempDir; + +#[test] +fn ticking_export_shader_settings_writes_the_json_listing_every_exported_set() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + let dir = TempDir::new("export-shader-parameters"); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + + h.get_by_role_and_label(egui::Role::CheckBox, "Export shader settings").click(); + h.run_steps(4); + + assert!(h.state().ui.export.shader_parameters); + h.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + h.run_steps(1); + if h.state().ui.export.job.is_none() { + break; + } + } + h.run_steps(2); + + let project = &h.state().session.doc.project; + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&project.name)); + let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap_or_else(|_| panic!("{} was written", file.display()))).unwrap(); + let names: Vec<&str> = project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + + assert_eq!(json["shaders"][0]["textureSets"], serde_json::json!(names), "every texture set of the export, written once: {json}"); + assert!(json["shaders"][0]["parameters"]["ior"].is_number()); +} diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 76aa9e39..f9a72c03 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -3,7 +3,7 @@ use egui::Key; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; @@ -169,3 +169,20 @@ fn the_settings_dropdown_asks_about_an_unfinished_edit_too() { texturecraft_ui_egui::export_templates::select(h.state_mut(), "Beta tpl".into()); assert_eq!(selected(&h), "Beta tpl", "a valid edit switches at once"); } + +#[test] +fn output_templates_keeps_export_and_save_until_an_edit_does_not_validate() { + let library = Library::new("footer-on-templates"); + let mut h = harness(&library); + + // The window's footer is drawn after the app's own menus, which have an Export too + let disabled = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_all_by_label(label).last().unwrap().accesskit_node().is_disabled(); + + assert!(!disabled(&h, "Export"), "Export works from the templates tab"); + assert!(!disabled(&h, "Save settings"), "Save settings works from the templates tab"); + + break_draft(&mut h); + + assert!(disabled(&h, "Export"), "an invalid edit holds Export"); + assert!(disabled(&h, "Save settings"), "an invalid edit holds Save settings"); +} diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index bfde2258..9e0cbdd5 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -1,6 +1,7 @@ //! Native file dialogs answer on a later frame; the tests answer them without a window. use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; use egui::{ViewportCommand, ViewportEvent, ViewportId}; use egui_kittest::Harness; @@ -10,6 +11,8 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; use texturecraft_ui_egui::state::Unsaved; +use super::temp_dir::TempDir; + fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; @@ -225,7 +228,7 @@ fn a_mesh_change_keeps_the_answer_for_the_same_project() { 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); + wait_for(&mut h, |h| h.state().session.path.as_deref() == file.to_str()); assert!(file.exists(), "a reimport or a UV layout change is still the same project"); } @@ -244,6 +247,15 @@ fn sends(h: &mut Harness<'_, TextureCraftApp>, frames: usize, cmd: &ViewportComm }) } +fn wait_for(h: &mut Harness<'_, TextureCraftApp>, ready: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) { + let deadline = Instant::now() + Duration::from_secs(10); + while !ready(h) { + assert!(Instant::now() < deadline, "save did not finish"); + h.step(); + std::thread::yield_now(); + } +} + fn untitled_with_prompt(h: &mut Harness<'_, TextureCraftApp>) { h.state_mut().session.path = None; request_close(h); @@ -263,16 +275,68 @@ fn closing_during_a_stroke_finishes_it_and_asks() { #[test] fn save_in_the_prompt_goes_on_once_the_dialog_has_saved() { - let file = temp_file("prompt-save", "saved.tcraft"); + let temp = TempDir::new("prompt-save"); + for untitled in [true, false] { + let file = temp.join(if untitled { "new.tcraft" } else { "existing.tcraft" }); + let mut h = harness(true); + h.state_mut().session.path = (!untitled).then(|| file.display().to_string()); + + request_close(&mut h); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + h.get_by_label("Save").click(); + wait_for(&mut h, |h| h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close))); + + assert!(file.exists()); + assert!(!h.state().session.modified); + assert!(h.state().ui.windows.unsaved.is_none()); + } +} + +#[test] +fn a_background_save_preserves_edits_made_while_the_file_is_written() { + let temp = TempDir::new("save-edits"); + let file = temp.join("project.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()); + h.state_mut().session.path = Some(file.display().to_string()); + let original = h.state().session.doc.project.texture_sets[0].name.clone(); + + invoke(&mut h, "file.save"); + assert!(!texturecraft_ui_egui::menus::enabled(h.state(), "file.save"), "the save returns with a worker still to collect"); + let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"})); + assert!(rename.is_some(), "editing remains available"); + + wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save")); + + let saved = texturecraft_engine::formats::load_project(&file).unwrap(); + assert_eq!(saved.project.texture_sets[0].name, original, "the first save writes the snapshot it started with"); + assert_eq!(h.state().session.doc.project.texture_sets[0].name, "Edited while saving"); + assert!(h.state().session.modified, "the later edit still needs to be saved"); + + invoke(&mut h, "file.save"); + h.state_mut().run("camera.view.front", serde_json::Value::Null); + wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save")); + + let saved = texturecraft_engine::formats::load_project(&file).unwrap(); + assert_eq!(saved.project.texture_sets[0].name, "Edited while saving"); + assert!(!h.state().session.modified, "moving the camera alone does not create an unsaved edit"); +} + +#[test] +fn a_failed_background_save_keeps_the_project_and_its_path() { + let temp = TempDir::new("save-failure"); + let file = temp.join("current.tcraft"); + let missing_parent = temp.join("missing").join("as.tcraft"); + let mut h = harness(true); + h.state_mut().session.path = Some(file.display().to_string()); + answer(&mut h, move |_| Answer::Paths(vec![missing_parent.clone()])); + + invoke(&mut h, "file.saveAs"); + wait_for(&mut h, |h| h.state().toasts.iter().any(|toast| toast.error)); + + assert!(h.state().session.modified); + assert_eq!(h.state().session.path.as_deref(), file.to_str()); + assert!(texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs")); } #[test] diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs new file mode 100644 index 00000000..6b7cb008 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -0,0 +1,84 @@ +//! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask +fn harness() -> Harness<'static, TextureCraftApp> { + harness_with("curvature") +} + +/// A plane whose bake makes only the position map, with a `generator` selected in a fill layer's mask +fn harness_with(generator: &str) -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + 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(); + execute(&mut session, "effect.add.generator", &json!({ "generator": generator })).unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .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 +} + +/// Run frames until the bake ends, then a few more for its result to show +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); +} + +#[test] +fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() { + let mut harness = harness(); + let description = harness.get_by_label("Curvature map not baked").accesskit_node().description(); + assert!(description.is_some_and(|reasons| !reasons.is_empty()), "why the note shows is read without hovering"); + + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap(); + harness.run_steps(3); + + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); + assert!(harness.query_by_label("Curvature map out of date").is_none(), "baked: no note"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + + harness.get_by_label("Curvature map out of date"); +} + +#[test] +fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() { + let mut harness = harness(); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature)); + + harness.get_by_label("Bake").click(); + harness.run_steps(1); + + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature), "turned on"); + assert!(harness.state().bake.is_some(), "a background bake started"); + + run_to_the_end(&mut harness); + + assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature))); + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); +} + +#[test] +fn rust_runoff_notes_the_occlusion_it_reads_though_no_input_replaces_it() { + let harness = harness_with("Dripping Rust"); + harness.get_by_label("Ambient Occlusion map not baked"); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 55d3879a..a2032fd2 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -1,5 +1,5 @@ -//! 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. +//! The Layers panel rows: thumbnails select and disclose their own effects without editing the +//! document, and the thumbnail images arrive from the worker. use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -43,11 +43,12 @@ fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2 /// The accessible name of the mask thumbnail of the layer "Masked fill" const MASK_THUMBNAIL_NAME: &str = "Select the mask (Alt+click: show it in the viewport, Shift+click: switch it on or off) (Masked fill)"; -/// 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); +/// Toggle the effect rows through the selected layer's content thumbnail. +pub(super) fn click_selected_content_thumbnail(h: &mut Harness<'_, TextureCraftApp>) { + let layer = h.state().session.selected_layer().unwrap(); + let name = &h.state().session.doc.project.layers[&layer].name; + h.get_by_label(&format!("Select the layer content ({name})")).click(); + h.run_steps(3); } fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { @@ -56,36 +57,135 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { h.run_steps(3); } +/// An instance without a mask of its own shows its source's mask thumbnail with the effect badge, so +/// that thumbnail opens the source mask's effects and each of those rows can be selected from the instance. #[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(); +fn an_instance_mask_thumbnail_opens_the_inherited_mask_effects() { + let (mut h, source) = harness(); + let instance = LayerId(id(execute(&mut h.state_mut().session, "layer.instance", &json!({"layer": source.0})).unwrap(), "layer")); + execute(&mut h.state_mut().session, "layer.rename", &json!({"layer": instance.0, "name": "Instance row"})).unwrap(); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap(); + h.run_steps(4); + assert!(h.state().session.doc.project.layers[&instance].mask.is_none(), "the instance draws with its source's mask"); + assert!(h.query_by_label("Effect M").is_none(), "stacks start closed"); + + let mask = thumb(&h, "Instance row", true); + click(&mut h, mask); + assert_eq!(h.state().session.selected_layer(), Some(instance)); + assert_eq!(h.state().session.target, StackTarget::Mask); + assert!(h.query_by_label("Effect M").is_some(), "the inherited mask effect is listed"); + click(&mut h, mask); + assert!(h.query_by_label("Effect M").is_none(), "the same thumbnail closes the stack"); + click(&mut h, mask); + + // Select the effect through the instance + let row = h.get_by_label("Effect M").rect(); click(&mut h, row.center()); - assert!(matches!(h.state().session.target, StackTarget::Effect(_))); + + let StackTarget::Effect(effect) = h.state().session.target else { panic!("{:?}", h.state().session.target) }; + assert_eq!(h.state().session.doc.project.effect(effect).map(|(owner, _)| owner), Some(source)); + assert_eq!(h.state().session.selected_layer(), Some(instance)); + assert!(h.query_by_label("Effect M").is_some(), "selecting an effect leaves its stack open"); +} + +/// An instance with a mask of its own lists that mask's effects, not its source's. +#[test] +fn an_instance_with_its_own_mask_opens_its_own_mask_effects() { + let (mut h, source) = harness(); + let instance = LayerId(id(execute(&mut h.state_mut().session, "layer.instance", &json!({"layer": source.0})).unwrap(), "layer")); + execute(&mut h.state_mut().session, "layer.rename", &json!({"layer": instance.0, "name": "Instance row"})).unwrap(); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap(); + execute(&mut h.state_mut().session, "mask.add.black", &Value::Null).unwrap(); + execute(&mut h.state_mut().session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Own effect"})).unwrap(); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap(); + h.run_steps(4); + + let mask = thumb(&h, "Instance row", true); + click(&mut h, mask); + + assert!(h.query_by_label("Own effect").is_some(), "the instance's own mask effect is listed"); + assert!(h.query_by_label("Effect M").is_none(), "the source's mask effect is not"); } #[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"); +fn mask_and_content_thumbnails_toggle_their_own_stacks() { + let (mut h, layer) = harness(); + let content = thumb(&h, "Masked fill", false); + let mask = thumb(&h, "Masked fill", true); + assert!(h.query_by_label("Effect A").is_none() && h.query_by_label("Effect M").is_none(), "stacks start closed"); + + click(&mut h, mask); + assert_eq!(h.state().session.selected_layer(), Some(layer)); + assert_eq!(h.state().session.target, StackTarget::Mask); + assert!(h.query_by_label("Effect M").is_some()); + click(&mut h, mask); + assert!(h.query_by_label("Effect M").is_none(), "the same mask thumbnail closes its stack"); + click(&mut h, mask); + assert!(h.query_by_label("Effect M").is_some()); + + click(&mut h, content); + assert_eq!(h.state().session.target, StackTarget::Content); + assert!(h.query_by_label("Effect M").is_none(), "switching thumbnails closes the mask stack"); + assert!(h.query_by_label("Effect A").is_some()); + click(&mut h, content); + assert!(h.query_by_label("Effect A").is_none(), "the same content thumbnail closes its stack"); + click(&mut h, content); + let row = h.get_by_label("Effect A").rect(); + click(&mut h, row.center()); + assert!(matches!(h.state().session.target, StackTarget::Effect(_))); + assert!(h.query_by_label("Effect A").is_some(), "selecting an effect leaves its stack open"); +} + +#[test] +fn keyboard_toggles_effects_without_editing_the_document() { + let (mut h, layer) = harness(); + let session = &h.state().session; + let (project, history, modified) = (session.doc.project.clone(), session.history_labels(), session.modified); + let content = "Select the layer content (Masked fill)"; + assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(false)); + + // Use the standard button keys so both paths preserve focus + h.get_by_label(content).focus(); + h.run_steps(3); + assert!(h.get_by_label(content).is_focused()); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.query_by_label("Effect A").is_some()); + h.key_press(egui::Key::Space); + h.run_steps(3); + assert!(h.query_by_label("Effect A").is_none()); + assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(false)); + + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.get_by_label(content).is_focused()); + assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(true)); + + let session = &h.state().session; + let empty = session.doc.project.texture_sets[session.ts()] + .stack + .iter() + .rev() + .find_map(|id| { + let layer = session.doc.project.layers.get(id)?; + (layer.mask.is_none() && layer.content_effects.is_empty()).then(|| (*id, layer.name.clone())) + }) + .expect("sample contains an empty paint layer"); + let empty_thumbnail = format!("Select the layer content ({})", empty.1); + h.get_by_label(&empty_thumbnail).focus(); + h.run_steps(3); + assert!(h.get_by_label(&empty_thumbnail).is_focused()); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(h.state().session.selected_layer(), Some(empty.0)); + assert_ne!(empty.0, layer); + assert!(h.query_by_label("Effect A").is_none() && h.query_by_label("Effect M").is_none(), "switching layers closes the old stack"); + assert_eq!(h.get_by_label(&empty_thumbnail).accesskit_node().data().is_expanded(), None); + + let session = &h.state().session; + assert_eq!(session.doc.project, project); + assert_eq!(session.history_labels(), history); + assert_eq!(session.modified, modified); } #[test] @@ -93,14 +193,15 @@ 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 effect = h.state().session.doc.project.layers[&layer].content_effects[0].id; + let stage = ThumbTarget::Stage { effect, channel: Channel::BaseColor }; + click_selected_content_thumbnail(&mut h); let t0 = std::time::Instant::now(); - while !(h.state().layer_panel.service().is_fresh(content) && h.state().layer_panel.service().is_fresh(mask)) { + while ![content, mask, stage].iter().all(|target| h.state().layer_panel.service().is_fresh(*target)) { 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] @@ -131,6 +232,9 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); harness.run_steps(4); + harness.state_mut().run("layer.select", json!({"layer": layer.0})).unwrap(); + harness.run_steps(3); + click_selected_content_thumbnail(&mut harness); let row = harness.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); @@ -308,8 +412,8 @@ const LONG_EFFECT_NAME: &str = "Edge wear from curvature with dirt accumulation" fn an_effect_name_cut_short_shows_in_full_on_hover() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); - execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": LONG_EFFECT_NAME})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); let mut h = Harness::builder() .with_size(egui::vec2(1280.0, 800.0)) .with_context_setup(texturecraft_ui_egui::framework::install_headless) @@ -317,6 +421,7 @@ fn an_effect_name_cut_short_shows_in_full_on_hover() { h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); + click_selected_content_thumbnail(&mut h); let row = h.get_by_label(LONG_EFFECT_NAME).rect(); let before = h.query_all_by_label_contains(LONG_EFFECT_NAME).count(); h.hover_at(egui::pos2(row.left() + 75.0, row.center().y)); @@ -342,6 +447,7 @@ fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() { layer }; h.run_steps(3); + assert_eq!(h.state().session.selected_layer(), Some(selected)); let at = thumb(&h, "Masked fill", true); @@ -350,19 +456,22 @@ fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() { h.get_by_label("Toggle mask").click(); h.run_steps(3); let project = &h.state().session.doc.project; + assert!(!project.layers[&clicked].mask.as_ref().unwrap().enabled); assert!(project.layers[&selected].mask.as_ref().unwrap().enabled); assert_eq!(h.state().session.target, StackTarget::Mask); - // The same layer's mask is still selected when its material menu opens. + // Opening the material menu must preserve the selected mask let at = thumb(&h, "Masked fill", false); right_click(&mut h, at); assert!(h.query_by_label("Toggle mask").is_none()); + // The same items as the toolbar's Add effect on the content: a generator can't go there, so it is greyed assert!(h.get_by_label_contains("Add generator").accesskit_node().is_disabled()); h.get_by_label_contains("Add levels").click(); h.run_steps(3); let layer = &h.state().session.doc.project.layers[&clicked]; + assert_eq!(layer.content_effects.len(), 2); assert_eq!(layer.mask.as_ref().unwrap().effects.len(), 1); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0129eb7a..1c805d02 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -3,6 +3,7 @@ mod alpha_parameters; mod anchor_point; +mod auto_rebake; mod bake_job_mesh; mod bake_live_preview; mod bake_map_rows; @@ -10,6 +11,7 @@ mod bake_mode; mod bake_presets; mod bake_reset_menus; mod bake_sync; +mod baking_log; mod brush_drag; mod brush_section_reset; mod camera_views; @@ -32,6 +34,7 @@ mod export_overrides; mod export_progress; mod export_reference_texts; mod export_settings; +mod export_shader_parameters; mod export_template_guards; mod export_usd_asset; mod file_dialogs; @@ -43,6 +46,7 @@ mod fill_symmetry_rows; mod filter_picker; mod folder_properties; mod frame_selection; +mod generator_bake_note; mod generator_panel; mod generator_picker; mod help_menu_664; @@ -83,12 +87,17 @@ mod rail; mod reference_order; mod rename_anchor; mod reset_ui; +mod resources_updater; mod sample_project; mod settings_window; mod shelf_click; +mod shelf_drag_ghost; mod shelf_drop; mod shelf_hover_preview; +mod shelf_menu; mod shelf_panel; +mod shelf_second; +mod shelf_updates; mod shift_lines_2d; mod shift_lines_3d; mod shortcut_keys; @@ -193,6 +202,24 @@ fn assert_list_leaves_the_wheel_and_closes(harness: &mut Harness<'_, TextureCraf assert!(!egui::Popup::is_any_open(&harness.ctx), "a click outside closes the list"); } +/// Maximum frames to wait for a test condition +const STEP_UNTIL_FRAMES: usize = 4000; +/// Time to yield to background workers between frames +const STEP_UNTIL_PAUSE: std::time::Duration = std::time::Duration::from_millis(2); + +/// Step frames until `done` holds, up to a generous limit +fn step_until(harness: &mut Harness<'_, TextureCraftApp>, expected_event: &str, done: impl Fn(&TextureCraftApp) -> bool) { + for _ in 0..STEP_UNTIL_FRAMES { + harness.run_steps(1); + if done(harness.state()) { + return; + } + + std::thread::sleep(STEP_UNTIL_PAUSE); + } + panic!("{expected_event} did not happen"); +} + /// Presses and releases the primary button at `at` without moving, as a pointer click does fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { harness.hover_at(at); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index d8033152..edb10bfe 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -18,9 +18,13 @@ use template_library::TemplateLibrary; /// OUTPUT TEMPLATES with the user template "Mine" selected fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> { + harness_at(library, egui::vec2(1600.0, 960.0)) +} + +fn harness_at(library: &TemplateLibrary, size: egui::Vec2) -> 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)) + .with_size(size) .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); @@ -98,24 +102,38 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:"] { assert!(h.query_by_label(text).is_some(), "{text}"); } + let hint = "Drop an input map onto a channel to assign it to that output."; + + assert!(h.query_by_label(hint).is_none(), "the drag hint is no line under the cards"); + let metallic = h.get_by_role_and_label(egui::Role::ListItem, "Metallic").rect().center(); + h.hover_at(metallic); + h.run_steps(30); + + assert!(h.query_by_label(hint).is_some(), "a map entry's tooltip says how to use it"); + h.hover_at(egui::pos2(1.0, 1.0)); + h.run_steps(4); + assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); let maps = h.state().session.export_preset("Mine").unwrap().maps.len(); let ts = h.state().session.ts(); let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); let exported = plan.as_array().unwrap().len(); - assert!(h.query_by_label(&format!("{exported} output maps will be exported.")).is_some()); + + assert!(h.query_by_label(&format!("{exported} output maps will be exported")).is_some()); for create in ["Gray", "RGB", "R+G+B", "RGB+A", "R+G+B+A"] { assert!(h.query_by_label(create).is_some(), "{create}"); } click(&mut h, "R+G+B+A"); + assert_eq!(h.state().session.export_preset("Mine").unwrap().maps.len(), maps + 1, "Create adds an output map"); let info = h.get_by_label(egui_phosphor::regular::INFO).rect().center(); h.hover_at(info); h.run_steps(30); + assert!(h.query_by_label("Choose how the input maps are named in this editor.").is_some()); assert!(h.query_by_label("The active texture set’s shader can affect the available map names.").is_some()); } @@ -152,12 +170,17 @@ fn the_right_click_menu_renames_and_removes_user_templates_only() { assert!(!h.get_by_label(item).accesskit_node().is_disabled(), "{item}"); } click(&mut h, "Rename"); + assert_eq!(h.state().ui.export.renaming.as_deref(), Some("Mine")); h.key_press(egui::Key::Escape); h.run_steps(4); + assert!(h.state().ui.export.renaming.is_none(), "Escape ends the rename"); + assert!(h.state().ui.windows.export, "and leaves the window open"); + right_click(&mut h, "Mine"); click(&mut h, "Remove"); + assert!(matches!(&h.state().ui.export.ask, Some(texturecraft_ui_egui::export_templates::Ask::Delete(n)) if n == "Mine")); h.state_mut().ui.export.ask = None; h.run_steps(2); @@ -191,17 +214,19 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { h.state_mut().run("export.preset.save", json!({ "preset": two })).unwrap(); let own = "Unreal Engine (Packed)".to_string(); let mut o = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() }; - o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None }); + o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); let ts = h.state().session.ts(); h.state_mut().ui.export.sets.insert(ts, o); h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); + assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show"); let plan = h.state_mut().run("export.plan", json!({"preset": "Two", "ts": ts})).unwrap(); for index in 0..2 { let file = plan.as_array().unwrap().iter().find(|f| f["map"] == index).unwrap()["file"].as_str().unwrap().to_string(); hover_name_field(&mut h, index); let planned = format!("{} {file}", egui_phosphor::regular::ARROW_RIGHT); + assert!(h.query_all_by_label(&planned).next().is_some(), "map {index} shows its own file {file}"); } } @@ -211,7 +236,7 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { let library = TemplateLibrary::new("follow"); let mut h = harness(&library); let mut o = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() }; - o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None }); + o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); // The override is there when the window opens h.state_mut().ui.windows.export = false; @@ -229,19 +254,23 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { h.state_mut().ui.export.renaming = Some("Yours".into()); h.key_press(egui::Key::Enter); h.run_steps(4); + assert_eq!(h.state().ui.export.preset, "Yours"); let o = h.state().ui.export.sets[&0].clone(); + assert_eq!((o.preset.as_deref(), o.maps_template.as_str()), (Some("Yours"), "Yours"), "the set keeps its template and map ticks"); assert_eq!(o.maps.len(), 1); right_click(&mut h, "Yours"); click(&mut h, "Remove"); click(&mut h, "Delete"); + assert!(h.state().session.export_preset("Yours").is_none()); assert!(!h.state().ui.export.sets.contains_key(&0), "the set exports with the global settings again"); // Cancel goes back to the settings the window opened with, minus the removed template click(&mut h, "Cancel"); + assert!(h.state().ui.export.sets.values().all(|o| o.preset.as_deref() != Some("Yours") && o.preset.as_deref() != Some("Mine"))); } @@ -260,11 +289,12 @@ fn the_footer_counts_only_the_maps_the_texture_set_exports() { h.run_steps(4); let ts = h.state().session.ts(); let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1, "the sample set has no sheen: {plan}"); hover_name_field(&mut h, 1); assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen row says so"); - assert!(h.query_by_label("1 output maps will be exported.").is_some()); - assert!(h.query_by_label("2 output maps will be exported.").is_none()); + assert!(h.query_by_label("1 output maps will be exported").is_some()); + assert!(h.query_by_label("2 output maps will be exported").is_none()); } #[test] @@ -273,13 +303,14 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { let mut h = harness(&library); // The first texture set leaves out the template's first map - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone(); move_map(&mut h, 0, "Move down"); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[1].file, first, "the map moved down"); let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); + assert_eq!(maps, [(1, off)].into(), "the setting moved with its map"); } @@ -287,7 +318,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { let library = TemplateLibrary::new("stale"); let mut h = harness(&library); - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let saved = h.state().session.export_preset("Mine").unwrap(); @@ -309,8 +340,10 @@ fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { h.run_steps(2); move_map(&mut h, 0, "Move down"); let now = h.state().session.export_preset("Mine").unwrap(); + assert_eq!(now.maps[1].file, saved.maps[1].file, "{:?}", now.maps.iter().map(|m| &m.file).collect::>()); let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); + assert_eq!(maps, [(1, off)].into(), "counted from the agent's order, not the edit's old base"); } @@ -324,7 +357,7 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { let mut external = saved.clone(); external.maps.swap(0, 1); harness.state_mut().run("export.preset.save", json!({"preset": external})).unwrap(); - let disabled = MapExport { enabled: false, file_type: None }; + let disabled = MapExport { enabled: false, file_type: None, size: None }; harness.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, disabled.clone())].into(), ..SetExport::default() }); harness.run_steps(3); @@ -334,17 +367,18 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { harness.run_steps(4); let current = harness.state().session.export_preset("Mine").unwrap(); + assert_eq!(current, saved, "the corrected draft was saved in its own order"); assert_eq!(harness.state().ui.export.sets[&0].maps, [(1, disabled)].into()); } #[test] -fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { +fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_has_no_count_or_reset() { let library = TemplateLibrary::new("bottom-bar"); let h = harness(&library); let naming = h.get_by_label("Naming pattern").rect(); - let tabs = h.get_by_label("OUTPUT TEMPLATES").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Output templates").rect(); let presets = h.get_by_label("Presets").rect(); assert!(naming.center().y < presets.top() && (naming.center().y - tabs.center().y).abs() < tabs.height(), "on the tab row: {naming:?}"); @@ -353,13 +387,13 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { assert!(h.query_by_label(absent).is_none(), "{absent}"); } assert!(h.query_by_label_contains("textures selected for export").is_none()); - for greyed in ["Save settings", "Export"] { + for active in ["Save settings", "Export", "Cancel"] { // The rail at the right edge has an Export button of its own let button = - h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)).unwrap(); - assert!(button.accesskit_node().is_disabled(), "{greyed}"); + h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(active)).unwrap(); + + assert!(!button.accesskit_node().is_disabled(), "{active}"); } - assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); } #[test] @@ -494,6 +528,31 @@ fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { assert!(h.query_all_by_label("RGB: Base color, RGB").next().is_some()); } +#[test] +fn escape_in_a_file_name_field_leaves_the_field_and_keeps_the_window() { + let library = TemplateLibrary::new("escape-in-a-field"); + let mut h = harness(&library); + let field = name_field(&h, 0).center(); + h.hover_at(field); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: field, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + + assert!(h.ctx.egui_wants_keyboard_input(), "the field has the keyboard"); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().ui.windows.export, "the window stays open"); + assert!(!h.ctx.egui_wants_keyboard_input(), "the field let go of the keyboard"); + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export, "a second Escape is Cancel"); +} + #[test] fn escape_closes_the_from_popup_without_assigning() { let library = TemplateLibrary::new("drop-escape"); @@ -513,6 +572,7 @@ fn escape_closes_the_from_popup_without_assigning() { assert!(h.query_by_label("Which part of Metallic?").is_none(), "Escape closes the popup"); assert!(h.state().ui.export.pending_drop.is_none()); + assert!(h.state().ui.windows.export, "the window stays open"); assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); } @@ -592,7 +652,7 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { click(&mut h, "R+G+B+A"); let input_maps = h.get_by_label("Input maps").rect(); - let removes: Vec = h.get_all_by_label("Remove this output").map(|node| node.rect()).collect(); + let removes: Vec = h.get_all_by_label_contains("Remove output ").map(|node| node.rect()).collect(); let alpha = last_window_button(&h, "A: Empty (writes white)").rect(); assert!(!removes.is_empty()); @@ -610,12 +670,121 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { // The row's file format list starts right of its last swatch instead of covering it let format = h.get_all_by_role(egui::Role::Button).rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png"))).unwrap().rect(); + assert!(alpha.right() <= format.left(), "the swatches and the lists do not overlap: {alpha:?} {format:?}"); // The panes stay inside the window: the side pane ends where the bottom bar's buttons end let cancel = h.get_all_by_label("Cancel").last().unwrap().rect(); let export = last_window_button(&h, "Export").rect(); let converted = h.get_by_label("Converted maps").rect(); + assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); assert!(converted.left() < export.right() && converted.right() <= export.right() + 1.0, "{converted:?} {export:?}"); } + +#[test] +fn a_narrow_template_editor_keeps_the_alpha_swatch_clear_of_the_file_type_menu() { + let library = TemplateLibrary::new("narrow-template-editor"); + let mut harness = harness_at(&library, egui::vec2(800.0, 480.0)); + let create = harness.get_by_role_and_label(egui::Role::Button, "R+G+B+A"); + create.scroll_to_me(); + harness.run_steps(4); + + click(&mut harness, "R+G+B+A"); + let alpha = last_window_button(&harness, "A: Empty (writes white)").rect(); + let format = harness + .get_all_by_role(egui::Role::Button) + .rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png"))) + .unwrap() + .rect(); + + assert!(alpha.right() <= format.left(), "alpha {alpha:?} overlaps format {format:?}"); +} + +#[test] +fn hovering_a_channel_swatch_shows_the_file_its_output_writes() { + let library = TemplateLibrary::new("map-preview"); + let mut h = harness(&library); + let swatch = + h.get_all_by_role(egui::Role::Button).find(|b| b.accesskit_node().label().is_some_and(|l| l.starts_with("B: Metallic"))).unwrap().rect().center(); + let pictures = h.query_all_by_role(egui::Role::Image).count(); + let roughness_lines = h.query_all_by_label("Roughness, gray value").count(); + let file_names = h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count(); + + assert!(h.query_by_label_contains(" · png").is_none(), "nothing shows before the hover"); + + h.hover_at(swatch); + h.run_steps(30); + + assert!(h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count() > file_names, "the file's name"); + assert!(h.query_by_label_contains(" · png").is_some(), "the file's size and type"); + assert!(h.query_all_by_role(egui::Role::Image).count() > pictures, "the file and its channels, small"); + assert!(h.query_all_by_label("Roughness, gray value").count() > roughness_lines, "another channel's source is named"); +} + +#[test] +fn leaving_output_templates_releases_pictures_from_each_hovered_map() { + let library = TemplateLibrary::new("preview-lifetime"); + let mut h = harness(&library); + let previews = |h: &Harness<'_, TextureCraftApp>| { + h.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("export_map_preview_")).count() + }; + let hover_map = |h: &mut Harness<'_, TextureCraftApp>, name: &str| { + let swatch = h + .get_all_by_role(egui::Role::Button) + .find(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with(name))) + .unwrap_or_else(|| panic!("no swatch for {name}")) + .rect(); + h.hover_at(swatch.center()); + h.run_steps(30); + }; + + hover_map(&mut h, "B: Metallic"); + let first = previews(&h); + + assert!(first > 0); + hover_map(&mut h, "RGB: Base color"); + assert!(previews(&h) > first); + + click(&mut h, "Settings"); + + assert_eq!(previews(&h), 0); + + click(&mut h, "Output templates"); + hover_map(&mut h, "B: Metallic"); + assert_eq!(previews(&h), first); + click(&mut h, "Cancel"); + + assert_eq!(previews(&h), 0); + + h.state_mut().ui.windows.export = true; + h.run_steps(4); + click(&mut h, "Output templates"); + hover_map(&mut h, "B: Metallic"); + assert_eq!(previews(&h), first); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(previews(&h), 0); +} + +#[test] +fn feedback_template_preview_counts_overrides_only_for_its_own_maps() { + let library = TemplateLibrary::new("preview-map-overrides"); + let mut h = harness(&library); + let ts = h.state().session.ts(); + let plan = h.state_mut().run("export.plan", json!({"ts": ts, "preset": "Mine"})).unwrap(); + let initial = plan.as_array().unwrap().len(); + assert!(initial > 0); + let disabled = MapExport { enabled: false, ..MapExport::default() }; + h.state_mut().ui.export.sets.insert(ts, SetExport { maps_template: "Mine".into(), maps: [(0, disabled)].into(), ..SetExport::default() }); + + h.run_steps(4); + + assert!(h.query_by_label(&format!("{} output maps will be exported", initial - 1)).is_some()); + h.state_mut().ui.export.sets.get_mut(&ts).unwrap().preset = Some("Separate maps".into()); + h.run_steps(4); + assert!(h.query_by_label(&format!("{initial} output maps will be exported")).is_some()); +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 700ae461..88723d9a 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -766,6 +766,14 @@ fn project_config_snapshots() { h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap(); } +fn type_project_name(h: &mut Harness<'_, TextureCraftApp>, name: &str) { + in_window(h, Role::TextInput, "Project name").focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + in_window(h, Role::TextInput, "Project name").type_text(name); + h.run_steps(2); +} + #[test] fn a_typed_project_name_applies_only_with_ok() { let dir = temp_dir("project-name"); @@ -774,11 +782,7 @@ fn a_typed_project_name_applies_only_with_ok() { for button in ["Cancel", "OK"] { open_window(&mut h); - in_window(&h, Role::TextInput, "Project name").focus(); - h.run_steps(2); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - in_window(&h, Role::TextInput, "Project name").type_text("Knight"); - h.run_steps(2); + type_project_name(&mut h, "Knight"); click_in_window(&mut h, Role::Button, button); let expected = if button == "OK" { "Knight" } else { before.as_str() }; @@ -786,3 +790,74 @@ fn a_typed_project_name_applies_only_with_ok() { assert!(!window_is_open(&h), "{button} closes the window"); } } + +#[test] +fn an_invalid_project_name_leaves_other_configuration_changes_pending() { + use texturecraft_engine::core::NormalFormat; + + let dir = temp_dir("invalid-project-name"); + let mut h = app_on_a_quad(&dir); + let triangle = dir.join("tri.obj"); + std::fs::write(&triangle, TRIANGLE).unwrap(); + + open_window(&mut h); + select(&mut h, &triangle); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + type_project_name(&mut h, " "); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, "quad"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); + let message = h.get_by_label("Project name must be 1 to 128 characters after trimming, without control characters."); + assert_eq!(message.accesskit_node().live(), egui::accesskit::Live::Polite); + + type_project_name(&mut h, "Knight"); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, "Knight"); + assert_eq!(h.state().session.mesh.triangle_count(), 1); + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); +} + +#[test] +fn the_project_name_limit_applies_after_trimming_in_the_dialog() { + use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; + + let dir = temp_dir("project-name-limit"); + let mut h = app_on_a_quad(&dir); + let name = format!("{}Z", "x".repeat(MAX_PROJECT_NAME_CHARS - 1)); + + open_window(&mut h); + type_project_name(&mut h, &format!(" {name} ")); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, name); +} + +#[test] +fn a_reopened_name_field_cannot_undo_to_a_discarded_draft() { + let dir = temp_dir("project-name-history"); + let mut h = app_on_a_quad(&dir); + let original = h.state().session.doc.project.name.clone(); + + open_window(&mut h); + type_project_name(&mut h, "Discard this name"); + + // Drive enough virtual frames for the text edit to record an undo point + h.run_steps(90); + click_in_window(&mut h, Role::Button, "Cancel"); + + open_window(&mut h); + in_window(&h, Role::TextInput, "Project name").focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + h.run_steps(2); + + let field = in_window(&h, Role::TextInput, "Project name"); + assert_eq!(field.accesskit_node().value().as_deref(), Some(original.as_str())); +} diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index 37f5d9ff..8a97fa90 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -14,6 +14,8 @@ use texturecraft_engine::{Session, StackTarget}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::Answer; +use super::layers_panel::click_selected_content_thumbnail; + const BLACK: [f32; 3] = [0.0; 3]; const WHITE: [f32; 3] = [1.0; 3]; @@ -45,7 +47,21 @@ fn save_to(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![path.clone()])))); let ctx = h.ctx.clone(); texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.saveAs"); - h.run_steps(3); + + // Wait for the app to collect the worker result + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + h.step(); + let target = file.display().to_string(); + while !(file.exists() && h.state().session.path.as_deref() == Some(target.as_str()) && texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs")) { + if let Some(toast) = h.state().toasts.iter().find(|toast| toast.error) { + panic!("the save failed: {}", toast.text); + } + + assert!(std::time::Instant::now() < deadline, "the save did not finish"); + h.step(); + std::thread::yield_now(); + } + assert!(file.exists(), "Save as wrote the project"); assert!(!h.state().session.modified, "the project counts as saved"); } @@ -72,7 +88,9 @@ fn effect_harness() -> (Harness<'static, TextureCraftApp>, u64) { "effect", ); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); - (harness_for(session), effect) + let mut h = harness_for(session); + click_selected_content_thumbnail(&mut h); + (h, effect) } /// Choose Rename effect from the row's context menu and type `text` over the old name. @@ -119,10 +137,56 @@ fn renaming_an_effect_row_undoes_redoes_and_survives_save_and_reopen() { let layer = h.state().session.doc.project.effect(LayerId(effect)).unwrap().0; h.state_mut().run("layer.select", json!({"layer": layer.0})); h.run_steps(3); + assert!(h.query_by_label("Pitted rust").is_none(), "the reopened stack starts closed"); + click_selected_content_thumbnail(&mut h); assert!(h.query_by_label("Pitted rust").is_some(), "the reopened stack shows the name"); std::fs::remove_dir_all(file.parent().unwrap()).unwrap(); } +#[test] +fn collapsing_an_effect_stack_finishes_its_rename() { + let (mut h, effect) = effect_harness(); + rename_from_the_menu(&mut h, "Effect A", "Pitted rust"); + click_selected_content_thumbnail(&mut h); + assert!(h.state().ui.rename.is_none(), "the hidden editor has committed the name"); + assert_eq!(effect_name(&h, effect), "Pitted rust"); + assert!(h.query_by_label("Pitted rust").is_none(), "the effect stack closed"); + click_selected_content_thumbnail(&mut h); + assert!(h.query_by_label("Pitted rust").is_some()); +} + +#[test] +fn reopening_a_project_discards_an_uncommitted_effect_rename() { + let (mut harness, effect) = effect_harness(); + let file = temp_file("pending-rename"); + save_to(&mut harness, &file); + rename_from_the_menu(&mut harness, "Effect A", "Uncommitted name"); + + reopen(&mut harness, &file); + std::fs::remove_dir_all(file.parent().unwrap()).unwrap(); + + assert_eq!(effect_name(&harness, effect), "Effect A"); + assert!(!harness.state().session.modified); + assert!(harness.state().ui.rename.is_none()); +} + +#[test] +fn undoing_an_effect_removal_restores_its_committed_name() { + let (mut harness, effect) = effect_harness(); + rename_from_the_menu(&mut harness, "Effect A", "Uncommitted name"); + + harness.state_mut().ui.hide_ui = true; + harness.state_mut().run("effect.remove", json!({"effect": effect})).unwrap(); + harness.run_steps(3); + harness.state_mut().run("edit.undo", Value::Null).unwrap(); + harness.state_mut().ui.hide_ui = false; + harness.run_steps(3); + click_selected_content_thumbnail(&mut harness); + + assert_eq!(effect_name(&harness, effect), "Effect A"); + assert!(harness.state().ui.rename.is_none()); +} + #[test] fn escape_in_the_effect_editor_keeps_the_name() { let (mut h, effect) = effect_harness(); diff --git a/crates/ui-egui/tests/it/reset_ui.rs b/crates/ui-egui/tests/it/reset_ui.rs index 445993f4..66593d24 100644 --- a/crates/ui-egui/tests/it/reset_ui.rs +++ b/crates/ui-egui/tests/it/reset_ui.rs @@ -16,6 +16,7 @@ fn changed_app() -> Harness<'static, TextureCraftApp> { .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); + let ui = &mut h.state_mut().ui; ui.dock.close(Panel::Assets); ui.layout = ViewLayout::Only3D; @@ -63,30 +64,37 @@ fn reset_ui_asks_first_and_cancel_changes_nothing() { #[test] fn reset_ui_ok_resets_everything_as_before() { let mut h = changed_app(); + invoke(&mut h, "ui.resetUi"); h.get_by_label("Reset").click(); h.run_steps(2); + let ui = &h.state().ui; assert!(!ui.windows.confirm_reset_ui); assert!(ui.dock.is_open(Panel::Assets)); assert_eq!((ui.layout, ui.uv_zoom, ui.mesh_wireframe, ui.mode), (ViewLayout::Split, 1.0, false, Mode::Painting)); + assert_eq!(ui.prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE); } #[test] fn reset_ui_escape_keeps_everything_and_enter_resets() { let mut h = changed_app(); + invoke(&mut h, "ui.resetUi"); h.key_press(Key::Escape); h.run_steps(2); + assert!(!h.state().ui.windows.confirm_reset_ui); assert!(view_kept(&h) && !h.state().ui.dock.is_open(Panel::Assets)); invoke(&mut h, "ui.resetUi"); h.key_press(Key::Enter); h.run_steps(2); + assert!(!h.state().ui.windows.confirm_reset_ui); assert!(h.state().ui.dock.is_open(Panel::Assets)); assert_eq!(h.state().ui.layout, ViewLayout::Split); + assert_eq!(h.state().ui.prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE); } #[test] @@ -105,13 +113,16 @@ fn the_menu_invoke_command_asks_first_like_a_click() { fn the_ui_reset_control_command_resets_without_asking() { let mut h = changed_app(); let ctx = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &ctx, "ui.reset", &serde_json::Value::Null); h.run_steps(2); + assert!(reply.get("error").is_none(), "{reply}"); let ui = &h.state().ui; assert!(!ui.windows.confirm_reset_ui, "no question for a script"); assert!(ui.dock.is_open(Panel::Assets)); assert_eq!((ui.layout, ui.uv_zoom, ui.mesh_wireframe, ui.mode), (ViewLayout::Split, 1.0, false, Mode::Painting)); + assert_eq!(ui.prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE); } #[test] diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs new file mode 100644 index 00000000..dbb100b4 --- /dev/null +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -0,0 +1,240 @@ +//! The Resources Updater window, driven from the keyboard: the shelf button opens it, outdated +//! resources come first, Update reads a changed file again as one undo step and Select new resource +//! follows another file. File pickers are answered by the override, never shown. + +use std::path::{Path, PathBuf}; + +use egui::{Key, Role, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; +use texturecraft_ui_egui::state::ViewLayout; + +use super::temp_dir::TempDir; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + h +} + +/// Write a `size` × `size` PNG (each size is a different file size, so a change is seen at once) +fn png(dir: &Path, name: &str, size: u32) -> PathBuf { + let file = dir.join(name); + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(&file).unwrap(); + + file +} + +fn import(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { + h.state_mut().run("resource.import", json!({ "path": file.to_str().unwrap() })).unwrap(); + h.run_steps(2); +} + +fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) { + h.key_press(key); + h.run_steps(3); +} + +/// Move the keyboard focus to button `label` and press Enter +fn activate(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_role_and_label(Role::Button, label).focus(); + h.run_steps(2); + press(h, Key::Enter); +} + +fn shows(h: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + h.query_by_label(text).is_some() +} + +fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 { + h.state().session.images[name].width +} + +#[test] +fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() { + let dir = TempDir::new("resources-updater-update"); + let (kept, changed) = (png(&dir, "aa_kept.png", 4), png(&dir, "zz_changed.png", 4)); + let mut h = app(); + import(&mut h, &kept); + import(&mut h, &changed); + png(&dir, "zz_changed.png", 8); + + activate(&mut h, "Resources Updater"); + + let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows; + assert_eq!(rows[0].name, "zz_changed.png", "outdated resources come first, before names that sort earlier"); + assert!(shows(&h, "Project : Test")); + assert_eq!(h.get_all_by_label("Shelf : project").count(), 2, "the reference's shelf line, one per row"); + assert!(shows(&h, "(2 resources, 1 outdated)")); + assert!(shows(&h, "Outdated"), "the status is written out, not only coloured"); + assert!(h.get_by_role_and_label(Role::Button, "Update aa_kept.png").accesskit_node().is_disabled(), "only outdated resources update"); + + let steps = h.state().session.history_labels().len(); + activate(&mut h, "Update zz_changed.png"); + + assert_eq!(width_of(&h, "zz_changed.png"), 8, "the new file's pixels are in the project"); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step"); + assert!(shows(&h, "(2 resources, 0 outdated)")); + let result = h.get_by_label("Updated 1 resources"); + assert_eq!(result.accesskit_node().live(), egui::accesskit::Live::Polite, "the update result is announced away from focus"); + + // Undo brings the old pixels back, so Refresh shows the file as changed again + h.state_mut().run("edit.undo", json!({})).unwrap(); + activate(&mut h, "Refresh resources"); + + assert_eq!(width_of(&h, "zz_changed.png"), 4); + assert!(shows(&h, "(2 resources, 1 outdated)")); + + activate(&mut h, "Update All"); + assert_eq!(width_of(&h, "zz_changed.png"), 8); + + // Update All went grey with nothing left to update; the keyboard moves on to another button of the window + h.get_by_role_and_label(Role::Button, "Select new resource aa_kept.png").focus(); + h.run_steps(2); + press(&mut h, Key::Escape); + assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window while it has the keyboard"); +} + +#[test] +fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_list() { + let dir = TempDir::new("resources-updater-relink"); + let (first, second) = (png(&dir, "first.png", 4), png(&dir, "second.png", 4)); + let other = png(&dir, "other.png", 16); + let mut h = app(); + import(&mut h, &first); + import(&mut h, &second); + activate(&mut h, "Resources Updater"); + + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![other.clone()])))); + activate(&mut h, "Select new resource first.png"); + h.run_steps(3); + + assert_eq!(width_of(&h, "first.png"), 16, "the resource keeps its name and takes the chosen file's pixels"); + let source = &h.state().session.doc.project.resource_sources["first.png"].path; + assert!(source.ends_with("other.png")); + let announcement = format!("first.png now reads {source}"); + let result = h.get_by_label(&announcement); + assert_eq!(result.accesskit_node().live(), egui::accesskit::Live::Polite, "the relink result is announced away from focus"); + + h.get_by_role_and_label(Role::TextInput, "Name filter:").focus(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Name filter:").type_text("SEC"); + h.run_steps(3); + + assert!(h.query_by_label("Update first.png").is_none(), "the filter hides other names"); + assert!(h.query_by_label("Update second.png").is_some(), "names match ignoring case"); +} + +#[test] +fn show_in_folder_shows_the_folder_of_the_resource_file_and_materials_have_no_file() { + let dir = TempDir::new("resources-updater-folder"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + + // A linked MaterialCraft material keeps its package as a resource without a file + let layer = h.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + let session = &mut h.state_mut().session; + session.doc.resources.insert("brick.mcmat".to_string(), std::sync::Arc::new(b"package".to_vec())); + let link = serde_json::from_value(json!({"name": "Brick", "package": "brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut session.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind + { + fill.link = Some(link); + } + activate(&mut h, "Resources Updater"); + + activate(&mut h, "Show in folder bricks.png"); + + let shown = h.state().file_dialogs.shown_folders().to_vec(); + assert_eq!(shown.len(), 1); + assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); + assert!(shows(&h, "Name : brick.mcmat"), "the material is listed"); + assert!(h.query_by_label("Select new resource brick.mcmat").is_none(), "a material cannot point at an image file"); + assert!(h.query_by_label("Show in folder brick.mcmat").is_none(), "it has no file"); + assert!(h.get_by_label("Update brick.mcmat").accesskit_node().is_disabled()); + assert!( + h.get_all_by_label("Material").any(|node| node.accesskit_node().description().is_some_and(|text| text.contains("stored in the project"))), + "the material status explains the stored package in the accessibility tree" + ); +} + +#[test] +fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() { + const FRAMES_PER_DRAG_EVENT: usize = 2; + + let mut h = app(); + h.state_mut().run("layer.add.paint", json!({})).unwrap(); + h.state_mut().ui.layout = ViewLayout::Only3D; + h.run_steps(3); + let center = h.state().viewport_rect.center(); + h.drag_at(center); + h.run_steps(FRAMES_PER_DRAG_EVENT); + h.hover_at(center + vec2(20.0, 0.0)); + h.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(h.state().session.stroke_active()); + + // Opened from the shelf mid-stroke, the keyboard stays on the shelf button + activate(&mut h, "Resources Updater"); + assert!(h.state().ui.windows.resources_updater.is_some()); + assert!(h.state().session.stroke_active()); + + press(&mut h, Key::Escape); + + assert!(!h.state().session.stroke_active(), "Escape cancels the stroke"); + assert!(h.state().ui.windows.resources_updater.is_some(), "the window keeps open: its controls do not have the keyboard"); + h.drop_at(center + vec2(30.0, 0.0)); + h.run_steps(3); +} + +#[test] +fn a_file_changed_while_the_window_stays_open_shows_without_refresh() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + + let dir = TempDir::new("resources-updater-idle"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + activate(&mut h, "Resources Updater"); + assert!(shows(&h, "(1 resources, 0 outdated)")); + + png(&dir, "bricks.png", 8); + h.run_steps(FRAMES); + + let summary = h.get_by_label("(1 resources, 1 outdated)"); + assert_eq!(summary.accesskit_node().live(), egui::accesskit::Live::Polite, "an idle change is announced away from keyboard focus"); +} + +#[test] +fn the_keyboard_focus_stays_with_its_resource_when_the_rows_reorder() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + const SELECT_LATER: &str = "Select new resource zz_later.png"; + + let dir = TempDir::new("resources-updater-focus"); + let (earlier, later) = (png(&dir, "aa_earlier.png", 4), png(&dir, "zz_later.png", 4)); + let mut h = app(); + import(&mut h, &earlier); + import(&mut h, &later); + activate(&mut h, "Resources Updater"); + h.get_by_role_and_label(Role::Button, SELECT_LATER).focus(); + h.run_steps(2); + + // The changed file moves to the top of the list + png(&dir, "zz_later.png", 8); + h.run_steps(FRAMES); + + let rows = &h.state().ui.windows.resources_updater.as_ref().unwrap().rows; + assert_eq!(rows[0].name, "zz_later.png", "the outdated resource moved up"); + assert!(h.get_by_role_and_label(Role::Button, SELECT_LATER).accesskit_node().is_focused(), "the focus moved with it"); +} diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index df1b1d06..78e8b4e2 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -4,8 +4,10 @@ use egui::{Event, Key, Modifiers, Role}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::Session; -use texturecraft_ui_egui::settings_window::{DEFAULT_LIBRARY_NOTE, GPU_RAYTRACING_UNAVAILABLE, PROJECT_OPEN_NOTE, SHORTCUT_ERRORS, SettingsPage}; -use texturecraft_ui_egui::state::{LibraryLocation, UiState}; +use texturecraft_ui_egui::settings_window::{ + DEFAULT_LIBRARY_NOTE, GPU_RAYTRACING_UNAVAILABLE, PROJECT_OPEN_NOTE, SHORTCUT_ERRORS, SettingsPage, gpu_raytracing_check, +}; +use texturecraft_ui_egui::state::{LibraryLocation, Prefs, UiState}; use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; use texturecraft_ui_egui::{TextureCraftApp, menus}; @@ -87,47 +89,174 @@ fn the_left_column_switches_between_the_three_pages() { fn the_general_page_starts_at_the_reference_defaults() { let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); open_settings(&mut h); - h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs.language = texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE.into(); + + // Keep the app in English while the draft displays first-run defaults + h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs = Prefs::default(); h.run_steps(3); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Language").value().as_deref(), Some("Default (System Language)")); - assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Viewport Scaling").value().as_deref(), Some("Auto")); + let scaling = h.get_by_role_and_label(Role::ComboBox, "Viewport Scaling"); + assert_eq!(scaling.value().as_deref(), Some("Auto")); + assert!(!scaling.accesskit_node().is_disabled(), "Viewport Scaling can be opened"); assert_eq!(h.get_by_role_and_label(Role::SpinButton, "Local cache budget (in MB)").accesskit_node().numeric_value(), Some(4000.0)); - for label in [ - "Show keyboard helper", - "Show world axes", - "Use simplified thumbnails (improves performance)", - "Save preprocessed scene files", - "Enable live preview baking process", - "Enable GPU raytracing", - "Hardware support acceleration", - ] { + for label in ["Show keyboard helper", "Show world axes", "Save preprocessed scene files", "Enable live preview baking process"] { + assert!(toggled(&h, label), "{label} is ticked"); + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} can be changed"); + } + for label in ["Use simplified thumbnails (improves performance)", "Hardware support acceleration"] { assert!(toggled(&h, label), "{label} is ticked"); } - for label in ["Only display the selected material when painting", "CPU"] { - assert!(!toggled(&h, label), "{label} is not ticked"); - } + let only_selected = "Only display the selected material when painting"; + assert!(!toggled(&h, only_selected) && !h.get_by_label(only_selected).accesskit_node().is_disabled()); assert!(h.query_all_by_label("Inverse direction").all(|node| node.accesskit_node().toggled() == Some(egui::accesskit::Toggled::False))); - let prefs = texturecraft_ui_egui::state::Prefs::default(); + let local_cache = h.get_by_role_and_label(Role::TextInput, "Local cache directory"); + assert!(!local_cache.accesskit_node().is_disabled(), "the local cache directory can be edited"); + assert_ne!(texturecraft_ui_egui::local_cache_folder(&Prefs::default().local_cache_directory), std::env::temp_dir()); + + let prefs = Prefs::default(); + assert_eq!(prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE, "the default follows the system language"); assert_eq!((prefs.rotation_speed, prefs.zoom_speed, prefs.wheel_speed), (2.0, 1.0, 1.0)); } +#[test] +fn confirming_settings_keeps_a_texture_resolution_chosen_in_display_settings() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + let old_display = h.state().session.doc.project.display.clone(); + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, "ui.view.display"); + h.run_steps(4); + + let by_width = |left: &egui_kittest::Node<'_>, right: &egui_kittest::Node<'_>| left.rect().width().total_cmp(&right.rect().width()); + h.get_all_by_label("Render settings").max_by(by_width).unwrap().scroll_to_me(); + h.run_steps(3); + h.get_all_by_label("Render settings").max_by(by_width).unwrap().click(); + h.run_steps(10); + open_settings(&mut h); + + click(&mut h, "Half"); + assert_eq!(h.state().ui.prefs.viewport_texture, 1, "Display Settings applies the resolution immediately"); + click(&mut h, "OK"); + + assert_eq!(h.state().ui.prefs.viewport_texture, 1, "Settings leaves the Display Settings choice in place"); + assert_eq!(h.state().session.doc.project.display, old_display, "viewport resolution is an app preference"); +} + +#[test] +fn the_general_page_keeps_the_reference_sections_and_moves_data_folder_and_recent_projects() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + + for gone in ["TEMPORARY FILES", "IRAY HARDWARE", "APPEARANCE", "FOLDERS", "VIEWPORT", "Interface scale", "Accent color"] { + assert!(h.query_by_label(gone).is_none(), "{gone} is not on the page"); + } + for hint in ["Saving uses the other cores", "0 turns autosave off", "A new folder applies on restart"] { + assert!(h.query_by_label_contains(hint).is_none(), "the hint \"{hint}\" is gone"); + } + + let top = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_by_label(label).rect().top(); + let data_folder = h.get_by_role_and_label(Role::TextInput, "Data folder").rect().top(); + assert!(top(&h, "FILES") < data_folder && data_folder < top(&h, "SPARSE VIRTUAL TEXTURE"), "Data folder is in Files"); + let recent = h.get_by_role_and_label(Role::SpinButton, "Recent projects limit").rect().top(); + assert!(top(&h, "RESOURCES") < recent && recent < top(&h, "AUTOSAVE"), "Recent projects limit is in Resources"); + assert!(top(&h, "INTERFACE OPTIONS") < top(&h, "RESOURCES")); +} + +#[test] +fn the_resource_sliders_step_by_one_and_follow_the_arrow_keys() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + + let threads = h.get_by_role_and_label(Role::Slider, "Max CPU threads for work").accesskit_node(); + let cores = threads.max_numeric_value().unwrap(); + assert_eq!(threads.numeric_value(), Some(cores), "every thread works by default"); + assert_eq!(threads.min_numeric_value(), Some(1.0)); + let reserved = h.get_by_role_and_label(Role::Slider, "Cores kept for the UI").accesskit_node(); + assert_eq!((reserved.min_numeric_value(), reserved.max_numeric_value()), (Some(0.0), Some(cores))); + let ram = h.get_by_role_and_label(Role::Slider, "Max RAM while saving").accesskit_node(); + assert_eq!((ram.min_numeric_value(), ram.max_numeric_value()), (Some(0.0), Some(100.0))); + for label in ["Max CPU threads for work", "Cores kept for the UI", "Max RAM while saving"] { + assert_eq!(h.get_by_role_and_label(Role::Slider, label).accesskit_node().numeric_value_step(), Some(1.0), "{label} moves in steps of 1"); + } + assert_eq!(h.query_all_by_label(&format!("{cores} cores in total")).count(), 2, "both core sliders name the total"); + + let ram_percent = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.save_ram_percent; + let before = ram_percent(&h); + h.get_by_role_and_label(Role::Slider, "Max RAM while saving").scroll_to_me(); + h.run_steps(3); + h.get_by_role_and_label(Role::Slider, "Max RAM while saving").focus(); + h.run_steps(2); + + press_key(&mut h, Key::ArrowRight); + let after_right = ram_percent(&h); + press_key(&mut h, Key::ArrowLeft); + press_key(&mut h, Key::ArrowLeft); + let after_left = ram_percent(&h); + + assert_eq!(after_right, before + 1, "the right arrow adds one percent"); + assert_eq!(after_left, before - 1, "the left arrow takes one percent"); +} + +#[test] +fn show_world_axes_draws_the_3d_view_axes_and_off_hides_them() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + let painted_z = |h: &Harness<'_, TextureCraftApp>| { + h.output().shapes.iter().filter(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Z")).count() + }; + + h.state_mut().ui.prefs.show_world_axes = true; + h.run_steps(3); + let shown = painted_z(&h); + + h.state_mut().ui.prefs.show_world_axes = false; + h.run_steps(3); + let hidden = painted_z(&h); + + assert_eq!(shown, hidden + 1, "the 3D view's Z axis letter is drawn only while Show world axes is on"); +} + +#[test] +fn the_enabled_interface_options_answer_the_keyboard() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + let draft = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.clone(); + let before = draft(&h); + + for label in ["Show keyboard helper", "Show world axes", "Only display the selected material when painting"] { + h.get_by_label(label).focus(); + h.run_steps(2); + press_key(&mut h, Key::Space); + } + let after = draft(&h); + + assert_ne!(after.show_keyboard_helper, before.show_keyboard_helper); + assert_ne!(after.show_world_axes, before.show_world_axes); + assert_ne!(after.only_selected_material_when_painting, before.only_selected_material_when_painting); +} + +#[test] +fn the_local_cache_directory_takes_a_folder_and_r_goes_back_to_the_default() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + let folder = std::env::temp_dir().join("tc-settings-local-cache").display().to_string(); + let stored = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.local_cache_directory.clone(); + + type_into(&mut h, "Local cache directory", &folder); + let typed = stored(&h); + click(&mut h, "R, Reset to the default folder"); + let reset = stored(&h); + + assert_eq!(typed, folder); + assert!(reset.is_empty(), "R goes back to the default folder"); +} + #[test] fn a_control_the_app_lacks_is_disabled_and_says_so_on_hover() { let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); h.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); open_settings(&mut h); let away = h.get_by_role_and_label(Role::Tab, "Libraries").rect().center(); - for label in [ - "Show keyboard helper", - "Show world axes", - "Only display the selected material when painting", - "Use simplified thumbnails (improves performance)", - "Save preprocessed scene files", - "Enable live preview baking process", - "Hardware support acceleration", - "CPU", - ] { + for label in ["Use simplified thumbnails (improves performance)", "Hardware support acceleration"] { h.hover_at(away); h.run_steps(3); assert!(h.query_by_label(NOT_AVAILABLE).is_none(), "no hint before hovering {label}"); @@ -142,7 +271,6 @@ fn a_control_the_app_lacks_is_disabled_and_says_so_on_hover() { for step in ["−", "+"] { assert!(h.query_all_by_label(step).any(|node| node.accesskit_node().is_disabled()), "the cache budget's {step} is disabled"); } - assert!(!h.get_by_label("Enable GPU raytracing").accesskit_node().is_disabled(), "GPU raytracing switches bakes to the CPU"); for label in ["Rotation speed", "Zoom speed", "Wheel speed"] { assert!(h.query_by_label(label).is_some(), "{label} is shown"); } @@ -154,10 +282,13 @@ fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() { let before = h.state().ui.prefs.clone(); open_settings(&mut h); h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0); - click(&mut h, "Enable GPU raytracing"); + click(&mut h, "Show world axes"); h.run_steps(2); + assert_eq!(h.state().ui.prefs, before, "edits wait for OK"); + click(&mut h, "Cancel"); + assert!(!h.state().ui.windows.settings && h.state().ui.windows.settings_draft.is_none(), "Cancel closes the window"); assert_eq!(h.state().ui.prefs, before, "Cancel drops the edits"); @@ -167,21 +298,26 @@ fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() { Some(f64::from(before.autosave_minutes)), "a new window starts from the settings in use" ); + h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0); - h.get_by_role_and_label(Role::SpinButton, "Max CPU threads for work").set_value_accesskit(1.0); + h.get_by_role_and_label(Role::Slider, "Max CPU threads for work").set_value_accesskit(1.0); h.get_by_role_and_label(Role::SpinButton, "Max project size on open").set_value_accesskit(12.0); h.run_steps(2); h.query_all_by_label("Inverse direction").next().unwrap().scroll_to_me(); h.run_steps(3); h.query_all_by_label("Inverse direction").next().unwrap().click(); h.run_steps(2); - click(&mut h, "Enable GPU raytracing"); + click(&mut h, "Show world axes"); click(&mut h, "OK"); let prefs = h.state().ui.prefs.clone(); assert!(!h.state().ui.windows.settings, "OK closes the window"); - assert_eq!((prefs.autosave_minutes, prefs.work_threads, prefs.project_open_limit_gib), (25, 1, 12)); - assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.gpu_raytracing); + + // The slider's end stores 0, which is the only step on a one-core machine + let (cores, _) = texturecraft_engine::formats::available_save_resources(); + let expected_work_threads = if cores <= 1 { 0 } else { 1 }; + assert_eq!((prefs.autosave_minutes, prefs.work_threads, prefs.project_open_limit_gib), (25, expected_work_threads, 12)); + assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.show_world_axes); assert!(prefs.drag_zoom_scale() < 0.0, "inverted zoom runs the other way"); let mut storage = MemoryStorage::default(); @@ -437,16 +573,22 @@ fn the_libraries_page_hides_the_add_row_with_a_project_open_and_explains_the_def } #[test] -fn the_baking_options_say_when_there_is_no_gpu_to_trace_on() { - // The condition, with and without an adapter (the harness's own adapter is not under test) +fn gpu_raytracing_is_on_and_checkable_with_a_gpu_and_off_and_disabled_without() { + let with_gpu = !cfg!(target_arch = "wasm32"); + assert_eq!(gpu_raytracing_check(true, true), (with_gpu, with_gpu), "supported hardware keeps it on and checkable"); + assert_eq!(gpu_raytracing_check(true, false), (with_gpu, false), "supported hardware shows the stored choice"); + assert_eq!(gpu_raytracing_check(false, true), (false, false), "without support it is off and disabled"); assert!(texturecraft_ui_egui::settings_window::gpu_note_shown(None)); - assert_eq!(texturecraft_ui_egui::settings_window::gpu_note_shown(Some("Some GPU")), cfg!(target_arch = "wasm32")); - // The page shows the note exactly when the harness has no adapter (the IRAY HARDWARE row says "no GPU") + // The baker selects its own adapter independently of the window let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); open_settings(&mut h); - let no_gpu = h.query_by_label("no GPU").is_some(); - assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), no_gpu, "the note shows with no GPU and only then"); + let supported = texturecraft_render::gpu_bake::raytracing_available(); + + let check = h.get_by_label("Enable GPU raytracing"); + assert_eq!(!check.accesskit_node().is_disabled(), supported, "it can be changed exactly when there is a GPU"); + assert_eq!(toggled(&h, "Enable GPU raytracing"), supported, "it is on exactly when there is a GPU"); + assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), !supported, "the note shows with no GPU and only then"); } #[test] diff --git a/crates/ui-egui/tests/it/shelf_drag_ghost.rs b/crates/ui-egui/tests/it/shelf_drag_ghost.rs new file mode 100644 index 00000000..eb5525ba --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_drag_ghost.rs @@ -0,0 +1,100 @@ +//! A dragged asset or layer shows at the pointer with a badge saying whether the place under it takes it + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::materials::MATERIALS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_drag_ghost::{ShelfDragVerdict, shown}; + +/// Distance between the view points searched for a set or the background +const SEARCH_STEP: f32 = 8.0; + +/// How far the pointer moves off the tile before it counts as a drag +const DRAG_START: f32 = 12.0; + +/// The sample project at 1600 x 960, the shelf on Materials +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)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + 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() +} + +#[test] +fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_covering_the_pointer() { + // The grid's first plain material (by name), so its tile is in view + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = sample_app(); + let (set, background) = (point_over(&harness, Some(0)), point_over(&harness, None)); + let tile = harness.get_all_by_label(material.label).next().unwrap().rect().center(); + assert!(shown(&harness.ctx).is_none(), "nothing follows the pointer before a drag"); + + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + vec2(DRAG_START, DRAG_START)); + harness.run_steps(2); + + let mut seen = Vec::new(); + for target in [set, background] { + harness.hover_at(target); + harness.run_steps(2); + let ghost = shown(&harness.ctx).expect("the dragged asset follows the pointer"); + assert!(ghost.badge.min.x > target.x && ghost.badge.min.y > target.y, "the badge leaves the pointer's tip clear"); + seen.push(ghost.verdict); + } + assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "a texture set takes a material, the background doesn't"); + + harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); +} + +#[test] +fn a_layer_dragged_in_the_layer_stack_gets_the_same_ghost_and_badge() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for name in ["Ghost low", "Ghost high"] { + texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::json!({ "name": name })).unwrap(); + } + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + let background = point_over(&harness, None); + let (high, low) = (harness.get_by_label("Ghost high").rect().center(), harness.get_by_label("Ghost low").rect().center()); + + harness.event(Event::PointerButton { pos: high, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(high + vec2(DRAG_START, DRAG_START)); + harness.run_steps(2); + + let mut seen = Vec::new(); + for target in [low, background] { + harness.hover_at(target); + harness.run_steps(2); + seen.push(shown(&harness.ctx).expect("the dragged layer follows the pointer").verdict); + } + assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "another row takes the layer, the 3D view doesn't"); + + harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); +} diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 7ad7b187..13cb15ab 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -48,7 +48,7 @@ fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { /// 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() }); + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into(), thumb: None }); harness.hover_at(position); harness.run_steps(2); diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs new file mode 100644 index 00000000..261b72ac --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -0,0 +1,268 @@ +//! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it + +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::materials::MATERIALS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; + +/// The types' positions in the shelf's type row (its table is crate-private) +const MATERIALS_TYPE: usize = 0; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; + +/// The sample project with the shelf on type `tab` +fn shelf(tab: usize) -> 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)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = tab; + harness.run_steps(4); + harness +} + +fn right_click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no tile {label}")).click_secondary(); + harness.run_steps(3); +} + +#[test] +fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() { + // The grid's first plain material (by name), so its tile is in view + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = shelf(MATERIALS_TYPE); + + right_click(&mut harness, material.label); + + for row in [ + format!("Name {}", material.label), + "Usages material".to_string(), + format!("Path /Starter assets/Materials/{}/", material.category), + format!("Category {}", material.category), + ] { + assert!(harness.query_by_label(&row).is_some(), "the menu has the info row {row:?}"); + } + assert!(harness.get_by_label("Export resource...").accesskit_node().is_disabled(), "a built-in has no file to export"); + assert!(harness.get_by_label("Show in").accesskit_node().is_disabled(), "a built-in has no file to show"); + + harness.get_by_label("Close").click(); + harness.run_steps(3); + assert!(harness.query_by_label("Usages material").is_none(), "Close closes the menu"); +} + +#[test] +fn export_resource_writes_the_image_as_imported() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes.clone()).unwrap(); + harness.run_steps(3); + let dir = super::temp_dir::TempDir::new("shelf-export-resource"); + let target = dir.join("exported.png"); + let answer = target.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + + right_click(&mut harness, &name); + harness.get_by_label("Export resource...").click(); + harness.run_steps(4); + + assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes"); +} + +fn preset_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.brush_presets.list.iter().map(|preset| preset.name.clone()).collect() +} + +/// Selects the menu's Name field text and types `text` +fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + harness.get_by_role_and_label(egui::Role::TextInput, "Name").click(); + harness.run_steps(3); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(3); +} + +#[test] +fn a_saved_brush_menu_renames_replaces_and_deletes_it() { + // A name that sorts before every built-in brush, so its tile is in view + let mut harness = shelf(BRUSHES_TYPE); + texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Never applied"); + harness.key_press(Key::Escape); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa ink"], "Escape keeps the name"); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Aa pen"); + harness.key_press(Key::Enter); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa pen"], "Enter renames the brush"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({"size": 77})).unwrap(); + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Replace with the current brush").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.brush_presets.list[0].brush, harness.state().session.tool.brush, "the preset holds the current brush"); + + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + assert!(preset_names(&harness).is_empty(), "Delete removes the brush"); +} + +#[test] +fn delete_removes_a_project_image() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, &name); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + + assert!(!harness.state().session.doc.resources.contains_key(&name)); +} + +#[test] +fn a_project_image_menu_renames_it_keeping_its_star_and_greys_reload_without_a_file() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + pick_from_menu(&mut harness, &name, "Add to favorites"); + + right_click(&mut harness, &name); + assert!(harness.get_by_label("Reload").accesskit_node().is_disabled(), "an image not imported from a file can't reload"); + type_name(&mut harness, "stone"); + harness.key_press(Key::Enter); + harness.run_steps(3); + + let resources = &harness.state().session.doc.resources; + assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension"); + let favorites: Vec<&str> = harness.state().ui.shelf_favorites.iter().map(|favorite| favorite.id.as_str()).collect(); + assert_eq!(favorites, ["stone.png"], "the star follows the rename"); +} + +#[test] +fn show_in_opens_the_folder_of_a_saved_brush() { + let dir = super::temp_dir::TempDir::new("shelf-show-in"); + let mut harness = shelf(BRUSHES_TYPE); + harness.state_mut().session.brush_presets.dir = Some(dir.to_path_buf()); + texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, "Aa ink"); + harness.get_by_label("Show in").click(); + harness.run_steps(3); + let item = if cfg!(target_os = "windows") { + "Show in Explorer..." + } else if cfg!(target_os = "macos") { + "Show in Finder..." + } else { + "Show in file manager..." + }; + harness.get_by_label(item).click(); + harness.run_steps(3); + + let shown = harness.state().file_dialogs.shown_folders().to_vec(); + assert!(shown.iter().any(|folder| folder.canonicalize().ok() == dir.canonicalize().ok()), "the brush's folder is shown: {shown:?}"); +} + +#[test] +fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_returns_to_it() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + harness.get_all_by_label(&name).next().unwrap().focus(); + harness.run_steps(2); + assert!(harness.get_all_by_label(&name).next().unwrap().is_focused(), "the tile takes the focus"); + harness.key_press_modifiers(Modifiers::SHIFT, Key::F10); + harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_some(), "Shift+F10 opens the menu"); + assert!(harness.get_by_label("Delete").is_focused(), "the first row that can be picked takes the focus (Reload can't: no file)"); + + harness.key_press(Key::Escape); + harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it"); + assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile"); +} + +/// Whether the tile `first` comes before the tile `second` in the grid (rows top to bottom, each left to right) +fn comes_before(harness: &Harness<'_, TextureCraftApp>, first: &str, second: &str) -> bool { + let place = |label: &str| { + let rect = harness.get_by_label(label).rect(); + (rect.top(), rect.left()) + }; + place(first) < place(second) +} + +fn pick_from_menu(harness: &mut Harness<'_, TextureCraftApp>, tile: &str, row: &str) { + right_click(harness, tile); + harness.get_by_label(row).click(); + harness.run_steps(3); +} + +#[test] +fn favorites_come_first_newest_first_with_a_star_until_removed() { + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + let (first, second, third) = (plain[0].label, plain[1].label, plain[2].label); + let mut harness = shelf(MATERIALS_TYPE); + + pick_from_menu(&mut harness, third, "Add to favorites"); + pick_from_menu(&mut harness, second, "Add to favorites"); + + assert!(comes_before(&harness, second, third) && comes_before(&harness, third, first), "favorites first, the newest first"); + assert_eq!(harness.get_by_label(second).accesskit_node().description().as_deref(), Some("Favorite"), "the star is announced"); + assert_eq!(harness.get_by_label(first).accesskit_node().description(), None); + + pick_from_menu(&mut harness, second, "Remove from favorites"); + + assert!(comes_before(&harness, first, second), "a removed favorite goes back to its place by name"); + assert!(comes_before(&harness, third, first), "the other favorite stays first"); +} + +#[test] +fn set_custom_preview_shows_a_picked_picture_until_removed() { + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = shelf(MATERIALS_TYPE); + let dir = super::temp_dir::TempDir::new("shelf-custom-preview"); + let picture = dir.join("preview.png"); + image::RgbaImage::from_pixel(8, 4, image::Rgba([40, 160, 90, 255])).save(&picture).unwrap(); + let not_a_picture = dir.join("notes.png"); + std::fs::write(¬_a_picture, b"not a picture").unwrap(); + let answers = std::sync::Arc::new(std::sync::Mutex::new(vec![picture.clone(), not_a_picture])); + let pick = answers.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![pick.lock().unwrap().remove(0)])))); + let picked = + |harness: &Harness<'_, TextureCraftApp>| harness.state().ui.shelf_custom_previews.iter().map(|preview| preview.file.clone()).collect::>(); + + pick_from_menu(&mut harness, material.label, "Set custom preview..."); + harness.run_steps(2); + + assert_eq!(picked(&harness), std::slice::from_ref(&picture), "the tile shows the picked picture"); + + pick_from_menu(&mut harness, material.label, "Set custom preview..."); + harness.run_steps(2); + + assert_eq!(picked(&harness), [picture], "a file that isn't a picture leaves the preview as it was"); + + pick_from_menu(&mut harness, material.label, "Remove custom preview"); + + assert!(picked(&harness).is_empty(), "the tile shows its own thumbnail again"); + right_click(&mut harness, material.label); + assert!(harness.query_by_label("Remove custom preview").is_none(), "only a tile with a custom preview offers to remove it"); +} diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index f576fb7f..5c3c9275 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -19,6 +19,8 @@ const MATERIALS_TYPE: usize = 0; const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; const ENVIRONMENTS_TYPE: usize = 7; +/// The type row with no type picked: every type shows +const EVERY_TYPE: usize = 8; /// 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 @@ -155,6 +157,8 @@ fn refresh_reads_the_saved_brushes_again() { harness.run_steps(1); button(&harness, "Refresh").click(); + harness.run_steps(2); + button(&harness, "Update Assets panel").click(); harness.run_steps(3); assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again"); @@ -204,7 +208,13 @@ fn many_saved_searches_keep_the_path_filter_reachable() { 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() }) + .map(|index| SavedSearch { + name: format!("search {index}"), + filter: format!("filter {index}"), + tab: MATERIALS_TYPE, + path: Vec::new(), + favorites_only: false, + }) .collect(); harness.run_steps(3); @@ -218,7 +228,13 @@ 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() }) + .map(|index| SavedSearch { + name: format!("search {index}"), + filter: format!("filter {index}"), + tab: MATERIALS_TYPE, + path: Vec::new(), + favorites_only: false, + }) .collect(); harness.run_steps(3); assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); @@ -388,10 +404,10 @@ fn the_panes_list_the_reference_rows_and_grey_the_missing_ones() { let tops: Vec = rows.iter().map(|label| latest_node_with_label(&harness, label).rect().top()).collect(); assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}"); } - for label in ["Favorites", "3D Assets", "Flattened layers", "System fonts", "User fonts"] { + for label in ["3D Assets", "Flattened layers", "System fonts", "User fonts"] { assert!(latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} is greyed"); } - for label in ["All", "All libraries", "Project", "Starter assets", "Your assets"] { + for label in ["All", "Favorites", "All libraries", "Project", "Starter assets", "Your assets"] { assert!(!latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} works"); } assert!(shows_not_available(&mut harness, "Flattened layers"), "a greyed saved search explains itself"); @@ -458,7 +474,7 @@ fn the_smallest_saved_search_pane_can_scroll_to_and_select_the_last_query() { harness.state_mut().ui.shelf_panes.filter_by_path = true; harness.state_mut().ui.shelf_panes_split = 0.0; harness.state_mut().ui.shelf_saved_searches = - vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new() }]; + vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new(), favorites_only: false }]; harness.run_steps(3); scroll_pane_to_end(&mut harness, "SAVED SEARCHES"); @@ -519,3 +535,111 @@ fn the_splitter_is_exposed_as_a_resizable_control() { assert!(harness.state().ui.shelf_panes_split > before); } + +#[test] +fn the_favorites_search_shows_only_favorites_until_all_is_picked() { + let plain = plain_materials(); + let (favorite, other) = (plain[1].label, plain[0].label); + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + button(&harness, favorite).click_secondary(); + harness.run_steps(3); + button(&harness, "Add to favorites").click(); + harness.run_steps(3); + + button(&harness, "Favorites").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(favorite).is_some(), "the favorite shows"); + assert!(harness.query_by_label(other).is_none(), "an asset that is no favorite is hidden"); + assert!(harness.query_by_label("My brushes").is_none(), "the saved brushes list is no favorite either"); + + button(&harness, "All").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(other).is_some(), "All shows every asset again"); + assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again"); +} + +/// The shelf on the Materials type with the first plain material made a favorite through its menu +fn shelf_with_a_favorite(session: texturecraft_engine::Session) -> Harness<'static, TextureCraftApp> { + let favorite = plain_materials()[0].label; + let mut harness = Harness::builder() + .with_size(REFERENCE_WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; + harness.run_steps(4); + button(&harness, favorite).click_secondary(); + harness.run_steps(3); + button(&harness, "Add to favorites").click(); + harness.run_steps(3); + harness +} + +#[test] +fn a_search_saved_under_favorites_shows_only_favorites_again() { + let mut harness = shelf_with_a_favorite(texturecraft_engine::sample_session(256, 64).unwrap()); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + button(&harness, "Favorites").click(); + harness.run_steps(3); + button(&harness, "Save the current search").click(); + harness.run_steps(2); + button(&harness, "All").click(); + harness.run_steps(3); + + // The saved search lists below the fixed Favorites row, under the same name + harness.get_all_by_label("Favorites").last().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1); + assert!(harness.state().ui.shelf_favorites_only, "the saved search shows only favorites, as when it was saved"); +} + +#[test] +fn hiding_non_applicable_folders_under_favorites_hides_the_folders_of_other_assets() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + session.import_resource_bytes("photo.png", png).unwrap(); + let mut harness = shelf_with_a_favorite(session); + harness.state_mut().ui.shelf_tab = EVERY_TYPE; + harness.state_mut().ui.shelf_favorites_only = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.state_mut().ui.shelf_panes.hide_non_applicable = true; + harness.run_steps(4); + + assert!(harness.query_by_label("Starter assets").is_some(), "the favorite's library shows"); + assert!(harness.query_by_label("Project").is_none(), "the project image is no favorite, so its library hides"); +} + +#[test] +fn the_edge_between_the_panes_and_the_grid_drags_and_the_width_is_saved() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + + const DRAG_DISTANCE_POINTS: f32 = 40.0; + let (initial_share, edge) = (harness.state().ui.shelf_panes_share, harness.get_by_label("Resize Assets filter panes and grid").rect()); + let from = edge.center(); + let to = from + egui::vec2(DRAG_DISTANCE_POINTS, 0.0); + harness.hover_at(from); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(3); + + let moved = harness.get_by_label("Resize Assets filter panes and grid").rect(); + assert!(moved.center().x > edge.center().x, "the edge follows the drag: {edge:?} to {moved:?}"); + assert!(harness.state().ui.shelf_panes_share > initial_share, "the panes take a larger share"); + + let saved = serde_json::to_value(&harness.state().ui).unwrap(); + let restored: texturecraft_ui_egui::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(restored.shelf_panes_share, harness.state().ui.shelf_panes_share, "the width is saved"); +} diff --git a/crates/ui-egui/tests/it/shelf_second.rs b/crates/ui-egui/tests/it/shelf_second.rs new file mode 100644 index 00000000..ef3413db --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_second.rs @@ -0,0 +1,47 @@ +//! The Assets panel's folder button opens a second Assets panel with its own search + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// The sample project 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)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// Type `text` into the search field of the Assets panel shown left of the 3D view +fn search_shown_panel(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + let left_of_view = harness.state().viewport_rect.min.x; + harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the shown Assets panel has a search field").click(); + harness.run_steps(2); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(2); +} + +#[test] +fn the_folder_button_opens_a_second_assets_panel_that_searches_on_its_own() { + let mut harness = sample_app(); + assert!(!harness.state().ui.dock.is_open(Panel::AssetsSecond), "one Assets panel at first"); + + harness.get_by_label("New Assets panel").click(); + harness.run_steps(3); + assert!(harness.state().ui.dock.is_visible(Panel::AssetsSecond), "the folder button shows a second Assets panel"); + + search_shown_panel(&mut harness, "brick"); + let ui = &harness.state().ui; + assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", ""), "the second panel's search leaves the first panel's alone"); + + harness.state_mut().ui.dock.focus(Panel::Assets); + harness.run_steps(3); + search_shown_panel(&mut harness, "rust"); + let ui = &harness.state().ui; + assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", "rust"), "the first panel's search leaves the second panel's alone"); +} diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs new file mode 100644 index 00000000..717a6d4a --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -0,0 +1,134 @@ +//! The Assets panel's refresh popup: automatic updates of the panel and of the project's images + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::brush_preset_cmds::UserBrush; +use texturecraft_ui_egui::TextureCraftApp; + +/// A little more than the shortest update interval, in seconds +const PAST_A_MINUTE: f64 = 61.0; + +/// The sample project with the Assets panel open and its refresh popup shown +fn refresh_popup() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1920.0, 1032.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(2); + harness.get_all_by_label("Refresh").next().unwrap().click(); + harness.run_steps(2); + harness +} + +/// Moves the app's clock on by more than a minute in one frame, then lets the frames after it settle +fn pass_a_minute(harness: &mut Harness<'_, TextureCraftApp>) { + let now = harness.ctx.input(|input| input.time); + harness.input_mut().time = Some(now + PAST_A_MINUTE); + harness.run_steps(2); +} + +/// Writes `bytes` over the file at `path` with a later time, as a later save would (an equal-size file keeping its time reads as unchanged) +fn rewrite(path: &std::path::Path, bytes: &[u8]) { + std::fs::write(path, bytes).unwrap(); + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); + std::fs::File::options().write(true).open(path).unwrap().set_modified(later).unwrap(); +} + +/// A grey one-pixel PNG of `value` +fn grey_png(value: f32) -> Vec { + texturecraft_engine::formats::gray16_png(1, 1, [value].into_iter()).unwrap() +} + +#[test] +fn turning_on_project_resources_reads_a_changed_image_file_again_every_minute() { + let mut harness = refresh_popup(); + let path = std::env::temp_dir().join(format!("texturecraft-auto-update-{}.png", std::process::id())); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = harness.state().session.images[&name].rgba.clone(); + rewrite(&path, &grey_png(0.8)); + + pass_a_minute(&mut harness); + let while_off = harness.state().session.images[&name].rgba.clone(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + pass_a_minute(&mut harness); + let after = harness.state().session.images[&name].rgba.clone(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(while_off, before, "nothing is read again while automatic updates are off"); + assert!(harness.state().ui.shelf_updates.resources, "the switch turned the update on"); + assert_ne!(after, before, "the changed file was read again within a minute"); +} + +#[test] +fn turning_on_the_assets_panel_reads_the_saved_brushes_again_every_minute() { + let mut harness = refresh_popup(); + let stale = UserBrush { name: "Stale brush marker".into(), brush: Default::default(), channels: None, file: None }; + harness.state_mut().session.brush_presets.list.push(stale); + + harness.get_by_label("Assets panel").click(); + harness.run_steps(2); + pass_a_minute(&mut harness); + + assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again"); +} + +#[test] +fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { + let mut harness = refresh_popup(); + let path = std::env::temp_dir().join(format!("texturecraft-auto-update-stroke-{}.png", std::process::id())); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = harness.state().session.images[&name].rgba.clone(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + rewrite(&path, &grey_png(0.8)); + + let steps_before_stroke = harness.state().session.history_labels().len(); + harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + pass_a_minute(&mut harness); + let during_stroke = harness.state().session.images[&name].rgba.clone(); + harness.state_mut().session.end_stroke().unwrap(); + harness.run_steps(2); + let after_stroke = harness.state().session.images[&name].rgba.clone(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(during_stroke, before, "nothing is read again while a stroke is under way"); + assert_ne!(after_stroke, before, "the update runs once the stroke ended"); + assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.8).as_slice(), "the stroke's undo state didn't swallow the update"); + + harness.state_mut().session.undo().unwrap(); + + assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.2).as_slice(), "one undo takes back the update"); + assert_eq!(harness.state().session.history_labels().len(), steps_before_stroke + 1, "the stroke is still its own step"); +} + +#[test] +fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() { + let mut harness = refresh_popup(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + + let mut reported = Vec::new(); + for project in ["first", "second"] { + if project == "second" { + harness.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + } + let folder = std::env::temp_dir().join(format!("texturecraft-failed-read-{project}-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("photo.png"); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + std::fs::remove_dir_all(&folder).unwrap(); + harness.state_mut().toasts.clear(); + + pass_a_minute(&mut harness); + + reported.push(harness.state().toasts.iter().any(|toast| toast.error && toast.text.starts_with(&format!("{name}:")))); + } + + assert_eq!(reported, [true, true], "each project says once that its file can't be read"); +} diff --git a/crates/ui-egui/tests/it/shortcut_list.rs b/crates/ui-egui/tests/it/shortcut_list.rs index 88a92296..a3cf2641 100644 --- a/crates/ui-egui/tests/it/shortcut_list.rs +++ b/crates/ui-egui/tests/it/shortcut_list.rs @@ -4,7 +4,7 @@ use egui::{Event, Key, Modifiers, Role}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; -use texturecraft_ui_egui::keymap::{NOT_AVAILABLE_ACTIONS, bindings}; +use texturecraft_ui_egui::keymap::{NOT_AVAILABLE_ACTIONS, REFERENCE_ACTIONS, bindings}; use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness() -> Harness<'static, TextureCraftApp> { @@ -32,8 +32,9 @@ fn no_two_default_shortcuts_are_the_same() { } } for (_, row) in &NOT_AVAILABLE_ACTIONS { - let key = row.default.unwrap(); - assert!(!seen.contains_key(key), "{} shows {key}, which another item has", row.label); + if let Some(key) = row.default { + assert_eq!(seen.insert(key, row.id), None, "{key} is reserved for {} and another item", row.label); + } } } @@ -45,7 +46,7 @@ fn the_settings_page_disables_editing_shortcuts_for_unavailable_actions() { h.run_steps(4); h.get_by_role_and_label(Role::Tab, "Shortcuts").click(); h.run_steps(4); - for (_, row) in &NOT_AVAILABLE_ACTIONS { + for row in NOT_AVAILABLE_ACTIONS.iter().map(|(_, row)| row).chain(&REFERENCE_ACTIONS) { let action = row.label; h.get_by_label(action).scroll_to_me(); h.run_steps(3); @@ -86,3 +87,74 @@ fn a_key_listed_for_a_missing_function_is_reported_as_shared() { assert!(h.query_by_label_contains("One or several errors").is_some(), "Space is Toggle animation's"); assert!(h.get_by_label("OK").accesskit_node().is_disabled()); } + +#[test] +fn recording_shift_escape_warns_that_the_key_is_reserved() { + let mut h = harness(); + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, "ui.settings"); + h.run_steps(4); + h.get_by_role_and_label(Role::Tab, "Shortcuts").click(); + h.run_steps(4); + h.get_by_label("Edit the shortcut of Save project").click(); + h.run_steps(4); + + press(&mut h, Key::Escape, Modifiers::SHIFT); + + assert!(h.query_by_label_contains("One or several errors").is_some(), "Shift+Escape is reserved for Pause Engine Computation"); + assert!(h.get_by_label("OK").accesskit_node().is_disabled()); +} + +#[test] +fn a_saved_shortcut_on_a_reference_key_does_not_block_settings() { + let mut h = harness(); + h.state_mut().ui.keymap.insert("ui.hideUi".into(), "Q".into()); + + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, "ui.settings"); + h.run_steps(4); + h.get_by_label("OK").click(); + h.run_steps(3); + + assert!(!h.state().ui.windows.settings, "an existing shortcut must not prevent confirming Settings"); + assert_eq!(h.state().ui.keymap.get("ui.hideUi").map(String::as_str), Some("Q")); +} + +#[test] +fn the_standalone_shortcut_editor_lists_the_reference_keys() { + let mut harness = harness(); + let context = harness.ctx.clone(); + let windows = texturecraft_ui_egui::state::Windows { shortcuts: true, ..Default::default() }; + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &context, "ui.set", &json!({"windows": windows})); + harness.run_steps(4); + + assert_eq!(reply["ok"], true); + assert!(harness.query_by_label("Toggle transform handles").is_some()); + assert!(harness.get_by_role_and_label(Role::Button, "Q").accesskit_node().is_disabled()); +} + +#[test] +fn the_manipulator_rows_follow_export_textures_in_the_reference_order() { + let mut h = harness(); + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, "ui.settings"); + h.run_steps(4); + h.get_by_role_and_label(Role::Tab, "Shortcuts").click(); + h.run_steps(4); + + let rows = [ + "Export Textures...", + "Toggle transform handles", + "Enlarge transform handles", + "Shrink transform handles", + "Switch transform coordinate space", + "Toggle warp editing", + "Move with transform handles", + "Rotate with transform handles", + "Reimport mesh", + ]; + let tops: Vec = rows.iter().map(|label| h.get_by_label(label).rect().top()).collect(); + + assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}"); +} diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 76962df4..cd50cbca 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -115,22 +115,26 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { harness.run_steps(SETTLE_FRAMES); assert!(harness.state().ui.windows.export, "Export Textures... opens the Export textures window"); - for label in - ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS", "Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] - { + for tab in ["Settings", "Output templates", "List of exports"] { + assert!(harness.query_by_role_and_label(egui::Role::Tab, tab).is_some(), "{tab}"); + } + for label in ["Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] { assert!(harness.query_by_label(label).is_some(), "{label}"); } assert!(harness.query_by_label_contains("textures selected for export").is_some()); - assert!(!says_not_available(&mut harness, "Export USD asset")); - assert!(says_not_available(&mut harness, "Export shader settings")); + for label in ["Export USD asset", "Export shader settings"] { + assert!(!says_not_available(&mut harness, label), "{label}"); + } harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); + assert!(!harness.state().ui.windows.export, "Save settings closes the window"); click_rail(&mut harness, "Export"); button_left_of_rail(&harness, "Export Mesh...").click(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Mesh Export Options").is_some(), "Export Mesh... asks for the options first"); } @@ -177,6 +181,31 @@ fn export_mesh_asks_the_options_then_the_file() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn recompute_normals_is_an_enabled_keyboard_operable_checkbox() { + let mut harness = app(); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "file.exportMesh"); + harness.run_steps(SETTLE_FRAMES); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); + assert!(!checkbox.accesskit_node().is_disabled(), "the option is really available"); + assert!(!is_on(&checkbox), "stored normals are kept until the user opts in"); + assert!(!harness.state().ui.mesh_recompute_normals); + + checkbox.focus(); + harness.key_press(egui::Key::Space); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export"); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); + assert!(is_on(&checkbox), "the accessibility tree reports the checked state"); + assert_eq!(checkbox.accesskit_node().label().as_deref(), Some("Recompute vertex normals")); + + checkbox.click(); + harness.run_steps(SETTLE_FRAMES); + assert!(!harness.state().ui.mesh_recompute_normals, "a pointer click turns it back off"); + assert!(!is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"))); +} + /// Whether the Log lists `line` (the status bar under it repeats the last message) fn log_lists(harness: &Harness<'_, TextureCraftApp>, line: &str) -> bool { harness.query_all_by_label(line).any(|node| node.rect().bottom() < STATUS_BAR_TOP) @@ -289,6 +318,70 @@ fn shader_settings_show_the_reference_rows_and_the_shader_choice() { assert!(harness.get_by_label(&tiles[1]).accesskit_node().is_disabled(), "the others are not available yet"); } +#[test] +fn the_unchecked_ior_control_is_visible_at_each_brightness() { + use craft_theme::{Contrast, Rgba, contrast_ratio, non_text_contrast_min}; + use texturecraft_ui_egui::theme::{Brightness, Tokens}; + + let mut harness = app(); + click_rail(&mut harness, "Shader Settings"); + let minimum_contrast = non_text_contrast_min(Contrast::Standard); + + for brightness in Brightness::ALL { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(SETTLE_FRAMES); + + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Use IOR for specular reflection"); + let bounds = checkbox.rect(); + let panel = Tokens::get(&harness.ctx).panel; + let indicator = harness + .output() + .shapes + .iter() + .filter_map(|painted| match &painted.shape { + egui::Shape::Rect(frame) if painted.clip_rect.contains_rect(frame.rect) && bounds.contains_rect(frame.rect) => Some(frame), + _ => None, + }) + .find(|frame| frame.fill.a() > 0 || !frame.stroke.is_empty()) + .expect("the unchecked indicator is painted inside its accessibility bounds"); + let fill = panel.blend(indicator.fill); + let outline = if indicator.stroke.width > 0.0 { fill.blend(indicator.stroke.color) } else { fill }; + let contrast = |color: egui::Color32| contrast_ratio(Rgba(color.to_array()), Rgba(panel.to_array())); + let ratio = contrast(fill).max(contrast(outline)); + + assert!(ratio >= minimum_contrast, "{brightness:?}: the unchecked box has {ratio:.2}:1 contrast against the panel"); + } +} + +#[test] +fn keyboard_toggles_ior_reflectance_only_in_metallic_roughness() { + let mut harness = app(); + let label = "Use IOR for specular reflection"; + harness.state_mut().ui.dock.focus(Panel::Shader); + harness.state_mut().session.modified = false; + harness.run_steps(SETTLE_FRAMES); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, label); + assert_eq!(checkbox.accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + checkbox.focus(); + harness.run_steps(SETTLE_FRAMES); + + harness.key_press(egui::Key::Space); + harness.run_steps(SETTLE_FRAMES); + + let checkbox = harness.get_by_role_and_label(Role::CheckBox, label); + assert!(checkbox.is_focused()); + assert!(is_on(&checkbox)); + assert!(harness.state().session.doc.project.display.ior_specular); + assert!(harness.state().session.modified); + + harness.state_mut().run("display.set", serde_json::json!({"specGloss": true})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + let checkbox = harness.get_by_role_and_label(Role::CheckBox, label); + assert!(checkbox.accesskit_node().is_disabled()); + assert!(is_on(&checkbox), "the current preference is retained"); +} + #[test] fn a_shader_edit_marks_the_project_modified() { let mut harness = app(); diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index 8ec6b680..fc72b047 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -88,7 +88,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { assert!(harness.state().session.tool.stencil.is_none()); let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center(); - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); harness.hover_at(slot); harness.run_steps(2); harness.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs index f9626b4b..42fe417d 100644 --- a/crates/ui-egui/tests/project_limits.rs +++ b/crates/ui-egui/tests/project_limits.rs @@ -12,6 +12,7 @@ use memory_storage::MemoryStorage; 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; @@ -19,6 +20,7 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() 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() @@ -37,17 +39,20 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() harness.run_steps(3); let edited = |harness: &Harness<'_, TextureCraftApp>| harness.state().ui.windows.settings_draft.as_ref().unwrap().prefs.clone(); assert_eq!(edited(&harness).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.get_by_role_and_label(egui::Role::Slider, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX)); harness.run_steps(3); assert_eq!(edited(&harness).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.get_by_role_and_label(egui::Role::Slider, "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(), 16, "an edit waits for OK"); + harness.get_by_label("OK").click(); harness.run_steps(3); assert_eq!(formats::project_open_limit_gib(), 24, "OK applies the edited value"); @@ -58,6 +63,7 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() 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/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index d78b23db..ae1e7c83 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -89,6 +89,9 @@ fn empty_start_snapshot() { harness.get_by_label("Edit").click(); harness.run_steps(3); harness.get_by_label("Settings").click(); + harness.run_steps(3); + harness.get_by_label("Recent projects limit").scroll_to_me(); + harness.run_steps(3); save(&mut harness, &output_dir, "settings-recent-project-limit"); assert!(!harness.get_by_label("Recent projects limit").accesskit_node().is_disabled()); } @@ -726,6 +729,244 @@ fn smart_material_shelf_snapshot() { save(&mut harness, &output_dir, "smart-material-hover"); } +/// Writes `name` and, beside it, where the pointer is (`.pointer.txt`: x y), so a picture can draw the system's pointer +fn save_with_pointer(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { + save(harness, dir, name); + if let Some(pointer) = harness.ctx.input(|input| input.pointer.hover_pos()) { + std::fs::write(dir.join(format!("{name}.pointer.txt")), format!("{} {}", pointer.x, pointer.y)).unwrap(); + } +} + +/// Assets types the pass 2 snapshots show, as indexes into the Assets panel's type row +const SMART_MATERIALS_TYPE: usize = 1; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; + +/// A move from a pressed tile or row long enough to start a drag +const DRAG_START: egui::Vec2 = egui::vec2(12.0, 12.0); + +/// A point in the window's top bar, so no tile shows its hover outline +const AWAY_FROM_TILES: egui::Pos2 = egui::pos2(800.0, 40.0); + +/// How far down the window a point is inside Properties +const PROPERTIES_HEIGHT_SHARE: f32 = 0.75; + +/// The panes' edge drag: steps and points per step +const EDGE_DRAG_STEPS: usize = 4; +const EDGE_DRAG_STEP: f32 = 15.0; + +/// Assets pass 2, every screen mid-interaction (menus, submenu, favorites, custom preview, drag ghost, refresh popup, second panel); `TC_UI_THEMES` adds dark and light +#[test] +#[ignore] +fn assets_pass_two_snapshots() { + use egui::{Event, Modifiers, PointerButton, Role, vec2}; + use texturecraft_engine::materials::MATERIALS; + use texturecraft_ui_egui::file_dialogs::Answer; + + 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 files = std::env::temp_dir().join(format!("texturecraft-assets-pass-two-{}", std::process::id())); + std::fs::create_dir_all(&files).unwrap(); + let brushes = files.join("brushes"); + let plate = files.join("rust_plate.png"); + image::RgbaImage::from_fn(128, 128, |x, y| { + let grain = ((x * 7 + y * 13) % 23) as u8 * 3; + image::Rgba([120 + grain, 66 + grain / 2, 38, 255]) + }) + .save(&plate) + .unwrap(); + let preview = files.join("brushed_preview.png"); + image::RgbaImage::from_fn(160, 120, |x, y| { + let line = 140 + ((y * 37 + x / 9) % 41) as u8; + image::Rgba([line, line, line + 8, 255]) + }) + .save(&preview) + .unwrap(); + let show_in = if cfg!(target_os = "windows") { + "Show in Explorer..." + } else if cfg!(target_os = "macos") { + "Show in Finder..." + } else { + "Show in file manager..." + }; + + let mut themes = vec![(Brightness::MediumDark, "medium")]; + if std::env::var_os("TC_UI_THEMES").is_some() { + themes.extend([(Brightness::Dark, "dark"), (Brightness::Light, "light")]); + } + for (brightness, theme) in themes { + 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) + // The system draws the pointer, not the app + .with_render_cursor(false) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.ui.prefs.brightness = brightness; + app.ui.prefs.language = "en".into(); + let theme_brushes = brushes.join(theme); + std::fs::create_dir_all(&theme_brushes).unwrap(); + app.session.brush_presets.dir = Some(theme_brushes); + app.run("brush.preset.store", serde_json::json!({"name": "Ink soft"})).unwrap(); + let image = app.run("resource.import", serde_json::json!({"path": plate.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let answer = preview.clone(); + app.file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + app.ui.shelf_tab = SMART_MATERIALS_TYPE; + 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)); + } + let shot = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| save_with_pointer(harness, &output_dir, &format!("assets-{name}-{theme}")); + let right_click = |harness: &mut Harness<'_, TextureCraftApp>, tile: &str| { + harness.get_all_by_label(tile).next().unwrap_or_else(|| panic!("no tile {tile}")).click_secondary(); + harness.run_steps(3); + }; + let close_menu = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + }; + + // 01: a built-in smart material, a row hovered; 03: its greyed Show in + right_click(&mut harness, "Brass Tarnished"); + harness.get_by_label("Export resource...").hover(); + shot(&mut harness, "01-menu-built-in"); + harness.get_by_label("Show in").hover(); + harness.run_steps(30); + shot(&mut harness, "03-show-in-built-in"); + close_menu(&mut harness); + + // 04: two favorites, the newest first, then a favorite's menu; 08: a custom preview on a third tile + for tile in ["Gold Dirty", "Bronze Statue"] { + right_click(&mut harness, tile); + harness.get_by_label("Add to favorites").click(); + harness.run_steps(3); + } + right_click(&mut harness, "Brass Tarnished"); + harness.get_by_label("Set custom preview...").click(); + harness.run_steps(3); + settle_thumbnails(&mut harness); + harness.hover_at(AWAY_FROM_TILES); + shot(&mut harness, "04-favorites-and-custom-preview"); + right_click(&mut harness, "Bronze Statue"); + harness.get_by_label("Remove from favorites").hover(); + shot(&mut harness, "04-menu-favorite"); + close_menu(&mut harness); + + // 05: the drag ghost over the layer stack (takes a material) and over Properties (doesn't) + let viewport_right = harness.state().viewport_rect.max.x; + let layer = harness.get_all_by_role(Role::ListItem).find(|row| row.rect().min.x > viewport_right).expect("a layer row").rect().center(); + // Properties fills the right column under the layer stack, in the window's lower part + let properties = egui::pos2(layer.x, harness.ctx.content_rect().height() * PROPERTIES_HEIGHT_SHARE); + let tile = harness.get_all_by_label("Gold Dirty").next().unwrap().rect().center(); + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + DRAG_START); + harness.run_steps(2); + for (target, name) in [(layer, "05-drag-valid-layer-stack"), (properties, "05-drag-not-valid-properties")] { + harness.hover_at(target); + harness.run_steps(2); + shot(&mut harness, name); + } + harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + // 09: a layer dragged in the layer stack over another row (takes it) and over Properties (doesn't) + harness.state_mut().run("layer.add.paint", serde_json::json!({"name": "Dragged layer"})).unwrap(); + harness.run_steps(3); + let dragged = harness.get_by_role_and_label(Role::ListItem, "Dragged layer").rect().center(); + let rows: Vec<_> = harness.get_all_by_role(Role::ListItem).filter(|row| row.rect().min.x > viewport_right).map(|row| row.rect().center()).collect(); + let other = *rows.iter().find(|at| at.y > dragged.y).expect("a row below it"); + harness.event(Event::PointerButton { pos: dragged, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(dragged + DRAG_START); + harness.run_steps(2); + for (target, name) in [(other, "09-layer-drag-valid-row"), (properties, "09-layer-drag-not-valid-properties")] { + harness.hover_at(target); + harness.run_steps(2); + shot(&mut harness, name); + } + harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + // 02: a project image and a saved brush; 03: Show in open on the image + harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; + settle_thumbnails(&mut harness); + right_click(&mut harness, &image); + harness.get_by_label("Reload").hover(); + shot(&mut harness, "02-menu-project-image"); + harness.get_by_label("Show in").click(); + harness.run_steps(3); + harness.get_by_label(show_in).hover(); + shot(&mut harness, "03-show-in-image"); + close_menu(&mut harness); + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + settle_thumbnails(&mut harness); + right_click(&mut harness, "Ink soft"); + harness.get_by_label("Replace with the current brush").hover(); + shot(&mut harness, "02-menu-saved-brush"); + close_menu(&mut harness); + + // 06: the refresh popup, then with an i hovered + harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE; + harness.run_steps(3); + harness.get_all_by_label("Refresh").next().unwrap().click(); + harness.run_steps(3); + harness.get_by_label("Update Assets panel").hover(); + shot(&mut harness, "06-refresh-popup"); + harness.get_by_label("Reads your saved assets from disk again every few minutes, so new and changed ones show here.").hover(); + harness.run_steps(30); + shot(&mut harness, "06-refresh-info"); + close_menu(&mut harness); + + // 10: both filter panes open, their edge with the grid dragged wider + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.run_steps(3); + let edge = harness.get_by_label("Resize Assets filter panes and grid").rect().center(); + harness.hover_at(edge); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: edge, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=EDGE_DRAG_STEPS { + harness.hover_at(edge + vec2(EDGE_DRAG_STEP * step as f32, 0.0)); + harness.run_steps(1); + } + shot(&mut harness, "10-panes-edge-drag"); + harness.event(Event::PointerButton { + pos: edge + vec2(EDGE_DRAG_STEP * EDGE_DRAG_STEPS as f32, 0.0), + button: PointerButton::Primary, + pressed: false, + modifiers: Modifiers::NONE, + }); + harness.state_mut().ui.shelf_panes.saved_searches = false; + harness.state_mut().ui.shelf_panes.filter_by_path = false; + harness.run_steps(3); + + // 07: the folder button hovered, then the second panel searching "brick" + harness.get_by_label("New Assets panel").hover(); + harness.run_steps(30); + shot(&mut harness, "07-folder-button"); + harness.get_all_by_label("New Assets panel").next().unwrap().click(); + harness.run_steps(3); + let left_of_view = harness.state().viewport_rect.min.x; + harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the second panel's search").click(); + harness.run_steps(2); + harness.event(Event::Text("brick".into())); + settle_thumbnails(&mut harness); + shot(&mut harness, "07-second-panel"); + } + std::fs::remove_dir_all(files).unwrap(); +} + /// Compact nested rows must keep their content, mask and effect controls in the panel. #[test] #[ignore] @@ -3204,3 +3445,93 @@ fn sheet_scroll_end_snapshots() { harness.run_steps(30); save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } + +/// The Export textures window on each tab at its mocks' size; TC_SNAPSHOT_THEME=medium (default), dark or light +#[test] +#[ignore] +fn export_window_snapshots() { + use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; + + // Below General Export Parameters, where the 1112x662 window draws nothing + const EMPTY_SPOT: egui::Pos2 = egui::pos2(736.0, 530.0); + + 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 (brightness, theme) = match std::env::var("TC_SNAPSHOT_THEME").as_deref() { + Ok("dark") => (Brightness::Dark, "dark"), + Ok("light") => (Brightness::Light, "light"), + _ => (Brightness::MediumDark, "medium"), + }; + + // Ball and Base, then enough texture sets that the set list scrolls + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let template = session.doc.project.texture_sets[0].clone(); + while session.doc.project.texture_sets.len() < 60 { + let mut set = template.clone(); + set.name = format!("Set {}", session.doc.project.texture_sets.len() + 1); + session.doc.project.texture_sets.push(set); + } + let mut harness = Harness::builder() + .with_size(egui::vec2(1112.0, 662.0)) + .with_pixels_per_point(2.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .wgpu() + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.prefs.brightness = brightness; + harness.set_render_cursor(false); + { + let e = &mut harness.state_mut().ui.export; + e.dir = "/home/user/Documents/TextureCraft/export".into(); + e.preset = "Document channels + Normal + AO (No Alpha)".into(); + e.padding = "infinite".into(); + e.skip = vec![4]; + } + harness.state_mut().ui.windows.export = true; + harness.run_steps(4); + let color_space = harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Default")).unwrap().rect(); + harness.hover_at(color_space.center()); + harness.run_steps(30); + save(&mut harness, &output_dir, &format!("ep-settings-global-{theme}")); + harness.hover_at(egui::pos2(1.0, 1.0)); + + harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Based on output template")).unwrap().click(); + harness.run_steps(3); + save(&mut harness, &output_dir, &format!("ep-settings-file-type-open-{theme}")); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The closed list keeps the keyboard focus (and its ring) until a click lands on the page's empty column + harness.hover_at(EMPTY_SPOT); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: EMPTY_SPOT, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(3); + + // Base with its own size and its height map as 32-bit exr + { + let e = &mut harness.state_mut().ui.export; + e.page = Some(1); + let mut set = SetExport { size: Some(1024), ..SetExport::default() }; + set.maps_template = e.preset.clone(); + let template = texturecraft_engine::formats::builtin_preset(&e.preset).unwrap(); + let height = template.maps.iter().position(|map| texturecraft_engine::formats::export::channel_label(map) == "height").unwrap(); + set.maps.insert(height, MapExport { file_type: Some(FileType { format: "exr".into(), bit_depth: 32, dithering: false }), ..MapExport::default() }); + set.maps.insert(2, MapExport { enabled: false, ..MapExport::default() }); + e.sets.insert(1, set); + } + save(&mut harness, &output_dir, &format!("ep-settings-set-{theme}")); + + harness.state_mut().ui.export.page = None; + harness.state_mut().ui.export.tab = 1; + harness.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Unreal Engine (Packed)").scroll_to_me(); + save(&mut harness, &output_dir, &format!("ep-templates-unreal-{theme}")); + + harness.state_mut().ui.export.preset = "Document channels + Normal + AO (No Alpha)".into(); + harness.state_mut().ui.export.tab = 2; + save(&mut harness, &output_dir, &format!("ep-list-{theme}")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 184c1e75..8233c5a7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -13,6 +13,12 @@ Everything TextureCraft does is an engine command with a stable id (`layer.add.f Programmatic calls never open dialogs: a command runs with its defaults. Only `ui.menu.invoke` behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and painted tile count, so an agent can verify its work without a screenshot. + +`project.rename {name}` sets the internal project name used by `$project` in export +templates and returns `{name}` with the trimmed value. The name must contain 1–128 +characters after trimming and contain no control characters. Renaming is undoable. +Submitting the current name leaves history unchanged. The project file keeps its own name. + `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. `effect.move {effect, index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies @@ -20,9 +26,10 @@ one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. `layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer` is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and -Ctrl+click do in the Layers panel. `layer.select {all: true}` (Ctrl+A with the pointer over the -Layers panel) selects every shown row of the active texture set: the folder rows and the layers -of open folders, not the layers of collapsed ones. `{layer, toggle: true}` on the only selected +Ctrl+click do in the Layers panel. `layer.select {layer, target}` takes `content`, `mask`, or +the ID of an effect on the layer or on the mask it draws with. `layer.select {all: true}` +(Ctrl+A with the pointer over the Layers panel) selects every shown row of the active texture +set, including folder rows and layers in open folders. `{layer, toggle: true}` on the only selected layer leaves nothing selected. `layer.visible {layers, layer}` gives every listed layer the opposite of `layer`'s visibility (the Layers panel's eye uses `{layer}` and acts on that layer only). `layer.group` puts the new folder at the place and in the folder of the topmost selected @@ -41,11 +48,19 @@ file runs it; Copy mask to clipboard puts the same mask on the system clipboard grayscale image (the whole tile atlas for a UV-tiled set). `file.exportTextures`, `export.plan`, the automation `textures.export` method and the MCP -`textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?}]`. +`textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?, size?}]`. Each entry overrides that map's export settings. The `map` field is its index in the selected -template. `enabled: false` suppresses that file while reserving its name. When several texture -sets produce the same name (ignoring case), programmatic and browser exports keep the first file -and warn about later duplicates. The desktop export window reports the collision before writing. +template. A map's `size` in pixels overrides the export size. `enabled: false` leaves out a PSD layer +or suppresses a raster file while reserving its name. When several texture sets produce the same +name (ignoring case), programmatic and browser exports keep the first file and warn about later +duplicates. The desktop export window reports the collision before writing. Texture planning +rejects a selection that uses the same path as both a file and a folder before rendering. + +`shaderParameters: true` writes `_shaders.json` beside the textures with the shader +model, its settings and the names of the exported texture sets. An array of texture set +indexes selects which sets to list. The desktop command, headless `textures.export` and MCP +`textures_export` include a written sidecar in `files` and report a sidecar write failure in +`warnings` after writing the textures. `file.exportTextures` with `usdAsset` also writes `.usd` (binary USD, Crate) next to the textures: the whole mesh (every texture set, whatever `ts` selects) with one UsdPreviewSurface material per texture set. A @@ -76,9 +91,31 @@ shared by different sets. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and -`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by +`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). +Tiled files include their UV tile number in `tile` and, when available, their filename template +with a `` placeholder in `udimPattern`. These fields are null when they do not apply. +`export.preview` takes the same parameters plus `map` (an index into the template's maps) and +`side` (the maximum width or height, in pixels, capped at 512). It returns +`{width, height, channels, pixels}` for the first texture set named by `ts`, or null when the +set writes no file for that map. For a UV-tiled set the picture shows the atlas. HDR previews +list RGB without alpha. TIFF and WebP previews list RGB or RGBA when the encoder stores +luminance in three channels. PSD previews show the output layer's RGBA channels. The preview uses 8-bit values, +with sRGB colour channels and linear data channels. Texels outside the UV islands use the +channel defaults. +`padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. +Layered PSD: the maps written as `psd` are the layers of one `_.psd` per +texture set and UV tile (`_..psd` for a tiled set), so the template's file +names don't name the file: they become the layer names, a `/` in one making layer groups. The +document name is sanitized like other file names and can be shortened or disambiguated (a +texture-set index suffix when two sets' names give the same stem, as "A B" and "A_B" do), so read +the actual names from `export.plan`. A PSD that would pass 30000 pixels a side or 2 GiB is left +out with a warning on the set's first other file (an error when it is the set's only file). In the +browser, estimates of a PSD's working buffers and of a batch's encoded PSD output are also bounded; +they don't bound the tab's total memory, as raster outputs and ZIP packaging use memory outside +them. MaterialX uses compatible companion maps for this format. USD omits their texture bindings and returns a warning. + `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 @@ -234,14 +271,14 @@ keeps its state in a throwaway file. | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | | `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, checked}` | -| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | +| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave button and the Resources Updater button (enabled while a project is open) stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | | `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a picker for a `.tcraft` file. On desktop, it copies any missing bundled samples (currently `Material Ball.tcraft`) into `Samples` under the data folder and opens the picker there. If preparation fails, it shows an error and opens the picker without a start folder. In the browser, the picker uses local files. The direct `project.sample` engine command generates a sample for automation. | | `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled | | `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) | | `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before | -| `ui.reset` | | resets the panels, view layout, zoom and every other view setting at once, without the question the Reset UI menu item asks; settings and shortcuts stay | +| `ui.reset` | | resets the panels, view settings and interface language without asking for confirmation. Other preferences and shortcuts stay | | `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.bake.cancel` | | Stops the running bake and restores the previous view mode. Finished sets stay applied. Eligible maps from the current set are kept in one undo step (see *Live bake preview*) | | `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`, `Log`, `BakingLog`, `MeshMapBakers`, `BakeMaps`, `BakeSettings`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `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), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | @@ -253,6 +290,7 @@ The empty-project menus keep Recent Projects openable with Clear disabled when t `ui.recent.clear` clears that list. More Save Options is disabled until a project is open. Help > Shortcuts list opens Settings on its Shortcuts page. Window > Reset UI restores the Assets, Layers, Properties, Texture Set List and Texture Set Settings panels and both toolbars. +It also restores Default (System Language). Baking Log and the bake/render settings views are disabled without a project. Import resources can open its dialog on desktop without a project; importing still requires an open project, and the dialog explains that asset-library import is not available yet. @@ -283,8 +321,9 @@ bake of its own, so with a high poly the transfer rays are cast once per map; th 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 +until a texture set's bake is applied (one undo step); a cancelled bake applies the maps the set it was +baking had finished in one undo step. A changed output size, a replaced mesh, or a worker failure +discards the current set's partial results. 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. @@ -307,6 +346,41 @@ also `session.inspect`'s `bakePreview`: `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. +`bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). +A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. +`highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, +`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`. `matching` lists each low poly +part with the high poly part it bakes from, then the high poly parts no set paired with; a `null` side is a part +with no partner. It is `null` when no set of the bake matches by mesh name: + +```json +{"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "texture set Head has no UV tiles selected for baking"}], + "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}], + "matching": {"lowSuffix": "_low", "highSuffix": "_high", + "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} +``` + +Each texture set in `project.inspect` / `session.inspect` lists its out-of-date mesh maps as +`outOfDate`: map id → what changed since that map was baked, any of `lowPoly`, `highPoly`, `cage`, +`settings` (the bake settings every map shares, or the UV tiles baked) and `mapSettings` (the map's +own). The low-poly inputs include its tangent frame. For Opacity and material-color ID maps that +read the low poly's material, a change to the packed mesh file also counts as `lowPoly`. +Imported maps, and maps saved before this record existed, never show: +`"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. + +`bake.autoRebake` `{ts?, map: id | null}` turns on Auto-rebake for one mesh map of a texture set +(the active one by default), replacing its previous one, or turns it off with `null`; it is saved +with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web +app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the +background, alone (with every checked map when the output size changed), once what it is baked +from has stopped changing for half a second; a change during that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that +bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV +box and pads the result. Curvature, height, thickness, UV-tiled sets, and resized maps bake +whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its +`normal` map when the set has none, in the stroke's undo step. The headless CLI does not rebake by +itself: run `bake.run` there. + A minimal client (Python, for illustration): ```python @@ -338,10 +412,16 @@ Other preferences set through `ui.set {"prefs": {...}}`: `language` (`""` follow language), `work_threads` (worker threads for painting, baking and export; 0 uses every logical CPU; read at startup), `rotation_speed` (default 2), `zoom_speed` and `wheel_speed` (default 1, each from 0.1 to 10) with `zoom_inverse` and `wheel_inverse`, `gpu_raytracing` (false keeps bake -rays on the CPU) and `libraries` (the folders the shelf scans for saved smart materials and masks). +rays on the CPU), `show_world_axes` (the 3D view's X, Y and Z corner, default true) and `libraries` +(the folders the shelf scans for saved smart materials and masks). `live_preview_baking` enables +the automatic Bake mode map preview when the panel's Map Preview switch is also on. +`show_keyboard_helper`, `only_selected_material_when_painting`, `save_preprocessed_scene_files` and +`local_cache_directory` are stored preferences for future use. For `local_cache_directory`, an +empty or relative path selects the app's per-user cache directory, or the profile cache for Nightly. For example, the `libraries` field can contain `[{"name": "Studio", "path": "/assets/studio"}]`. Use an absolute path on the host running TextureCraft. To change one preference, read `state.prefs` with `ui.inspect`, update that field and send the full `prefs` object to `ui.set`. +A `prefs` object without `language` sets the system language (`""`), the default. ## MCP server @@ -352,7 +432,8 @@ with `ui.inspect`, update that field and send the full `prefs` object to `ui.set them: `--read-root ` for `project_open` / `mesh_import` / `mesh_reimport` / `bake_mesh_add`, `--write-root ` for `project_save` / `material_save` / `textures_export` / `mesh_export` (`--automation-read-root` / `--automation-write-root`, as in the other crafting apps, are the - same flags). Without roots there is no file access. `..`, absolute + same flags). Headless mcp refuses to start unless both roots are set; file access is only + below them. `..`, absolute paths, drive letters, device names and symlink or junction escapes are refused. - **Bridge**: `--bridge ` forwards to a running `texturecraft --control ` (token from `--token`, `TEXTURECRAFT_CONTROL_TOKEN` or the app's token file). The app reads and writes its @@ -360,7 +441,8 @@ with `ui.inspect`, update that field and send the full `prefs` object to `ui.set 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`, at the top level or in +`file.reimportMesh` without a `path`) is refused, and so are `resource.status`, `resource.update` and `resource.relink` (they read +the files a project names) and 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. @@ -382,7 +464,7 @@ With `rebuildUvs: true`, the project file saves the generated layout. Reopening | `project_save` | `{path?}` | `.tcraft` (appended if missing), relative to the write root | | `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl; a .gltf's buffers and images and a loose USD layer's textures are read from its folder | | `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?}` | +| `mesh_export` | `{path, format?, recomputeNormals?}` | The mesh as obj, glb, usda, usdc or usdz below the write root; `recomputeNormals: true` writes smooth area-weighted normals on the exported copy (default false) (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); 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 | @@ -457,7 +539,7 @@ File access follows `--read-root` / `--write-root` as for MCP. | `project.save` | `{path?}` | | `mesh.import` | `{path, resolution?, name?}` | | `mesh.reimport` | `{path?, preserveStrokes?}` | -| `mesh.export` | `{path, format?}` | +| `mesh.export` | `{path, format?, recomputeNormals?}` | | `bake.mesh.add` | `{path, cage?}` | | `resource.import` | `{path}` | | `material.save` | `{path, layer?, name?}` | @@ -482,6 +564,31 @@ 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 ``` +## Resources Updater + +An image resource read from a file remembers that file (its absolute path and modification time, +saved with the project): `resource.import {path}`, the images `file.importPbrFolder` stores unchanged +(not ORM channels split out, not archive entries), the images of `file.importMaterialX` and the files of +`textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the +old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater +window lists the project's images and linked MaterialCraft packages. It checks image files when it opens, on +Refresh, twice a second while it stays open, once after a project opens and when the app gets the +focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of +outdated resources differs from the last notice. A file whose size matches but whose time changed is +read once. Its verdict is kept until its size or time changes again. When the file has no usable +modification time, each check compares its contents. + +| Command | Params and result | +|---|---| +| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate`, `noSource` (made in the app or imported without a path) or `material` (the package of a linked MaterialCraft material, stored in the project without a source file); outdated first, then by name. An equal-size file is compared when its modification time changed or is unknown | +| `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | +| `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | + +For linked fill layers, `material.link.cook` refreshes the separate cooked image maps from the stored package. + +These commands read host paths stored in the project, so MCP and `serve` refuse them through +`command_run`; the desktop app's control channel and the trusted local CLI run them. + ## PBR texture folders `file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer @@ -626,6 +733,10 @@ None is an undo step. `display.set` also takes `alignment` (`world` or `camera`: the environment, and the key light with it, turns with the camera about the vertical axis), `shadowMode` (`intensive`, `average` or `lightweight`, the default: the shadow map's resolution) and `shadowOpacity` (0 to 1, default 1: how dark the shadows are). +Set `iorSpecular` to true to derive the Metallic Roughness surface reflectance at normal incidence +from `ior` (clamped to 1–3). Specular Level scales this reflectance in the viewport, both path +tracers and F0 map export. Path-traced transmission uses its own Fresnel calculation for glass +interfaces. The setting defaults to false and is saved with the project and its templates. `viewport.view {mode: "image", image: }` shows a project image as it is, stretched over the UV square, on the mesh and in the 2D view (the view picker's "Other..."). `display.set {soloUnlit}` @@ -714,15 +825,15 @@ set. ## CLI ```sh -texturecraft-cli --version # TextureCraft 0.1.0 (abc1234 2026-10-14) +texturecraft-cli --version # texturecraft-cli 0.1.0 (abc1234 2026-10-14) texturecraft-cli info model.glb # triangles, materials, UV report texturecraft-cli info project.tcraft # texture sets, layers, baked maps -texturecraft-cli commands --filter mask +texturecraft-cli commands --filter mask --json texturecraft-cli new builtin:material_ball ball.tcraft --resolution 1024 --sample # mesh maps baked at ≤ 1024 px texturecraft-cli new model.glb model.tcraft --resolution 2048 -texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft +texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft --in-place texturecraft-cli batch script.json -texturecraft-cli bake model.tcraft --resolution 2048 --maps ambientOcclusion,curvature,thickness +texturecraft-cli bake model.tcraft --resolution 2048 --maps ambientOcclusion,curvature,thickness --in-place texturecraft-cli export model.tcraft out/ --preset "Unreal Engine (Packed)" --format png --size 2048 texturecraft-cli render ball.tcraft ball.png --size 1280x800 --view 3d --yaw 30 --pitch 15 texturecraft-cli render scene.tcraft hero.png --size 1200x900 --camera Hero --samples 2048 # a saved camera (camera.add), path traced @@ -743,5 +854,24 @@ steps or an object with an optional input and output (paths relative to the curr } ``` -Errors print `texturecraft-cli : error: …` and exit 1; usage errors exit 2. The CLI is a -console program and never opens a window; `render` needs a GPU or software adapter. +The CLI is a console program and never opens a window; `render` needs a GPU or software adapter. + +`texturecraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md) +(command-line conventions); `texturecraft-cli --help` and ` --help` are the reference for every flag. +Exit status: 0 success, 1 a command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that +conflict or that the subcommand doesn't use, all checked before any file is touched), and 128 plus the signal number +when a signal ends the process. Errors are `error: ` on stderr. `--version`/`-V` work on every subcommand +(`texturecraft-cli 0.6.1 ( )`, with no `version` subcommand), and no arguments print the help on +stderr and exit 2. `info`, `run`, `batch` and `bake` print JSON because agents read it; `commands --json` prints the +list as JSON where it prints a table without it. + +- **Environment.** `TEXTURECRAFT_CONTROL_TOKEN` is the one variable the CLI reads for a flag (`mcp --bridge`'s + `--token`; `serve --port` reads it for its own token). The flag wins, an empty or blank variable counts as unset, + and `--help` never shows its value. No variable grants file access (roots come from `--read-root`/`--write-root`) + or replaces a file. The app's own `TEXTURECRAFT_NO_PREFS` is a setting of the app, not a flag fallback. +- **Replacing files.** `run -o` and `bake -o` onto the project they opened, and `bake` of a project without `-o`, + need `--in-place`; `render` and `new` never replace their input, and `bake` of a mesh needs `-o`. +- **Packages.** The Linux packages (deb, rpm, tar.gz) and the FreeBSD package install `texturecraft-cli`'s man pages + and its bash, zsh and fish completions. Nightly packages ship no CLI, so none; macOS and Windows are outside + RFC-0018's scope. +- **Not yet.** The ast-grep scan of RFC-0018 section 3 is not switched on. diff --git a/docs/features.md b/docs/features.md index 520ff678..e66cc81e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -98,6 +98,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and alpha images become the brush alpha. Filter by role or remove selected rows before importing. Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are unavailable. The browser imports images straight from its file picker. +- **Resources Updater:** the desktop tool shelf lists the project's image resources, with outdated + resources first. Filter by status or name, and use *Show in folder* to find a linked file. Images + imported from disk through Import resources, PBR folders, MaterialX and mesh map import remember + their source file. *Update* and *Update All* reread changed files in one undo step. Layers see the + updated image, and an imported mesh map refreshes while it still matches the previous source. + *Select new resource* links an image to another file. The list refreshes while the window is open, + and a notice offers *Update* when changed files are found on opening a project or regaining focus. + Linked MaterialCraft packages appear without a source file. Re-cooking a linked fill layer refreshes + its cooked maps. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under @@ -164,9 +173,20 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel with the summary and the message for each failed set. - **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. +- **Baking Log** at the bottom of Bake mode: the latest bake map by map (Baking Process), the high + poly files each set loads (High Poly Parameters) and how parts paired by name (Matching by Name), + with an issues filter; a failed or canceled map opens its settings. `bake.log` returns the same rows. +- **Out-of-date mesh maps:** each bake records what every map was baked from; a map whose mesh, high + poly, cage or settings changed since shows a clock in Mesh Map Bakers (`outOfDate` in + `project.inspect`), and a generator reading a missing or out-of-date map shows one line with a + Bake button. +- **Auto-rebake:** one map per texture set (`bake.autoRebake`, a row icon in Mesh Map Bakers) is + baked again in the background in Bake mode once what it is baked from stops changing. On an + eligible map, a skew or cage stroke rebakes the stroke's box and pads the result. The first skew + stroke turns it on for the Normal map if the set has no Auto-rebake map. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, Sketchfab (metalness), separate maps, mesh maps and document channels, in PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. @@ -254,10 +274,17 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Swap 3D/2D** (F4, Viewport menu and the layout dropdown, rebindable) puts the 2D view on the left and the 3D view on the right in the split layout. Painting, the divider and the views' headers work on both sides, and the choice is kept with the UI state. - A modern look in **four brightness levels** (dark, medium dark, medium light and light) with - **seven accent colors**, set in Settings › General › Appearance. + **seven accent colors**, set for now only through `ui.set` (`prefs.brightness`, `prefs.accent`). - **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same - strip, and Settings › General › Appearance › System title bar for the system's frame instead. + strip, and the system's frame instead with `prefs.system_title_bar` through `ui.set` (for now). +- **A pen on a Linux Wayland desktop** can move the cursor and paint as a pointer through Xwayland. + At launch, TextureCraft uses Xwayland when it detects a pen, finds the X11 libraries and the + local X server accepts setup. Otherwise it uses native Wayland. Set + `TEXTURECRAFT_NATIVE_WAYLAND=1` to keep native Wayland. The Flatpak grants X11 access only as a + fallback when Wayland is unavailable. Linux pen pressure is tracked separately in + [#818](https://github.com/storytold/texturecraft/pull/818) and + [#816](https://github.com/storytold/texturecraft/issues/816). - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar. @@ -277,21 +304,28 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **No project at launch**: empty views, panels and toolbars until you create or open one (File › New project, Open, Recent projects, Open sample project); File › Close returns to that state. - A **data folder** of your choice for autosaves, smart materials, presets, templates and UI - layouts, on any drive (Settings › General › Folders; `Documents/TextureCraft` by default). + layouts, on any drive (Settings › General › Files › Data folder, with `Documents/TextureCraft` as + the default). Nightly shows its fixed profile path in the same row. +- **Autosave**: each project keeps its own copy in the data folder's `autosave`, named + `-copy-.tcraft` after its saved file (or, until it is saved, the project), so projects made from + one mesh never overwrite each other's copy. - A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits (worker threads, cores kept for the UI, RAM while saving, project size on open) and the autosave - interval. Shortcuts rebinds any command in the sections Actions, Mouse shortcuts and Modifiers shortcuts (Delete clears a binding, a shared shortcut warns and keeps OK disabled, Reset all to default restores every key); the window reopens on the page it was closed on. Libraries adds or removes folders whose saved smart + interval. Reset UI restores the system language. The General page also controls the automatic + Bake mode map preview. Shortcuts rebinds any command in the sections Actions, Mouse shortcuts and Modifiers shortcuts (Delete clears a binding, a shared shortcut warns and keeps OK disabled, Reset all to default restores every key); the window reopens on the page it was closed on. Libraries adds or removes folders whose saved smart materials and masks the shelf lists. -- The **shortcut list** (Settings › Shortcuts and Help › Shortcuts list) names the actions as the reference does and starts with its default keys (Switch to baking mode Ctrl+Shift+B, Select next and previous camera `>` and `<`, Viewers layout F1 to F4); Show mesh wireframe is a bindable command. +- The **shortcut list** (Settings › Shortcuts and Help › Shortcuts list) names the actions as the reference does and starts with its default keys (Switch to baking mode F8, Select next and previous camera `>` and `<`, Viewers layout F1 to F4); Show mesh wireframe is a bindable command. - A **shortcut editor** with conflict detection, listing every menu item and every command a key can run (commands that need a path, name or similar are left out), and every shortcut shown in its tooltip. - **Help menu:** Release notes... opens the project's releases page. Export log... writes every channel to a text file with each entry's recorded UTC time, severity and source. The desktop app asks for a destination, and the browser downloads the file. - A **History** panel: click any step to go back to it, or forward again to an undone one. -- **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, - Korean and Arabic, switchable live. +- **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese, + Chinese, Korean and Arabic, switchable live. A build without the shared craft-i18n catalogs + offers English only, and Japanese, Chinese, Korean and Arabic can be picked only where a font + for their script is available (craft-fonts or the system's); otherwise they show greyed out. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch navigation and project open, save and download. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index fb6a8a49..3625d0cd 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -29,6 +29,7 @@ generator, filter and brush alpha names (**KEYS** strings, counted by the | Arabic | `ar` | KEYS (100%) | yes | Arabic glyphs: craft-fonts (Noto Sans Arabic) or system fonts on desktop; egui shapes the text and orders it right to left (panels keep the left-to-right layout) | yes | full | 0 h | | French | `fr` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | | Portuguese (Brazil) | `pt-BR` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | +| Russian | `ru` | KEYS (~99%) | yes | Cyrillic: egui's built-in fonts | yes | full with the craft-i18n `ru/texturecraft.tsv` catalog | 0 h | | Indonesian | `id` | 0 | no | Latin | no | none | 3 h | | Japanese | `ja` | KEYS (100%) | yes | CJK glyphs: craft-fonts (BIZ UDPGothic) or system fonts on desktop | no | full | 2 h (review) | | German | `de` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 6ed80ba0..616c743c 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -15,8 +15,8 @@ gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation permissions are for its isolated attester; its compiler narrows to contents and Actions read only, with no OIDC, attestation write, release environment or platform signing secrets. -Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions -main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the +Shared tooling is pinned to `f94a43818dabb2e85f2f4d5cd768bb8e5662600a`, the craft-common-actions +main commit that merged [#382](https://github.com/storytold/craft-common-actions/pull/382) (first-signer-attempt creation time is reconciled on re-read) after [#371](https://github.com/storytold/craft-common-actions/pull/371) (the candidate is admitted on the built commit's own Sonar analysis, not main's latest) after [#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly registry rows for the 14 apps) and @@ -80,7 +80,7 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` |---|---|---| | `repository_id` | `1419654881` | `gh api repos/storytold/texturecraft --jq .id` | | `producer_workflow_id` | `429738073` | `gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id` | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions #371 after #370, #369 and #364) | The callers' pin | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `f94a4381…` (craft-common-actions #382 after #379, #376, #371, #370, #369 and #364) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | Stable suite signing identities (`Learning Machines Inc` Authenticode subject, Linux OpenPGP fingerprint `2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, Apple Team ID `DJ6XS33FX8`) | diff --git a/docs/parity.md b/docs/parity.md index a8bc242d..bf1345ae 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -4,97 +4,99 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac **63 of 64 menu items live (98%).** +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 39 no (window 33, os 5, engine-gap 1), 4 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`). + ## File -| Item | Id | Shortcut | Status | -|---|---|---|---| -| New Project | `ui.newProject` | Ctrl+N | live | -| Open | `file.open` | Ctrl+O | live | -| Recent Projects ▸ Clear | `ui.recent.clear` | | live | -| Open Sample Project | `project.sample` | | live | -| Close | `file.close` | Ctrl+F4 | live | -| Save | `file.save` | Ctrl+S | live | -| Save As | `file.saveAs` | Ctrl+Shift+S | live | -| More Save Options ▸ Save As Template | `ui.saveAsTemplate` | | live | -| More Save Options ▸ Save and Reduce File Size | `ui.saveReduced` | | missing | -| More Save Options ▸ Save As Copy | `file.saveCopy` | | live | -| Remove Unused Resources | `file.removeUnused` | | live | -| Import Resources | `resource.import` | | live | -| Export Textures | `ui.export` | Ctrl+Shift+E | live | -| Export Mesh | `file.exportMesh` | | live | -| Quit | `ui.quit` | Ctrl+Q | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| New Project | `ui.newProject` | Ctrl+N | live | partial, reach: window (the dialog is desktop-only; `project.new` creates the project) | +| Open | `file.open` | Ctrl+O | live | yes | +| Recent Projects ▸ Clear | `ui.recent.clear` | | live | no, reach: window (the desktop recent-projects list) | +| Open Sample Project | `project.sample` | | live | yes | +| Close | `file.close` | Ctrl+F4 | live | yes | +| Save | `file.save` | Ctrl+S | live | yes | +| Save As | `file.saveAs` | Ctrl+Shift+S | live | yes | +| More Save Options ▸ Save As Template | `ui.saveAsTemplate` | | live | partial, reach: window (the dialog is desktop-only; `project.template.save` saves it) | +| More Save Options ▸ Save and Reduce File Size | `ui.saveReduced` | | missing | no, reach: engine-gap (a smaller save could be a command) | +| More Save Options ▸ Save As Copy | `file.saveCopy` | | live | yes | +| Remove Unused Resources | `file.removeUnused` | | live | yes | +| Import Resources | `resource.import` | | live | yes | +| Export Textures | `ui.export` | Ctrl+Shift+E | live | partial, reach: window (the dialog is desktop-only; `file.exportTextures` exports) | +| Export Mesh | `file.exportMesh` | | live | yes | +| Quit | `ui.quit` | Ctrl+Q | live | no, reach: window (quits the desktop app) | ## Edit -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Undo | `edit.undo` | Ctrl+Z | live | -| Redo | `edit.redo` | Ctrl+Y | live | -| Project Configuration | `ui.projectConfig` | | live | -| Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | -| Settings | `ui.settings` | | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Undo | `edit.undo` | Ctrl+Z | live | yes | +| Redo | `edit.redo` | Ctrl+Y | live | yes | +| Project Configuration | `ui.projectConfig` | | live | partial, reach: window (the dialog is desktop-only; `project.rename` sets the project name) | +| Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | yes | +| Settings | `ui.settings` | | live | no, reach: window (the desktop settings window) | ## Mode -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Bake Mesh Maps | `ui.mode.bake` | F8 | live | -| Painting | `ui.mode.paint` | F9 | live | -| Rendering | `ui.mode.render` | F10 | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Bake Mesh Maps | `ui.mode.bake` | F8 | live | no, reach: window (switches the desktop workspace; `bake.run` bakes) | +| Painting | `ui.mode.paint` | F9 | live | no, reach: window (switches the desktop workspace) | +| Rendering | `ui.mode.render` | F10 | live | no, reach: window (switches the desktop workspace) | ## Window -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Views ▸ Assets | `ui.view.assets` | | live | -| Views ▸ Baking Log | `ui.view.bakingLog` | | live | -| Views ▸ Common Settings | `ui.view.bakeSettings` | | live | -| Views ▸ Display Settings | `ui.view.display` | | live | -| Views ▸ Export | `ui.view.export` | | 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 ▸ Renderer Settings | `ui.view.renderer` | | live | -| Views ▸ Shader Settings | `ui.view.shader` | | live | -| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | -| Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | -| Toolbars ▸ Docks | `ui.toolbar.docks` | | live | -| Toolbars ▸ Tools | `ui.toolbar.tools` | | live | -| Save UI Layout ▸ Painting Mode | `ui.layout.save.painting` | | live | -| Save UI Layout ▸ Rendering Mode | `ui.layout.save.rendering` | | live | -| Save UI Layout ▸ Baking Mode | `ui.layout.save.baking` | | live | -| Load UI Layout | `ui.layout.load` | | live | -| Hide UI | `ui.hideUi` | Tab | live | -| Reset UI | `ui.resetUi` | | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Views ▸ Assets | `ui.view.assets` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Baking Log | `ui.view.bakingLog` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Common Settings | `ui.view.bakeSettings` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Display Settings | `ui.view.display` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Export | `ui.view.export` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ History | `ui.view.history` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Layers | `ui.view.layers` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Log | `ui.view.log` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Mesh Map Bakers | `ui.view.meshMapBakers` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Mesh Map Settings | `ui.view.bakeMaps` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Properties | `ui.view.properties` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Renderer Settings | `ui.view.renderer` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Shader Settings | `ui.view.shader` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | no, reach: window (a desktop panel or toolbar) | +| Toolbars ▸ Docks | `ui.toolbar.docks` | | live | no, reach: window (a desktop panel or toolbar) | +| Toolbars ▸ Tools | `ui.toolbar.tools` | | live | no, reach: window (a desktop panel or toolbar) | +| Save UI Layout ▸ Painting Mode | `ui.layout.save.painting` | | live | no, reach: window (desktop window layout) | +| Save UI Layout ▸ Rendering Mode | `ui.layout.save.rendering` | | live | no, reach: window (desktop window layout) | +| Save UI Layout ▸ Baking Mode | `ui.layout.save.baking` | | live | no, reach: window (desktop window layout) | +| Load UI Layout | `ui.layout.load` | | live | no, reach: window (desktop window layout) | +| Hide UI | `ui.hideUi` | Tab | live | no, reach: window (desktop window layout) | +| Reset UI | `ui.resetUi` | | live | no, reach: window (desktop window layout) | ## Viewport -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Display Material | `viewport.displayMaterial` | M | live | -| Display Next Channel | `viewport.nextChannel` | C | live | -| Display Previous Channel | `viewport.previousChannel` | Shift+C | live | -| Display Next Mesh Map | `viewport.nextMeshMap` | B | live | -| Display Previous Mesh Map | `viewport.previousMeshMap` | Shift+B | live | -| Show Entire Mesh/Path | `viewport.frame` | F | live | -| Enable Quick Mask | `viewport.quickMask` | Y | live | -| Edit Quick Mask | `viewport.quickMask.edit` | U | live | -| Invert Quick Mask | `viewport.quickMask.invert` | Ctrl+Shift+I | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Display Material | `viewport.displayMaterial` | M | live | yes | +| Display Next Channel | `viewport.nextChannel` | C | live | yes | +| Display Previous Channel | `viewport.previousChannel` | Shift+C | live | yes | +| Display Next Mesh Map | `viewport.nextMeshMap` | B | live | yes | +| Display Previous Mesh Map | `viewport.previousMeshMap` | Shift+B | live | yes | +| Show Entire Mesh/Path | `viewport.frame` | F | live | yes | +| Enable Quick Mask | `viewport.quickMask` | Y | live | yes | +| Edit Quick Mask | `viewport.quickMask.edit` | U | live | yes | +| Invert Quick Mask | `viewport.quickMask.invert` | Ctrl+Shift+I | live | yes | ## Help -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Release Notes | `ui.help.releaseNotes` | | live | -| Documentation | `ui.help.docs` | | live | -| Shortcuts List | `ui.help.shortcuts` | | live | -| Discord | `ui.help.discord` | | live | -| Report a Bug | `ui.help.bug` | | live | -| Show Log | `ui.help.showLog` | | live | -| Export Log | `ui.help.exportLog` | | live | -| Check for Updates | `ui.help.checkForUpdates` | | live | -| About TextureCraft | `ui.about` | | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Release Notes | `ui.help.releaseNotes` | | live | no, reach: os (opens a web page in the browser) | +| Documentation | `ui.help.docs` | | live | no, reach: os (opens a web page in the browser) | +| Shortcuts List | `ui.help.shortcuts` | | live | no, reach: window (a desktop window) | +| Discord | `ui.help.discord` | | live | no, reach: os (opens a web page in the browser) | +| Report a Bug | `ui.help.bug` | | live | no, reach: os (opens a web page in the browser) | +| Show Log | `ui.help.showLog` | | live | no, reach: window (a desktop window) | +| Export Log | `ui.help.exportLog` | | live | no, reach: window (saves the desktop app's log) | +| Check for Updates | `ui.help.checkForUpdates` | | live | no, reach: os (an online update check) | +| About TextureCraft | `ui.about` | | live | no, reach: window (a desktop window) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1e45c49d..73f4c393 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -71,8 +71,10 @@ that closes it back onto the bar; the float is saved with the UI state. with materials that refer to the exported textures; greyed in the browser), *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). *Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` to the - export. The prompt's *With displacement/tessellation* choice and both option checkboxes are - greyed; TextureCraft exports the mesh as it is. + export. The prompt's *With displacement/tessellation* choice and *Apply triangulation* are greyed + (TextureCraft exports the mesh as it is, triangulated). *Recompute vertex normals* works and sits under + *Without displacement/tessellation*, off by default: it writes smooth area-weighted normals to the + exported copy only. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering mode), *Properties - Paint* while a project is open (other tools read "Properties - ", @@ -154,7 +156,7 @@ that closes it back onto the bar; the float is saved with the UI state. | UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | | UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged | | UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid | -| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (with Default (System Language)), the camera rotation, zoom and wheel speeds with Inverse direction, Enable GPU raytracing, the Shortcuts page and adding or removing library locations work. Show keyboard helper, Show world axes, Background color, Only display the selected material when painting, Viewport Scaling, Default UV scale for materials, simplified thumbnails, the other baking options, the preview cache and shader, the temporary cache directory, sparse virtual texture and the IRAY HARDWARE choices are shown disabled with "Not available yet". A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. TextureCraft's own settings (appearance, viewport textures, resources, autosave, folders) follow the reference sections | Run the window in the native app; wire each disabled control as its function lands | +| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (Default (System Language) by default and after a reset), the camera rotation, zoom and wheel speeds with Inverse direction, Show world axes (the 3D view's X, Y and Z corner), the Shortcuts page and adding or removing library locations work. Enable GPU raytracing defaults to on when the native bake adapter supports its compute shaders. Unsupported hardware and the browser show it off and disabled ([#823](https://github.com/storytold/texturecraft/issues/823)). Show keyboard helper (on), Only display the selected material when painting (off), Save preprocessed scene files (on) and the Local cache directory are editable preferences saved for future use. R restores the default per-user cache path or the Nightly profile cache path. Enable live preview baking process (on) controls the automatic Bake mode map preview when the panel's Map Preview switch is also on. Viewport Scaling opens but lists only Auto, so there is nothing to change. Default UV scale for materials, simplified thumbnails, the preview cache budget and shader, the Files cache directory and sparse virtual texture are shown disabled with "Not available yet". There is no IRAY HARDWARE section. A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Save as project", "Switch to baking mode" F8, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". Seven unavailable transform and warp actions follow "Export Textures...". Their example keys can still be bound to working commands. The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under Baking options when GPU baking is unavailable. The reference's TEMPORARY FILES section is called FILES and also holds the Data folder. Stable installations can edit the path. Nightly shows the fixed profile path. TextureCraft's own settings follow the reference sections: RESOURCES (Max CPU threads for work, default every thread, and Cores kept for the UI as sliders in steps of 1 with the core count beside them, Max RAM while saving as a 0-100% slider, Max project size on open, Recent projects limit) and AUTOSAVE. There is no appearance, viewport, folders or analytics section: the viewport texture resolution (Full, Half, Quarter) is in Display Settings › Render settings, and interface scale, brightness, accent color and the system title bar stay in the saved settings and `ui.set` | Run the window in the native app; wire each disabled control as its function lands | Bake workflow (issue [#651](https://github.com/storytold/texturecraft/issues/651)): Mesh Map Bakers has a Presets menu (save, load, delete named bake settings; Apply to All Texture Sets) and a finished @@ -189,7 +191,7 @@ list, not a feature-completion denominator. | F09 Generator editing | UI | Pass | Layer context menu added a generator to that mask. Selecting Position and dragging Global balance changed the mask/viewport; inspection recorded balance about 0.279 | | F10 Duplicate an effect | UI | Pass | Ctrl+D produced a separate Generator copy with the same parameters and a Duplicate effect history step | | F11 UV rectangle fill | UI | Pass | Tool 4, UV-island mode and a rectangle across two UV islands wrote 88 tiles per painted channel on a new paint layer. Undo removed that fill. Topology was visible in the tool | -| F12 Bake from the UI | UI | Pass | F8 (now Ctrl+Shift+B), 256 px, low mesh used as high mesh, Check All and Bake completed all ten map types. The UI log reported CPU execution; this is separate from the GPU command check | +| F12 Bake from the UI | UI | Pass | F8, 256 px, low mesh used as high mesh, Check All and Bake completed all ten map types. The UI log reported CPU execution; this is separate from the GPU command check | | F13 Texture-export flow | UI + accessibility text entry | Pass | Inspected Settings, Output templates and List of exports, then clicked Export. Eight 1024 px PNGs decoded successfully; all eight were byte-identical to command exports from the same saved project/options. The base-color output was inspected visually. Template creation/editing was not exercised | | F14 Save and reopen | Mixed | Pass within scope | Ctrl+S and the native Save As dialog saved four layers, two generator effects, 21 painted tiles per channel and ten 256 px baked maps. Reopening through `file.open` matched inspected layers, texture sets and mesh. This was not a complete keyboard-only open-dialog test | | F15 Smaller window | Scripted resize + UI inspection | Partial | 1280 × 800 rendered with working layout structure; the readability limits are UI-13. No full task suite at that size | diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 6927f0a4..39ff32fa 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -54,8 +54,14 @@ 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}" +# The man-and-completions example writes texturecraft-cli's man pages and shell completions below. +# It is built in its own cargo run: built with the binaries, its dev-dependencies' features would +# be unified into them. if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli) + # The example is run on this host to write man pages and completions, so it must be a host + # binary even when CARGO_BUILD_TARGET is set for a cross package. + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p texturecraft-cli --example man-and-completions) fi WORK="$CARGO_TARGET_DIR/freebsd-package" STAGE="$WORK/$BASENAME" @@ -73,6 +79,16 @@ if [[ "$DRY_RUN" = 1 ]]; then printf '#!/bin/sh\necho "%s %s (dry-run stub)"\n' "$b" "$VERSION" >"$BIN/$b" chmod 755 "$BIN/$b" done + # A stub of the example: it writes the files the real one does. + mkdir -p "$BIN/examples" + cat >"$BIN/examples/man-and-completions" <<'STUB' +#!/bin/sh +mkdir -p "$1" +for f in texturecraft-cli.bash _texturecraft-cli texturecraft-cli.fish texturecraft-cli.elv _texturecraft-cli.ps1 texturecraft-cli.1 texturecraft-cli-info.1; do + echo "dry-run stub" >"$1/$f" +done +STUB + chmod 755 "$BIN/examples/man-and-completions" fi # ---- stage a /usr/local-style tree -------------------------------------------------------------- @@ -88,10 +104,32 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$TEXTURECRAFT_BUILD_DATE/g" \ "$LINUX/$APP_ID.metainfo.xml.in" >"$STAGE/share/metainfo/$APP_ID.metainfo.xml" cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" copy_docs "$STAGE/share/doc/texturecraft" +# texturecraft-cli's man pages and shell completions, from its clap definition, written by the +# example built above (a --skip-build run needs it built too). Under /usr/local, man pages go in +# man/ and the completions in the directories bash, zsh and fish read there. +if [[ "$DRY_RUN" = 1 ]]; then + CLI_DOCS="$BIN/examples/man-and-completions" +else + # Host path: the example is built with CARGO_BUILD_TARGET unset, above. + CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" +fi +if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p texturecraft-cli --example man-and-completions)" >&2 + exit 1 +fi +"$CLI_DOCS" "$WORK/cli-docs" +mkdir -p "$STAGE/man/man1" "$STAGE/share/bash-completion/completions" \ + "$STAGE/share/zsh/site-functions" "$STAGE/share/fish/vendor_completions.d" +install -m 644 "$WORK"/cli-docs/*.1 "$STAGE/man/man1/" +install -m 644 "$WORK/cli-docs/texturecraft-cli.bash" "$STAGE/share/bash-completion/completions/texturecraft-cli" +install -m 644 "$WORK/cli-docs/_texturecraft-cli" "$STAGE/share/zsh/site-functions/_texturecraft-cli" +install -m 644 "$WORK/cli-docs/texturecraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/texturecraft-cli.fish" 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 + share/doc/texturecraft/LICENSE-MIT share/doc/texturecraft/LICENSE-APACHE \ + man/man1/texturecraft-cli.1 share/bash-completion/completions/texturecraft-cli share/zsh/site-functions/_texturecraft-cli \ + share/fish/vendor_completions.d/texturecraft-cli.fish; do if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done diff --git a/packaging/linux/ai.storyteller.texturecraft.desktop b/packaging/linux/ai.storyteller.texturecraft.desktop index 8c27063c..d2b626cf 100644 --- a/packaging/linux/ai.storyteller.texturecraft.desktop +++ b/packaging/linux/ai.storyteller.texturecraft.desktop @@ -1,8 +1,11 @@ [Desktop Entry] Type=Application Name=TextureCraft +Name[ru]=TextureCraft GenericName=3D Texture Painter +GenericName[ru]=Рисование 3D-текстур Comment=Paint PBR textures directly on 3D meshes +Comment[ru]=Рисование PBR-текстур прямо на 3D-моделях Exec=texturecraft %F TryExec=texturecraft Icon=ai.storyteller.texturecraft @@ -11,4 +14,5 @@ StartupNotify=true StartupWMClass=ai.storyteller.texturecraft Categories=Graphics;3DGraphics; Keywords=texture;paint;pbr;material;3d;mesh;bake;gltf;fbx;usd; +Keywords[ru]=текстура;рисование;pbr;материал;3d;сетка;меш;запекание;gltf;fbx;usd; MimeType=application/x-texturecraft;model/gltf-binary;model/gltf+json;model/x-fbx;model/vnd.collada+xml;model/x-usd;model/vnd.usda;model/vnd.usdz+zip;model/x-alembic;model/obj;model/x-ply;model/stl; diff --git a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in index e04f156c..65088b0f 100644 --- a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in +++ b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in @@ -1,4 +1,5 @@ + @@ -7,6 +8,7 @@ MIT OR Apache-2.0 TextureCraft Paint PBR textures directly on 3D meshes + Рисование PBR-текстур прямо на 3D-моделях Learning Machines LLC @@ -16,11 +18,21 @@ expect: familiar menus, shortcuts, panels and tools, with texture sets, layers, masks, fills and effects painted straight onto the model.

+

+ TextureCraft — открытая нативная программа для рисования 3D-текстур, устроенная так, + как привыкли художники по текстурам: знакомые меню, сочетания клавиш, панели и + инструменты, а наборы текстур, слои, маски, заливки и эффекты наносятся прямо на + модель. +

  • Open glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY and STL meshes and save projects as .tcraft
  • +
  • Открытие сеток glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY и STL и сохранение проектов в .tcraft
  • Paint base colour, roughness, metallic, normal and height together with PBR brushes
  • +
  • Рисование базового цвета, шероховатости, металличности, нормалей и высоты одновременно с помощью PBR-кистей
  • Bake mesh maps and export texture sets as PNG, EXR, TGA, JPEG or TIFF
  • +
  • Запекание карт сетки и экспорт наборов текстур в PNG, EXR, TGA, JPEG или TIFF
  • Every action is a command, scriptable from a CLI and a JSON control channel
  • +
  • Каждое действие — это команда, которую можно вызывать из CLI и через управляющий канал JSON
ai.storyteller.texturecraft.desktop @@ -36,9 +48,13 @@ texture painting + рисование текстур pbr + pbr 3d + 3d mesh + сетка #f0c39c diff --git a/packaging/linux/ai.storyteller.texturecraft.mime.xml b/packaging/linux/ai.storyteller.texturecraft.mime.xml index cf5204b3..cb7c1b99 100644 --- a/packaging/linux/ai.storyteller.texturecraft.mime.xml +++ b/packaging/linux/ai.storyteller.texturecraft.mime.xml @@ -5,12 +5,14 @@ TextureCraft project + Проект TextureCraft glTF binary model + Двоичная модель glTF @@ -18,11 +20,13 @@ glTF model + Модель glTF FBX model + Модель FBX @@ -30,11 +34,13 @@ COLLADA model + Модель COLLADA Universal Scene Description + Universal Scene Description @@ -44,17 +50,20 @@ Universal Scene Description (text) + Universal Scene Description (текст) Universal Scene Description package + Пакет Universal Scene Description Alembic model + Модель Alembic @@ -62,11 +71,13 @@ Wavefront OBJ model + Модель Wavefront OBJ PLY model + Модель PLY @@ -75,6 +86,7 @@ STL model + Модель STL diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 1cea1c4b..bbabbf7e 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -81,6 +81,13 @@ contents: - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree + # Debian's zsh reads vendor-completions, not /usr/share/zsh/site-functions as Fedora's and + # openSUSE's do (its debian/rules sets --enable-additional-fpath). package.sh drops this entry + # from a Nightly build, which has no CLI. + - src: /usr/share/zsh/site-functions/_texturecraft-cli + dst: /usr/share/zsh/vendor-completions/_texturecraft-cli + type: symlink + packager: deb scripts: postinstall: packaging/linux/postinst.sh diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 8c2ca936..52358cf4 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -65,6 +65,14 @@ echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS, channel=${TEXTURECRAF if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) + # The man-and-completions example writes texturecraft-cli's man pages and shell completions + # below (Stable only: a Nightly ships no CLI). It is built in its own cargo run: built with the + # binaries, its dev-dependencies' features would be unified into them. It is run here, so a + # cross build builds it for the host. + if [[ "$IS_NIGHTLY" = 0 ]]; then + # Unset CARGO_BUILD_TARGET so a cross package still builds a host example (run below). + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p texturecraft-cli --example man-and-completions) + fi fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" WORK="$CARGO_TARGET_DIR/linux-package" @@ -80,6 +88,20 @@ install -Dm755 "$BIN/texturecraft" "$STAGE/usr/bin/texturecraft" if [[ "$IS_NIGHTLY" = 0 ]]; then install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true + # texturecraft-cli's man pages and shell completions (RFC-0018 rule 1.9), from its clap + # definition, written by the example built above (a --skip-build run needs it built too). zsh + # reads site-functions on Fedora and openSUSE; the deb also links the completion into Debian's + # vendor-completions (nfpm.yaml). + CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" + if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p texturecraft-cli --example man-and-completions)" >&2 + exit 1 + fi + "$CLI_DOCS" "$WORK/cli-docs" + install -Dm644 -t "$STAGE/usr/share/man/man1" "$WORK"/cli-docs/*.1 + install -Dm644 "$WORK/cli-docs/texturecraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/texturecraft-cli" + install -Dm644 "$WORK/cli-docs/_texturecraft-cli" "$STAGE/usr/share/zsh/site-functions/_texturecraft-cli" + install -Dm644 "$WORK/cli-docs/texturecraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/texturecraft-cli.fish" fi install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" if [[ "$IS_NIGHTLY" = 1 ]]; then @@ -192,6 +214,9 @@ WRAPPER # A Nightly package has no CLI, so its file list must not name one either. # shellcheck disable=SC2016 [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI='\|^ - src: \${STAGE}/usr/bin/\${NFPM_CLI}|,+2d;/Includes texturecraft-cli/d;' + # ... nor the zsh link into Debian's vendor-completions for the CLI's completion. + # shellcheck disable=SC2016 + [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI="$DROP_CLI"'\|^ - src: /usr/share/zsh/site-functions/_texturecraft-cli|,+3d;' # shellcheck disable=SC2016 sed "${DROP_LIB_TREE}${DROP_CLI}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39.