diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7bef15d1..1145b532 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,6 @@ jobs: # Same craft-fonts commit as release.yml. craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc os: '["ubuntu-24.04","windows-latest"]' - toolchain: "1.96.0" # xtask ci runs cargo test (including doctests), not cargo nextest. tools: "" packages: >- diff --git a/AGENTS.md b/AGENTS.md index c9b40de3..9a78849f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -229,3 +229,7 @@ after every arc of work that builds and passes. - `docs/releasing.md`: release builds and signing. - `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent. - `log/` (local, gitignored): the dev log. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage. diff --git a/CODE_STYLE.md b/CODE_STYLE.md new file mode 100644 index 00000000..92a74a1c --- /dev/null +++ b/CODE_STYLE.md @@ -0,0 +1,77 @@ +# Code style + +Style conventions for TextureCraft's Rust code. +Read alongside [AGENTS.md](AGENTS.md) for repository requirements. + +## Naming and Rust conventions + +- Use descriptive names that explain purpose; include units where useful. Avoid misleading names + and abbreviations whose meaning is unclear in context. +- Follow Rust naming conventions: `snake_case` for functions, variables, fields, and modules; + `UpperCamelCase` for types and traits; `SCREAMING_SNAKE_CASE` for constants and statics. +- Conventional Rust names are not cryptic abbreviations. Keep names such as `fmt`, `iter`, `len`, + `args`, `err`, `id`, and `ui` when their meaning is clear. Do not expand them just to make them + longer. +- Keep standard file and directory names such as `lib.rs`, `main.rs`, `mod.rs`, `src`, `tests`, + `examples`, and `benches`. Rust keywords such as `mut`, `ref`, `impl`, and `mod` are language + syntax, not naming problems. +- Short names are appropriate in a clear local context: `i` for an index, `x` and `y` for + coordinates, `w` and `h` for image dimensions, and conventional generic parameters such as `T`. + Use more descriptive names when scope or ambiguity makes those hard to follow. + +## Magic numbers + +- Give non-obvious limits, thresholds, sizes, and tuning values descriptive named constants + instead of leaving unexplained numeric literals in the code. +- Name constants for their purpose, with units where useful, rather than for their literal value. + Keep them in the narrowest useful scope. +- Reuse an existing constant when it represents the same concept. Equal numeric values alone do + not mean two concepts should share a constant. +- Explain the origin or rationale of non-obvious coefficients and tolerances in a short comment. + Use standard library constants for standard mathematical values. +- Keep literals inline when their role is clear, such as zero initialization, incrementing by one, + or dividing by two to find a midpoint. Do not introduce names such as `ZERO` or `TWO` that add + no meaning. +- Apply this guidance to tests too; clear fixture values and expected results can remain literal. + +## Formatting and spacing + +- Let `cargo fmt` and the repository's [rustfmt.toml](rustfmt.toml) handle mechanical formatting. + Do not introduce a competing indentation or line-wrapping convention. +- Use one blank line between distinct logical steps: input preparation, validation, computation, + mutation, and result construction. +- Keep closely related statements together. Do not add a blank line after every declaration or + fragment a single operation with extra spacing. +- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before + the next statement. +- Put a blank line before a comment introducing a new step, with no blank line between the + comment and the code it explains. +- Keep documentation and attributes attached to their declarations. +- Separate function definitions with one blank line. Avoid extra empty lines just inside braces + or between every field, argument, or statement. +- In tests, separate preparation, action, and verification with blank lines when those phases + are distinct; keep related assertions together. + +## Source organization + +- Give each struct or enum its own source file, with its implementation beside it. Use the full + type name in `snake_case`, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings`. +- Preserve conventional crate roots and module entry points such as `lib.rs`, `main.rs`, and + `mod.rs`. Follow the command and node module placement required by `AGENTS.md`. +- Prefer singular folder names for new domain modules, such as `map`, `setting`, or `tracing`. + Keep standard Rust directories and repository-mandated paths unchanged. +- Group related types into focused modules rather than collecting unrelated types in one large file. +- Apply these preferences to new types and source organization changes within scope. Do not + reorganize unrelated existing code to enforce them. + +## Comments + +- Explain intent or a non-obvious constraint rather than narrating the code. +- Use short `//` comments. Avoid block comments and wrapped prose in ordinary implementation + comments; adjacent comment lines should each express a concise point. +- Do not add trailing punctuation to ordinary code comments. +- Preserve explanations of guards and invariants. Remove stale or redundant comments without + losing necessary rationale. +- API documentation, required license headers, and examples may use conventional multiline + formatting and punctuation. +- Apply the same comment guidance to production code and tests. diff --git a/Cargo.lock b/Cargo.lock index bcd091ae..54f6ef82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -755,10 +755,19 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -771,12 +780,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "fixed_decimal", "icu_decimal", @@ -799,17 +808,37 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "egui", "serde", "serde_json", ] +[[package]] +name = "craft-materialx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "craft-xml", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-mcmat" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-keymap", "craft-quit", @@ -819,10 +848,19 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-mesh" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52)", + "miniz_oxide 0.9.1", +] + [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "dispatch2", "egui", @@ -830,10 +868,21 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-tcraft" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -854,7 +903,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "chrono", "dunce", @@ -878,10 +927,19 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-usd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f7655fb3ea59d6b21681700c0ff880823f5bb709#f7655fb3ea59d6b21681700c0ff880823f5bb709" +dependencies = [ + "lz4_flex", + "thiserror 2.0.21", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "egui", "objc2 0.6.5", @@ -889,6 +947,36 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -2454,6 +2542,16 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -4369,6 +4467,13 @@ name = "texturecraft-formats" version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-cms", + "craft-materialx", + "craft-mcmat", + "craft-mesh", + "craft-tcraft", + "craft-usd", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", "exr", "flate2", "gltf", @@ -4385,7 +4490,6 @@ dependencies = [ "texturecraft-geom", "texturecraft-texel", "thiserror 2.0.21", - "tobj", "zip", ] @@ -4425,6 +4529,7 @@ dependencies = [ "log", "pollster 0.4.0", "rayon", + "serde", "texturecraft-bake", "texturecraft-compose", "texturecraft-core", @@ -4582,12 +4687,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "tobj" -version = "4.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2" - [[package]] name = "tokio" version = "1.53.3" diff --git a/Cargo.toml b/Cargo.toml index 692bd9f4..88936e5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f7655fb3ea59d6b21681700c0ff880823f5bb709" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } @@ -49,7 +50,6 @@ wgpu = "30" rfd = "0.17" zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } -tobj = { version = "4", default-features = false } flate2 = "1" lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } quick-xml = "0.41" @@ -66,20 +66,25 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } +craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] @@ -117,6 +122,13 @@ opt-level = 1 lto = "thin" codegen-units = 1 +# Fast optimized verification: each test executable otherwise repeats cross-crate LTO. +# `false` keeps thin LTO within each crate; release packaging keeps the profile above. +[profile.verify] +inherits = "release" +lto = false +codegen-units = 16 + [profile.wasm-release] inherits = "release" opt-level = "s" diff --git a/ROADMAP.md b/ROADMAP.md index 6fef234f..11c66321 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -14,7 +14,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — | | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | +| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | | Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 29 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 686bee97..4cb6a5aa 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -1,12 +1,34 @@ //! Drives the `texturecraft-cli` binary. +use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use serde_json::Value; +// Nextest 0.9.130+ remaps this variable when an archive is extracted on another +// runner. Cargo's compile-time path still supports ordinary `cargo test`. +fn cli_binary() -> OsString { + cli_binary_path(std::env::var_os("CARGO_BIN_EXE_texturecraft-cli")) +} + +fn cli_binary_path(runner_path: Option) -> OsString { + runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into()) +} + +#[test] +fn cli_binary_prefers_relocated_runner_path() { + let relocated = OsString::from("relocated archive/texturecraft-cli"); + assert_eq!(cli_binary_path(Some(relocated.clone())), relocated); +} + +#[test] +fn cli_binary_defaults_to_cargo_path() { + assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli"))); +} + fn cli(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")).args(args).output().unwrap() + Command::new(cli_binary()).args(args).output().unwrap() } fn ok(args: &[&str]) -> String { @@ -101,7 +123,7 @@ fn info_on_a_mesh_reports_uvs() { fn serve_takes_the_automation_root_spelling_too() { use std::io::Write as _; let d = tmp("automation-root"); - let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + let mut child = Command::new(cli_binary()) .args(["serve", "--automation-write-root", p(&d)]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs index e1664219..07a8eff2 100644 --- a/crates/bake/src/cage/cage_shell.rs +++ b/crates/bake/src/cage/cage_shell.rs @@ -16,6 +16,8 @@ pub struct CageShell { pub starts: Vec, /// Corner pairs along the low poly's polygon edges, for the wireframe pub edges: Vec<[u32; 2]>, + /// Corner pairs along the low poly's hard edges without a UV seam + pub missing_seams: Vec<[u32; 2]>, /// World units per unit of the max frontal distance setting pub cage_units: f32, } @@ -24,6 +26,30 @@ impl CageShell { /// The cage of `request`'s texture set, from the same ray starts the bake uses pub fn new(request: &BakeRequest) -> Result { let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + Self::build(request, ray_frame, || { + // Each scan drops other materials' edges before the next scan starts + let wire_edges = request.mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let missing_seam_edges = request.mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + (wire_edges, missing_seam_edges) + }) + } + + /// Build a cage using edges already scanned for every material of the low mesh + pub fn new_with_edges(request: &BakeRequest, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result { + let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + Self::build(request, ray_frame, || { + ( + wire_edges.get(request.material).into_iter().flatten().copied().collect(), + missing_seam_edges.get(request.material).into_iter().flatten().copied().collect(), + ) + }) + } + + fn build( + request: &BakeRequest, + ray_frame: RayFrame, + edge_sets: impl FnOnce() -> (HashSet<(u32, u32)>, HashSet<(u32, u32)>), + ) -> Result { let (frame, mesh) = (&ray_frame, request.mesh); let triangles: Vec = mesh.triangles_of(request.material).collect(); let (positions, starts): (Vec, Vec) = triangles @@ -36,8 +62,8 @@ impl CageShell { }) .unzip(); - let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); - let mut edge_corners = HashMap::new(); + let (wire_edges, missing_seam_edges) = edge_sets(); + let (mut edge_corners, mut seam_corners) = (HashMap::new(), HashMap::new()); for (triangle_index, &triangle) in triangles.iter().enumerate() { let Some(vertices) = mesh.tri(triangle) else { continue }; @@ -45,16 +71,23 @@ impl CageShell { let next = (corner + 1) % 3; let (from, to) = (vertices[corner] as u32, vertices[next] as u32); let key = (from.min(to), from.max(to)); + let first_corner = (triangle_index * 3) as u32; + let corners = [first_corner + corner as u32, first_corner + next as u32]; if wire_edges.contains(&key) { - let first_corner = (triangle_index * 3) as u32; - edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]); + edge_corners.entry(key).or_insert(corners); + } + if missing_seam_edges.contains(&key) { + seam_corners.entry(key).or_insert(corners); } } } - let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect(); - edges.sort_unstable(); + let sorted = |corners: HashMap<(u32, u32), [u32; 2]>| { + let mut pairs: Vec<[u32; 2]> = corners.into_values().collect(); + pairs.sort_unstable(); + pairs + }; - Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units }) + Ok(CageShell { positions, starts, edges: sorted(edge_corners), missing_seams: sorted(seam_corners), cage_units: ray_frame.cage_units }) } /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index eb8a61de..1d99ab36 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -9,6 +9,7 @@ mod bake_request; mod cage; mod high_poly; mod mesh_extent; +mod name_pair; mod progress; pub use bake_error::BakeError; @@ -17,6 +18,7 @@ pub use bake_request::BakeRequest; pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; +pub use name_pair::NamePair; pub use progress::Progress; mod map; diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index c9c30fd6..08a98224 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -4,8 +4,10 @@ mod curvature_tuning; mod diffusion; mod normal_curvature; mod normalization; +mod part_key; pub(crate) use diffusion::diffuse; pub(crate) use normalization::normalize; +pub(crate) use part_key::part_key; mod sample; mod seam; pub(crate) use seam::fix_seams; diff --git a/crates/bake/src/map/part_key.rs b/crates/bake/src/map/part_key.rs new file mode 100644 index 00000000..bda45809 --- /dev/null +++ b/crates/bake/src/map/part_key.rs @@ -0,0 +1,18 @@ +use std::collections::HashMap; + +/// A mesh part's key in `keys` (shared by names that agree once `suffix` is dropped), whether it ignores backfaces, and its lowercase name without that suffix +pub(crate) fn part_key(name: &str, suffix: &str, backface_suffix: &str, keys: &mut HashMap) -> (u32, bool, String) { + let name = name.trim().to_lowercase(); + let ignore_backface = !backface_suffix.is_empty() && name.ends_with(backface_suffix); + let name = if ignore_backface { name.strip_suffix(backface_suffix).unwrap_or(&name).to_owned() } else { name }; + + (match_key(&name, suffix, keys), ignore_backface, name) +} + +/// The key in `keys` of the lowercase part name `name` without `suffix` +fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { + let suffix = suffix.trim().to_lowercase(); + let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(name).to_string(); + let next = keys.len() as u32; + *keys.entry(base).or_insert(next) +} diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index ad057b11..c5cd5f3f 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,3 +1,4 @@ +use super::part_key::part_key; use super::sampling::{generated_hue, interpolate, splitmix64}; use crate::BakeRequest; use crate::tracing::{ANY, TraceMesh}; @@ -50,21 +51,24 @@ impl<'a> Source<'a> { let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len()); let mut part_keys = Vec::with_capacity(mesh.submeshes.len()); let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase(); + for (part_index, submesh) in mesh.submeshes.iter().enumerate() { let first_triangle = (submesh.start / 3) as usize; let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize; let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count); part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32); - let name = submesh.name.trim().to_lowercase(); - let ignore_backface = !backface_suffix.is_empty() && name.ends_with(&backface_suffix); + + let (key, ignore_backface, name) = part_key(&submesh.name, suffix, &backface_suffix, keys); backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface); - let name = if ignore_backface { name.strip_suffix(&backface_suffix).unwrap_or(&name) } else { &name }; - part_keys.push(match_key(name, suffix, keys)); + part_keys.push(key); + let next = mesh_keys.len() as u32; let file_id = file_ids.get(part_index).copied().unwrap_or(0); - mesh_ids.push(*mesh_keys.entry((file_id, name.to_owned())).or_insert(next)); + mesh_ids.push(*mesh_keys.entry((file_id, name)).or_insert(next)); } + let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect(); + Source { mesh, bvh, @@ -138,11 +142,3 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { let color = sampled_color * material.factor; Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) } - -fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { - let name = name.trim().to_lowercase(); - let suffix = suffix.trim().to_lowercase(); - let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string(); - let next = keys.len() as u32; - *keys.entry(base).or_insert(next) -} diff --git a/crates/bake/src/name_pair.rs b/crates/bake/src/name_pair.rs new file mode 100644 index 00000000..8863cc58 --- /dev/null +++ b/crates/bake/src/name_pair.rs @@ -0,0 +1,103 @@ +//! How "By Mesh Name" pairs low-poly parts with high-poly parts, listed before a bake runs + +use std::collections::{HashMap, HashSet}; + +use texturecraft_core::HighPolySettings; +use texturecraft_geom::Mesh; + +use crate::map::part_key; + +/// A low-poly part and the high-poly part its rays may hit under "By Mesh Name"; one side is missing when that part pairs with nothing +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NamePair { + /// The low-poly part's name as in its mesh + pub low: Option, + /// The high-poly part's name as in its mesh + pub high: Option, +} + +impl NamePair { + /// Each part of `low` in `material` with every `high` part it pairs with (a row per pair), then the `high` parts pairing with none; keyed like the bake, low poly first + pub fn list(low: &Mesh, material: usize, high: &Mesh, settings: &HighPolySettings) -> Vec { + let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase(); + let mut keys = HashMap::new(); + let mut keyed = |mesh: &Mesh, suffix: &str, only_material: Option| { + let mut seen = HashSet::new(); + let mut parts = Vec::new(); + for part in mesh.submeshes.iter().filter(|part| only_material.is_none_or(|material| part.material == material)) { + let (key, ..) = part_key(&part.name, suffix, &backface_suffix, &mut keys); + if seen.insert(part.name.as_str()) { + parts.push((key, part.name.clone())); + } + } + parts + }; + let low_parts = keyed(low, &settings.low_suffix, Some(material)); + let high_parts = keyed(high, &settings.high_suffix, None); + + let mut pairs = Vec::new(); + for (key, low_name) in &low_parts { + let matches: Vec<&String> = high_parts.iter().filter(|(high_key, _)| high_key == key).map(|(_, name)| name).collect(); + if matches.is_empty() { + pairs.push(NamePair { low: Some(low_name.clone()), high: None }); + } + pairs.extend(matches.into_iter().map(|high_name| NamePair { low: Some(low_name.clone()), high: Some(high_name.clone()) })); + } + + let low_keys: HashSet = low_parts.iter().map(|(key, _)| *key).collect(); + pairs.extend(high_parts.into_iter().filter(|(key, _)| !low_keys.contains(key)).map(|(_, name)| NamePair { low: None, high: Some(name) })); + pairs + } + + /// Whether one side is missing: a part the bake will leave unpaired + pub fn unpaired(&self) -> bool { + self.low.is_none() || self.high.is_none() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_geom::SubMesh; + + /// A mesh with one empty part per (name, material) + fn parts(names: &[(&str, usize)]) -> Mesh { + Mesh { + submeshes: names.iter().map(|(name, material)| SubMesh { name: (*name).into(), material: *material, start: 0, count: 0 }).collect(), + materials: vec!["first".into(), "second".into()], + ..Default::default() + } + } + + fn pair(low: Option<&str>, high: Option<&str>) -> NamePair { + NamePair { low: low.map(Into::into), high: high.map(Into::into) } + } + + #[test] + fn parts_pair_by_name_without_their_suffixes() { + let low = parts(&[("Barrel_low", 0), ("Base_low", 0), ("Slide_low", 1)]); + let high = parts(&[("Barrel_high", 0), ("Slide_high", 0), ("Grip_high", 0), ("BARREL_high_ignorebf", 0)]); + let settings = HighPolySettings::default(); + + assert_eq!( + NamePair::list(&low, 0, &high, &settings), + vec![ + pair(Some("Barrel_low"), Some("Barrel_high")), + pair(Some("Barrel_low"), Some("BARREL_high_ignorebf")), + pair(Some("Base_low"), None), + pair(None, Some("Slide_high")), + pair(None, Some("Grip_high")), + ], + "another material's parts are left out, so its high-poly part counts as unpaired here" + ); + assert_eq!(NamePair::list(&low, 1, &high, &settings).iter().filter(|pair| !pair.unpaired()).count(), 1); + } + + #[test] + fn a_part_split_over_triangle_ranges_is_listed_once() { + let low = parts(&[("Body_low", 0), ("Body_low", 0)]); + let high = parts(&[("Body_high", 0), ("Body_high", 0)]); + + assert_eq!(NamePair::list(&low, 0, &high, &HighPolySettings::default()), vec![pair(Some("Body_low"), Some("Body_high"))]); + } +} diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 2d114b06..40edd3b8 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -101,3 +101,92 @@ fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() { assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is"); assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO)); } + +#[test] +fn the_cage_lists_its_hard_edges_without_a_uv_seam() { + // A quad whose diagonal is split into two vertices with the same UV, smooth or hard by the copy's normal + let quad_with_diagonal_normal = |normal: Vec3| { + let mut mesh = Mesh::from_parts( + vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y], + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(normal); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(mesh.uvs[0]); + mesh.indices[3] = 4; + mesh + }; + let shell_of = |low: &Mesh| { + let bvh = Bvh::new(low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: low, bvh: &bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let shared = CageShell::new_with_edges(&request, &low.wire_edges(), &low.missing_seam_edges()).unwrap(); + assert_eq!(shared.positions, shell.positions); + assert_eq!(shared.corners(0.1), shell.corners(0.1)); + assert_eq!(shared.edges, shell.edges); + assert_eq!(shared.missing_seams, shell.missing_seams); + shell + }; + + let smooth = quad_with_diagonal_normal(Vec3::Z); + assert!(shell_of(&smooth).missing_seams.is_empty(), "the same normal on both sides is a smooth edge"); + + let hard = quad_with_diagonal_normal(Vec3::new(1.0, 0.0, 1.0).normalize()); + let shell = shell_of(&hard); + let diagonal = [Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)]; + assert_eq!(shell.missing_seams.len(), 2, "the diagonal, once per triangle"); + for [from, to] in &shell.missing_seams { + let mut ends = [shell.positions[*from as usize], shell.positions[*to as usize]]; + ends.sort_by(|a, b| a.x.total_cmp(&b.x)); + assert_eq!(ends, diagonal, "the line runs along the hard diagonal"); + } +} + +#[test] +fn shared_edges_select_the_requested_material() { + let mut mesh = primitives::cube(1.0); + mesh.append(&primitives::cube(1.0)); + let bvh = Bvh::new(&mesh); + let bake_settings = settings(16, &[BakedMap::Normal]); + let wire_edges = mesh.wire_edges(); + let missing_seam_edges = mesh.missing_seam_edges(); + + for material in 0..mesh.materials.len() { + let request = BakeRequest { + low_base_color: &[], + mesh: &mesh, + bvh: &bvh, + material, + settings: &bake_settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let direct = CageShell::new(&request).unwrap(); + let shared = CageShell::new_with_edges(&request, &wire_edges, &missing_seam_edges).unwrap(); + + assert_eq!(shared.positions, direct.positions); + assert_eq!(shared.starts, direct.starts); + assert_eq!(shared.edges, direct.edges); + assert_eq!(shared.missing_seams, direct.missing_seams); + } +} diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cf675d4f..61bf2e95 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -10,10 +10,12 @@ use std::collections::{BTreeSet, HashMap, VecDeque}; use std::sync::Arc; use texturecraft_core::project::MAX_DEPTH; -use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet}; +use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet}; use texturecraft_texel::TileImage; use crate::eval::{Inputs, PaintTarget}; +use crate::held_fields::HeldFields; +use crate::image_identity::ImageIdentity; use crate::store::{BakedMaps, ImageStore, PixelStore}; /// Default byte budget of a [`BelowCache`], per nesting level it holds (see @@ -40,11 +42,28 @@ pub struct BelowCache { /// Tiles of the whole pass a caller splits into several composites (0: each composite is a /// pass). A pass larger than the cache records only what fits. pub pass: usize, + /// Tiles the caller composites next in this pass, after those of the coming composite (empty: none, or a pass that is one + /// composite). A stack with neighbourhood filters then filters the coming tiles and these at once and keeps the result for + /// the composites that follow, instead of filtering each small chunk's surroundings again. + pub ahead: Vec<(u32, u32)>, + pub(crate) held: Option, } impl Default for BelowCache { fn default() -> Self { - BelowCache { hot: None, key: None, tiles: HashMap::new(), order: VecDeque::new(), clock: 0, bytes: 0, budget: BELOW_BUDGET, levels: 1, pass: 0 } + BelowCache { + hot: None, + key: None, + tiles: HashMap::new(), + order: VecDeque::new(), + clock: 0, + bytes: 0, + budget: BELOW_BUDGET, + levels: 1, + pass: 0, + ahead: Vec::new(), + held: None, + } } } @@ -78,48 +97,83 @@ pub struct StackKey { layers: Vec, pixels: Vec<(LayerId, Option, Shared)>, baked: (u32, Vec<(BakedMap, usize)>), - images: Vec<(String, usize)>, + images: Vec<(String, ImageIdentity)>, } impl StackKey { - /// The key of `roots` (layers of texture set `ts`, bottom → top) and their effects. - pub fn new(project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, ts: usize, roots: &[LayerId]) -> Option { - StackKey::of_tree(project, pixels, baked, images, ts, roots.to_vec(), &project.render_tree(roots)) + /// The key of `roots` (layers of a texture set, bottom → top) and their effects. + pub fn new( + project: &Project, + pixels: &PixelStore, + baked: &BakedMaps, + images: &ImageStore, + texture_set_index: usize, + roots: &[LayerId], + ) -> Option { + StackKey::of_tree(project, pixels, baked, images, texture_set_index, roots.to_vec(), &project.render_tree(roots)) } - /// The key of the layers in `tree` (and their effects), drawn as `roots` arrange them. + /// The key of the layers in `render_tree` (and their effects), drawn as `roots` arrange them. fn of_tree( project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, - ts: usize, + texture_set_index: usize, roots: Vec, - tree: &BTreeSet, + render_tree: &BTreeSet, ) -> Option { - let mut set = project.texture_set(ts).ok()?.clone(); + let mut set = project.texture_set(texture_set_index).ok()?.clone(); set.name.clear(); set.description.clear(); set.stack.clear(); set.bake = Default::default(); - let effects: BTreeSet = tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect(); - let pixels = tree + + let effect_ids: BTreeSet = render_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect(); + let pixel_handles = render_tree .iter() - .chain(&effects) + .chain(&effect_ids) .flat_map(|id| { - let layer = Channel::ALL.into_iter().filter_map(move |c| pixels.layer(*id, c).map(|img| (*id, Some(c), Shared(img.clone())))); - layer.chain(pixels.masks.get(id).map(|img| (*id, None, Shared(img.clone())))) + let layer_channels = + Channel::ALL.into_iter().filter_map(move |channel| pixels.layer(*id, channel).map(|image| (*id, Some(channel), Shared(image.clone())))); + layer_channels.chain(pixels.masks.get(id).map(|image| (*id, None, Shared(image.clone())))) }) .collect(); - let mut images: Vec<(String, usize)> = images.iter().map(|(n, i)| (n.clone(), Arc::as_ptr(i) as usize)).collect(); - images.sort(); + + let mut referenced_images = BTreeSet::new(); + if !images.is_empty() { + let mut record_image_reference = |source: &Source| { + if let Source::Image { name, .. } = source + && let Some((name, _)) = images.get_key_value(name) + { + referenced_images.insert(name); + } + }; + for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) { + if let LayerKind::Fill(fill) = &layer.kind { + fill.sources.values().for_each(&mut record_image_reference); + } + for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + match &effect.kind { + EffectKind::Fill { source, .. } => record_image_reference(source), + EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference), + EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference), + _ => {} + } + } + } + } + + let image_identities = + referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect(); + Some(StackKey { set, roots, - layers: tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(), - pixels, - baked: (baked.resolution, baked.maps.iter().map(|(m, d)| (*m, Arc::as_ptr(d) as usize)).collect()), - images, + layers: render_tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(), + pixels: pixel_handles, + baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()), + images: image_identities, }) } } @@ -173,23 +227,30 @@ impl BelowCache { pub fn clear(&mut self) { let tiles = std::mem::take(&mut self.tiles); - // Freeing a full cache (up to the byte budget in small bands) can take most of a - // second: a thread does it so the frame that switched the hot layer doesn't stall. + + // Native builds free cached bands off-thread to avoid a frame stall #[cfg(not(target_arch = "wasm32"))] if !tiles.is_empty() { let _ = std::thread::Builder::new().name("texturecraft-free".into()).spawn(move || drop(tiles)); } #[cfg(target_arch = "wasm32")] drop(tiles); + self.order.clear(); self.bytes = 0; self.key = None; + self.held = None; } pub fn bytes(&self) -> usize { self.bytes } + /// Whether neighbourhood-filter fields are kept for the composites that follow (see [`BelowCache::ahead`]). + pub fn holds_fields(&self) -> bool { + self.held.is_some() + } + /// The byte limit: the budget for the top level and as much again for a hot layer nested in /// folders (each tile then holds the stack at two or more levels). pub fn limit(&self) -> usize { @@ -219,7 +280,7 @@ impl BelowCache { self.clock += 1; *stamp = self.clock; self.order.push_back((t, self.clock)); - // Drop superseded uses once they outnumber the tiles. + // Drop superseded uses once they outnumber the tiles if self.order.len() > 2 * self.tiles.len() + 64 { let tiles = &self.tiles; self.order.retain(|(t, s)| tiles.get(t).is_some_and(|(stamp, _)| stamp == s)); @@ -256,43 +317,53 @@ impl BelowCache { /// live stroke). Empties the cache when what the cached part reads changed. pub(crate) fn prepare(&mut self, inp: &Inputs) -> Option> { let hot = self.hot?; - let p = inp.project; - let set = p.texture_set(inp.ts).ok()?; - // Anchor readers depend on the stack below them. - if p.render_tree(&set.stack).iter().any(|id| p.layers.get(id).is_some_and(Layer::reads_anchor)) { + let project = inp.project; + let set = project.texture_set(inp.ts).ok()?; + + // Anchor readers depend on the stack below them + if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) { return None; } - let levels = path(p, &set.stack, hot)?; - let rest: Vec = levels.iter().flat_map(|l| l.below.iter().chain(&l.above)).copied().collect(); - if rest.is_empty() && levels.len() == 1 { + + let levels = path(project, &set.stack, hot)?; + let off_path_roots: Vec = levels.iter().flat_map(|level| level.below.iter().chain(&level.above)).copied().collect(); + if off_path_roots.is_empty() && levels.len() == 1 { return None; } - let mut tree = p.render_tree(&rest); - // Folders holding the hot layer (and the folders their instances draw) count with their - // own state only, not their children. - for l in levels.iter().take(levels.len() - 1) { - let mut id = Some(l.at); + + let mut cached_tree = project.render_tree(&off_path_roots); + + // Cache containing folders by state, without their children + for level in levels.iter().take(levels.len() - 1) { + let mut id = Some(level.at); for _ in 0..=MAX_DEPTH { - let Some(i) = id.filter(|i| tree.insert(*i)) else { break }; - id = p.layers.get(&i).and_then(Layer::instance_source); + let Some(instance_id) = id.filter(|instance_id| cached_tree.insert(*instance_id)) else { break }; + id = project.layers.get(&instance_id).and_then(Layer::instance_source); } } - if tree.contains(&hot) { + + // Repeated hot instances cannot share the off-path cache + if cached_tree.contains(&hot) { return None; } - if let Some(pv) = inp.preview { - let (PaintTarget::Layer(t) | PaintTarget::Mask(t)) = pv.target; - if tree.contains(&t) || tree.iter().filter_map(|id| p.layers.get(id)).flat_map(effect_ids).any(|e| e == t) { + + if let Some(preview) = inp.preview { + let (PaintTarget::Layer(target) | PaintTarget::Mask(target)) = preview.target; + if cached_tree.contains(&target) + || cached_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).any(|effect_id| effect_id == target) + { return None; } } - let roots = set.stack.iter().chain(levels.iter().map(|l| &l.at)).copied().collect(); - let key = StackKey::of_tree(p, inp.pixels, inp.baked, inp.images, inp.ts, roots, &tree)?; + + let roots = set.stack.iter().chain(levels.iter().map(|level| &level.at)).copied().collect(); + let key = StackKey::of_tree(project, inp.pixels, inp.baked, inp.images, inp.ts, roots, &cached_tree)?; self.levels = levels.len(); if self.key.as_ref() != Some(&key) { self.clear(); self.key = Some(key); } + Some(levels) } } diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index d04e7f62..0b7138bc 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -125,8 +125,8 @@ fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: sizes }; - // One layout per curvature map, with the most recently used map at the end - cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature))); + // Keep layout variants so thumbnails and the viewport reuse their own levels + cache.retain(|entry| entry.0.strong_count() > 0 && !is_entry_for(entry, curvature, key, scales)); let sizes = Arc::new(sizes); cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); trim_cache(&mut cache, CACHE_BYTES); @@ -338,6 +338,7 @@ mod tests { #[test] fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect(); let scales = BlockScales::default(); let key = ((4, 4), (4, 4), (4, 4)); @@ -408,18 +409,46 @@ mod tests { } } + // Cache lifecycle tests must not evict each other's entries in parallel + static CACHE_TESTS: Mutex<()> = Mutex::new(()); + #[test] - fn a_new_layout_replaces_the_sizes_of_the_old_one() { + fn alternating_layouts_reuse_their_cached_sizes() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let curvature = Arc::new(vec![0.5; 16]); let scales = BlockScales::default(); - let entries_for_curvature = || { - let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count() - }; + let viewport_key = ((4, 4), (4, 4), (4, 4)); + let thumbnail_key = ((4, 4), (4, 4), (2, 2)); + let viewport = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() }); + let thumbnail = store(&curvature, thumbnail_key, &scales, CurvatureSizes { levels: Vec::new() }); - store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() }); - store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() }); - assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached"); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "a thumbnail must not evict the viewport layout"); + assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "both layouts stay reusable"); + let mut set = texturecraft_core::TextureSet::new("Tiles", 0, 4); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 2); + let scaled = set.block_scales(); + assert_ne!(scaled, scales); + assert!(cached(&curvature, viewport_key, &scaled).is_none(), "different tile scales cannot read the unscaled result"); + let scaled_sizes = store(&curvature, viewport_key, &scaled, CurvatureSizes { levels: Vec::new() }); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scaled).unwrap(), &scaled_sizes)); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "scale variants also coexist"); + let replacement = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() }); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &replacement)); + assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "updating one layout keeps the other"); + } + + #[test] + fn layout_variants_obey_the_entry_limit() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let key = |size| ((4, 4), (4, 4), (size, size)); + for size in 1..=CACHE_MAPS as u32 + 1 { + store(&curvature, key(size), &scales, CurvatureSizes { levels: Vec::new() }); + } + assert!(cached(&curvature, key(1), &scales).is_none(), "layout variants cannot grow without bound"); + assert!(cached(&curvature, key(CACHE_MAPS as u32 + 1), &scales).is_some(), "the newest layout stays cached"); } #[test] diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index fe0bdb23..d427988f 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -18,8 +18,9 @@ use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; -use crate::below::{Band, BelowCache, Level}; +use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; +use crate::held_fields::HeldFields; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -278,12 +279,24 @@ fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } +/// Below this a coverage weight counts as no coverage at all. +const MIN_COVERAGE_WEIGHT: f32 = 1e-6; +/// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. +const FILTER_SIZE_RESOLUTION: f32 = 2048.0; +/// The smallest radius a filter runs at, in texels. +const MIN_FILTER_RADIUS: f32 = 0.5; +/// Sharpen's blur radius at [`FILTER_SIZE_RESOLUTION`], and the smallest it runs at, in texels. +const SHARPEN_RADIUS: f32 = 1.5; +const MIN_SHARPEN_RADIUS: f32 = 0.75; + /// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does. fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { - let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5); + let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), - EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), + EffectKind::Filter(Filter::Sharpen { amount }) => { + Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount)))) + } EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) @@ -297,6 +310,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator Some((index, texels(*width * 0.5), Op::Bevel)), EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), + // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them + EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { + Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + } EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) } @@ -434,15 +451,29 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; +/// Texels one parallel task of a neighbourhood filter handles at least. Compositing in frame slices filters regions of a few tiles: split per texel, +/// handing that little work to every thread costs far more than the work itself. Each texel is computed on its own, so the split does not change results. +const MIN_PARALLEL_TEXELS: usize = 1 << 14; + +/// How many lines of `length` texels make a parallel task of at least [`MIN_PARALLEL_TEXELS`]. +fn lines_per_task(length: usize) -> usize { + (MIN_PARALLEL_TEXELS / length.max(1)).max(1) +} + /// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { - let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; - let mut fixed: Vec = data.par_iter().map(to_fixed).collect(); + // Bound samples before fixed-point accumulation + const MAX_INPUT_MAGNITUDE: f32 = 1e6; + + let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-MAX_INPUT_MAGNITUDE, MAX_INPUT_MAGNITUDE)) * FIX).round() as i64 } else { 0 }; + let mut fixed: Vec = data.par_iter().with_min_len(MIN_PARALLEL_TEXELS).map(to_fixed).collect(); blur_rows(&mut fixed, width, radius); let mut columns = transpose(&fixed, width, height); blur_rows(&mut columns, height, radius); - data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); + transpose_into(&columns, height, width, &mut fixed); + + data.par_iter_mut().with_min_len(MIN_PARALLEL_TEXELS).zip(fixed).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } /// The box blurs `blur` runs along each axis @@ -453,11 +484,12 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { if w == 0 { return; } - data.par_chunks_mut(w).for_each(|row| { - let mut tmp = vec![0i64; row.len()]; + + data.par_chunks_mut(w).with_min_len(lines_per_task(w)).for_each(|row| { + let mut scratch = vec![0i64; row.len()]; for _ in 0..BLUR_BOX_PASSES { - box_line(row, &mut tmp, r); - row.copy_from_slice(&tmp); + box_line(row, &mut scratch, r); + row.copy_from_slice(&scratch); } }); } @@ -465,7 +497,8 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { /// One box blur of radius `r` of a line (texels past the ends count as 0). fn box_line(src: &[i64], dst: &mut [i64], r: usize) { let n = (2 * r + 1) as i64; - // Rounded division of a window sum. + + // Rounded division of a window sum let avg = |acc: i64| (2 * acc + n).div_euclid(2 * n); let mut acc: i64 = src.iter().take(r + 1).sum(); for (i, d) in dst.iter_mut().enumerate() { @@ -480,14 +513,18 @@ fn box_line(src: &[i64], dst: &mut [i64], r: usize) { /// `src` (`w × h`, row-major) transposed to `h × w`. fn transpose(src: &[i64], w: usize, h: usize) -> Vec { let mut out = vec![0i64; src.len()]; + transpose_into(src, w, h, &mut out); + out +} + +fn transpose_into(src: &[i64], w: usize, h: usize, out: &mut [i64]) { if h > 0 { - out.par_chunks_mut(h).enumerate().for_each(|(x, col)| { + out.par_chunks_mut(h).with_min_len(lines_per_task(h)).enumerate().for_each(|(x, col)| { for (y, d) in col.iter_mut().enumerate() { *d = src.get(y * w + x).copied().unwrap_or(0); } }); } - out } /// Covered texels of tile (tx, ty): (x, y, offset inside the tile). @@ -597,59 +634,74 @@ fn is_box_blur(op: Op) -> bool { /// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. #[allow(clippy::too_many_arguments)] fn filter_region( - inp: &Inputs, + inputs: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, effects: &[Effect], (index, radius, op): (usize, f32, Op), - (rx0, ry0, w, h): (u32, u32, u32, u32), + (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { - let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height)); - let comps = match job { + let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); + let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); + + // Generator stages keep their ramp beside the mask stack below + let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) { + (Job::Mask(_), Some((EffectKind::Generator(generator), blend))) => Some((generator, blend)), + _ => None, + }; + let components = match job { + Job::Mask(_) if generator.is_some() => 2, Job::Mask(_) => 1, Job::Content(_) => 4, }; // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) - let (rx1, ry1) = (rx0 + w, ry0 + h); - let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect(); + let (region_right, region_bottom) = (region_x + width, region_y + height); + let region_tiles: Vec<(u32, u32)> = + (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect(); let parts: Vec> = region_tiles .par_iter() - .map(|&(tx, ty)| { - let full = anchor_plan(inp, id, channels, tx, ty, Some(below)); - let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); + .map(|&(tile_x, tile_y)| { + let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below)); + let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); let mut mask = None; let mut nodes = Vec::new(); + let mut generator_sizes = None; match job { Job::Mask(layer_mask) => { - let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() }; + let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() }; + generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); mask_stack.effects.truncate(index); mask_stack.start = start; mask = Some(mask_stack); } Job::Content(channel) => { - nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below)); - if let Some(chan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { - chan.effects.truncate(index); - chan.start = start; + nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below)); + if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { + channel_plan.effects.truncate(index); + channel_plan.start = start; } } } - tile_texels(inp.gbuf, tx, ty) + tile_texels(inputs.gbuf, tile_x, tile_y) .map(|(x, y, offset)| { - let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); - if !full.is_empty() { - texel.anchors_below(&full, id); + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + texel.anchors_below(&anchor_nodes, id); } + let value = match (&mask, nodes.first()) { - (Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0], - (None, Some(node)) => match node.chans.first().and_then(|chan| texel.content(&node.content, chan)) { - Some((color, cov)) => [color[0] * cov, color[1] * cov, color[2] * cov, cov], + (Some(mask_stack), _) => { + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); + [texel.mask(mask_stack), ramp, 0.0, 0.0] + } + (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { + Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], None => [0.0; 4], }, (None, None) => [0.0; 4], @@ -661,55 +713,62 @@ fn filter_region( .collect(); // Scatter into the region, a row of tiles at a time (the region is tile aligned) - let texel_count = (w * h) as usize; - let mut orig = vec![0.0f32; texel_count * comps]; + let texel_count = (width * height) as usize; + let mut stack_values = vec![0.0f32; texel_count * components]; let mut cover = vec![0.0f32; texel_count]; - let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize; - let band = (TILE * w) as usize; - orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| { + let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize; + let band = (TILE * width) as usize; + stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| { for &(x, y, value) in row.iter().flatten() { - let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize; - if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), orig.get_mut(texel * comps..(texel + 1) * comps)) { + let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; + if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) { *covered = 1.0; - pixel.copy_from_slice(&value[..comps]); + pixel.copy_from_slice(&value[..components]); } } }); - // High pass centers on the channel's mid value (0 for signed channels like height) - let mid = match job { + // Release tile scatter data before allocating filter buffers + drop(parts); + + // High pass centers on the channel's middle value (0 for signed channels like height) + let middle = match job { Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { - let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1); - let scaled_radius = neighbourhood_filters(effects, res) + let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1); + if let Some((generator, blend)) = generator { + let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution); + return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); + } + let scaled_radius = neighbourhood_filters(effects, tile_resolution) .find(|filter| filter.0 == index) .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); if !is_box_blur(op) { - return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), scaled_radius as f32, res, opacity); + return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity); } // Weighted so uncovered texels don't bleed in - let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize); + let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize); let mut weights = cover.clone(); - blur(&mut weights, width, height, blur_radius); - let mut data = orig.clone(); - for component in 0..comps { - let mut sums: Vec = orig.par_chunks(comps).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); - blur(&mut sums, width, height, blur_radius); - data.par_chunks_mut(comps).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { - // Content is premultiplied, so the mid value is too (coverage itself is kept) - let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *weight > 1e-6 + blur(&mut weights, columns, rows, blur_radius); + let mut filtered_values = stack_values.clone(); + for component in 0..components { + let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); + blur(&mut sums, columns, rows, blur_radius); + filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { + // Content is premultiplied, so the middle value is too (coverage itself is kept) + let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *weight > MIN_COVERAGE_WEIGHT && let Some(slot) = pixel.get_mut(component) { let (original, blurred) = (*slot, sum / weight); let result = match op { Op::Blur(Some(amount)) => original + amount * (original - blurred), - Op::HighPass if component < 3 => original - blurred + mid * cov, + Op::HighPass if component < 3 => original - blurred + middle * coverage, // Away from 0 by at most the value itself: 0 at the edge, full inside Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), Op::Glow(amount) if component < 3 => original + amount * blurred, @@ -720,40 +779,160 @@ fn filter_region( } }); } - data + filtered_values }; // Each block keeps the result at its tile's scale (blocks are TILE aligned) - let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default(); - let mut levels: Vec = - (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect(); + let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default(); + let mut levels: Vec = (region_y..region_bottom) + .step_by(TILE as usize) + .flat_map(|y| (region_x..region_right).step_by(TILE as usize).map(move |x| (x, y))) + .map(|(x, y)| scales.at(x, y)) + .collect(); levels.sort_by(f32::total_cmp); levels.dedup(); let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest)); - let mut data = filtered(first); + + // A generator stage's field is the mask alone + let field_components = if generator.is_some() { 1 } else { components }; + let mut result = filtered(first); for &scale in rest { - let other = filtered(scale); - let row = w as usize * comps; - data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| { - for (x, (target, source)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { - if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { + let rescaled = filtered(scale); + let row = width as usize * field_components; + result.par_chunks_mut(row).zip(rescaled.par_chunks(row)).enumerate().for_each(|(y, (target_row, source_row))| { + for (x, (target, source)) in target_row.chunks_mut(field_components).zip(source_row.chunks(field_components)).enumerate() { + if scales.at(region_x + x as u32, region_y + y as u32) == scale { target.copy_from_slice(source); } } }); } - unpremultiply(&mut data, comps); - Some(Field { x0: rx0, y0: ry0, w, h, comps, data }) + unpremultiply(&mut result, field_components); + Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result }) +} + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +fn generator_region( + generator: &Generator, + blend: BlendMode, + opacity: f32, + stack: &[f32], + cover: &[f32], + (region_x, region_y, width, height): (u32, u32, u32, u32), + (uv_tile, texture_set): (u32, u32), +) -> Vec { + let (columns, rows) = (width as usize, height as usize); + let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + + // Coarser than the UV tile: averaged over cells, then the blur around them + let cell = generator.resolution.cell(uv_tile, texture_set) as usize; + if cell > 1 { + ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); + } + + let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; + if blur_radius > 0 { + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, blur_radius); + let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); + blur(&mut sums, columns, rows, blur_radius); + ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { + if *weight > MIN_COVERAGE_WEIGHT { + *ramp = sum / weight; + } + }); + } + + // Finished and blended over the stack below, like the generator effect itself + stack + .par_chunks(2) + .zip(ramps.par_iter()) + .map(|(texel, ramp)| { + let below = texel.first().copied().unwrap_or(0.0); + let generated = finish_generator(generator, *ramp); + below + (blend1(blend, below, generated) - below) * opacity + }) + .collect() +} + +/// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. +fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { + // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region + let (first_column, first_row) = (region_x / cell, region_y / cell); + let columns = (region_x + width).div_ceil(cell) - first_column; + let rows = (region_y + height).div_ceil(cell) - first_row; + + // Each cell's coverage-weighted average, a row of cells at a time + let averages: Vec> = (0..rows) + .into_par_iter() + .flat_map_iter(|row| { + let mut sums = vec![(0.0f32, 0.0f32); columns]; + let first_y = ((first_row + row) * cell).saturating_sub(region_y); + let last_y = ((first_row + row + 1) * cell).saturating_sub(region_y).min(height); + for y in first_y..last_y { + for x in 0..width { + let texel = y * width + x; + let covered = cover.get(texel).copied().unwrap_or(0.0); + if let Some((sum, weight)) = sums.get_mut((region_x + x) / cell - first_column) { + *sum += values.get(texel).copied().unwrap_or(0.0) * covered; + *weight += covered; + } + } + } + sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight)) + }) + .collect(); + let average = |column: isize, row: isize| -> Option { + let column = column.clamp(0, columns as isize - 1) as usize; + let row = row.clamp(0, rows as isize - 1) as usize; + averages.get(row * columns + column).copied().flatten() + }; + + let cell_size = cell as f32; + (0..height) + .into_par_iter() + .flat_map_iter(|y| (0..width).map(move |x| (x, y))) + .map(|(x, y)| { + // Position in cells, relative to the first cell's center + let cell_x = ((region_x + x) as f32 + 0.5) / cell_size - 0.5 - first_column as f32; + let cell_y = ((region_y + y) as f32 + 0.5) / cell_size - 0.5 - first_row as f32; + let (left, top) = (cell_x.floor(), cell_y.floor()); + let (offset_x, offset_y) = (cell_x - left, cell_y - top); + let (left, top) = (left as isize, top as isize); + let corners = [ + (left, top, (1.0 - offset_x) * (1.0 - offset_y)), + (left + 1, top, offset_x * (1.0 - offset_y)), + (left, top + 1, (1.0 - offset_x) * offset_y), + (left + 1, top + 1, offset_x * offset_y), + ]; + let (sum, weight) = corners.iter().fold((0.0, 0.0), |(sum, weight), &(column, row, corner_weight)| match average(column, row) { + Some(value) => (sum + value * corner_weight, weight + corner_weight), + None => (sum, weight), + }); + if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } + }) + .collect() +} + +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset. +fn finish_generator(generator: &Generator, ramp: f32) -> f32 { + let value = generator.global.apply(ramp); + let value = if generator.invert { 1.0 - value } else { value }; + let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; + (value + offset).clamp(0.0, 1.0) } /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. fn unpremultiply(data: &mut [f32], comps: usize) { - data.par_chunks_mut(comps).for_each(|px| match px { + // Avoid amplifying rounding error near transparent texels + const MIN_COVERAGE: f32 = 1e-5; + + data.par_chunks_mut(comps).with_min_len(MIN_PARALLEL_TEXELS).for_each(|px| match px { [v] => *v = v.clamp(0.0, 1.0), [r, g, b, cov] => { *cov = cov.clamp(0.0, 1.0); - let inv = if *cov > 1e-5 { 1.0 / *cov } else { 0.0 }; + let inv = if *cov > MIN_COVERAGE { 1.0 / *cov } else { 0.0 }; *r *= inv; *g *= inv; *b *= inv; @@ -794,12 +973,14 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { continue; } + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { out.insert(FieldKey::Content(id, *channel), filtered); } } } + out } @@ -1216,15 +1397,21 @@ impl<'a, 'b> Texel<'a, 'b> { } } - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert. + fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let coords = self.coords(); let signal = match (generator.kind, &generator.detail) { - (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), - (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { + // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let curvature = self.generator_input(generator, BakedMap::Curvature); + self.curvature_detail(detail, sizes, curvature) + } + (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; @@ -1241,12 +1428,29 @@ impl<'a, 'b> Texel<'a, 'b> { signal }; - // A smooth step from black to white over 2 × softness around 1 − level, then the offset - generator.shape(signal) + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(Generator::MIN_SOFTNESS); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + ramp * ramp * (3.0 - 2.0 * ramp) } - /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let ramp = self.generator_ramp(generator, curvature_sizes); + finish_generator(generator, ramp) + } + + /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). + fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]), + None => self.baked(map), + } + } + + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { let combine = |edges: f32, cavities: f32| match detail.mode { CurvatureMode::Edges => edges, CurvatureMode::Cavities => cavities, @@ -1255,7 +1459,7 @@ impl<'a, 'b> Texel<'a, 'b> { }; // Without curvature to read the texel is flat: no edges or cavities - let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; + let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; @@ -1661,7 +1865,7 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) } /// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory). -const BLOCK: u32 = 16; +pub const BLOCK: u32 = 16; /// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and /// filling it). Results are identical to [`composite_tiles`]. @@ -1670,9 +1874,10 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { return; } + let split = below.as_deref_mut().and_then(|b| b.prepare(inp)); - // A pass over more tiles than the cache holds records only what fits: recording the rest - // would just evict it again. Tiles hold the stack per level plus a tape of varying size. + + // Avoid caching tiles that would immediately evict each other let levels = split.as_ref().map_or(1, Vec::len); let estimate = TILE_AREA * levels * set.channel_list().iter().map(|c| c.components()).sum::() * std::mem::size_of::(); let tile_bytes = below.as_deref().and_then(BelowCache::tile_bytes).unwrap_or(estimate).max(1); @@ -1681,14 +1886,66 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, for t in tiles { blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); } - for block in blocks.values() { + + let channels = set.channel_list(); + let hot = split.as_deref().and_then(<[Level]>::last); + + // A stroke preview is absent from StackKey, so it disables field retention + let retain_fields = below.is_some() && inp.preview.is_none() && has_neighbourhood(inp, &set.stack); + let key = if retain_fields { StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new) } else { None }; + let size = (inp.gbuf.width, inp.gbuf.height); + + // Release fields when a stroke or stack change disables retention + if key.is_none() + && let Some(cache) = below.as_deref_mut() + { + cache.held = None; + } + + for (block_index, block) in &blocks { + let uncached = |tile: &(u32, u32)| below.as_deref().zip(split.as_deref()).is_none_or(|(cache, _)| cache.tile(*tile).is_none()); + let fresh: Vec<(u32, u32)> = block.iter().copied().filter(uncached).collect(); + let held = below.as_deref().and_then(|cache| cache.held.as_ref()).filter(|held| { + key.as_ref().is_some_and(|key| **key == *held.key) + && held.size == size + && fresh.iter().all(|tile| held.stack_tiles.contains(tile)) + && block.iter().all(|tile| held.hot_tiles.contains(tile)) + }); + let ahead: Vec<(u32, u32)> = match (&key, below.as_deref()) { + (Some(_), Some(cache)) if held.is_none() => { + cache.ahead.iter().copied().filter(|tile| (tile.1 / BLOCK, tile.0 / BLOCK) == *block_index && !block.contains(tile)).collect() + } + _ => Vec::new(), + }; + let fields: Arc = match (held, &key) { + (Some(held), _) => held.fields.clone(), + (None, Some(key)) if !ahead.is_empty() => { + // Filter the current and following tiles as one run + let planned_tiles: Vec<(u32, u32)> = block.iter().chain(&ahead).copied().collect(); + let uncached_planned_tiles: Vec<(u32, u32)> = planned_tiles.iter().copied().filter(uncached).collect(); + let fields = Arc::new(block_fields(inp, &channels, &set.stack, hot, &uncached_planned_tiles, &planned_tiles)); + let hot_tiles: std::collections::BTreeSet<(u32, u32)> = planned_tiles.iter().copied().collect(); + let stack_tiles = if hot.is_some() && uncached_planned_tiles.len() < planned_tiles.len() { + uncached_planned_tiles.into_iter().collect() + } else { + hot_tiles.clone() + }; + if let Some(cache) = below.as_deref_mut() { + cache.held = Some(HeldFields { key: key.clone(), size, stack_tiles, hot_tiles, fields: fields.clone() }); + } + fields + } + _ => Arc::new(block_fields(inp, &channels, &set.stack, hot, &fresh, block)), + }; + let quota = match below.as_deref() { Some(_) if fits => usize::MAX, Some(b) => b.limit().saturating_sub(b.bytes()) / tile_bytes, None => 0, }; + let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota); + let records = composite_block(inp, &set.stack, out, block, cached, quota, &fields); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -1698,6 +1955,35 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, } } } + + // Release fields at the end of the pass + if let Some(cache) = below.filter(|cache| cache.ahead.is_empty()) { + cache.held = None; + } +} + +/// Whether a layer drawn by `stack` has a neighbourhood filter in its mask or content effects. +fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { + let working_width = inp.gbuf.width; + let mut order = Vec::new(); + draw_order(inp.project, stack, 0, &mut order); + order.into_iter().any(|id| { + let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); + masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some()) + }) +} + +/// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`), +/// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`. +fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { + match hot { + Some(hot) if fresh.len() < tiles.len() => { + let mut fields = fields_of(inp, channels, stack, fresh); + fields.extend(fields_of(inp, channels, &[hot.at], tiles)); + fields + } + _ => fields_of(inp, channels, stack, tiles), + } } /// Rows of a tile composited as one parallel task. @@ -1719,6 +2005,7 @@ fn composite_block( tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, quota: usize, + fields: &Fields, ) -> Vec<((u32, u32), Vec)> { let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); let (w, h) = (out.resolution, out.height); @@ -1726,20 +2013,12 @@ fn composite_block( let cached = |t: (u32, u32)| below.and_then(|(b, _)| b.tile(t)); let fresh: Vec<(u32, u32)> = tiles.iter().copied().filter(|t| cached(*t).is_none()).collect(); let recorded: std::collections::BTreeSet<(u32, u32)> = if split.is_some() { fresh.iter().copied().take(quota).collect() } else { Default::default() }; - // Off the path, layers are only evaluated on tiles the cache lacks. - let fields = match split.and_then(<[Level]>::last) { - Some(hot) if fresh.len() < tiles.len() => { - let mut fields = fields_of(inp, &channels, stack, &fresh); - fields.extend(fields_of(inp, &channels, &[hot.at], tiles)); - fields - } - _ => fields_of(inp, &channels, stack, tiles), - }; let lanes: Vec = channels.iter().map(|c| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed }).collect(); let stride: usize = lanes.iter().map(|l| l.n).sum(); - let nlev = split.map_or(0, <[Level]>::len); + let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); - // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy. + + // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy let bands = TILE / BAND; let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect(); let mut results: Vec = tasks @@ -1747,20 +2026,20 @@ fn composite_block( .map(|&((tx, ty), band)| { let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); - let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some())); - let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() }; + let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, fields, warm.is_some())); + let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(fields)) } else { Vec::new() }; let rows = (BAND * TILE) as usize; - let mut accs = vec![defaults; nlev]; - let mut masks = vec![0.0f32; nlev]; + let mut level_values = vec![defaults; level_count]; + let mut masks = vec![0.0f32; level_count]; let mut tape = match warm { Some(b) => Tape::Replay(b, 0), None if record => Tape::Record(Vec::new()), None => Tape::Off, }; - // The levels whose stack the band stores (its header): a level with nothing drawn - // before the path layer repeats the level above it. + + // Empty lower stacks reuse the enclosing level instead of storing a duplicate let stored: Vec = match (&levels, warm) { - (Some(_), Some(_)) => tape.take(nlev).iter().map(|v| *v > 0.0).collect(), + (Some(_), Some(_)) => tape.take(level_count).iter().map(|v| *v > 0.0).collect(), (Some(levels), None) => levels.iter().map(|l| !l.below.is_empty()).collect(), (None, _) => Vec::new(), }; @@ -1769,7 +2048,7 @@ fn composite_block( } let slots = stored.iter().filter(|s| **s).count() * stride; let preview_tile = inp.preview.and_then(|p| p.alpha.tile(tx, ty)); - let mut bufs: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); + let mut channel_buffers: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); let mut anchors = Vec::new(); let mut any = false; for ly in band * BAND..(band + 1) * BAND { @@ -1782,20 +2061,20 @@ fn composite_block( if x >= w { break; } - let gi = (y * w + x) as usize; - // Offset in the tile, and in this band. - let o = (ly * TILE + lx) as usize; - let ob = ((ly - band * BAND) * TILE + lx) as usize; - let covered = inp.gbuf.tri.get(gi).is_some_and(|t| *t != NO_TRI); + let gbuffer_index = (y * w + x) as usize; + let tile_offset = (ly * TILE + lx) as usize; + let band_offset = ((ly - band * BAND) * TILE + lx) as usize; + let covered = inp.gbuf.tri.get(gbuffer_index).is_some_and(|t| *t != NO_TRI); let mut acc = defaults; if covered { any = true; - let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); - // Reuse one anchor buffer per band. - tex.anchors = std::mem::take(&mut anchors); + let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset)); + + // Reuse one anchor buffer per band + texel.anchors = std::mem::take(&mut anchors); match &levels { Some(levels) => { - // The texel's stream starts with the stack at each level. + // The texel's stream starts with the stack at each level let start = match &mut tape { Tape::Record(t) => { t.resize(t.len() + slots, 0.0); @@ -1804,38 +2083,39 @@ fn composite_block( _ => 0, }; if warm.is_some() { - load_levels(tape.take(slots), &lanes, stride, &stored, &defaults, &mut accs); + load_levels(tape.take(slots), &lanes, stride, &stored, &defaults, &mut level_values); } - acc = tex.eval_split(defaults, levels, &mut accs, &mut masks, warm.is_some(), &mut tape); + acc = texel.eval_split(defaults, levels, &mut level_values, &mut masks, warm.is_some(), &mut tape); if let Tape::Record(t) = &mut tape && let Some(below) = t.get_mut(start..start + slots) { - store_levels(below, &lanes, stride, &stored, &accs); + store_levels(below, &lanes, stride, &stored, &level_values); } } None => { - tex.eval(&nodes, &mut acc); + texel.eval(&nodes, &mut acc); } } - anchors = tex.anchors; + anchors = texel.anchors; anchors.clear(); } - for (l, buf) in lanes.iter().zip(&mut bufs) { + for (l, buf) in lanes.iter().zip(&mut channel_buffers) { let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); for (k, x) in v.iter().take(l.n).enumerate() { - let enc = if l.signed { to_u16_signed(*x) } else { to_u16(*x) }; - if let Some(slot) = buf.get_mut(ob * l.n + k) { - *slot = enc; + let encoded = if l.signed { to_u16_signed(*x) } else { to_u16(*x) }; + if let Some(slot) = buf.get_mut(band_offset * l.n + k) { + *slot = encoded; } } } } } let cache = if let Tape::Record(t) = tape { Some(t) } else { None }; - (bufs, cache, any) + (channel_buffers, cache, any) }) .collect(); - // Join the bands of each tile (in parallel; uncovered tiles are freed). + + // Join the bands of each tile (in parallel; uncovered tiles are freed) let joined: Vec = results .par_chunks(bands as usize) .map(|parts| { @@ -1861,7 +2141,8 @@ fn composite_block( img.set_tile(tx, ty, d); } } - // Tiles without covered texels cost nothing to composite: not worth caching. + + // Tiles without covered texels cost nothing to composite: not worth caching if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::>>() { records.push(((tx, ty), bands)); } @@ -2272,7 +2553,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti #[cfg(test)] mod tests { use super::*; - use texturecraft_core::{ChannelBlend, Effect, Layer, Procedural, ProceduralKind, TextureSet}; + use texturecraft_core::{ChannelBlend, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; use texturecraft_geom::primitives; struct Fixture { @@ -2323,6 +2604,53 @@ mod tests { (0..3).all(|i| (a[i] - b[i]).abs() < 2e-4) } + #[test] + fn retained_filter_buffers_release_after_the_last_tile() { + let mut fixture = fixture(); + const RESOLUTION: u32 = 128; + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, RESOLUTION, RESOLUTION); + fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, RESOLUTION); + let layer = fill_layer(&mut fixture.project, [0.4; 3], 0.5); + let mut mask = Mask::new(MaskBackground::White); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 8.0 }))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + + let second_layer = fill_layer(&mut fixture.project, [0.2; 3], 0.7); + let mut second_mask = Mask::new(MaskBackground::White); + second_mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 4.0 }))); + fixture.project.layer_mut(second_layer).unwrap().mask = Some(second_mask); + + let images = ImageStore::default(); + let input = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RESOLUTION); + let mut cache = BelowCache::default(); + cache.ahead = vec![(1, 0), (0, 1), (1, 1)]; + + composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); + let retained = cache.held.as_ref().expect("filter fields should be retained while tiles follow"); + let field_bytes: usize = retained.fields.values().map(|field| field.data.capacity() * std::mem::size_of::()).sum(); + let field_count = retained.fields.len(); + let weak_fields = Arc::downgrade(&retained.fields); + assert_eq!(field_count, 2); + assert!(field_bytes > 0); + println!("retained fields: {field_count}, buffer capacity: {field_bytes} bytes"); + + cache.ahead.clear(); + composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache)); + assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers"); + } + #[test] fn histogram_samples_spread_over_every_column() { assert_eq!(histogram_tiles(1024, 1024), all_tiles(1024, 1024), "small sets are read whole"); @@ -2564,42 +2892,154 @@ mod tests { assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); } - #[test] - fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + /// A 256² set whose curvature map has a one-texel ridge in column `ridge_x` (flat elsewhere), and a white fill layer to mask. + fn ridge_fixture(ridge_x: usize) -> (Fixture, LayerId) { let mut fixture = fixture(); fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256); fixture.project.texture_sets[0].resolution = 256; - let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect(); + let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == ridge_x { 1.0 } else { 0.5 }).collect(); fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() }; let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); - let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec { + (fixture, layer) + } + + /// `layer`'s mask made of `effects` (bottom first) on black, read along row 128 over `xs`. + fn mask_row(fixture: &mut Fixture, layer: LayerId, effects: Vec, xs: std::ops::Range) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects = effects; + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, layer, &xs.map(|x| (x, 128)).collect::>()).unwrap() + } + + /// A generator effect of `fixture`'s project. + fn generator_effect(fixture: &mut Fixture, generator: Generator) -> Effect { + Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)) + } + + /// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step). + fn ridge_generator() -> Generator { + Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) } + } + + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let (mut fixture, layer) = ridge_fixture(128); + let mut row_with = |weights: [f32; 7]| { let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights }; let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + let effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 120..137) + }; + + // The sampled ridge is index 8; five texels to its left is index 3 + let (ridge, five_texels_away) = (8, 3); + let finest = row_with([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); + assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); + } + + #[test] + fn a_replaced_curvature_input_is_read_at_its_own_size_only() { + let (mut fixture, layer) = ridge_fixture(128); + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] }; + let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + generator.inputs.insert(BakedMap::Curvature, Source::Uniform([0.5; 3])); + let effect = generator_effect(&mut fixture, generator); + let row = mask_row(&mut fixture, layer, vec![effect], 120..137); + + // The largest size alone would mark the ridge and texels around it; the flat input marks nothing + assert!(row.iter().all(|value| *value < 0.01), "the detail sizes of the mesh map are not read: {row:?}"); + } + + #[test] + fn generator_blur_softens_only_the_generator_not_the_stack_below() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |blur: f32| { + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }); + let mut generator = ridge_generator(); + generator.global.blur = blur; + let mut lighten = generator_effect(&mut fixture, generator); + lighten.blend = BlendMode::Lighten; + mask_row(&mut fixture, layer, vec![below, lighten], 40..111) + }; + + // The sampled row crosses a checker edge; indices below 30 are outside the blur + let (ridge, five_texels_away, far) = (60, 55, 0..30); + let sharp = row_with(0.0); + let blurred = row_with(1.0); + assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}"); + assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}"); + assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}"); + for texel in far { + assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}"); + } + } + + #[test] + fn a_lower_generator_resolution_spreads_a_ridge_over_its_cell() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |factor: i8| { + let mut generator = ridge_generator(); + generator.resolution.factor = factor; + let effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 80..121) + }; + + // At one eighth resolution, each cell spans eight texels + let (ridge, beside, far) = (20, 18, 0); + let full = row_with(0); + let eighth = row_with(-3); + assert!(full[ridge] > 0.99 && full[beside] < 0.01, "at full resolution the ridge is one texel: {full:?}"); + assert!(eighth[ridge] < 0.5 && eighth[beside] > 0.01, "an eighth of the resolution averages it over its cell: {eighth:?}"); + assert!(eighth[far] < 0.01, "texels a few cells away stay black: {eighth:?}"); + } + + #[test] + fn every_caller_lists_the_same_generator_stages_whatever_resolution_it_passes() { + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 1024, factor: 0 }; + let effects = [Effect::new(LayerId(1), EffectKind::Generator(Generator { resolution: custom, ..Generator::new(GeneratorKind::Dirt) }))]; + + // Tile and whole-set resolutions must select the same generator stage + let at_tile: Vec = neighbourhood_filters(&effects, 1024).map(|stage| stage.0).collect(); + let at_set_width: Vec = neighbourhood_filters(&effects, 2048).map(|stage| stage.0).collect(); + assert_eq!(at_tile, at_set_width); + assert_eq!(at_tile, [0], "a custom resolution can be coarser than some UV tile, so it is a stage"); + } + + #[test] + fn a_generator_input_replaced_by_a_value_is_read_instead_of_the_mesh_map() { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let value_with = |fixture: &mut Fixture, input: Option| -> f32 { + let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) }; + if let Some(value) = input { + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3])); + } let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); - let images = Default::default(); - let inputs = Inputs { - project: &fixture.project, - ts: 0, - mesh: &fixture.mesh, - gbuf: &fixture.gbuf, - pixels: &fixture.pixels, - baked: &fixture.baked, - block_scales: BlockScales::default(), - preview: None, - images: &images, - bounds: fixture.mesh.bounds(), - }; - mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::>()).unwrap() + run(fixture, None).value(Channel::BaseColor, 20, 20)[0] }; - // The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth - let (ridge, five_texels_away) = (8, 3); - let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); - let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); - assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); - assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); + // Dark occlusion reveals dirt while the baked white map stays clear + let (baked, black) = (value_with(&mut fixture, None), value_with(&mut fixture, Some(0.0))); + assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}"); } #[test] diff --git a/crates/compose/src/held_fields.rs b/crates/compose/src/held_fields.rs new file mode 100644 index 00000000..476b92d4 --- /dev/null +++ b/crates/compose/src/held_fields.rs @@ -0,0 +1,24 @@ +use std::collections::BTreeSet; +use std::sync::Arc; + +use crate::below::StackKey; +use crate::eval::Fields; + +/// Neighbourhood-filter fields kept between the composites of one pass. +pub(crate) struct HeldFields { + /// Everything the fields read. + pub key: Arc, + /// The working size they were built at. + pub size: (u32, u32), + /// The tiles every layer's fields hold. + pub stack_tiles: BTreeSet<(u32, u32)>, + /// The tiles the hot layer's fields hold (the same tiles when the stack was not split). + pub hot_tiles: BTreeSet<(u32, u32)>, + pub fields: Arc, +} + +impl std::fmt::Debug for HeldFields { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HeldFields").field("stack_tiles", &self.stack_tiles.len()).field("hot_tiles", &self.hot_tiles.len()).finish_non_exhaustive() + } +} diff --git a/crates/compose/src/image_identity.rs b/crates/compose/src/image_identity.rs new file mode 100644 index 00000000..28584ba8 --- /dev/null +++ b/crates/compose/src/image_identity.rs @@ -0,0 +1,19 @@ +use std::sync::{Arc, Weak}; + +use crate::store::ImageRes; + +/// Keeps an image's allocation identity stable without retaining pixels after resource removal. +#[derive(Debug)] +pub(crate) struct ImageIdentity(Weak); + +impl ImageIdentity { + pub(crate) fn new(image: &Arc) -> Self { + Self(Arc::downgrade(image)) + } +} + +impl PartialEq for ImageIdentity { + fn eq(&self, other: &Self) -> bool { + self.0.ptr_eq(&other.0) + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 46c3c6b5..79da6732 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -13,6 +13,8 @@ mod curvature_size_level; pub mod curvature_sizes; pub mod display; pub mod eval; +mod held_fields; +mod image_identity; pub mod pattern; pub mod store; pub mod thumb; @@ -20,8 +22,8 @@ pub mod thumb; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_at, mask_image, pad_tiles, + BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, + flatten_layer, mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index d7df0258..ead117eb 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -6,8 +6,8 @@ use std::collections::BTreeMap; use texturecraft_compose::{BelowCache, Composite, Inputs, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached}; use texturecraft_core::{ - BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, - ProceduralKind, Project, Projection, Source, TextureSet, + BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, + Procedural, ProceduralKind, Project, Projection, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use texturecraft_texel::{TILE, TileImage, to_u16}; @@ -573,3 +573,262 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } + +/// Composite every tile in chunks of `chunk`, telling the cache the `ahead` tiles that follow each chunk, as a pass spread over frames does. +fn run_sliced(fixture: &Fixture, cache: &mut BelowCache, chunk: usize, ahead: usize) -> Composite { + let all = all_tiles(RES, RES); + let (images, baked) = (Default::default(), Default::default()); + let mut out = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + + for (index, tiles) in all.chunks(chunk).enumerate() { + let done = (index * chunk + tiles.len()).min(all.len()); + cache.ahead = all.iter().skip(done).take(ahead).copied().collect(); + composite_tiles_cached(&inputs(fixture, 0, &images, &baked), &mut out, tiles, Some(&mut *cache)); + assert_eq!(cache.holds_fields(), !cache.ahead.is_empty(), "fields are kept exactly while tiles follow (chunk {chunk}, ahead {ahead})"); + } + + out +} + +#[test] +fn filter_fields_kept_across_the_chunks_of_a_pass_composite_exactly() { + let mut fixture = fixture(); + let top = heavy_stack(&mut fixture); + let blurred_fill = fixture.project.texture_sets[0].stack[1]; + let expected = reference(&fixture, 0); + + for hot in [None, Some(top), Some(blurred_fill)] { + // Exercise reuse within and recomputation beyond retained runs + for (chunk, ahead) in [(1, 1), (1, 5), (3, 4), (5, 16), (2, 0)] { + let mut cache = BelowCache::default(); + cache.set_hot(hot); + assert!(run_sliced(&fixture, &mut cache, chunk, ahead) == expected, "a cold sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})"); + + // A warm hot-layer cache needs fewer fields + assert!(run_sliced(&fixture, &mut cache, chunk, ahead) == expected, "a warm sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})"); + } + } + + // Evicted tiles need fields from every layer again + let mut full = BelowCache::default(); + full.set_hot(Some(top)); + run(&fixture, 0, &all_tiles(RES, RES), Some(&mut full)); + let tile_bytes = full.tile_bytes().unwrap(); + for tiles_held in [2, 5, 9] { + for (chunk, ahead) in [(1, 5), (3, 4), (2, 16)] { + let mut cache = BelowCache::default(); + cache.budget = tiles_held * tile_bytes; + cache.set_hot(Some(top)); + for pass in 0..3 { + assert!( + run_sliced(&fixture, &mut cache, chunk, ahead) == expected, + "pass {pass} differs with {tiles_held} cached tiles (chunk {chunk}, ahead {ahead})" + ); + } + } + } +} + +#[test] +fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { + let mut fixture = fixture(); + let top = heavy_stack(&mut fixture); + let all = all_tiles(RES, RES); + let (first, rest) = all.split_at(3); + let mut cache = BelowCache::default(); + cache.set_hot(Some(top)); + + // Keep fields for the remaining tiles + cache.ahead = rest.to_vec(); + let mut out = run(&fixture, 0, first, Some(&mut cache)); + assert!(cache.holds_fields()); + + // Changing the hot mask must invalidate the retained fields + let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); + mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); + let (images, baked) = (Default::default(), Default::default()); + cache.ahead = Vec::new(); + composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); + assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it"); + assert!(!cache.holds_fields()); + + // A live stroke must bypass retained fields + let preview = stroke(top); + cache.ahead = rest.to_vec(); + let mut live = run_with(&fixture, 0, first, Some(&mut cache), Some(&preview)); + assert!(!cache.holds_fields()); + + let mut inp = inputs(&fixture, 0, &images, &baked); + inp.preview = Some(&preview); + composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs"); +} + +/// Kept fields hold a layer off the hot path only over the tiles the cache lacked when they were built. A tile the cache drops +/// while they are in use needs that layer's fields again. +#[test] +fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { + const SIZE: u32 = 512; + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, SIZE, SIZE); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, SIZE)); + let mut fixture = Fixture { project, mesh, gbuf, pixels: PixelStore::default() }; + add(&mut fixture, 0, fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); + + // Pattern detail exposes any missing blur field + let mut blurred = Mask::new(MaskBackground::Black); + blurred.effects.push(effect(&mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); + add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred)); + + // Keep the blurred layer visible under the hot layer + let hot = add(&mut fixture, 0, LayerKind::Paint, None); + paint_rect_at(&mut fixture, hot, SIZE, (10, 10), (40, 40), 0.2); + + let mut all = all_tiles(SIZE, SIZE); + all.sort_by_key(|&(x, y)| (y, x)); + let channels = fixture.project.texture_sets[0].channel_list(); + let (images, baked) = (Default::default(), Default::default()); + let mut expected = Composite::new(&channels, SIZE); + composite_tiles(&inputs(&fixture, 0, &images, &baked), &mut expected, &all); + + // Prime the cache with only the two bottom rows + let rows = (SIZE / TILE) as usize; + let (above, bottom) = all.split_at(all.len() - 2 * rows); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot)); + let mut out = Composite::new(&channels, SIZE); + composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache)); + assert_eq!(cache.len(), bottom.len()); + cache.budget = cache.bytes(); + + // Cache eviction during the run must rebuild missing lower-layer fields + let mut out = Composite::new(&channels, SIZE); + for (index, tile) in all.iter().enumerate() { + cache.ahead = all.iter().skip(index + 1).copied().collect(); + composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &[*tile], Some(&mut cache)); + if index == 0 { + assert!(cache.holds_fields()); + } + } + assert!(above.len() > bottom.len()); + assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path"); +} + +/// A stroke that starts while fields are kept must not leave them allocated for as long as it lasts, even though tiles still follow. +#[test] +fn a_live_stroke_releases_the_fields_kept_before_it_started() { + let mut fixture = fixture(); + let top = heavy_stack(&mut fixture); + let all = all_tiles(RES, RES); + let (first, rest) = all.split_at(3); + let mut cache = BelowCache::default(); + cache.set_hot(Some(top)); + + cache.ahead = rest.to_vec(); + run(&fixture, 0, first, Some(&mut cache)); + assert!(cache.holds_fields()); + + // A stroke must release fields even while tiles remain + let preview = stroke(top); + let mut live = run_with(&fixture, 0, first, Some(&mut cache), Some(&preview)); + assert!(!cache.holds_fields(), "fields kept before the stroke stay allocated while it lasts"); + + let (images, baked) = (Default::default(), Default::default()); + let mut inp = inputs(&fixture, 0, &images, &baked); + inp.preview = Some(&preview); + composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a stroke that starts during a sliced pass differs"); +} + +#[test] +fn cached_stack_tracks_referenced_images_only() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore}; + + let mut fixture = fixture(); + let hot_layer = heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") }; + + fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() }); + let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let mut images = ImageStore::default(); + let baked = Default::default(); + let tiles = all_tiles(RES, RES); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot_layer)); + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + let mut previous_image = None; + + for stage in ["cold", "resolve", "unused1", "unused2", "unused3", "replace", "remove"] { + match stage { + "resolve" => { + let image = image_with_value(1.0); + previous_image = Some(Arc::downgrade(&image)); + images.insert("used".into(), image); + } + "replace" => { + let replacement = image_with_value(0.4); + let replacement_weak = Arc::downgrade(&replacement); + images.insert("used".into(), replacement); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels"); + previous_image = Some(replacement_weak); + } + "remove" => { + images.remove("used"); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels"); + } + "cold" => {} + _ => { + images.insert(stage.into(), image_with_value(0.5)); + } + } + + fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); + let input = inputs(&fixture, 0, &images, &baked); + composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; + composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}"); + + let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); + } +} + +#[test] +fn generator_input_image_changes_invalidate_stack_key() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore, StackKey}; + + let mut fixture = fixture(); + heavy_stack(&mut fixture); + let generated_layer = fixture.project.texture_sets[0].stack[1]; + let mask = fixture.project.layer_mut(generated_layer).unwrap().mask.as_mut().unwrap(); + let EffectKind::Generator(generator) = &mut mask.effects[0].kind else { panic!("expected generator") }; + *generator = Generator::new(GeneratorKind::Dirt); + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used")); + + let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let mut images = ImageStore::default(); + images.insert("used".into(), image(0.1)); + let baked = Default::default(); + let roots = &fixture.project.texture_sets[0].stack; + let key = |images: &ImageStore| StackKey::new(&fixture.project, &fixture.pixels, &baked, images, 0, roots).unwrap(); + let original = key(&images); + + images.insert("unrelated".into(), image(0.5)); + assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged"); + + let old_image = Arc::downgrade(&images["used"]); + images.insert("used".into(), image(0.9)); + assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels"); + assert!(key(&images) != original, "replacing a generator input must invalidate the cache"); + + images.remove("used"); + assert!(key(&images) != original, "removing a generator input must invalidate the cache"); +} diff --git a/crates/core/src/bake/bake_settings.rs b/crates/core/src/bake/bake_settings.rs index 4528270d..8d121419 100644 --- a/crates/core/src/bake/bake_settings.rs +++ b/crates/core/src/bake/bake_settings.rs @@ -1,4 +1,4 @@ -use super::{CageSettings, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; +use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; use serde::{Deserialize, Serialize}; /// Persisted clean-room bake settings, grouped by the controls they belong to @@ -11,3 +11,10 @@ pub struct BakeSettings { pub skew: SkewSettings, pub maps: MeshMapSettings, } + +impl BakeSettings { + /// Whether a painted skew map steers the rays: it needs a separate high poly and a distance-based cage with averaged normals + pub fn skew_applies(&self) -> bool { + !self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 27d454c6..70a87615 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,13 +4,19 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::{BlendMode, Channel, ChannelKind, lum}; +use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; mod curvature_detail; mod curvature_mode; +mod generator_global; +mod output_resolution; +mod resolution_mode; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; +pub use generator_global::GeneratorGlobal; +pub use output_resolution::OutputResolution; +pub use resolution_mode::ResolutionMode; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -550,6 +556,17 @@ impl GeneratorKind { GeneratorKind::Direction => "Light / direction", } } + + /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. + pub fn inputs(self) -> &'static [BakedMap] { + match self { + GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature], + GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], + GeneratorKind::ThinAreas => &[BakedMap::Thickness], + GeneratorKind::Position | GeneratorKind::Direction => &[], + } + } + pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s)) @@ -576,9 +593,25 @@ pub struct Generator { /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). #[serde(default, skip_serializing_if = "Option::is_none")] pub detail: Option, + /// Blur, balance and contrast of the finished value (neutral for generators saved before they existed). + #[serde(default, skip_serializing_if = "GeneratorGlobal::is_neutral")] + pub global: GeneratorGlobal, + /// The resolution the generator is computed at (the texture set's for generators saved before it existed). + #[serde(default, skip_serializing_if = "OutputResolution::is_default")] + pub resolution: OutputResolution, + /// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub inputs: BTreeMap, } impl Generator { + /// The softest a ramp gets, so its threshold never divides by zero. + pub const MIN_SOFTNESS: f32 = 1e-3; + /// The most noise a generator mixes in, and the range of its noise scale. + pub const MAX_NOISE_AMOUNT: f32 = 2.0; + pub const MIN_NOISE_SCALE: f32 = 0.01; + pub const MAX_NOISE_SCALE: f32 = 1000.0; + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -592,7 +625,21 @@ impl Generator { GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, offset: 0.0, direction: [0.0, 1.0, 0.0], invert: false, detail } + Generator { + kind, + level, + softness, + noise_amount, + noise_scale: 8.0, + seed: 7, + offset: 0.0, + direction: [0.0, 1.0, 0.0], + invert: false, + detail, + global: GeneratorGlobal::default(), + resolution: OutputResolution::default(), + inputs: BTreeMap::new(), + } } /// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over @@ -1062,14 +1109,46 @@ impl EffectKind { matches!(self, EffectKind::Paint | EffectKind::Path(_)) } - /// Anchor points read by this effect's sources. + /// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point. fn reads_anchor(&self) -> bool { match self { EffectKind::Fill { source, .. } => source.anchor().is_some(), - EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()), + EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()), + EffectKind::Generator(generator) => generator.inputs.values().any(|source| source.anchor().is_some()), _ => false, } } + + /// The anchor points this effect's sources read, with the channel each reads. + pub fn anchors_read(&self) -> Vec<(LayerId, Channel)> { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Material(fill) => fill.sources.values().collect(), + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources + .into_iter() + .filter_map(|source| match source { + Source::Anchor { anchor, channel } => Some((*anchor, *channel)), + _ => None, + }) + .collect() + } + + /// The image resources this effect's sources read (a fill, material or generator input). + pub fn images_read(&self) -> impl Iterator { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Material(fill) => fill.sources.values().collect(), + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources.into_iter().filter_map(|source| match source { + Source::Image { name, .. } => Some(name.as_str()), + _ => None, + }) + } } impl Layer { @@ -1104,6 +1183,15 @@ impl Effect { mod tests { use super::*; + #[test] + fn material_effect_images_are_reported_as_used() { + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::image("material.png")); + let effect = EffectKind::Material(fill); + + assert_eq!(effect.images_read().collect::>(), vec!["material.png"]); + } + #[test] fn generator_offset_shifts_the_mask_value() { let mut g = Generator::new(GeneratorKind::Position); @@ -1139,6 +1227,22 @@ mod tests { assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes"); } + #[test] + fn generators_saved_before_the_new_settings_load_and_save_unchanged() { + let saved = serde_json::to_value(Generator::new(GeneratorKind::Dirt)).unwrap(); + for field in ["global", "resolution", "inputs"] { + assert!(saved.get(field).is_none(), "a default `{field}` is not written, so saved files stay as they were"); + } + + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert!(loaded.global.is_neutral()); + + let mut blurred = Generator::new(GeneratorKind::Dirt); + blurred.global.blur = 0.5; + let round_trip: Generator = serde_json::from_value(serde_json::to_value(&blurred).unwrap()).unwrap(); + assert_eq!(round_trip, blurred); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/core/src/layer/generator_global.rs b/crates/core/src/layer/generator_global.rs new file mode 100644 index 00000000..15349e0d --- /dev/null +++ b/crates/core/src/layer/generator_global.rs @@ -0,0 +1,96 @@ +use serde::{Deserialize, Serialize}; + +/// Adjustments every generator applies to its finished value: a blur, then balance and contrast. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct GeneratorGlobal { + /// Blur of the generated value (0..1 of [`GeneratorGlobal::MAX_BLUR`]). + pub blur: f32, + /// Shifts the value darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged. + pub balance: f32, + /// Narrows the ramp around its middle (0 unchanged, 1 a hard step). + pub contrast: f32, +} + +impl GeneratorGlobal { + /// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub const MAX_BLUR: f32 = 64.0; + /// Narrower than this, the balanced range is a hard step. + pub const MIN_RANGE: f32 = 1e-6; + /// The texels per side the blur radius is measured at (2K). + pub const BLUR_RESOLUTION: f32 = 2048.0; + + pub fn is_neutral(&self) -> bool { + *self == GeneratorGlobal::default() + } + + /// The blur as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub fn blur_radius(&self) -> f32 { + self.blur.clamp(0.0, 1.0) * GeneratorGlobal::MAX_BLUR + } + + /// The blur as a radius in texels at `resolution` texels per side. + pub fn blur_radius_at(&self, resolution: u32) -> f32 { + self.blur_radius() * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION + } + + /// `value` after balance and contrast: balance picks the input range stretched to 0..1, contrast narrows it around its middle. + pub fn apply(&self, value: f32) -> f32 { + if self.balance == 0.5 && self.contrast == 0.0 { + return value; + } + let balance = self.balance.clamp(0.0, 1.0); + let (low, high) = ((1.0 - 2.0 * balance).max(0.0), (2.0 - 2.0 * balance).min(1.0)); + let middle = (low + high) * 0.5; + let keep = 1.0 - self.contrast.clamp(0.0, 1.0); + let (low, high) = (middle - (middle - low) * keep, middle + (high - middle) * keep); + if high - low < GeneratorGlobal::MIN_RANGE { + return if value >= middle { 1.0 } else { 0.0 }; + } + ((value - low) / (high - low)).clamp(0.0, 1.0) + } +} + +impl Default for GeneratorGlobal { + fn default() -> Self { + GeneratorGlobal { blur: 0.0, balance: 0.5, contrast: 0.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn neutral_settings_leave_the_value_unchanged() { + let global = GeneratorGlobal::default(); + for value in [0.0, 0.1, 0.5, 0.93, 1.0] { + assert_eq!(global.apply(value), value); + } + } + + #[test] + fn balance_darkens_below_the_middle_and_brightens_above() { + let darker = GeneratorGlobal { balance: 0.25, ..GeneratorGlobal::default() }; + assert_eq!(darker.apply(0.4), 0.0, "the lower half goes black"); + assert!((darker.apply(0.75) - 0.5).abs() < 1e-6, "the upper half stretches over the whole range"); + + let brighter = GeneratorGlobal { balance: 0.75, ..GeneratorGlobal::default() }; + assert!((brighter.apply(0.25) - 0.5).abs() < 1e-6); + assert_eq!(brighter.apply(0.6), 1.0, "the upper half goes white"); + + assert_eq!(GeneratorGlobal { balance: 0.0, ..GeneratorGlobal::default() }.apply(0.99), 0.0); + assert_eq!(GeneratorGlobal { balance: 1.0, ..GeneratorGlobal::default() }.apply(0.01), 1.0); + } + + #[test] + fn full_contrast_is_a_step_at_the_middle_of_the_balanced_range() { + let step = GeneratorGlobal { contrast: 1.0, ..GeneratorGlobal::default() }; + assert_eq!(step.apply(0.49), 0.0); + assert_eq!(step.apply(0.51), 1.0); + + let half = GeneratorGlobal { contrast: 0.5, ..GeneratorGlobal::default() }; + assert_eq!(half.apply(0.25), 0.0); + assert!((half.apply(0.5) - 0.5).abs() < 1e-6); + assert_eq!(half.apply(0.75), 1.0); + } +} diff --git a/crates/core/src/layer/output_resolution.rs b/crates/core/src/layer/output_resolution.rs new file mode 100644 index 00000000..c0e5173c --- /dev/null +++ b/crates/core/src/layer/output_resolution.rs @@ -0,0 +1,120 @@ +use serde::{Deserialize, Serialize}; + +use super::resolution_mode::ResolutionMode; + +/// The resolution a generator computes its output at, before it is sampled onto the texture set. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputResolution { + pub mode: ResolutionMode, + /// Texels per side for [`ResolutionMode::Custom`]. + pub custom: u32, + /// Power of two applied to the base size (−3 = 1/8 … 3 = ×8; 0 = the same as the context). + pub factor: i8, +} + +impl OutputResolution { + /// The factors the reference app offers: 1/8 to ×8. + pub const FACTORS: std::ops::RangeInclusive = -3..=3; + /// The sizes offered for [`ResolutionMode::Custom`]. + pub const CUSTOM_SIZES: [u32; 6] = [128, 256, 512, 1024, 2048, 4096]; + /// The largest output, the largest texture set resolution. + pub const MAX_SIZE: u32 = 8192; + /// The coarsest output: one value per this many texels of the context per side (a compositing tile). + pub const MAX_CELL: u32 = 64; + + pub fn is_default(&self) -> bool { + *self == OutputResolution::default() + } + + /// Whether some UV tile can get a coarser output than its own resolution (a custom size, the set's size or a factor below 1). + pub fn can_reduce(&self) -> bool { + matches!(self.mode, ResolutionMode::Custom | ResolutionMode::TextureSet) || self.factor < 0 + } + + /// The largest cell a UV tile of up to `uv_tile` texels per side can get, whatever its texture set's resolution. + pub fn largest_cell(&self, uv_tile: u32) -> u32 { + if self.mode == ResolutionMode::TextureSet { OutputResolution::MAX_CELL } else { self.cell(uv_tile, uv_tile) } + } + + /// Texels per side of the output for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`. + pub fn output_size(&self, uv_tile: u32, texture_set: u32) -> u32 { + let base = match self.mode { + ResolutionMode::Auto | ResolutionMode::UvTile => uv_tile, + ResolutionMode::TextureSet => texture_set, + ResolutionMode::Custom => self.custom, + }; + let factor = self.factor.clamp(*OutputResolution::FACTORS.start(), *OutputResolution::FACTORS.end()); + let scaled = if factor >= 0 { base.saturating_mul(1 << factor) } else { base >> -factor }; + + // Hostile tile sizes can make the minimum exceed the supported maximum + let minimum = (uv_tile / OutputResolution::MAX_CELL).clamp(1, OutputResolution::MAX_SIZE); + scaled.clamp(minimum, OutputResolution::MAX_SIZE) + } + + /// How many texels of the UV tile one output texel covers per side (1 when the output is as fine or finer). + pub fn cell(&self, uv_tile: u32, texture_set: u32) -> u32 { + (uv_tile / self.output_size(uv_tile, texture_set)).max(1) + } +} + +impl Default for OutputResolution { + fn default() -> Self { + OutputResolution { mode: ResolutionMode::Auto, custom: 2048, factor: 0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_follows_the_uv_tile() { + let resolution = OutputResolution::default(); + assert_eq!(resolution.output_size(1024, 2048), 1024); + assert_eq!(resolution.cell(1024, 2048), 1); + assert!(!resolution.can_reduce()); + } + + #[test] + fn the_texture_set_mode_reads_the_set_not_the_uv_tile() { + let resolution = OutputResolution { mode: ResolutionMode::TextureSet, factor: -1, ..OutputResolution::default() }; + assert_eq!(resolution.output_size(512, 2048), 1024, "half the set's 2048"); + assert_eq!(resolution.cell(512, 2048), 1, "finer than the 512 tile: one texel per texel"); + } + + #[test] + fn factors_and_custom_sizes_scale_the_output() { + let eighth = OutputResolution { factor: -3, ..OutputResolution::default() }; + assert_eq!((eighth.output_size(2048, 2048), eighth.cell(2048, 2048)), (256, 8)); + + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 512, factor: 1 }; + assert_eq!((custom.output_size(2048, 2048), custom.cell(2048, 2048)), (1024, 2)); + + let finer = OutputResolution { factor: 3, ..OutputResolution::default() }; + assert_eq!((finer.output_size(2048, 2048), finer.cell(2048, 2048)), (8192, 1), "a finer output than the tile keeps one texel per texel"); + } + + #[test] + fn the_largest_cell_covers_any_texture_set() { + let set = OutputResolution { mode: ResolutionMode::TextureSet, ..OutputResolution::default() }; + assert!(set.can_reduce(), "a UV tile larger than its set gets the set's coarser size"); + assert_eq!(set.largest_cell(2048), OutputResolution::MAX_CELL); + assert_eq!(OutputResolution { factor: -2, ..OutputResolution::default() }.largest_cell(2048), 4); + } + + #[test] + fn hostile_sizes_stay_within_the_largest_output_and_the_coarsest_cell() { + let huge = OutputResolution { mode: ResolutionMode::Custom, custom: u32::MAX, factor: i8::MAX }; + assert_eq!(huge.output_size(2048, 2048), OutputResolution::MAX_SIZE); + + let tiny = OutputResolution { mode: ResolutionMode::Custom, custom: 1, factor: -3 }; + assert_eq!(tiny.cell(4096, 4096), OutputResolution::MAX_CELL); + } + + #[test] + fn hostile_uv_tile_size_does_not_panic() { + let resolution = OutputResolution::default(); + + assert_eq!(resolution.output_size(u32::MAX, 2048), OutputResolution::MAX_SIZE); + } +} diff --git a/crates/core/src/layer/resolution_mode.rs b/crates/core/src/layer/resolution_mode.rs new file mode 100644 index 00000000..ffd6a140 --- /dev/null +++ b/crates/core/src/layer/resolution_mode.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +/// What a generator's output resolution is based on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ResolutionMode { + /// The context: the resolution of the UV tile it is computed for. + Auto, + /// The texture set's resolution. + TextureSet, + /// The UV tile's resolution. + UvTile, + /// A size of its own. + Custom, +} + +impl ResolutionMode { + pub const ALL: [ResolutionMode; 4] = [ResolutionMode::Auto, ResolutionMode::TextureSet, ResolutionMode::UvTile, ResolutionMode::Custom]; + + pub fn label(self) -> &'static str { + match self { + ResolutionMode::Auto => "Auto", + ResolutionMode::TextureSet => "Texture set", + ResolutionMode::UvTile => "UV tile", + ResolutionMode::Custom => "Custom", + } + } + + pub fn parse(name: &str) -> Option { + let norm = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + ResolutionMode::ALL.into_iter().find(|mode| norm(&format!("{mode:?}")) == norm(name) || norm(mode.label()) == norm(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 75ea2405..4a17e89e 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,9 +24,9 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, - hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask, + Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, OutputResolution, PathShape, Procedural, ProceduralKind, + Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/bake/bake_cage_inputs.rs b/crates/engine/src/bake/bake_cage_inputs.rs index ab559beb..be6eef7c 100644 --- a/crates/engine/src/bake/bake_cage_inputs.rs +++ b/crates/engine/src/bake/bake_cage_inputs.rs @@ -23,6 +23,16 @@ impl BakeCageInputs { CageShell::new(&self.request()) } + /// Whether this set uses the session's shared low mesh + pub fn uses_mesh(&self, mesh: &Arc) -> bool { + Arc::ptr_eq(&self.mesh, mesh) + } + + /// Build a cage from edges shared across sets using the same low mesh + pub fn cage_shell_with_edges(&self, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result { + CageShell::new_with_edges(&self.request(), wire_edges, missing_seam_edges) + } + /// Where each high-poly vertex sits relative to the bake's transfer rays pub fn high_poly_reach(&self) -> Result { HighPolyReach::new(&self.request()) diff --git a/crates/engine/src/bake/bake_checks.rs b/crates/engine/src/bake/bake_checks.rs new file mode 100644 index 00000000..3ea93729 --- /dev/null +++ b/crates/engine/src/bake/bake_checks.rs @@ -0,0 +1,109 @@ +//! What can spoil a texture set's bake, checked before it runs: overlapping UVs and parts "By Mesh Name" leaves unpaired + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_bake::NamePair; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::{Mesh, SubMesh, UvGBuffer, glam::Vec2}; + +use crate::{Result, Session}; + +/// Side of the UV raster the overlap check counts texels on, per UV tile (as mesh import does) +const OVERLAP_CHECK_RESOLUTION: u32 = 512; + +/// The only material of the UV-only mesh the overlap check builds per UV tile +const BLOCK_MATERIAL: usize = 0; + +impl Session { + /// About the share (0..1) of texture set `texture_set`'s UV layout the bake sees covered more than once, over the UV tiles it bakes: a texel under three triangles counts twice + pub fn bake_uv_overlap(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + let mesh = self.bake_mesh(texture_set)?; + let (overlaps, covered) = match set.tile_grid() { + Some(grid) => { + let baked_blocks: BTreeSet<(u32, u32)> = + set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid.block(*tile)).collect(); + let blocks = triangles_by_block(&mesh, set.material, (grid.cols, grid.rows), &baked_blocks); + blocks + .values() + .map(|block| overlap_counts(block, BLOCK_MATERIAL)) + .fold((0, 0), |(overlaps, covered), (block_overlaps, block_covered)| (overlaps + block_overlaps, covered + block_covered)) + } + None => overlap_counts(&mesh, set.material), + }; + + Ok(if covered == 0 { 0.0 } else { (overlaps as f32 / covered as f32).min(1.0) }) + } + + /// How texture set `texture_set`'s low-poly parts pair with the high-poly parts ([`NamePair::list`]); `None` unless it bakes from a high poly "By Mesh Name" + pub fn bake_name_pairs(&self, texture_set: usize) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let settings = &set.bake.high_poly; + let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); + + Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings))) + } + + /// The high-poly parts none of `texture_sets` bakes from, by name: a set matching "Always" bakes from every part, one matching "By Mesh Name" only from the parts its names pair with + pub fn bake_unpaired_high_parts(&self, texture_sets: &[usize]) -> Result> { + let (mut paired, mut unpaired) = (BTreeSet::new(), BTreeSet::new()); + for &texture_set in texture_sets { + let settings = &self.doc.project.texture_set(texture_set)?.bake.high_poly; + if !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always { + return Ok(Vec::new()); + } + + for pair in self.bake_name_pairs(texture_set)?.unwrap_or_default() { + match pair { + NamePair { low: Some(_), high: Some(high) } => paired.insert(high), + NamePair { low: None, high: Some(high) } => unpaired.insert(high), + _ => false, + }; + } + } + + Ok(unpaired.difference(&paired).cloned().collect()) + } +} + +/// Texels covered more than once and texels covered, rasterizing material `material`'s UVs over 0..1 +fn overlap_counts(mesh: &Mesh, material: usize) -> (usize, usize) { + let gbuffer = UvGBuffer::new(mesh, material, OVERLAP_CHECK_RESOLUTION, OVERLAP_CHECK_RESOLUTION); + (gbuffer.overlaps as usize, gbuffer.covered_count()) +} + +/// Material `material`'s triangles sorted into the `baked_blocks` of a `grid` (columns, rows) atlas their UVs reach, one UV-only mesh per block with the block's UVs over 0..1: a single pass, however many blocks +fn triangles_by_block(mesh: &Mesh, material: usize, grid: (u32, u32), baked_blocks: &BTreeSet<(u32, u32)>) -> BTreeMap<(u32, u32), Mesh> { + let scale = Vec2::new(grid.0 as f32, grid.1 as f32); + let mut blocks: BTreeMap<(u32, u32), Mesh> = BTreeMap::new(); + for triangle in mesh.triangles_of(material) { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(first_uv), Some(second_uv), Some(third_uv)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { continue }; + let uvs = [*first_uv * scale, *second_uv * scale, *third_uv * scale]; + + // Every block the triangle's UV bounds touch, so a triangle across a border counts in both + let (uv_min, uv_max) = uvs.iter().fold((Vec2::INFINITY, Vec2::NEG_INFINITY), |(uv_min, uv_max), uv| (uv_min.min(*uv), uv_max.max(*uv))); + + // Capped at the grid: a stray huge UV must not walk billions of blocks + let columns = uv_min.x.floor().max(0.0) as u32..=((uv_max.x.ceil() as u32).saturating_sub(1)).min(grid.0 - 1); + let rows = uv_min.y.floor().max(0.0) as u32..=((uv_max.y.ceil() as u32).saturating_sub(1)).min(grid.1 - 1); + for column in columns { + for row in rows.clone() { + if !baked_blocks.contains(&(column, row)) { + continue; + } + + let block = blocks.entry((column, row)).or_insert_with(|| Mesh { materials: vec![String::new()], ..Mesh::default() }); + let offset = Vec2::new(column as f32, row as f32); + block.indices.extend(block.uvs.len() as u32..block.uvs.len() as u32 + 3); + block.uvs.extend(uvs.iter().map(|uv| *uv - offset)); + } + } + } + + for block in blocks.values_mut() { + block.submeshes = vec![SubMesh { name: String::new(), material: BLOCK_MATERIAL, start: 0, count: block.indices.len() as u32 }]; + } + + blocks +} diff --git a/crates/engine/src/bake/high_poly_missed.rs b/crates/engine/src/bake/high_poly_missed.rs index 21de6c05..c9663ac1 100644 --- a/crates/engine/src/bake/high_poly_missed.rs +++ b/crates/engine/src/bake/high_poly_missed.rs @@ -1,9 +1,10 @@ use rayon::prelude::*; use texturecraft_bake::HighPolyReach; -/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0 -/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked -/// `vertex_count` is the validated high-poly mesh's vertex count +/// The value [`high_poly_missed`] gives a vertex that `only_set` doesn't own, which the 3D view leaves out +pub const HIDDEN_HIGH_POLY_VERTEX: f32 = -1.0; + +/// Per vertex of the validated high poly: 1.0 if its owning set's bake misses it at that set's (max frontal, max rear), 0.0 if reached or unknown, [`HIDDEN_HIGH_POLY_VERTEX`] if `only_set` doesn't own it pub fn high_poly_missed(reach: &[Option], distances: &[(f32, f32)], only_set: Option, vertex_count: usize) -> Vec { // Ownership is already assigned by HighPolyReach; other sets must not color the vertex let sets: Vec<(&HighPolyReach, f32, f32)> = reach @@ -13,11 +14,21 @@ pub fn high_poly_missed(reach: &[Option], distances: &[(f32, f32) .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set)) .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear))) .collect(); + (0..vertex_count) .into_par_iter() .map(|vertex| { + if only_set.is_some_and(|only| !owns(reach, only, vertex)) { + return HIDDEN_HIGH_POLY_VERTEX; + } + let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear)); f32::from(u8::from(missed.unwrap_or(false))) }) .collect() } + +/// Whether texture set `texture_set`'s reach claims high-poly vertex `vertex` +fn owns(reach: &[Option], texture_set: usize, vertex: usize) -> bool { + reach.get(texture_set).and_then(Option::as_ref).and_then(|set| set.vertices.get(vertex)).is_some_and(Option::is_some) +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 14248cc3..f8826b44 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -182,12 +182,13 @@ impl Session { /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result>> { let set = self.doc.project.texture_set(texture_set)?; - let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high); + let steers = has_high && (target != BakePaintTarget::Skew || set.bake.skew_applies()); + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| steers); paint.map(|map| super::layout::paint_for_bake(map, set)).transpose() } /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas - fn bake_mesh(&self, texture_set: usize) -> Result> { + pub(super) fn bake_mesh(&self, texture_set: usize) -> Result> { let set = self.doc.project.texture_set(texture_set)?; Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) { Some(grid) => { diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index f06ab265..bfe9b22c 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,6 +1,7 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API mod bake_cage_inputs; +mod bake_checks; mod bake_mesh; mod bake_meshes; mod bake_task; @@ -19,7 +20,7 @@ pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; -pub use high_poly_missed::high_poly_missed; +pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed}; pub use merged_high::MergedHigh; pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; pub use model_patch::settings_patch; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index d754fc70..a03a58a9 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -195,16 +195,26 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result Option<[f32; 3]> { - color_of(p.get(key)?) +pub(crate) fn color_param(cmd: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")"))), + } } /// A color value (see [`color_param`]). pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { match v { Value::Array(a) if a.len() >= 3 => { - let v: Vec = a.iter().take(3).map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - if v.iter().all(|x| x.is_finite()) { Some([v[0], v[1], v[2]]) } else { None } + let mut out = [0.0f32; 3]; + for (i, x) in a.iter().take(3).enumerate() { + let f = x.as_f64()? as f32; + if !f.is_finite() { + return None; + } + out[i] = f; + } + Some(out) } Value::Number(n) => n.as_f64().map(|v| [v as f32; 3]).filter(|v| v[0].is_finite()), Value::String(s) => { @@ -218,3 +228,51 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { _ => None, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn color_param_accepts_valid_forms() { + let p = json!({ + "hex": "#336699", + "hex_plain": "336699", + "rgb": [0.2, 0.4, 0.6], + "grey": 0.5, + }); + assert!(color_param("cmd", &p, "hex").unwrap().is_some()); + assert!(color_param("cmd", &p, "hex_plain").unwrap().is_some()); + assert_eq!(color_param("cmd", &p, "rgb").unwrap(), Some([0.2, 0.4, 0.6])); + assert_eq!(color_param("cmd", &p, "grey").unwrap(), Some([0.5, 0.5, 0.5])); + assert_eq!(color_param("cmd", &p, "missing").unwrap(), None); + assert_eq!(color_param("cmd", &json!({"c": null}), "c").unwrap(), None); + } + + #[test] + fn color_param_rejects_invalid_forms() { + let bad_cases = [ + ("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ]; + for (input, expected_err) in bad_cases { + let p = json!({ "color": input }); + let err = color_param("test.cmd", &p, "color").unwrap_err(); + assert_eq!(err.to_string(), format!("`test.cmd`: {expected_err}")); + } + + let bad_array = json!({ "color": ["a", "b", "c"] }); + assert!(color_param("test.cmd", &bad_array, "color").is_err()); + + let short_array = json!({ "color": [0.5, 0.5] }); + assert!(color_param("test.cmd", &short_array, "color").is_err()); + + let overflow_array = json!({ "color": [1e40, 0.0, 0.0] }); + assert!(color_param("test.cmd", &overflow_array, "color").is_err()); + + let overflow_scalar = json!({ "color": 1e40 }); + assert!(color_param("test.cmd", &overflow_scalar, "color").is_err()); + } +} diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 36aa5f3a..5aedd49b 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -2,7 +2,7 @@ //! clipboard: it holds a layer or an effect. use serde_json::{Value, json}; -use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; +use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground}; use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::layer_ops::{empty_texel, fit}; @@ -55,26 +55,29 @@ fn cut(s: &mut Session, p: &Value) -> Result { Ok(json!({ "cut": eid })) } -fn paste(s: &mut Session, p: &Value) -> Result { +fn paste(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.paste"; - let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let layer = layer_param(s, CMD, p)?; - // The selected effect's stack, or the content or mask the selection targets. - let selected = match s.target { - StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x), + let (copied, copied_id) = session.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let effect = copied.project.effect(copied_id).map(|(_, effect)| effect.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let layer = layer_param(session, CMD, params)?; + + // The selected effect's stack, or the content or mask the selection targets + let selected = match session.target { + StackTarget::Effect(selected) if session.selected_layer() == Some(layer) => Some(selected), _ => None, }; - let in_content = |s: &Session, x: LayerId| { - s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x)) + let in_content = |session: &Session, effect_id: LayerId| { + let owner = session.doc.project.effect(effect_id).and_then(|(owner, _)| session.doc.project.layers.get(&owner)); + owner.is_some_and(|owner| owner.content_effects.iter().any(|effect| effect.id == effect_id)) }; - let asked = strp(p, "target").is_some(); + let asked = strp(params, "target").is_some(); let content = match selected { - _ if asked => content_target(p, CMD)?, - Some(x) => in_content(s, x), - None => s.target == StackTarget::Content && s.selected_layer() == Some(layer), + _ if asked => content_target(params, CMD)?, + Some(selected) => in_content(session, selected), + None => session.target == StackTarget::Content && session.selected_layer() == Some(layer), }; - // Effects that fit one stack only go there, unless another was asked for. + + // Effects that fit one stack only go there, unless another was asked for let content = match effect.kind.content_only() { Some(only) if only != content && asked => { return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); @@ -82,46 +85,54 @@ fn paste(s: &mut Session, p: &Value) -> Result { Some(only) => only, None => content, }; - // An instance's content and (unless it has its own) mask belong to its source. - let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) }; - let owner_layer = s.doc.project.layer(owner)?; + + // An instance's content and (unless it has its own) mask belong to its source + let owner = if content { session.doc.project.content_layer(layer).map_or(layer, |source| source.id) } else { session.doc.project.mask_owner(layer) }; + let owner_layer = session.doc.project.layer(owner)?; if content && owner_layer.is_group() { return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name))); } - // A fill reading an anchor point needs one below its new layer. - if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { - anchor_source(s, CMD, owner, *anchor, *channel)?; + + // Each anchor point the effect reads must be below its new layer + for (anchor, channel) in effect.kind.anchors_read() { + anchor_source(session, CMD, owner, anchor, channel)?; } - let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; - let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; - let new = s.edit("Paste effect", |s| { - let new = s.doc.project.alloc_id(); - let l = s.doc.project.layer_mut(owner)?; - let list = if content { - &mut l.content_effects + + let (set, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; + let (size, channels) = session.doc.project.texture_set(set).map(|texture_set| (texture_set.size(), texture_set.channel_list()))?; + + let pasted = session.edit("Paste effect", |session| { + let pasted = session.doc.project.alloc_id(); + let owner_layer = session.doc.project.layer_mut(owner)?; + let stack = if content { + &mut owner_layer.content_effects } else { - let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; - &mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects + let background = + if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; + &mut owner_layer.mask.get_or_insert_with(|| Mask::new(background)).effects }; - let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1); - list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() }); - // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's). - if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) { - s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0])); + let index = selected.and_then(|selected| stack.iter().position(|effect| effect.id == selected)).map_or(stack.len(), |position| position + 1); + stack.insert(index, texturecraft_core::Effect { id: pasted, ..effect.clone() }); + + // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's) + if let Some(image) = copied.pixels.masks.get(&copied_id).filter(|_| !content) { + session.doc.pixels.masks.insert(pasted, fit(image, size, &[0, 0])); } - for c in channels.iter().copied().filter(|_| content) { - if let Some(img) = src.pixels.layer(eid, c) { - s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); + for channel in channels.iter().copied().filter(|_| content) { + if let Some(image) = copied.pixels.layer(copied_id, channel) { + session.doc.pixels.layers.insert((pasted, channel), fit(image, size, &empty_texel(channel))); } } - // The target belongs to the active set's selection: a paste into another set leaves it. - if let Some((lts, _, _)) = s.doc.project.locate(layer) { - s.selected.insert(lts, layer); - if lts == s.ts() { - s.target = StackTarget::Effect(new); + + // The target belongs to the active set's selection: a paste into another set leaves it + if let Some((layer_set, _, _)) = session.doc.project.locate(layer) { + session.selected.insert(layer_set, layer); + if layer_set == session.ts() { + session.target = StackTarget::Effect(pasted); } } - Ok(new) + Ok(pasted) })?; - Ok(json!({ "effect": new.0 })) + + Ok(json!({ "effect": pasted.0 })) } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index a728fd6c..e4d17f53 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -37,6 +37,15 @@ pub fn specs() -> Vec { always, reimport ), + cmd!( + "file.changeMesh", + "Change mesh", + [], + None, + "{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index", + always, + change_mesh + ), cmd!( "file.exportTextures", "Export textures", @@ -438,6 +447,16 @@ fn reimport(s: &mut Session, p: &Value) -> Result { Ok(reply) } +#[cfg(not(target_arch = "wasm32"))] +fn change_mesh(s: &mut Session, p: &Value) -> Result { + let path = native::path_param(p, "path", "file.changeMesh")?; + let file = native::read_mesh("file.changeMesh", path)?; + let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?; + // Only after the swap succeeded: Reimport mesh and Save keep following the new file. + s.doc.project.mesh_path = native::absolute(path); + Ok(reply) +} + #[cfg(not(target_arch = "wasm32"))] impl Session { /// The file the mesh was imported from, when it is still there: what Reimport mesh reads again. @@ -471,6 +490,19 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.sync_images(); + // The high polys and the skew map stay. The cage is sampled by triangle index and + // barycentrics, so it stays only for an identical mesh; the low poly's base colours are + // read again from the new mesh. + next.bake_meshes = self.bake_meshes.clone(); + next.bake_meshes.low_base_color = Default::default(); + if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { + next.bake_meshes.cage = None; + next.log.push("the cage mesh was dropped: the low-poly mesh changed".into()); + } + if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { + next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into()); + } next.modified = true; next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); @@ -621,6 +653,8 @@ use unsupported as save_copy; #[cfg(target_arch = "wasm32")] use unsupported as reimport; #[cfg(target_arch = "wasm32")] +use unsupported as change_mesh; +#[cfg(target_arch = "wasm32")] use unsupported as export_textures; #[cfg(target_arch = "wasm32")] use unsupported as export_mesh; @@ -764,6 +798,82 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + /// A project built on one mesh moves to another mesh file with its layers intact, even when + /// it carries its own copy of the mesh (a plain reimport would only re-read that copy). + #[test] + fn change_mesh_swaps_the_mesh_and_keeps_the_layers() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let quad = dir.join("quad.obj"); + std::fs::write(&quad, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n").unwrap(); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layers = s.doc.project.layers.len(); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap(); + assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use"); + assert_eq!(s.doc.project.mesh_file, "tri.obj"); + assert_eq!(s.doc.project.layers.len(), layers, "the layers stay"); + std::fs::remove_dir_all(&dir).ok(); + } + + /// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B, + /// not A. A failed change leaves the remembered path alone. + #[test] + fn change_mesh_remembers_the_new_file_for_reimport() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"); + let (a, b) = (dir.join("a.obj"), dir.join("b.obj")); + std::fs::write(&a, obj(1.0)).unwrap(); + std::fs::write(&b, obj(2.0)).unwrap(); + let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap(); + let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap(); + // A failed change (unreadable file) keeps A. + let missing = dir.join("missing.obj"); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err()); + assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str())); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert_eq!(width(&s), 2.0); + let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered"); + assert_ne!(a_abs, b_abs); + // The remembered path survives save and reopen. + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str())); + // Edit B, then Reimport from the remembered path: B's edits arrive, not A. + std::fs::write(&b, obj(3.0)).unwrap(); + let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap(); + crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap(); + assert_eq!(width(&reopened), 3.0); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.obj"); + std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + // Same triangle count, other vertices. + let b = dir.join("b.obj"); + std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); + let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.bake_meshes.cage = Some(cage); + let _ = s.bake_meshes.low_base_color.set(Err("old".into())); + // The same mesh again keeps the cage but not the cached colours. + crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_some()); + assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { // A GLB quad whose mesh and node have no name: its one part is named after the file. diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 7856f565..1e7c2b69 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -253,8 +253,8 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { } Filter::ColorBalance { shadows, midtones, highlights } => { for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] { - if p.get(key).is_some() { - let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; + if let Some(val) = p.get(key).filter(|v| !v.is_null()) { + let v = color_of(val).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; *slot = v.map(|x| x.clamp(-1.0, 1.0)); } } @@ -305,8 +305,7 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { } Filter::ReplaceColor { from, to, tolerance, softness } => { for (key, slot) in [("from", from), ("to", to)] { - if p.get(key).is_some() { - let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")")))?; + if let Some(v) = color_param(cmd, p, key)? { *slot = v.map(|x| x.clamp(0.0, 1.0)); } } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 233e9f4c..a1140aa1 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -69,9 +69,16 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { out } -/// A generator's settings, with its curvature mode and detail size weights when it has them. +/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them. fn generator_json(generator: &Generator) -> Value { - let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert }); + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast }); + if !generator.resolution.is_default() { + out["resolution"] = + json!({ "mode": format!("{:?}", generator.resolution.mode), "custom": generator.resolution.custom, "factor": generator.resolution.factor }); + } + if !generator.inputs.is_empty() { + out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::>().into(); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); @@ -105,7 +112,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { v["geometryMask"] = json!(parts); } if matches!(l.kind, LayerKind::Paint) { - // Sorted: the store is a hash map, and inspect output must be stable. + // Sort the hash map entries for stable inspection output let mut painted: Vec<(&str, usize)> = s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect(); painted.sort_unstable(); diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 36cd090c..5d5fc104 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -71,9 +71,9 @@ fn add_paint(s: &mut Session, p: &Value) -> Result { } /// A uniform fill from the `color`, `roughness`, `metallic`, `height` and `opacity` params. -pub(crate) fn fill_from(p: &Value) -> Fill { +pub(crate) fn fill_from(cmd: &str, p: &Value) -> Result { let mut fill = Fill::default(); - if let Some(c) = color_param(p, "color") { + if let Some(c) = color_param(cmd, p, "color")? { fill.sources.insert(Channel::BaseColor, Source::Uniform(c)); } for (key, ch) in [("roughness", Channel::Roughness), ("metallic", Channel::Metallic), ("height", Channel::Height), ("opacity", Channel::Opacity)] { @@ -81,13 +81,13 @@ pub(crate) fn fill_from(p: &Value) -> Fill { fill.sources.insert(ch, Source::Uniform([v; 3])); } } - fill + Ok(fill) } fn add_fill(s: &mut Session, p: &Value) -> Result { let ts = s.ts(); let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Fill layer")); - let fill = fill_from(p); + let fill = fill_from("layer.add.fill", p)?; let id = s.edit("Add fill layer", |s| { let id = s.doc.project.alloc_id(); insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &channels_of(s))) @@ -316,6 +316,10 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { let solo = boolp(p, "solo") == Some(true); let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; let normal_format = normal_format_param("layer.fill.set", p)?; + let low = color_param("layer.fill.set", p, "low")?.unwrap_or([0.0; 3]); + let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]); + let color = color_param("layer.fill.set", p, "color")?; + let value = color_param("layer.fill.set", p, "value")?; let source = if let Some(kind) = strp(p, "procedural") { let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; let mut pr = Procedural::new(kind); @@ -332,8 +336,8 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { pr.balance = v.clamp(-1.0, 1.0); } pr.invert = boolp(p, "invert").unwrap_or(false); - Some(Source::Procedural { pattern: pr, low: color_param(p, "low").unwrap_or([0.0; 3]), high: color_param(p, "high").unwrap_or([1.0; 3]) }) - } else if let Some(c) = color_param(p, "color").or_else(|| color_param(p, "value")) { + Some(Source::Procedural { pattern: pr, low, high }) + } else if let Some(c) = color.or(value) { Some(Source::Uniform(c)) } else if let Some(name) = strp(p, "image") { Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() }) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a8ea034a..8a5b3df0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -41,7 +41,7 @@ mod path_draft; pub mod path_tool; mod polygon_fill; mod polygon_fill_drag; -// Mesh reimport reads files: native only. +// Mesh reimport reads files on native targets only #[cfg(not(target_arch = "wasm32"))] mod preserve; pub mod preset_cmds; @@ -55,6 +55,7 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod thumbs; +mod tool_availability; pub mod tool_cmds; mod triangle_partition; mod uv_stroke_state; diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 36daf9a3..3a77ae50 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Save MaterialCraft package", [], None, - "{layer?, path} — writes the MaterialCraft package (.mcraft) behind a material layer, to open in MaterialCraft", + "{layer?, path} — writes the MaterialCraft source (.mcraft or .sbs) behind a material layer", has_layer, save_source ), @@ -178,7 +178,9 @@ fn save_source(s: &mut Session, p: &Value) -> Result { const CMD: &str = "material.link.saveSource"; let id = layer_param(s, CMD, p)?; let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; - let path = if path.to_ascii_lowercase().ends_with(&format!(".{MCRAFT_EXT}")) { path.to_string() } else { format!("{path}.{MCRAFT_EXT}") }; + let link = link_of(s, CMD, id)?; + let ext = source_extension(&link.package); + let path = if path.to_ascii_lowercase().ends_with(&format!(".{ext}")) { path.to_string() } else { format!("{path}.{ext}") }; let bytes = s.link_package(id)?; texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad(CMD, e.to_string()))?; Ok(json!({"path": path})) @@ -195,6 +197,10 @@ fn save_source(_: &mut Session, _: &Value) -> Result { pub struct LinkJob { pub layer: LayerId, pub package: Arc>, + /// The source package extension (`mcraft` or `sbs`). + pub source_ext: &'static str, + /// The named graph in a linked material; direct package imports use its default. + pub graph: Option, /// Pixels across (the texture set's resolution). pub size: u32, /// Every parameter's value, by id, in MaterialCraft's typed form. @@ -226,7 +232,7 @@ fn quiet(program: &std::path::Path) -> std::process::Command { c } -/// Open `package` (a `.mcraft` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this +/// Open `package` (a `.mcraft` or `.sbs` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this /// program, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { @@ -236,11 +242,21 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Source file extensions are chosen from the linked resource name, never an untrusted path. +pub fn source_extension(name: &str) -> &'static str { + if name.to_ascii_lowercase().ends_with(".sbs") { "sbs" } else { MCRAFT_EXT } +} + impl LinkJob { /// Cook through `materialcraft-cli` (`$MATERIALCRAFT_CLI`, next to this program, or on /// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K). #[cfg(not(target_arch = "wasm32"))] pub fn run(&self) -> Result> { + self.run_with_cli(&materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI")) + } + + #[cfg(not(target_arch = "wasm32"))] + fn run_with_cli(&self, cli: &std::path::Path) -> Result> { let other = |e: String| EngineError::Other(e); let n = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("texturecraft-link-{}-{n}", std::process::id())); @@ -252,15 +268,27 @@ impl LinkJob { std::fs::write(&p, bytes).map_err(|e| other(format!("{name}: {e}")))?; utf8(&p) }; - let src = write("source.mcraft", &self.package)?; + let ext = if self.source_ext == "sbs" { "sbs" } else { MCRAFT_EXT }; + let src = write(&format!("source.{ext}"), &self.package)?; let mut inputs = Map::new(); for (i, (id, png)) in self.inputs.iter().enumerate() { inputs.insert(id.clone(), json!(write(&format!("input{i}.png"), png)?)); } let out = dir.join(format!("out.{MCMAT_EXT}")); let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs}); - let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"); - let run = quiet(&cli).arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()).output().map_err(|e| { + let mut command = quiet(cli); + if let Some(graph) = &self.graph { + // Opening the source starts on its first graph; select the graph saved in the link. + let script = json!({"open": src, "steps": [ + {"id": "graph.open", "params": {"graph": graph}}, + {"id": "file.exportMaterial", "params": params}, + ]}); + let script_path = write("cook.json", script.to_string().as_bytes())?; + command.arg("batch").arg(script_path); + } else { + command.arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()); + } + let run = command.output().map_err(|e| { other(format!( "MaterialCraft's command line ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT_CLI", cli.display() @@ -301,7 +329,15 @@ impl Session { let bytes = if is_mcraft(bytes) { let ts = self.ts(); let size = self.doc.project.texture_set(ts)?.resolution; - let job = LinkJob { layer: LayerId(0), package: Arc::new(bytes.to_vec()), size, values: Map::new(), inputs: Vec::new() }; + let job = LinkJob { + layer: LayerId(0), + package: Arc::new(bytes.to_vec()), + source_ext: MCRAFT_EXT, + graph: None, + size, + values: Map::new(), + inputs: Vec::new(), + }; cooked = job.run()?; cooked.as_slice() } else { @@ -316,7 +352,7 @@ impl Session { let (id, names) = self.edit(&label, |s| { let ts = s.ts(); let stem = texturecraft_formats::sanitize_resource_name(&m.manifest.name); - let package = unique(s, &format!("{stem}.{MCRAFT_EXT}")); + let package = unique(s, &format!("{stem}.{}", source_extension(&m.manifest.source))); s.doc.resources.insert(package.clone(), Arc::new(m.source.clone())); let link = MaterialLink { name: m.manifest.name.clone(), @@ -345,7 +381,7 @@ impl Session { Ok(id) } - /// The `.mcraft` package behind linked layer `id`. + /// The source package behind linked layer `id`. pub fn link_package(&self, id: LayerId) -> Result>> { let link = link_of(self, "material.link", id)?; self.doc.resources.get(&link.package).cloned().ok_or_else(|| EngineError::Other(format!("the package of {} is missing", link.name))) @@ -376,45 +412,60 @@ impl Session { // UDIM tiles share one cook at the texture set's base resolution let size = self.doc.project.texture_set(texture_set)?.resolution; - Ok(LinkJob { layer: id, package: self.link_package(id)?, size, values, inputs }) + Ok(LinkJob { + layer: id, + package: self.link_package(id)?, + source_ext: source_extension(&link.package), + graph: Some(link.graph.clone()), + size, + values, + inputs, + }) } /// Swap in maps a [`LinkJob`] cooked (`.mcmat` bytes) and the values they were cooked with. /// With `merge`, this folds into the previous undo step when that was an edit of the same kind /// (a parameter set while the cook ran). pub fn apply_link_cook(&mut self, id: LayerId, bytes: &[u8], merge: bool) -> Result<()> { - let m = read_mcmat(bytes).map_err(|e| EngineError::Other(e.to_string()))?; - let maps = decoded_maps(&m)?; - let names = self.edit_merging(EDIT, merge, |s| { - let LayerKind::Fill(mut fill) = s.doc.project.layer(id)?.kind.clone() else { + let material = read_mcmat(bytes).map_err(|error| EngineError::Other(error.to_string()))?; + let maps = decoded_maps(&material)?; + + let names = self.edit_merging(EDIT, merge, |session| { + let LayerKind::Fill(mut fill) = session.doc.project.layer(id)?.kind.clone() else { return Err(EngineError::Other(format!("layer {} is not a fill", id.0))); }; + let link = fill.link.as_mut().ok_or_else(|| EngineError::Other(format!("layer {} is not a MaterialCraft material", id.0)))?; - for p in &mut link.params { - if let Some(cooked) = m.manifest.parameters.iter().find(|c| c.id == p.id) { - p.value = cooked.value.clone(); + for parameter in &mut link.params { + if let Some(cooked) = material.manifest.parameters.iter().find(|candidate| candidate.id == parameter.id) { + parameter.value = cooked.value.clone(); } } - link.size = m.manifest.size[0]; + link.size = material.manifest.size[0]; let stem = texturecraft_formats::sanitize_resource_name(&link.name); - let old: Vec = - fill.sources.values().filter_map(|src| if let Source::Image { name, .. } = src { Some(name.clone()) } else { None }).collect(); - let names = put_maps(s, &stem, &maps, &mut fill); - s.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill); - // Old maps go unless another layer (a duplicate) still shows them. - let mut used = Vec::new(); - for set in 0..s.doc.project.texture_sets.len() { - for root in s.doc.project.texture_sets.get(set).map(|t| t.stack.clone()).unwrap_or_default() { - crate::material_lib::images_used(&s.doc.project, root, &mut used, 0); + let old_names: Vec = + fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect(); + let names = put_maps(session, &stem, &maps, &mut fill); + session.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill); + + // Duplicated layers may still use the earlier maps + let mut used_names = Vec::new(); + for set in 0..session.doc.project.texture_sets.len() { + for root in session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.clone()).unwrap_or_default() { + crate::material_lib::images_used(&session.doc.project, root, &mut used_names, 0); } } - for name in old.iter().filter(|n| !used.contains(n)) { - s.doc.resources.remove(name); + for name in old_names.iter().filter(|name| !used_names.contains(name)) { + session.doc.resources.remove(name); } + Ok(names) })?; - self.sync_images(); + + // Reuse the validated maps before synchronization considers decoding missing images self.cache_decoded(names, maps); + self.sync_images(); + Ok(()) } @@ -449,3 +500,54 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec, texturecraft } names } + +#[cfg(all(test, unix))] +mod subprocess_tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn cook_uses_the_saved_graph_and_source_type_without_global_environment() { + let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("texturecraft-cook-test-{}-{id}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cli = dir.join("materialcraft-cli"); + let script = r#"#!/bin/sh +set -eu +case "$1" in + batch) + grep -F '"graph":"Second"' "$2" >/dev/null + grep -F '"id":"file.exportMaterial"' "$2" >/dev/null + test -f "$(dirname "$2")/source.sbs" + test -f "$(dirname "$2")/input0.png" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + run) + test "$(basename "$2")" = "source.mcraft" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + *) exit 1 ;; +esac +"#; + std::fs::write(&cli, script).unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::write(dir.join("result.mcmat"), b"cooked").unwrap(); + let mut job = LinkJob { + layer: LayerId(1), + package: Arc::new(b"source".to_vec()), + source_ext: "sbs", + graph: Some("Second".into()), + size: 64, + values: Map::new(), + inputs: vec![("curvature".into(), b"png".to_vec())], + }; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = None; + job.source_ext = "mcraft"; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = Some("wrong".into()); + assert!(job.run_with_cli(&cli).is_err()); + assert!(job.run_with_cli(&dir.join("missing")).is_err()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 4c286955..c0887849 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, - Procedural, ProceduralKind, Project, Source, + BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, + MaskBackground, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -141,7 +141,7 @@ fn add_mask(s: &mut Session, p: &Value, bg: MaskBackground) -> Result { } fn add_color_mask(s: &mut Session, p: &Value) -> Result { - let color = color_param(p, "color").unwrap_or([1.0, 0.0, 0.0]); + let color = color_param("mask.add.colorSelection", p, "color")?.unwrap_or([1.0, 0.0, 0.0]); let tolerance = f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0); with_mask(s, p, "mask.add.colorSelection", "Add mask with color selection", |s, id| { let eid = s.doc.project.alloc_id(); @@ -242,7 +242,7 @@ fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) - let label = format!("Add {}", kind.name().to_ascii_lowercase()); let eid = with_mask(s, p, "effect.add", &label, |s, id| { let eid = s.doc.project.alloc_id(); - // An instance's content and (unless it has its own) mask belong to its source. + // An instance's content and inherited mask belong to its source let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) }; let l = s.doc.project.layer_mut(id)?; let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; @@ -285,7 +285,7 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { let blend = blend_param("effect.add.fill", p, "blend")?.unwrap_or(BlendMode::Normal); let id = layer_param(s, "effect.add.fill", p)?; if content_target(p, "effect.add.fill")? { - let mut fill = crate::layer_cmds::fill_from(p); + let mut fill = crate::layer_cmds::fill_from("effect.add.fill", p)?; if fill.sources.is_empty() { fill.sources = s.doc.project.layer(id)?.channels.keys().map(|c| (*c, Source::uniform_of(*c))).collect(); } @@ -323,13 +323,13 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R generator.softness = softness.clamp(0.0, 1.0); } if let Some(noise) = f32p(params, "noise") { - generator.noise_amount = noise.clamp(0.0, 2.0); + generator.noise_amount = noise.clamp(0.0, Generator::MAX_NOISE_AMOUNT); } if let Some(offset) = f32p(params, "offset") { generator.offset = offset.clamp(-1.0, 1.0); } if let Some(noise_scale) = f32p(params, "noiseScale") { - generator.noise_scale = noise_scale.clamp(0.01, 1000.0); + generator.noise_scale = noise_scale.clamp(Generator::MIN_NOISE_SCALE, Generator::MAX_NOISE_SCALE); } if let Some(seed) = u64p(params, "seed") { generator.seed = seed as u32; @@ -337,9 +337,29 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if let Some(invert) = boolp(params, "invert") { generator.invert = invert; } - if let Some(direction) = color_param(params, "direction") { + if let Some(direction) = color_param(command, params, "direction")? { generator.direction = direction; } + if let Some(blur) = f32p(params, "blur") { + generator.global.blur = blur.clamp(0.0, 1.0); + } + if let Some(balance) = f32p(params, "balance") { + generator.global.balance = balance.clamp(0.0, 1.0); + } + if let Some(contrast) = f32p(params, "contrast") { + generator.global.contrast = contrast.clamp(0.0, 1.0); + } + if let Some(value) = params.get("resolution") { + let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; + generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; + } + if let Some(custom) = u64p(params, "customResolution") { + generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; + } + if let Some(factor) = params.get("resolutionFactor") { + let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; + generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; + } // A mode or sizes also give a curvature generator saved before detail sizes its detail let mode = params @@ -378,6 +398,35 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S Ok(weights) } +/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. +fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { + const CMD: &str = "effect.set"; + let Some(name) = params.get("input") else { return Ok(None) }; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?; + let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?; + + let image = strp(params, "inputImage"); + let value = f32p(params, "inputValue"); + let anchor = u64p(params, "inputAnchor"); + let baked = boolp(params, "inputBaked") == Some(true); + let source = match (image, value, anchor, baked) { + (Some(image), None, None, false) => { + if !session.images.contains_key(image) { + return Err(bad(CMD, format!("no image resource `{image}`"))); + } + Some(Source::Image { name: image.to_string(), normal_format: Default::default() }) + } + (None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])), + (None, None, Some(anchor), false) => { + let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height); + Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?) + } + (None, None, None, true) => None, + _ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")), + }; + Ok(Some((map, source))) +} + fn add_generator(session: &mut Session, params: &Value) -> Result { let kind = match strp(params, "generator") { Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, @@ -458,6 +507,13 @@ fn set(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.set"; let effect = effect_id(session, params, CMD)?; let blend = blend_param(CMD, params, "blend")?; + let generator_kind = params + .get("generator") + .map(|value| { + let name = value.as_str().ok_or_else(|| bad(CMD, "`generator` must be a string"))?; + GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`"))) + }) + .transpose()?; // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one let anchor = match session.doc.project.effect(effect) { @@ -475,6 +531,12 @@ fn set(session: &mut Session, params: &Value) -> Result { _ => None, }; + // `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back + let input = match session.doc.project.effect(effect) { + Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => generator_input_param(session, owner, params)?, + _ => None, + }; + // Naming the filter the effect already is edits its parameters like a plain effect.set let swapped = match strp(params, "filter") { Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None, @@ -508,7 +570,26 @@ fn set(session: &mut Session, params: &Value) -> Result { } match &mut edited.kind { - EffectKind::Generator(generator) => generator_from(CMD, params, generator)?, + EffectKind::Generator(generator) => { + if let Some(kind) = generator_kind + && kind != generator.kind + { + generator.kind = kind; + generator.detail = Generator::new(kind).detail; + generator.inputs.retain(|map, _| kind.inputs().contains(map)); + } + generator_from(CMD, params, generator)?; + if let Some((map, source)) = input { + if !generator.kind.inputs().contains(&map) { + return Err(bad(CMD, format!("this generator has no `{}` input", map.id()))); + } + match source { + Some(source) => generator.inputs.insert(map, source), + None => generator.inputs.remove(&map), + }; + } + } + _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), EffectKind::Levels(levels) => levels_from(params, levels), // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index bdd2fbdd..8c5c819f 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use texturecraft_compose::PixelStore; -use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet}; use crate::commands::{CommandSpec, always, has_layer}; use crate::materials::Place; @@ -36,27 +36,26 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and fill effects). -pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec, depth: usize) { +/// Image resources a layer subtree uses (fill sources and mask or content effects). +pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; } - let Some(l) = p.layers.get(&id) else { return }; - if let LayerKind::Fill(f) = &l.kind { - for s in f.sources.values() { - if let Source::Image { name, .. } = s { + let Some(layer) = project.layers.get(&id) else { return }; + + if let LayerKind::Fill(fill) = &layer.kind { + for source in fill.sources.values() { + if let Source::Image { name, .. } = source { out.push(name.clone()); } } - out.extend(f.link.as_ref().map(|link| link.package.clone())); + out.extend(fill.link.as_ref().map(|link| link.package.clone())); } - for e in l.mask.iter().flat_map(|m| m.effects.iter()) { - if let EffectKind::Fill { source: Source::Image { name, .. }, .. } = &e.kind { - out.push(name.clone()); - } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { + out.extend(effect.kind.images_read().map(str::to_string)); } - for c in l.children() { - images_used(p, *c, out, depth + 1); + for child in layer.children() { + images_used(project, *child, out, depth + 1); } } diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6344311f..5d5bfbf4 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -1,5 +1,5 @@ //! Interactive painting on the session: strokes (begin / continue / end / cancel), polygon fill -//! and the color picker. The UI, CLI and agents all go through these. +//! and the material picker. The UI, CLI and agents all go through these. use std::collections::{BTreeMap, BTreeSet}; @@ -343,9 +343,7 @@ impl Session { let Some(cache) = self.caches.get_mut(active.ts) else { return }; let settings = &active.stroke.settings; - let pressure = pressure.clamp(0.0, 1.0); - let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 }; - let radius = settings.size * 2.0 * size_scale; + let radius = settings.uv_stamp_radius(pressure); let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP); // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down) @@ -555,20 +553,22 @@ impl Session { Ok(()) } - /// Color picker: copy the material under the cursor into the tool's paint values. + /// Material picker: copy the material under the cursor into the tool's paint values pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result> { let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); - let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; - let (w, h) = (cache.size.0 as f32, cache.size.1 as f32); - let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32); - let mut out = BTreeMap::new(); - for c in cache.composite.channels.keys() { - let v = cache.composite.value(*c, x, y); - self.tool.values.insert(*c, v); - out.insert(*c, v); + let texture_set = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); + let cache = self.caches.get(texture_set).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + + let (width, height) = (cache.size.0 as f32, cache.size.1 as f32); + let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32); + + let mut picked = BTreeMap::new(); + for channel in cache.composite.channels.keys() { + let value = cache.composite.value(*channel, x, y); + self.tool.values.insert(*channel, value); + picked.insert(*channel, value); } - Ok(out) + Ok(picked) } /// The stroke canvas alpha of the active stroke (for overlays and tests). diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 1607636c..745e3197 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use texturecraft_compose::{PaintTarget, PixelStore}; -use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; +use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape}; use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments}; @@ -368,6 +368,10 @@ impl Session { /// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool pub fn commit_path(&mut self, viewport: Vec2) -> Result { + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + if let Some((effect, index)) = self.tool.path.editing && self.paths(effect).and_then(|paths| paths.get(index)).is_some_and(|stored| self.same_as_stored(stored)) { @@ -396,20 +400,20 @@ impl Session { let shape = self.path_shape(self.camera, viewport); let editing = self.tool.path.editing; let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1)); - let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| { - let (eid, index) = match editing { + let report = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |session| { + let (effect_id, index) = match editing { Some(at) => at, - None => (s.path_effect()?, usize::MAX), + None => (session.path_effect()?, usize::MAX), }; - s.put_path(eid, index, shape) + session.put_path(effect_id, index, shape) })?; - if let Some(eid) = out.get("effect").and_then(Value::as_u64) { - self.target = StackTarget::Effect(LayerId(eid)); + if let Some(effect_id) = report.get("effect").and_then(Value::as_u64) { + self.target = StackTarget::Effect(LayerId(effect_id)); } self.tool.path.clear(); - Ok(out) + Ok(report) } /// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame @@ -429,9 +433,13 @@ impl Session { /// Preview a command's points in its supplied viewport, or the UI's current viewport fn path_live_in_view(&mut self, viewport: Vec2) -> Result { + if self.quick_mask.editing { + return Ok(false); + } + let stored = match self.tool.path.editing { - Some((eid, index)) => match self.paths(eid).and_then(|v| v.get(index)).cloned() { - Some(shape) => Some((eid, index, shape)), + Some((effect_id, index)) => match self.paths(effect_id).and_then(|paths| paths.get(index)).cloned() { + Some(shape) => Some((effect_id, index, shape)), None => { self.stop_path_edit(); return Ok(false); @@ -661,6 +669,11 @@ impl Session { let from = if back { &self.path_steps.0 } else { &self.path_steps.1 }; let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) }; + // Returning false here would let undo/redo consume document history instead. + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + let path = &mut self.tool.path; let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() }); if let Err(error) = self.path_live() { @@ -706,33 +719,40 @@ impl Session { self.path_steps = Default::default(); } - /// The selected path sublayer, or a new one on the selected layer's content or mask - /// (whichever is selected). + /// The selected path sublayer, or a new one on the selected paint layer's content or mask fn path_effect(&mut self) -> Result { - let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?; - let p = &self.doc.project; + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + + let selected = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?; + let project = &self.doc.project; let mask = match self.target { - StackTarget::Effect(e) => match p.effect(e) { - Some((_, x)) if matches!(x.kind, EffectKind::Path(_)) => return Ok(e), - Some((owner, _)) => !p.layer(owner)?.content_effects.iter().any(|x| x.id == e), + StackTarget::Effect(effect) => match project.effect(effect) { + // Paths saved in a fill layer before paths there were removed stay editable + Some((_, found)) if matches!(found.kind, EffectKind::Path(_)) => return Ok(effect), + Some((owner, _)) => !project.layer(owner)?.content_effects.iter().any(|candidate| candidate.id == effect), None => false, }, StackTarget::Mask => true, StackTarget::Content => false, }; - // An instance's content and (unless it has its own) mask belong to its source. - let owner = if mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) }; - let eid = self.doc.project.alloc_id(); - let l = self.doc.project.layer_mut(owner)?; - let e = Effect::new(eid, EffectKind::Path(Vec::new())); + + // An instance's content and (unless it has its own) mask belong to its source + let owner = if mask { project.mask_owner(selected) } else { project.content_layer(selected).map_or(selected, |layer| layer.id) }; + let path_id = self.doc.project.alloc_id(); + let layer = self.doc.project.layer_mut(owner)?; + let path = Effect::new(path_id, EffectKind::Path(Vec::new())); if mask { - l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(e); - } else if l.is_group() { - return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", l.name))); + layer.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(path); + } else if layer.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", layer.name))); + } else if matches!(layer.kind, LayerKind::Paint) { + layer.content_effects.push(path); } else { - l.content_effects.push(e); + return Err(EngineError::Other(format!("\"{}\" is not a paint layer: add the path to a paint layer or a mask", layer.name))); } - Ok(eid) + Ok(path_id) } /// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before @@ -1071,6 +1091,29 @@ mod tests { assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new()); } + #[test] + fn quick_mask_preserves_pending_path_undo_and_redo() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + session.path_checkpoint(); + session.tool.path.points[0].y = 0.3; + session.path_live().unwrap(); + for back in [true, false] { + let curve = session.tool.path.clone(); + let steps = (session.path_steps.0.len(), session.path_steps.1.len()); + let history = (session.history_labels(), session.redo_labels()); + let pixels = session.doc.pixels.clone(); + session.quick_mask.editing = true; + assert!(if back { session.undo() } else { session.redo() }.is_err()); + assert!(curve.same_curve(&session.tool.path)); + assert_eq!(steps, (session.path_steps.0.len(), session.path_steps.1.len())); + assert_eq!(history, (session.history_labels(), session.redo_labels())); + assert_eq!(format!("{:?}", pixels), format!("{:?}", session.doc.pixels)); + session.quick_mask.editing = false; + if back { session.undo() } else { session.redo() }.unwrap(); + } + } + #[test] fn point_checkpoints_skip_noops_and_bound_retained_points() { let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap(); diff --git a/crates/engine/src/preserve.rs b/crates/engine/src/preserve.rs index 38544edc..d68f20bc 100644 --- a/crates/engine/src/preserve.rs +++ b/crates/engine/src/preserve.rs @@ -16,8 +16,14 @@ use crate::Session; const REACH: f32 = 0.05; /// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s -/// document) from `old`'s UV layout. Returns how many texels found the old surface. +/// document) from `old`'s UV layout. Returns how many texels found the old surface; +/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the +/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already +/// sit where they belong, however far the mesh moved. pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { + if same_layout(&old.mesh, &next.mesh) { + return 0; + } let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius()); let mut found = 0; for ts in 0..next.set_count() { @@ -52,7 +58,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { ((tx, ty), src) }) .collect(); - found += table.values().flatten().filter(|p| p[0].is_finite()).count(); + let matched = table.values().flatten().filter(|p| p[0].is_finite()).count(); + found += matched; + // No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is. + if matched == 0 { + continue; + } let map = |x: f32, y: f32| { let (xi, yi) = (x as u32, y as u32); table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1])) @@ -63,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { found } +/// Same index buffer, same UVs per vertex and the same material ranges. +fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool { + let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::>(); + a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b) +} + #[cfg(test)] mod tests { use super::*; @@ -104,4 +121,50 @@ mod tests { } assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong"); } + + #[test] + fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..64 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout + // shortcut is not taken): nothing of the old surface is within reach. + let mut mesh = (*s.mesh).clone(); + for p in &mut mesh.positions { + p.x += 100.0; + } + for uv in &mut mesh.uvs { + *uv = Vec2::new(1.0 - uv.x, uv.y); + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there"); + } + + #[test] + fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..128 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // Slid along its own surface by a fraction of the plane: half of it still overlaps the old one. + let mut mesh = (*s.mesh).clone(); + let shift = mesh.radius() * 0.5; + for p in &mut mesh.positions { + p.x += shift; + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + for x in 0..128 { + assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved"); + assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint"); + } + } } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 93087c14..cfb0175c 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -35,44 +35,53 @@ pub fn specs() -> Vec { "Edit quick mask", ["Viewport"], Some("U"), - "{editing?: bool} — toggles when omitted; editing enables the mask", - always, + "{editing?: bool} — toggles when omitted; needs the quick mask enabled", + mask_enabled, edit ), - cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", always, invert), + cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", mask_enabled, invert), ] } -fn state(s: &Session) -> Value { - let q = &s.quick_mask; +fn mask_enabled(session: &Session) -> std::result::Result<(), String> { + if session.quick_mask.enabled { Ok(()) } else { Err("enable the quick mask first".into()) } +} + +fn state(session: &Session) -> Value { + let mask = &session.quick_mask; json!({ - "enabled": q.enabled, "editing": q.editing, "inverted": q.inverted, - "paintedTiles": q.masks.get(&s.ts()).map(TileImage::allocated_count).unwrap_or(0), + "enabled": mask.enabled, "editing": mask.editing, "inverted": mask.inverted, + "paintedTiles": mask.masks.get(&session.ts()).map(TileImage::allocated_count).unwrap_or(0), }) } -fn changed(s: &mut Session) -> Result { - s.quick_mask.revision = s.quick_mask.revision.wrapping_add(1); - s.revision = s.revision.wrapping_add(1); - Ok(state(s)) +fn changed(session: &mut Session) -> Result { + session.quick_mask.revision = session.quick_mask.revision.wrapping_add(1); + session.revision = session.revision.wrapping_add(1); + Ok(state(session)) } -fn enable(s: &mut Session, p: &Value) -> Result { - s.quick_mask.enabled = boolp(p, "enabled").unwrap_or(!s.quick_mask.enabled); - changed(s) +fn enable(session: &mut Session, params: &Value) -> Result { + let enabled = boolp(params, "enabled").unwrap_or(!session.quick_mask.enabled); + if !enabled && session.quick_mask.editing { + session.cancel_stroke(); + session.quick_mask.editing = false; + } + + session.quick_mask.enabled = enabled; + changed(session) } -fn edit(s: &mut Session, p: &Value) -> Result { - s.cancel_stroke(); - let q = &mut s.quick_mask; - q.editing = boolp(p, "editing").unwrap_or(!q.editing); - q.enabled |= q.editing; - changed(s) +fn edit(session: &mut Session, params: &Value) -> Result { + session.cancel_stroke(); + let quick_mask = &mut session.quick_mask; + quick_mask.editing = boolp(params, "editing").unwrap_or(!quick_mask.editing); + changed(session) } -fn invert(s: &mut Session, _: &Value) -> Result { - s.quick_mask.inverted = !s.quick_mask.inverted; - changed(s) +fn invert(session: &mut Session, _: &Value) -> Result { + session.quick_mask.inverted = !session.quick_mask.inverted; + changed(session) } impl Session { diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 86e7c9b8..2c973280 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Add fill layer from image", [], None, - "{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}", + "{name (exact resource name with extension or unique stem), channel?: baseColor, projection?: uv|triplanar|planar, scale?}", always, add_image_fill ), @@ -38,7 +38,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX)) + self.edit("Import resource", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) } /// Add an image within a decoded texel budget, inside the caller's edit @@ -47,39 +47,38 @@ impl Session { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } - let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; - let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); + let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; + let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); let mut name = base.clone(); - let mut n = 2; + let mut duplicate_index = 2; while self.doc.resources.contains_key(&name) { - name = format!("{n}_{base}"); - n += 1; + name = format!("{duplicate_index}_{base}"); + duplicate_index += 1; } self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); + Ok(name) } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). pub fn sync_images(&mut self) { - let keep: Vec = self.doc.resources.keys().cloned().collect(); - self.images.retain(|k, _| keep.contains(k)); - // Linked materials' packages are resources too, not images. - let missing: Vec<(String, Arc>)> = self - .doc - .resources - .iter() - .filter(|(k, _)| !self.images.contains_key(*k) && !k.ends_with(&format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT))) - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); - for (k, bytes) in missing { - match texturecraft_formats::decode_image(&bytes) { - Ok(d) => { - self.images.insert(k, decoded(d)); + self.images.retain(|name, _| self.doc.resources.contains_key(name)); + + // Linked material packages are resources but cannot be decoded as images + let package_suffix = format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT); + for (name, bytes) in &self.doc.resources { + if self.images.contains_key(name) || name.ends_with(&package_suffix) { + continue; + } + + match texturecraft_formats::decode_image(bytes) { + Ok(image) => { + self.images.insert(name.clone(), decoded(image)); } - Err(e) => self.log.push(format!("resource {k}: {e}")), + Err(error) => self.log.push(format!("resource {name}: {error}")), } } } @@ -179,11 +178,35 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { Ok(json!({ "removed": unused })) } -fn add_image_fill(s: &mut Session, p: &Value) -> Result { - let name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?.to_string(); - if !s.doc.resources.contains_key(&name) { - return Err(bad("layer.add.image", format!("no resource `{name}`"))); +#[cfg(not(target_arch = "wasm32"))] +const IMPORT_HINT: &str = "resource.import"; +#[cfg(target_arch = "wasm32")] +const IMPORT_HINT: &str = "File > Import resources"; + +/// Resolve an image resource by exact name or unique file stem. +fn resolve_resource_name(s: &Session, name: &str) -> Result { + if s.images.contains_key(name) { + return Ok(name.to_string()); } + let matches: Vec<&String> = s.images.keys().filter(|k| std::path::Path::new(k).file_stem().and_then(|stem| stem.to_str()) == Some(name)).collect(); + match matches.as_slice() { + [single] => Ok((*single).clone()), + [] => { + let available: Vec<&str> = s.images.keys().map(String::as_str).collect(); + let hint = + if available.is_empty() { format!(" (no resources imported: use {IMPORT_HINT})") } else { format!(" (available: {})", available.join(", ")) }; + Err(bad("layer.add.image", format!("no resource `{name}`{hint}"))) + } + multiple => { + let matches_str = multiple.iter().map(|m| format!("`{m}`")).collect::>().join(", "); + Err(bad("layer.add.image", format!("ambiguous resource `{name}` matches {matches_str}: give the full name with extension"))) + } + } +} + +fn add_image_fill(s: &mut Session, p: &Value) -> Result { + let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?; + let name = resolve_resource_name(s, raw_name)?; let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor); let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?; let ts = s.ts(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 41bfacbb..02c6279f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -109,7 +109,7 @@ impl Tool { Tool::PolygonFill => "Polygon fill", Tool::Smudge => "Smudge", Tool::Clone => "Clone", - Tool::ColorPicker => "Color picker", + Tool::ColorPicker => "Material picker", Tool::Path => "Path", Tool::GeometryMask => "Geometry mask", } @@ -571,23 +571,56 @@ impl Session { self.invalidate_changed(other); } - /// Mark dirty every texture set whose composite differs between `other` and the current + /// Mark dirty every texture set whose composite differs between the previous and current /// document (after an edit, undo or redo). - pub(crate) fn invalidate_changed(&mut self, other: &Document) { - self.follow_uv_layouts(&other.project); + pub(crate) fn invalidate_changed(&mut self, previous_document: &Document) { + self.follow_uv_layouts(&previous_document.project); self.sync_caches(); - let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); - let all = resources(other) != resources(&self.doc); - let (empty, images) = (BakedMaps::default(), Default::default()); - let key = |d: &Document, ts: usize| { - let stack = d.project.texture_sets.get(ts).map(|s| s.stack.as_slice()).unwrap_or_default(); - StackKey::new(&d.project, &d.pixels, d.baked.get(&ts).unwrap_or(&empty), &images, ts, stack) + + // Removed or replaced resources may change any set's rendered content + let removed_or_replaced_resource = + previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); + let added_resource_names: BTreeSet<_> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).collect(); + let uses_added_resource = |texture_set_index: usize| { + use texturecraft_core::{EffectKind, Fill, Source}; + + let uses_source = |source: &Source| matches!(source, Source::Image { name, .. } if added_resource_names.contains(name)); + let uses_fill = + |fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package)); + let project = &self.doc.project; + !added_resource_names.is_empty() + && project.texture_sets.get(texture_set_index).is_some_and(|set| { + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) + || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind { + EffectKind::Fill { source, .. } => uses_source(source), + EffectKind::Material(fill) => uses_fill(fill), + EffectKind::Generator(generator) => generator.inputs.values().any(uses_source), + _ => false, + }) + }) + }) }; - for ts in 0..self.caches.len() { - if (all || key(other, ts) != key(&self.doc, ts)) - && let Some(c) = self.caches.get_mut(ts) + + let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default()); + let stack_key = |document: &Document, texture_set_index: usize| { + let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default(); + StackKey::new( + &document.project, + &document.pixels, + document.baked.get(&texture_set_index).unwrap_or(&empty_baked_maps), + &empty_images, + texture_set_index, + stack, + ) + }; + for texture_set_index in 0..self.caches.len() { + if (removed_or_replaced_resource + || stack_key(previous_document, texture_set_index) != stack_key(&self.doc, texture_set_index) + || uses_added_resource(texture_set_index)) + && let Some(cache) = self.caches.get_mut(texture_set_index) { - c.invalidate_all(); + cache.invalidate_all(); } } } @@ -732,7 +765,8 @@ impl Session { self.modified = true; self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); - // An undone add or duplicate takes the selected effect away: select the stack it was in. + + // An undone add or duplicate takes the selected effect away if let StackTarget::Effect(e) = self.target && self.doc.project.effect(e).is_none() { @@ -740,6 +774,10 @@ impl Session { let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); self.target = if content { StackTarget::Content } else { StackTarget::Mask }; } + let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some()); + if self.target == StackTarget::Mask && !has_mask { + self.target = StackTarget::Content; + } } // ----------------------------------------------------------------------------------------- @@ -759,22 +797,24 @@ impl Session { /// of a finite budget, after the dirty ones. pub fn update_for(&mut self, budget_ms: f64, clock: impl Fn() -> f64) -> bool { let start = clock(); - let first = if budget_ms.is_finite() { rayon::current_num_threads().clamp(1, CHUNK) } else { CHUNK }; - // The layer being edited: everything else is cached per tile. - let hot = self.stroke.as_ref().and_then(|s| s.target).map(|t| self.paint_owner(t)).or_else(|| self.selected_layer()); - let stroke_size = self.stroke.as_ref().and_then(|s| self.caches.get(s.ts)).map(|c| c.size); - let preview = self.stroke.as_ref().and_then(|s| { + let initial_chunk_size = if budget_ms.is_finite() { rayon::current_num_threads().clamp(1, CHUNK) } else { CHUNK }; + + // The layer being edited: everything else is cached per tile + let hot = self.stroke.as_ref().and_then(|stroke| stroke.target).map(|target| self.paint_owner(target)).or_else(|| self.selected_layer()); + let stroke_size = self.stroke.as_ref().and_then(|stroke| self.caches.get(stroke.ts)).map(|cache| cache.size); + let preview = self.stroke.as_ref().and_then(|stroke| { Some(StrokePreview { - target: s.target?, - alpha: s.canvas.alpha.clone(), - opacity: s.stroke.settings.opacity, - erase: s.erase, - values: s.values.clone(), + target: stroke.target?, + alpha: stroke.canvas.alpha.clone(), + opacity: stroke.stroke.settings.opacity, + erase: stroke.erase, + values: stroke.values.clone(), mask_value: self.tool.mask_value, - stencil: s.stencil.clone(), - carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(), + stencil: stroke.stencil.clone(), + carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(), }) }); + let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); let mut changed = false; @@ -782,24 +822,27 @@ impl Session { let Some(cache) = self.caches.get_mut(ts) else { continue }; cache.below.set_hot(hot); cache.below.pass = cache.dirty.len() + cache.settle.len(); - // Instances in sets of the stroke's size show the live stroke too. + + // Instances in sets of the stroke's size show the live stroke too let preview = preview.as_ref().filter(|_| Some(cache.size) == stroke_size); - // Start at the size that fit the budget last time: with a heavy stack (smart - // materials at 8K) one tile per thread alone would take several frames' budget. - let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { first }; + + // Reuse the last affordable chunk size for heavy stacks + let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { initial_chunk_size }; loop { if cache.dirty.is_empty() { if cache.settle.is_empty() || clock() - start >= budget_ms.min(SETTLE_BUDGET_MS) { break; } - // Small chunks: the settle slice of the budget is short. - cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(first))); + + // Small chunks: the settle slice of the budget is short + cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(initial_chunk_size))); } - let t0 = clock(); + let chunk_started = clock(); let tiles = next_chunk(&mut cache.dirty, chunk); - for t in &tiles { - cache.settle.remove(t); + for tile in &tiles { + cache.settle.remove(tile); } + let empty = BakedMaps::default(); let inputs = texturecraft_compose::Inputs { project: &self.doc.project, @@ -813,30 +856,39 @@ impl Session { images: &self.images, bounds: self.mesh.bounds(), }; + + // Look ahead so sliced updates filter a run of tiles once + cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() }; texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); - // The composited tiles and the neighbours their padding reached change. + + // The composited tiles and the neighbours their padding reached change let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); cache.revision = cache.revision.wrapping_add(1); changed = true; + let now = clock(); - let left = budget_ms - (now - start); - // As many tiles as fit in what is left, at the pace of this chunk. - let per_tile = (now - t0) / tiles.len().max(1) as f64; - if budget_ms.is_finite() && per_tile > 0.0 { - // Never above one tile per thread: work can turn heavy from one frame to the next. - cache.chunk = ((budget_ms / per_tile) as usize).clamp(1, first); + let remaining_ms = budget_ms - (now - start); + + // Estimate how many tiles fit in the remaining frame budget + let ms_per_tile = (now - chunk_started) / tiles.len().max(1) as f64; + if budget_ms.is_finite() && ms_per_tile > 0.0 { + // Never above one tile per thread: work can turn heavy from one frame to the next + cache.chunk = ((budget_ms / ms_per_tile) as usize).clamp(1, initial_chunk_size); } - if left <= 0.0 { + if remaining_ms <= 0.0 { return changed; } - let fit = if per_tile > 0.0 { (left / per_tile) as usize } else { CHUNK }; - if fit == 0 { + + let fitting_tiles = if ms_per_tile > 0.0 { (remaining_ms / ms_per_tile) as usize } else { CHUNK }; + if fitting_tiles == 0 { return changed; } - chunk = fit.min(CHUNK); + + chunk = fitting_tiles.min(CHUNK); } } + changed } @@ -959,19 +1011,42 @@ pub const SETTLE_BUDGET_MS: f64 = 6.0; /// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters /// evaluate compact regions. -fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> { - if dirty.len() <= n { +fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> { + // A zero-sized request cannot select a pivot + if max_tiles == 0 { + return Vec::new(); + } + + if dirty.len() <= max_tiles { return std::mem::take(dirty).into_iter().collect(); } + let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect(); - tiles.sort_by_key(|&(x, y)| (y / 16, x / 16, y, x)); - tiles.truncate(n); - for t in &tiles { - dirty.remove(t); + + // Partition by block order so only the requested chunk needs sorting + tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); + tiles.truncate(max_tiles); + tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); + for tile in &tiles { + dirty.remove(tile); } + tiles } +/// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited. +const FILTER_AHEAD: usize = 64; + +/// The dirty tiles composited after `chunk` in its 16 × 16 tile blocks, in the order [`next_chunk`] takes them, at most [`FILTER_AHEAD`]. +fn tiles_ahead(dirty: &BTreeSet<(u32, u32)>, chunk: &[(u32, u32)]) -> Vec<(u32, u32)> { + let block = |&(x, y): &(u32, u32)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK); + let blocks: BTreeSet<(u32, u32)> = chunk.iter().map(block).collect(); + let mut ahead: Vec<(u32, u32)> = dirty.iter().copied().filter(|tile| blocks.contains(&block(tile))).collect(); + ahead.sort_by_key(|tile| (block(tile), tile.1, tile.0)); + ahead.truncate(FILTER_AHEAD); + ahead +} + /// Valid texture set resolutions: powers of two from 128 to 8192. pub fn check_resolution(r: u32) -> Result { if (128..=8192).contains(&r) && r.is_power_of_two() { diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index 7f39bd2a..5964813f 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -100,7 +100,7 @@ fn add_text(s: &mut Session, p: &Value) -> Result { let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?; let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0); let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?; - let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); + let rgb = color_param(cmd, p, "color")?.unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?; // The resource is named after the text (its first line, shortened) unless a name is given. let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect(); diff --git a/crates/engine/src/tool_availability.rs b/crates/engine/src/tool_availability.rs new file mode 100644 index 00000000..392388e3 --- /dev/null +++ b/crates/engine/src/tool_availability.rs @@ -0,0 +1,46 @@ +//! Which tools can act on the current selection: the tool shelf and its shortcuts grey the rest + +use texturecraft_core::{EffectKind, LayerKind}; + +use crate::{Session, StackTarget, Tool}; + +impl Session { + /// Whether `tool` can act on the selection (or on the quick mask while it is being edited) + pub fn tool_usable(&self, tool: Tool) -> bool { + match tool { + // The picker reads the composite under the cursor, whatever is selected + Tool::ColorPicker => return true, + Tool::GeometryMask => return self.selected_layer().is_some(), + _ => {} + } + + // Brushes paint the quick mask whatever is selected; paths can't edit it + if self.quick_mask.editing { + return tool != Tool::Path; + } + + let project = &self.doc.project; + let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false }; + + // Smudge and Clone read layer content, so they can't yet paint mask values + let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); + match self.target { + StackTarget::Content => matches!(layer.kind, LayerKind::Paint), + StackTarget::Mask => !reads_content, + StackTarget::Effect(effect) => { + let Some((owner, found)) = project.effect(effect) else { return false }; + let Some(owner_layer) = project.layers.get(&owner) else { return false }; + let in_content = owner_layer.content_effects.iter().any(|candidate| candidate.id == effect); + let in_fill_content = in_content && matches!(owner_layer.kind, LayerKind::Fill(_)); + + match found.kind { + // Paths saved in a fill layer before paths there were removed stay editable + EffectKind::Path(_) => tool == Tool::Path, + EffectKind::Paint if tool == Tool::Path => !in_fill_content, + EffectKind::Paint => in_content || !reads_content, + _ => false, + } + } + } + } +} diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 6a390866..cecc8495 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -6,7 +6,7 @@ use texturecraft_core::Channel; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas}; -use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp, vec3}; +use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_of, color_param, f32p, strp, vec3}; use crate::fill_hit_test::FillHitTest; use crate::fill_mode::FillMode; use crate::session::{CloneFrom, CloneSource, StackTarget, Tool}; @@ -20,7 +20,7 @@ pub fn specs() -> Vec { cmd!("tool.polygonFill", "Polygon fill", ["Tools"], Some("4"), "{}", always, |s, _| set_tool(s, Tool::PolygonFill)), cmd!("tool.smudge", "Smudge", ["Tools"], Some("5"), "{}", always, |s, _| set_tool(s, Tool::Smudge)), cmd!("tool.clone", "Clone", ["Tools"], Some("6"), "{}", always, |s, _| set_tool(s, Tool::Clone)), - cmd!("tool.colorPicker", "Color picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)), + cmd!("tool.colorPicker", "Material picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)), cmd!( "tool.geometryMask", "Geometry mask", @@ -105,7 +105,7 @@ pub fn specs() -> Vec { "Tool click", [], None, - "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", + "{x, y, viewport?: [w,h]} — polygon fill / material picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", always, click ), @@ -115,6 +115,7 @@ pub fn specs() -> Vec { pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result { session.cancel_stroke(); + // A box fill under way keeps what it filled as one undo step session.end_polygon_fill_box(); session.tool.tool = tool; @@ -285,11 +286,14 @@ pub(crate) fn brush_json(session: &Session) -> Value { } fn material(s: &mut Session, p: &Value) -> Result { + let channel = channel_param("tool.material", p, "channel")?; + let color = color_param("tool.material", p, "color")?; + let value = color_param("tool.material", p, "value")?; if let Some(v) = f32p(p, "maskValue") { s.tool.mask_value = v.clamp(0.0, 1.0); } - if let Some(c) = channel_param("tool.material", p, "channel")? { - if let Some(v) = color_param(p, "color").or_else(|| color_param(p, "value")) { + if let Some(c) = channel { + if let Some(v) = color.or(value) { let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) }; s.tool.values.insert(c, v); s.tool.enabled.insert(c); @@ -339,50 +343,53 @@ fn swap_mask_value(session: &mut Session, _: &Value) -> Result { Ok(json!({ "maskValue": session.tool.mask_value })) } -fn stencil(s: &mut Session, p: &Value) -> Result { - if boolp(p, "clear") == Some(true) { - s.tool.stencil = None; +fn stencil(session: &mut Session, params: &Value) -> Result { + if boolp(params, "clear") == Some(true) { + session.tool.stencil = None; return Ok(Value::Null); } - if let Some(name) = strp(p, "image") { - if !s.doc.resources.contains_key(name) { + + if let Some(name) = strp(params, "image") { + if !session.doc.resources.contains_key(name) { return Err(bad("tool.stencil", format!("no resource `{name}` (import it first)"))); } - let keep = s.tool.stencil.take(); - let mut st = crate::session::StencilState::new(name); - if let Some(k) = keep { - st = crate::session::StencilState { image: name.to_string(), ..k }; + + let previous_stencil = session.tool.stencil.take(); + let mut stencil_state = crate::session::StencilState::new(name); + if let Some(previous_stencil) = previous_stencil { + stencil_state = crate::session::StencilState { image: name.to_string(), ..previous_stencil }; } - s.tool.stencil = Some(st); + session.tool.stencil = Some(stencil_state); } - let st = s.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?; - if let Some(c) = color_param(p, "center").map(|c| [c[0], c[1]]).or_else(|| pair(p, "center")) { - st.center = c.map(|v| v.clamp(-4.0, 4.0)); + + let stencil_state = session.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?; + if let Some(center) = pair(params, "center").or_else(|| params.get("center").and_then(color_of).map(|color| [color[0], color[1]])) { + stencil_state.center = center.map(|value| value.clamp(-4.0, 4.0)); } - if let Some(v) = f32p(p, "scale") { - st.scale = v.clamp(0.01, 10.0); + if let Some(scale) = f32p(params, "scale") { + stencil_state.scale = scale.clamp(0.01, 10.0); } - if let Some(v) = f32p(p, "rotation") { - st.rotation = v.rem_euclid(360.0); + if let Some(rotation) = f32p(params, "rotation") { + stencil_state.rotation = rotation.rem_euclid(360.0); } - if let Some(v) = boolp(p, "tile") { - st.tile = v; + if let Some(tile) = boolp(params, "tile") { + stencil_state.tile = tile; } - if let Some(v) = f32p(p, "opacity") { - st.opacity = v.clamp(0.0, 1.0); + if let Some(opacity) = f32p(params, "opacity") { + stencil_state.opacity = opacity.clamp(0.0, 1.0); } - s.revision = s.revision.wrapping_add(1); - Ok(serde_json::to_value(&s.tool.stencil).unwrap_or(Value::Null)) + + session.revision = session.revision.wrapping_add(1); + Ok(serde_json::to_value(&session.tool.stencil).unwrap_or(Value::Null)) } /// A `[a, b]` param of two finite numbers. fn pair(p: &Value, key: &str) -> Option<[f32; 2]> { let a = p.get(key)?.as_array()?; - let v: Vec = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - match v.as_slice() { - [x, y] => Some([*x, *y]), - _ => None, - } + let [x, y] = a.as_slice() else { return None }; + let x = x.as_f64()? as f32; + let y = y.as_f64()? as f32; + (x.is_finite() && y.is_finite()).then_some([x, y]) } fn clone_source(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 9fb03ecf..db03435c 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -211,6 +211,7 @@ fn display(s: &mut Session, p: &Value) -> Result { if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) { return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); } + let scatter_color = color_param("display.set", p, "scatterColor")?; let d = &mut s.doc.project.display; if let Some(e) = env { d.environment = e; @@ -236,7 +237,7 @@ fn display(s: &mut Session, p: &Value) -> Result { if let Some(t) = tm { d.tone_mapping = t; } - if let Some(c) = color_param(p, "scatterColor") { + if let Some(c) = scatter_color { d.scatter_color = c.map(|v| v.clamp(0.0, 1.0)); } if let Some(b) = boolp(p, "shadows") { diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 85b0142c..acf54274 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -464,7 +464,8 @@ fn leaning_session(lean: bool) -> Session { } let high_text = obj(&mesh, 0.1, f32::MAX, [1.0; 3]); let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); - // A folder of its own per call: tests run in parallel, and another one removes the shared folder. + + // Tests run in parallel, so each call needs its own folder static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let call = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("texturecraft-lean-test-{}-{call}", std::process::id())); @@ -472,7 +473,8 @@ fn leaning_session(lean: bool) -> Session { let high = dir.join("high.obj"); std::fs::write(&high, high_text).unwrap(); execute(&mut s, "bake.highPoly.add", &json!({ "path": high.display().to_string() })).unwrap(); - // The mesh is parsed and kept on add, so the file can go. + + // The imported mesh remains after its source file is removed let _ = std::fs::remove_dir_all(&dir); execute( &mut s, @@ -489,10 +491,12 @@ fn the_skew_map_is_saved_with_the_project() { execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap(); let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); assert_eq!(back.doc.bake_paint, s.doc.bake_paint); - // No skew: none comes back. + + // Clearing skew persists execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.bake_paint.is_empty()); - // A map with a non-finite value is skipped with a log line, and the project still opens. + + // Invalid saved skew is skipped without preventing project load let mut pf = s.project_file(); pf.bake_paint.insert((0, texturecraft_core::BakePaintTarget::Skew), texturecraft_formats::BakePaintData { width: 1, height: 1, values: vec![f32::NAN] }); let opened = Session::from_project_file(pf).unwrap(); @@ -504,27 +508,46 @@ fn the_skew_map_is_saved_with_the_project() { ); } +#[test] +fn the_skew_map_steers_only_a_distance_cage_with_averaged_normals() { + let mut s = leaning_session(false); + execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap(); + assert!(s.bake_task(0).unwrap().skew.is_some()); + + s.doc.project.texture_sets[0].bake.cage.average_normals = false; + assert!(s.bake_task(0).unwrap().skew.is_none(), "without averaged normals the skew map is left out"); + s.doc.project.texture_sets[0].bake.cage.average_normals = true; + let cage = obj(&s.mesh.clone(), 0.05, f32::MAX, [1.0; 3]); + s.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + s.doc.project.texture_sets[0].bake.cage.kind = texturecraft_core::CageType::CustomFile; + assert!(s.bake_task(0).unwrap().skew.is_none(), "a cage file sets the rays itself"); +} + #[test] fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() { let mut s = leaning_session(true); - // Painting with no map makes a black one at `size` and puts the dab in it. + + // The first stroke creates a black map at the requested size let r = execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 })).unwrap(); assert_eq!(r["skew"]["width"], 64); let map = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); assert!(map.values.iter().any(|v| *v > 0.99) && map.values.contains(&0.0)); let rev = s.revision; - // Erasing with value 0 brings it back down; the size stays. + + // Erasing retains the map size execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.2, "value": 0.0, "hardness": 1.0 })).unwrap(); let after = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); assert_eq!(after.width, 64); assert!(after.values.iter().all(|v| *v < 0.01) && s.revision > rev); - // A constant map is widened, keeping its value where nothing is painted. + + // Resizing preserves untouched constant values execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.1, 0.1]], "radius": 0.05, "size": 32 })).unwrap(); let wide = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); assert_eq!(wide.width, 32); assert!((wide.values[wide.values.len() / 2] - 0.5).abs() < 1e-5, "{}", wide.values[wide.values.len() / 2]); - // Hostile input is an error and leaves the map alone. + + // Invalid strokes leave the map unchanged let before = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(); for bad in [ json!({}), @@ -541,7 +564,8 @@ fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() { assert!(execute(&mut s, "bake.skew.paint", &bad).is_err(), "{bad}"); } assert_eq!(s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(), before); - // And the painted map is saved with the project. + + // Painted skew survives a project round trip let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); assert_eq!(back.doc.bake_paint, s.doc.bake_paint); } @@ -612,3 +636,42 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { assert_eq!(session.doc.baked, original.baked); assert_eq!(session.history_labels(), history); } + +/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay, +/// the project counts as changed, and image resources are decoded in the new session. +#[test] +fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { + let mut s = plane_session(); + let plane = s.mesh.as_ref().clone(); + let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3])); + execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap(); + execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap(); + // 1x1 PNG as an image resource. + let png = [ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, + 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00, + 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + s.import_resource_bytes("dot.png", png.to_vec()).unwrap(); + s.modified = false; + let mesh_id = s.mesh_id; + + let mut low = String::new(); + for p in &plane.positions { + low += &format!("v {} {} {}\n", p.x, p.y, p.z); + } + for uv in &plane.uvs { + low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y); + } + for t in plane.indices.as_chunks::<3>().0 { + low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1); + } + let low = temp_file("change_low.obj", &low); + execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap(); + + assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh"); + assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays"); + assert!(s.modified, "the project differs from the saved one"); + assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); +} diff --git a/crates/engine/tests/it/bake_checks.rs b/crates/engine/tests/it/bake_checks.rs new file mode 100644 index 00000000..52825e95 --- /dev/null +++ b/crates/engine/tests/it/bake_checks.rs @@ -0,0 +1,112 @@ +//! What bake mode lists before a bake: overlapping UVs and parts "By Mesh Name" leaves unpaired + +use texturecraft_engine::Session; +use texturecraft_engine::bake::NamePair; +use texturecraft_engine::core::MeshMatchMode; + +/// Two quads side by side; `shared_uvs` lays both on the same UV square instead of side by side in UV space +fn two_quads(shared_uvs: bool) -> Session { + let second_u = if shared_uvs { 0.0 } else { 0.5 }; + let obj = format!( + "o Box_low\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\ + o Lone_low\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt {second_u} 0\nvt {} 0\nvt {} 1\nvt {second_u} 1\nf 5/5 6/6 7/7 8/8\n", + second_u + 0.5, + second_u + 0.5 + ); + Session::from_mesh_bytes("quads.obj", obj.as_bytes(), 128, "quads").unwrap() +} + +const HIGH_POLY: &[u8] = b"o Box_high\nv 0 0 0.01\nv 1 0 0.01\nv 0 1 0.01\nf 1 2 3\no Extra_high\nv 2 0 0.01\nv 3 0 0.01\nv 2 1 0.01\nf 4 5 6\n"; + +#[test] +fn overlapping_uvs_are_measured_before_the_bake() { + assert!(two_quads(true).bake_uv_overlap(0).unwrap() > 0.4, "the second quad covers the first one's UVs"); + assert_eq!(two_quads(false).bake_uv_overlap(0).unwrap(), 0.0, "side by side in UV space nothing overlaps"); + const MISSING_TEXTURE_SET: usize = 9; + assert!(two_quads(false).bake_uv_overlap(MISSING_TEXTURE_SET).is_err()); +} + +#[test] +fn overlap_in_a_uv_tile_left_out_of_the_bake_is_not_counted() { + // One quad in tile 1001, two on the same UVs in tile 1002 + let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\ + o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 5/5 6/6 7/7 8/8\n\ + o Third\nv 4 0 0\nv 5 0 0\nv 5 1 0\nv 4 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 9/9 10/10 11/11 12/12\n"; + let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "the last two quads share tile 1002's UVs"); + + session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002); + assert_eq!(session.bake_uv_overlap(0).unwrap(), 0.0, "tile 1001 alone has no overlap"); +} + +#[test] +fn overlap_is_measured_at_the_same_detail_in_every_uv_tile() { + // Tiles 1001 and 1010 make a grid ten tiles wide; 512 texels across all ten would give each tile about 51 + const TEXELS_PER_TILE: f32 = 512.0; + const SLIVER_TEXELS: f32 = 4.0; + + // Inside tile 1010 (column 9), clear of the wide raster's texel centres + const SLIVER_LEFT_U: f32 = 9.1; + let (left, right) = (SLIVER_LEFT_U, SLIVER_LEFT_U + SLIVER_TEXELS / TEXELS_PER_TILE); + let sliver = |name: &str, first: u32, x: f32| { + let (second, third, fourth) = (first + 1, first + 2, first + 3); + let corners = format!("v {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\n", x + 1.0, x + 1.0); + format!( + "o {name}\n{corners}vt {left} 0\nvt {right} 0\nvt {right} 1\nvt {left} 1\nf {first}/{first} {second}/{second} {third}/{third} {fourth}/{fourth}\n" + ) + }; + let corner = "o Corner\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; + let obj = [corner.to_owned(), sliver("First", 5, 2.0), sliver("Second", 9, 4.0)].concat(); + let session = Session::from_mesh_bytes("wide.obj", obj.as_bytes(), 128, "wide").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1010]); + + assert!(session.bake_uv_overlap(0).unwrap() > 0.0, "two slivers a few texels wide overlap in tile 1010"); +} + +#[test] +fn a_triangle_across_a_uv_tile_border_counts_in_both_tiles() { + // Two quads on the same UVs, from u 0.9 in tile 1001 to u 1.1 in tile 1002 + let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 1/1 2/2 3/3 4/4\n\ + o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 5/5 6/6 7/7 8/8\n"; + let mut session = Session::from_mesh_bytes("border.obj", obj.as_bytes(), 128, "border").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + + for (excluded, kept) in [(1002, 1001), (1001, 1002)] { + let excluded_tiles = &mut session.doc.project.texture_sets[0].bake_excluded_tiles; + excluded_tiles.clear(); + excluded_tiles.insert(excluded); + assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "tile {kept} holds part of the overlap"); + } +} + +#[test] +fn unpaired_parts_are_listed_only_when_matching_by_name() { + let mut session = two_quads(false); + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "no high poly"); + session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap(); + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "\"Always\" pairs every part"); + + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let pairs = session.bake_name_pairs(0).unwrap().unwrap(); + let unpaired: Vec<&NamePair> = pairs.iter().filter(|pair| pair.unpaired()).collect(); + assert_eq!(unpaired, [&NamePair { low: Some("Lone_low".into()), high: None }, &NamePair { low: None, high: Some("Extra_high".into()) }], "{pairs:?}"); + assert!(pairs.contains(&NamePair { low: Some("Box_low".into()), high: Some("Box_high".into()) })); + + session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "the low poly as its own high poly pairs every part"); +} + +#[test] +fn a_set_matching_always_bakes_from_every_high_poly_part() { + let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap(); + let both = [0, 1]; + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), Vec::::new(), "the other set matches \"Always\""); + + session.doc.project.texture_sets[1].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), ["Extra_high"]); +} diff --git a/crates/engine/tests/it/generator_inputs.rs b/crates/engine/tests/it/generator_inputs.rs new file mode 100644 index 00000000..d61dac5a --- /dev/null +++ b/crates/engine/tests/it/generator_inputs.rs @@ -0,0 +1,132 @@ +//! Generator inputs that read an anchor point or an image, through engine commands. + +use serde_json::{Value, json}; +use std::sync::Arc; +use texturecraft_engine::core::{BakedMap, Channel, EffectKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The texture set's texels per side. +const RESOLUTION: u32 = 256; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + session.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// Composited value of `channel` under the viewport center. +fn center(session: &mut Session, channel: Channel) -> [f32; 3] { + session.update(); + let hit = session.pick(session.viewport * 0.5, session.viewport).unwrap(); + let texels = RESOLUTION as f32; + session.caches[0].composite.value(channel, (hit.uv.x * texels) as u32, (hit.uv.y * texels) as u32) +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +/// A low fill (height 0.8) with an anchor, then a white fill whose black mask holds an AO generator reading it: (anchor, low layer, generator). +fn anchored_generator(session: &mut Session) -> (u64, u64, u64) { + let low = id(execute(session, "layer.add.fill", &json!({"height": 0.8})).unwrap(), "layer"); + let anchor = id(execute(session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(), "effect"); + execute(session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(session, "effect.add.generator", &json!({"generator": "ambientOcclusion", "level": 0.5, "softness": 0.5})).unwrap(), "effect"); + execute(session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputAnchor": anchor, "anchorChannel": "height"})).unwrap(); + (anchor, low, generator) +} + +#[test] +fn a_generator_input_reads_the_anchor_points_value() { + let mut session = session(); + anchored_generator(&mut session); + + // The low fill's gray, then white through the mask: an occlusion of 0.8 masks most of it, the channel default (0) none + let base = center(&mut session, Channel::BaseColor)[0]; + assert!(base > 0.9, "the generator reads the anchor's height, not the default: {base}"); +} + +#[test] +fn a_generator_reading_an_anchor_cannot_be_pasted_below_it() { + let mut session = session(); + let (_, low, generator) = anchored_generator(&mut session); + execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap(); + + let pasted = execute(&mut session, "effect.paste", &json!({"layer": low, "target": "mask"})); + assert!(pasted.is_err(), "the anchor point is on that layer, not below it"); +} + +#[test] +fn removing_unused_resources_keeps_an_image_read_by_a_generator_input() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("occlusion.png", bytes).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": name})).unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the generator input"); +} + +#[test] +fn removing_unused_resources_keeps_an_image_read_by_a_content_effect() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("content.png", bytes).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let effect = id(execute(&mut session, "effect.add.fill", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut session, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "image": name})).unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert!(session.doc.resources.contains_key(&name), "the content effect still reads the image"); +} + +#[test] +fn generator_input_rejects_a_resource_that_is_not_an_image() { + let mut session = session(); + session.doc.resources.insert("linked.mcmat".into(), Arc::new(vec![1, 2, 3])); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect"); + + let result = execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": "linked.mcmat"})); + + assert!(result.is_err(), "a package resource has no image pixels for the generator to sample"); +} + +#[test] +fn importing_a_missing_generator_input_invalidates_the_composite() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let effect = id(execute(&mut session, "effect.add.generator", &json!({"generator": "ambientOcclusion"})).unwrap(), "effect"); + session + .edit("Reference an absent image", |session| { + let effect = session.doc.project.effect_mut(texturecraft_engine::core::LayerId(effect)).unwrap(); + let EffectKind::Generator(generator) = &mut effect.kind else { panic!("expected generator") }; + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("later.png")); + Ok(()) + }) + .unwrap(); + let before = center(&mut session, Channel::BaseColor)[0]; + + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 0, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("later.png", bytes).unwrap(); + let after = center(&mut session, Channel::BaseColor)[0]; + + assert!((after - before).abs() > 0.2, "the new image must update the generator's composited mask: {before} -> {after}"); +} diff --git a/crates/engine/tests/it/high_poly_missed.rs b/crates/engine/tests/it/high_poly_missed.rs index c5b132fa..2af1e085 100644 --- a/crates/engine/tests/it/high_poly_missed.rs +++ b/crates/engine/tests/it/high_poly_missed.rs @@ -1,4 +1,4 @@ -use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed}; +use texturecraft_engine::bake::{HIDDEN_HIGH_POLY_VERTEX, HighPolyReach, RayStart, VertexReach, high_poly_missed}; use texturecraft_engine::geom::glam::Vec3; fn vertex(height: f32) -> Option { @@ -30,12 +30,13 @@ fn each_owning_set_uses_its_own_frontal_and_rear_distances() { } #[test] -fn selected_set_filter_leaves_other_sets_unmarked() { +fn selected_set_filter_hides_other_sets_vertices() { + const H: f32 = HIDDEN_HIGH_POLY_VERTEX; let reaches = sets(); - assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); - assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, H, H, H, H]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![H, H, 0.0, 1.0, H, H]); for only_set in [0, reaches.len(), usize::MAX] { - assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![H; 6], "a set without a reach shows none of the high poly"); } } diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index b9f14bcd..099a41b0 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -2,7 +2,7 @@ //! frame-budgeted compositor, through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId, LayerKind}; +use texturecraft_engine::core::{Channel, Fill, LayerId, LayerKind, Source}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; @@ -206,6 +206,52 @@ fn edits_invalidate_only_the_sets_they_change() { assert!((rough(&mut s, 0) - 0.4).abs() < 1e-3); } +#[test] +fn importing_images_invalidates_only_sets_with_newly_resolved_references() { + use std::sync::Arc; + + let mut session = session(); + let referenced_layer = session.doc.project.texture_sets[1].stack[0]; + session + .edit("Reference missing image", |session| { + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::image("later.png")); + session.doc.project.layer_mut(referenced_layer).unwrap().kind = LayerKind::Fill(fill); + Ok(()) + }) + .unwrap(); + session.update(); + + let mut image_bytes = Vec::new(); + let image = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])); + image.write_to(&mut std::io::Cursor::new(&mut image_bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("later.png", image_bytes.clone()).unwrap(); + assert!(session.caches[0].dirty.is_empty(), "unrelated set stays clean"); + assert!(!session.caches[1].dirty.is_empty(), "newly resolved image invalidates its set"); + session.update(); + let (x, y) = covered(&session, 1); + assert!(session.caches[1].composite.value(Channel::BaseColor, x, y)[0] > 0.9); + let imported_image = Arc::downgrade(&session.images["later.png"]); + + session.undo().unwrap(); + assert!(!session.caches[0].dirty.is_empty(), "resource removal retains broad invalidation"); + assert!(!session.caches[1].dirty.is_empty()); + assert!(imported_image.upgrade().is_none(), "undo releases the decoded image even while encoded bytes remain in history"); + session.update(); + session.redo().unwrap(); + assert!(session.caches[0].dirty.is_empty()); + assert!(!session.caches[1].dirty.is_empty()); + assert!(!imported_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "redo decodes a new image allocation"); + session.update(); + + session.import_resource_bytes("unused.png", image_bytes).unwrap(); + assert!(session.caches.iter().all(|cache| cache.dirty.is_empty()), "unused image leaves every set clean"); + + let resolved_image = Arc::downgrade(&session.images["later.png"]); + session.sync_images(); + assert!(resolved_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "sync reuses already decoded images"); +} + #[test] fn budgeted_updates_spread_work_and_end_identical() { let mut s = session(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e6157332..8973da23 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone session.rs target remains available. mod bake; +mod bake_checks; mod bake_resolution; mod bake_settings; mod bake_tiles; @@ -10,6 +11,7 @@ mod content_effects; mod export_colour_space; mod filter_swap; mod filters; +mod generator_inputs; mod high_poly_missed; mod instances; mod materialcraft_link; @@ -24,6 +26,7 @@ mod polygon_fill; mod project_recovery; mod sample; mod thumbs; +mod tool_availability; mod tools; mod udim; mod uv_strokes; diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index 19931786..cbe75532 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -21,9 +21,14 @@ fn session() -> Session { /// A `.mcmat` as MaterialCraft writes it: uniform maps, one float input `wear` cooked at `wear`. fn mcmat(roughness: f32, wear: f32) -> Vec { + mcmat_version(roughness, wear, 1) +} + +fn mcmat_version(roughness: f32, wear: f32, version: u32) -> Vec { + let source = if version == 2 { "source.sbs" } else { "source.mcraft" }; let gray = |v: f32| mesh_map_png(4, 1, &[v; 16]).unwrap(); let manifest = json!({ - "format": "craft-material", "version": 1, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], + "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [ {"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}, {"usage": "roughness", "file": "maps/roughness.png", "colorSpace": "linear"}, @@ -42,7 +47,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { {"identifier": "bentNormal", "kind": "color"} ], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}], - "source": "source.mcraft" + "source": source }); let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -51,7 +56,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { ("maps/baseColor.png", mesh_map_png(4, 3, &[0.5; 48]).unwrap()), ("maps/roughness.png", gray(roughness)), ("maps/ambientOcclusion.png", gray(1.0)), - ("source.mcraft", b"package bytes".to_vec()), + (source, b"package bytes".to_vec()), ] { z.start_file(name, o).unwrap(); z.write_all(&bytes).unwrap(); @@ -81,6 +86,24 @@ fn map_name(s: &Session, id: LayerId, c: Channel) -> String { } } +#[test] +fn version_two_preserves_the_sbs_source_for_future_cooks() { + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat_version(0.25, 0.5, 2), Place::Selection).unwrap(); + let linked = link(&session, id); + assert!(linked.package.ends_with(".sbs")); + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); + assert_eq!(job.source_ext, "sbs"); + assert_eq!(job.graph.as_deref(), Some("Brick_wall")); + assert_eq!(job.package.as_slice(), b"package bytes"); + let base = std::env::temp_dir().join(format!("texturecraft-sbs-source-{}", std::process::id())); + let saved = execute(&mut session, "material.link.saveSource", &json!({"layer": id.0, "path": base.to_str().unwrap()})).unwrap(); + let path = saved["path"].as_str().unwrap(); + assert!(path.ends_with(".sbs")); + assert_eq!(std::fs::read(path).unwrap(), b"package bytes"); + let _ = std::fs::remove_file(path); +} + #[test] fn imports_as_a_linked_fill_with_its_maps() { let mut s = session(); @@ -108,47 +131,55 @@ fn imports_as_a_linked_fill_with_its_maps() { /// An image marked DirectX keeps the mark when a re-cook replaces it. #[test] fn recooks_keep_the_normal_format_of_a_map() { - let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); - execute(&mut s, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap(); - s.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); - let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("a fill") }; + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap(); + + session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); + + let LayerKind::Fill(fill) = &session.doc.project.layer(id).unwrap().kind else { panic!("a fill") }; + assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { normal_format: NormalFormat::DirectX, .. }))); } #[test] fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { - let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); - let set = |s: &mut Session, p: Value| execute(s, "material.link.set", &p); - assert!(set(&mut s, json!({"id": "nope", "value": 1, "cook": false})).is_err()); - assert!(set(&mut s, json!({"id": "wear", "value": "soft", "cook": false})).is_err()); - assert!(set(&mut s, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err()); - set(&mut s, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap(); - assert_eq!(link(&s, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]})); - set(&mut s, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap(); - assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.9})); + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let set = |session: &mut Session, params: Value| execute(session, "material.link.set", ¶ms); + + assert!(set(&mut session, json!({"id": "nope", "value": 1, "cook": false})).is_err()); + assert!(set(&mut session, json!({"id": "wear", "value": "soft", "cook": false})).is_err()); + assert!(set(&mut session, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err()); + set(&mut session, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]})); + set(&mut session, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.9})); + + // Cooks follow the texture set resolution + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); - // The job carries every value and the texture set's resolution. - let job = s.link_job(id, &serde_json::Map::new()).unwrap(); assert_eq!(job.size, 128); assert_eq!(job.values["wear"], json!({"t": "float", "v": 0.9})); - // What the job cooked (here: built by hand) replaces the maps, merged into the edit. - let old = map_name(&s, id, Channel::Roughness); - s.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap(); - assert!((roughness(&mut s) - 0.75).abs() < 2e-3); - assert!(!s.doc.resources.contains_key(&old), "old maps are dropped"); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert!((roughness(&mut s) - 0.25).abs() < 2e-3, "undo restores the earlier maps"); - assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.5})); - execute(&mut s, "edit.redo", &Value::Null).unwrap(); - assert!((roughness(&mut s) - 0.75).abs() < 2e-3); + // Merge the cooked maps into the parameter edit + let old = map_name(&session, id, Channel::Roughness); + session.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap(); - // Presets skip inputs the painter can't set; unknown presets are errors. - assert!(execute(&mut s, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err()); - execute(&mut s, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap(); - assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 1.0})); + assert!((roughness(&mut session) - 0.75).abs() < 2e-3); + assert!(!session.doc.resources.contains_key(&old), "old maps are dropped"); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!((roughness(&mut session) - 0.25).abs() < 2e-3, "undo restores the earlier maps"); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.5})); + + execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert!((roughness(&mut session) - 0.75).abs() < 2e-3); + + // Presets skip unsupported inputs and reject unknown names + assert!(execute(&mut session, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err()); + execute(&mut session, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 1.0})); } #[test] @@ -191,7 +222,7 @@ fn cooks_through_materialcraft_cli_when_available() { let dir = std::env::temp_dir().join(format!("tc-mc-link-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("bricks.mcraft"); - let ok = std::process::Command::new(&cli).args(["new", "bricks"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); + let ok = std::process::Command::new(&cli).args(["new", "pbr"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); assert!(ok.success()); let exposed = dir.join("exposed.mcraft"); let ok = std::process::Command::new(&cli) @@ -209,9 +240,24 @@ fn cooks_through_materialcraft_cli_when_available() { assert_eq!(link(&s, id).size, 128, "cooked at the texture set's resolution"); assert!(link(&s, id).params.iter().any(|p| p.id == "wear")); execute(&mut s, "material.link.set", &json!({"layer": id.0, "id": "wear", "value": 0.8})).unwrap(); - assert_eq!(link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value, json!({"t": "float", "v": 0.8})); - let out = dir.join("back.mcraft"); + let wear = link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value["v"].as_f64().unwrap(); + assert!((wear - 0.8).abs() < 1e-6); + let out = dir.join("back.sbs"); execute(&mut s, "material.link.saveSource", &json!({"layer": id.0, "path": out.to_str().unwrap()})).unwrap(); assert!(std::fs::metadata(&out).unwrap().len() > 0); + + // The portable material can name a graph other than the first in the embedded source. + let multi = dir.join("multi.mcraft"); + let ok = std::process::Command::new(&cli).arg("run").arg(&exposed).arg("graph.duplicate").arg("{}").arg("-o").arg(&multi).status().unwrap(); + assert!(ok.success()); + let portable = dir.join("second.mcmat"); + let params = json!({"graph": 1, "size": 64, "path": portable.to_str().unwrap()}); + let ok = std::process::Command::new(&cli).arg("run").arg(&multi).arg("file.exportMaterial").arg(params.to_string()).status().unwrap(); + assert!(ok.success()); + let second = s.add_linked_material_bytes_at(&std::fs::read(&portable).unwrap(), Place::Selection).unwrap(); + let expected_graph = link(&s, second).graph; + let job = s.link_job(second, &serde_json::Map::new()).unwrap(); + let result = texturecraft_engine::formats::mcmat::read_mcmat(&job.run().unwrap()).unwrap(); + assert_eq!(result.manifest.graph, expected_graph); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/tests/it/perf.rs b/crates/engine/tests/it/perf.rs index e4691b6a..66988d42 100644 --- a/crates/engine/tests/it/perf.rs +++ b/crates/engine/tests/it/perf.rs @@ -397,3 +397,43 @@ fn bench_layer_thumbs_4k() { } eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len()); } + +/// A full recomposite in one call against the same one spread over frames, as the UI runs it, with and without a blurred mask +/// in the stack: neighbourhood filters are what a frame slice pays for apart from its own tiles. +#[test] +#[ignore] +fn bench_sliced_filters_4k() { + for blur in [false, true] { + let mut session = Session::new_project("sliced", primitives::sphere(1.0, 64, 32), "builtin:sphere", None, 4096).unwrap(); + session.viewport = Vec2::new(800.0, 800.0); + let run = |session: &mut Session, id: &str, params: Value| execute(session, id, ¶ms).unwrap(); + run(&mut session, "layer.add.fill", json!({"color": [0.6, 0.5, 0.4], "roughness": 0.6})); + run(&mut session, "layer.add.fill", json!({"color": [0.1, 0.3, 0.6]})); + run(&mut session, "mask.add.black", Value::Null); + run(&mut session, "effect.add.generator", json!({"generator": "position", "level": 0.5})); + if blur { + run(&mut session, "effect.add.filter", json!({"filter": "blur", "radius": 8})); + } + + session.update(); + + session.caches[0].invalidate_all(); + let started = Instant::now(); + session.update(); + let direct = started.elapsed(); + + session.caches[0].invalidate_all(); + let clock = Instant::now(); + let elapsed_ms = || clock.elapsed().as_secs_f64() * 1000.0; + let (mut frames, mut longest_frame) = (0, Duration::ZERO); + while session.pending_tiles() > 0 { + let started = Instant::now(); + session.update_for(30.0, elapsed_ms); + longest_frame = longest_frame.max(started.elapsed()); + frames += 1; + } + + let label = if blur { "blurred mask" } else { "no filter" }; + println!("[sliced 4096², {label}] one call {direct:.2?}; in 30 ms slices {frames} frames, worst {longest_frame:.2?}, total {:.2?}", clock.elapsed()); + } +} diff --git a/crates/engine/tests/it/tool_availability.rs b/crates/engine/tests/it/tool_availability.rs new file mode 100644 index 00000000..5c17e29b --- /dev/null +++ b/crates/engine/tests/it/tool_availability.rs @@ -0,0 +1,336 @@ +//! Which tools can act on each selection, and that every usable tool acts there in both views + +mod selection; + +use selection::Selection; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Effect, EffectKind, LayerId}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; +use texturecraft_engine::{Session, StackTarget, Tool, execute}; + +/// Two triangles side by side, each a mesh part with its own corner of the UV square +const PARTS_OBJ: &str = "o Lid\nv 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 0.5 0\nvt 0 0.5\nf 1/1 2/2 3/3\n\ +o Body\nv 2 2 0\nv 4 2 0\nv 2 4 0\nvt 0.5 0.5\nvt 1 0.5\nvt 0.5 1\nf 4/4 5/5 6/6\n"; + +const VIEWPORT_PIXELS: f32 = 400.0; + +fn stencil_png() -> Vec { + let mut out = Vec::new(); + let green = image::RgbaImage::from_fn(8, 8, |_, _| image::Rgba([0, 255, 0, 255])); + green.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn base_session() -> Session { + let mut session = Session::from_mesh_bytes("parts.obj", PARTS_OBJ.as_bytes(), 256, "parts").unwrap(); + session.viewport = Vec2::splat(VIEWPORT_PIXELS); + (session.camera.yaw, session.camera.pitch) = (0.0, 0.0); + let (low, high) = session.mesh.bounds(); + session.camera.frame(low, high); + session.update(); + + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap(); + let stencil = session.import_resource_bytes("stencil.png", stencil_png()).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": stencil})).unwrap(); + session +} + +fn screen(session: &Session, point: [f32; 3]) -> Vec2 { + let ndc = session.camera.project(Vec3::from(point), 1.0).unwrap(); + Vec2::new((ndc.x + 1.0) * VIEWPORT_PIXELS / 2.0, (1.0 - ndc.y) * VIEWPORT_PIXELS / 2.0) +} + +fn add_layer(session: &mut Session, command: &str) -> u64 { + execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn select(session: &mut Session, layer: u64, target: Value) { + execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap(); +} + +fn select_nothing(session: &mut Session) { + let set = session.ts(); + session.selected.remove(&set); + session.target = StackTarget::Content; +} + +/// Adds an effect with `command` to the layer's content or mask and selects it +fn select_new_effect(session: &mut Session, layer: u64, mask: bool, command: &str, effect_params: Value) { + if mask { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + } + + let target = if mask { "mask" } else { "content" }; + let mut params = effect_params; + params["layer"] = json!(layer); + params["target"] = json!(target); + execute(session, command, ¶ms).unwrap(); + + let owner = session.doc.project.layer(LayerId(layer)).unwrap(); + let effects = if mask { &owner.mask.as_ref().unwrap().effects } else { &owner.content_effects }; + let effect = effects.last().unwrap().id.0; + select(session, layer, json!(effect)); +} + +fn select_new_mask(session: &mut Session, layer: u64) { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + select(session, layer, json!("mask")); +} + +fn session_with(selection: Selection) -> Session { + let mut session = base_session(); + match selection { + Selection::PaintContent => { + let layer = add_layer(&mut session, "layer.add.paint"); + select(&mut session, layer, json!("content")); + } + Selection::FillContent => { + let layer = add_layer(&mut session, "layer.add.fill"); + select(&mut session, layer, json!("content")); + } + Selection::PaintMask => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_mask(&mut session, layer); + } + Selection::FillMask => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_mask(&mut session, layer); + } + Selection::FolderMask => { + let folder = add_layer(&mut session, "layer.add.group"); + select_new_mask(&mut session, folder); + } + Selection::InstanceOwnMask => { + let source = add_layer(&mut session, "layer.add.paint"); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + select_new_mask(&mut session, instance); + } + Selection::PaintSublayer => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, false, "effect.add.paint", json!({})); + } + Selection::PaintSublayerInMask => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, true, "effect.add.paint", json!({})); + } + Selection::PaintSublayerInFill => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_effect(&mut session, layer, false, "effect.add.paint", json!({})); + } + Selection::PathSublayer => { + let layer = add_layer(&mut session, "layer.add.paint"); + select(&mut session, layer, json!("content")); + let (start, end) = (screen(&session, [0.2, 0.2, 0.0]), screen(&session, [1.0, 0.4, 0.0])); + execute(&mut session, "tool.path", &json!({"points": [[start.x, start.y], [end.x, end.y]]})).unwrap(); + execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); + let path = session.doc.project.layer(LayerId(layer)).unwrap().content_effects.last().unwrap().id.0; + select(&mut session, layer, json!(path)); + } + Selection::FilterInPaint | Selection::FilterInFill | Selection::FilterInMask => { + let command = if selection == Selection::FilterInFill { "layer.add.fill" } else { "layer.add.paint" }; + let layer = add_layer(&mut session, command); + select_new_effect(&mut session, layer, selection == Selection::FilterInMask, "effect.add.filter", json!({"filter": "invert"})); + } + Selection::FillEffectInPaint => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, false, "effect.add.fill", json!({})); + } + Selection::GeneratorInFillMask => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_effect(&mut session, layer, true, "effect.add.generator", json!({})); + } + Selection::FolderContent => { + let folder = add_layer(&mut session, "layer.add.group"); + select(&mut session, folder, json!("content")); + } + Selection::InstanceOfPaint | Selection::InstanceOfFill => { + let command = if selection == Selection::InstanceOfFill { "layer.add.fill" } else { "layer.add.paint" }; + let source = add_layer(&mut session, command); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + select(&mut session, instance, json!("content")); + } + Selection::Nothing => select_nothing(&mut session), + Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill => { + let command = if selection == Selection::QuickMaskOverFill { "layer.add.fill" } else { "layer.add.paint" }; + let layer = add_layer(&mut session, command); + select(&mut session, layer, json!("content")); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + } + Selection::QuickMaskOverNothing => { + select_nothing(&mut session); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + } + } + + session +} + +/// Uses `tool` once the way the viewport does: a stroke, a click or a committed path +fn use_tool(session: &mut Session, tool: Tool, in_2d_view: bool) -> texturecraft_engine::Result<()> { + session.tool.tool = tool; + if tool == Tool::Clone { + let source = screen(session, [1.2, 0.3, 0.0]); + execute(session, "tool.cloneSource", &json!({"x": source.x, "y": source.y}))?; + } + + let points = [screen(session, [0.3, 0.3, 0.0]), screen(session, [0.6, 0.4, 0.0]), screen(session, [0.9, 0.5, 0.0])]; + let uv_points = [Vec2::new(0.05, 0.95), Vec2::new(0.1, 0.92), Vec2::new(0.15, 0.9)]; + if tool == Tool::Path { + let params = if in_2d_view { + json!({"uvPoints": uv_points.iter().map(|uv| [uv.x, uv.y]).collect::>()}) + } else { + json!({"points": points.iter().map(|point| [point.x, point.y]).collect::>()}) + }; + execute(session, "tool.path", ¶ms)?; + execute(session, "tool.path", &json!({"commit": true}))?; + return Ok(()); + } + + let single_click = matches!(tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask); + let viewport = session.viewport; + if in_2d_view { + session.begin_stroke_uv(uv_points[0], 1.0)?; + } else { + session.begin_stroke(points[0], viewport, 1.0)?; + } + + if single_click { + return Ok(()); + } + + for (point, uv) in points.iter().zip(&uv_points).skip(1) { + if in_2d_view { + session.continue_stroke_uv(*uv, 1.0); + } else { + session.continue_stroke(*point, 1.0); + } + } + + session.end_stroke() +} + +#[test] +fn every_selection_offers_the_tools_that_can_act_on_it() { + let mut wrong = Vec::new(); + for selection in Selection::ALL { + let session = session_with(selection); + for tool in Tool::ALL { + let usable = session.tool_usable(tool); + if usable != selection.offers(tool) { + wrong.push(format!("{selection:?} {tool:?}: usable {usable}")); + } + } + } + + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn every_usable_tool_acts_in_both_views() { + let mut wrong = Vec::new(); + for in_2d_view in [false, true] { + for selection in Selection::ALL { + for tool in Tool::ALL { + // The picker and the geometry mask read the 3D view only, whatever is selected + if in_2d_view && matches!(tool, Tool::ColorPicker | Tool::GeometryMask) { + continue; + } + + let mut session = session_with(selection); + let usable = session.tool_usable(tool); + + let result = use_tool(&mut session, tool, in_2d_view); + + let view = if in_2d_view { "2D" } else { "3D" }; + match result { + Err(error) if usable => wrong.push(format!("{view} {selection:?} {tool:?}: usable but {error}")), + Ok(()) if !usable && !selection.scripts_still_paint() => wrong.push(format!("{view} {selection:?} {tool:?}: greyed but acts")), + _ => {} + } + } + } + } + + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +fn commit_path(session: &mut Session) -> texturecraft_engine::Result { + execute(session, "tool.path", &json!({"uvPoints": [[0.05, 0.95], [0.15, 0.9]], "commit": true})) +} + +fn path_count(session: &Session, path_sublayer: LayerId) -> usize { + match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Path(paths)) => paths.len(), + _ => 0, + } +} + +#[test] +fn paths_are_refused_on_fill_layers_and_the_quick_mask_but_saved_ones_stay_editable() { + let mut session = session_with(Selection::FillContent); + let fill = session.selected_layer().unwrap(); + + assert!(commit_path(&mut session).is_err(), "no new paths in a fill layer"); + assert!(session.doc.project.layer(fill).unwrap().content_effects.is_empty()); + + let mut session = session_with(Selection::QuickMaskOverPaint); + assert!(commit_path(&mut session).is_err(), "paths can't edit the quick mask"); + + // A project saved while paths could go into fill layers + let mut session = session_with(Selection::FillContent); + let fill = session.selected_layer().unwrap(); + let saved_path = session.doc.project.alloc_id(); + session.doc.project.layer_mut(fill).unwrap().content_effects.push(Effect::new(saved_path, EffectKind::Path(Vec::new()))); + select(&mut session, fill.0, json!(saved_path.0)); + + assert!(session.tool_usable(Tool::Path)); + + commit_path(&mut session).unwrap(); + + assert_eq!(path_count(&session, saved_path), 1, "the saved path sublayer takes the new path"); +} + +#[test] +fn quick_mask_edit_and_invert_need_the_mask_on() { + let mut session = base_session(); + + assert!(execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).is_err()); + assert!(execute(&mut session, "viewport.quickMask.invert", &json!({})).is_err()); + + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap(); + + assert!(!session.quick_mask.editing, "turning the mask off stops editing it"); +} + +#[test] +fn a_saved_path_cannot_be_committed_while_editing_the_quick_mask() { + let mut session = session_with(Selection::PaintContent); + commit_path(&mut session).unwrap(); + let StackTarget::Effect(path_sublayer) = session.target else { panic!("the committed path is not selected") }; + + let points_before = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Path(paths)) => paths[0].points.clone(), + _ => panic!("the committed path is missing"), + }; + + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": path_sublayer.0, "index": 0})).unwrap(); + assert!(!session.tool_usable(Tool::Path)); + + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.3, 0.7]]})).unwrap(); + assert!(!session.path_live().unwrap(), "live preview must leave the stored path alone"); + let result = execute(&mut session, "tool.path", &json!({"commit": true})); + assert!(result.is_err(), "a greyed Path tool must not commit a stored path into the quick mask edit state"); + + let points_after = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Path(paths)) => paths[0].points.clone(), + _ => panic!("the stored path is missing"), + }; + assert_eq!(points_after, points_before); +} diff --git a/crates/engine/tests/it/tool_availability/selection.rs b/crates/engine/tests/it/tool_availability/selection.rs new file mode 100644 index 00000000..aaca56a8 --- /dev/null +++ b/crates/engine/tests/it/tool_availability/selection.rs @@ -0,0 +1,83 @@ +//! Selection cases for the tool availability tests + +use texturecraft_engine::Tool; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Selection { + PaintContent, + FillContent, + PaintMask, + FillMask, + FolderMask, + InstanceOwnMask, + PaintSublayer, + PaintSublayerInMask, + PaintSublayerInFill, + PathSublayer, + FilterInPaint, + FilterInFill, + FilterInMask, + FillEffectInPaint, + GeneratorInFillMask, + FolderContent, + InstanceOfPaint, + InstanceOfFill, + Nothing, + QuickMaskOverPaint, + QuickMaskOverFill, + QuickMaskOverNothing, +} + +impl Selection { + pub(super) const ALL: [Selection; 22] = [ + Selection::PaintContent, + Selection::FillContent, + Selection::PaintMask, + Selection::FillMask, + Selection::FolderMask, + Selection::InstanceOwnMask, + Selection::PaintSublayer, + Selection::PaintSublayerInMask, + Selection::PaintSublayerInFill, + Selection::PathSublayer, + Selection::FilterInPaint, + Selection::FilterInFill, + Selection::FilterInMask, + Selection::FillEffectInPaint, + Selection::GeneratorInFillMask, + Selection::FolderContent, + Selection::InstanceOfPaint, + Selection::InstanceOfFill, + Selection::Nothing, + Selection::QuickMaskOverPaint, + Selection::QuickMaskOverFill, + Selection::QuickMaskOverNothing, + ]; + + /// Whether the shelf offers `tool` for this selection + pub(super) fn offers(self, tool: Tool) -> bool { + let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); + match tool { + Tool::ColorPicker => true, + Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing), + _ => match self { + Selection::PaintContent | Selection::PaintSublayer => true, + Selection::PaintSublayerInFill => tool != Tool::Path, + Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => { + !reads_content + } + Selection::PathSublayer => tool == Tool::Path, + Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path, + _ => false, + }, + } + } + + /// Greyed in the shelf, but scripts still paint here: below the effect, or the instance's source + pub(super) fn scripts_still_paint(self) -> bool { + matches!( + self, + Selection::FilterInPaint | Selection::FillEffectInPaint | Selection::FilterInMask | Selection::GeneratorInFillMask | Selection::InstanceOfPaint + ) + } +} diff --git a/crates/engine/tests/it/tools.rs b/crates/engine/tests/it/tools.rs index afadf0b3..0e217d88 100644 --- a/crates/engine/tests/it/tools.rs +++ b/crates/engine/tests/it/tools.rs @@ -153,32 +153,39 @@ fn library_alphas_shape_the_stamp() { #[test] fn quick_mask_limits_painting() { - let mut s = session(); - paint_red(&mut s, 20.0); - let r = execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap(); - assert_eq!(r["editing"], json!(true)); - assert_eq!(r["enabled"], json!(true), "editing enables the mask"); - let undo = s.history_labels().len(); - dab(&mut s, 150.0, 200.0); - assert!(!red(color_at(&s, 150.0, 200.0)), "mask strokes do not paint the layer"); - assert_eq!(s.history_labels().len(), undo, "mask strokes stay out of the history"); - assert!(s.quick_mask_rgba(0, 64).is_some_and(|v| v.len() == 64 * 64 * 4)); - execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap(); + let mut session = session(); + paint_red(&mut session, 20.0); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); - execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); - dab(&mut s, 150.0, 200.0); - dab(&mut s, 250.0, 200.0); - assert!(red(color_at(&s, 150.0, 200.0)), "inside the mask"); - assert!(!red(color_at(&s, 250.0, 200.0)), "outside the mask"); + let state = execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap(); + let undo = session.history_labels().len(); + dab(&mut session, 150.0, 200.0); - execute(&mut s, "viewport.quickMask.invert", &Value::Null).unwrap(); - dab(&mut s, 250.0, 200.0); - assert!(red(color_at(&s, 250.0, 200.0)), "inverted: outside is open"); + assert_eq!(state["editing"], json!(true)); + assert!(!red(color_at(&session, 150.0, 200.0)), "mask strokes do not paint the layer"); + assert_eq!(session.history_labels().len(), undo, "mask strokes stay out of the history"); + let overlay_size: u32 = 64; + let rgba_bytes = (overlay_size * overlay_size * 4) as usize; + assert!(session.quick_mask_rgba(0, overlay_size).is_some_and(|pixels| pixels.len() == rgba_bytes), "an RGBA8 overlay of the requested size"); - execute(&mut s, "viewport.quickMask", &json!({"enabled": false})).unwrap(); - execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap(); - dab(&mut s, 150.0, 200.0); - assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); + execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap(); + dab(&mut session, 150.0, 200.0); + dab(&mut session, 250.0, 200.0); + + assert!(red(color_at(&session, 150.0, 200.0)), "inside the mask"); + assert!(!red(color_at(&session, 250.0, 200.0)), "outside the mask"); + + execute(&mut session, "viewport.quickMask.invert", &Value::Null).unwrap(); + dab(&mut session, 250.0, 200.0); + + assert!(red(color_at(&session, 250.0, 200.0)), "inverted: outside is open"); + + execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap(); + dab(&mut session, 150.0, 200.0); + + assert!(color_at(&session, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); } /// How much redder than green a texel must be to count as painted (faded edges included) @@ -244,3 +251,54 @@ fn swap_mask_value_inverts_only_while_a_mask_is_the_target() { assert_eq!(session.tool.mask_value, 0.0, "a mask effect paints the mask too"); } + +#[test] +fn stroke_after_undoing_mask_is_paint_stroke() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap(); + execute(&mut s, "tool.paint", &Value::Null).unwrap(); + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.9, 0.3, 0.9]})).unwrap(); + + execute(&mut s, "tool.stroke", &json!({"points": [[130, 130], [170, 150]]})).unwrap(); + s.update(); + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "tool.stroke", &json!({"points": [[167, 183], [207, 203]]})).unwrap(); + s.update(); + + let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(undone["undone"], "Paint stroke", "the stroke after undoing the mask was recorded as {}", undone["undone"]); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + s.update(); + + let settled = s.caches[0].composite.clone(); + s.caches[0].below.clear(); + s.caches[0].invalidate_all(); + s.update(); + assert_eq!(settled, s.caches[0].composite, "the composite after the stroke matches a full recomposite"); +} + +#[test] +fn undoing_after_painting_on_instance_source_mask_keeps_mask_target() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + execute(&mut s, "layer.instance", &Value::Null).unwrap(); + s.update(); + s.target = StackTarget::Mask; + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[170, 180], [210, 200]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.target, StackTarget::Mask); + + execute(&mut s, "tool.stroke", &json!({"points": [[180, 180], [210, 200]]})).unwrap(); + let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(undone["undone"], "Mask stroke"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 22a17cd5..c7511307 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -308,6 +308,67 @@ fn image_resources_fill_layers_and_round_trip() { assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err()); } +#[test] +fn image_resource_lookup_accepts_extension_and_stem() { + let mut s = session(); + + // No resources imported yet + let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err(); + assert!(err.to_string().contains("no resource `missing` (no resources imported: use resource.import)")); + + let mut png = Vec::new(); + let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.import_resource_bytes("tile.png", png.clone()).unwrap(); + + // Lookup by stem + let r = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap(); + assert!(r["layer"].as_u64().is_some()); + + // Lookup by full name + let r2 = execute(&mut s, "layer.add.image", &json!({"name": "tile.png"})).unwrap(); + assert!(r2["layer"].as_u64().is_some()); + + // Missing resource lists available + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err(); + assert!(err.to_string().contains("no resource `wood` (available: tile.png)")); + + // Ambiguous stem resolution + s.import_resource_bytes("tile.jpg", png).unwrap(); + let err = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap_err(); + assert!(err.to_string().contains("ambiguous resource `tile`")); +} + +#[test] +fn image_resource_lookup_ignores_linked_packages() { + use std::sync::Arc; + use texturecraft_engine::core::{LayerId, LayerKind, Source}; + + let mut s = session(); + s.doc.resources.insert("wood.mcraft".into(), Arc::new(b"package bytes".to_vec())); + s.sync_images(); + assert!(!s.images.contains_key("wood.mcraft")); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err(); + assert!(err.to_string().contains("no resources imported"), "{err}"); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood.mcraft"})).unwrap_err(); + assert!(err.to_string().contains("no resource `wood.mcraft` (no resources imported"), "{err}"); + + let mut png = Vec::new(); + let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.import_resource_bytes("wood.png", png).unwrap(); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err(); + assert!(err.to_string().contains("no resource `missing` (available: wood.png)"), "{err}"); + + let res = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap(); + let id = LayerId(res["layer"].as_u64().unwrap()); + let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("expected fill layer") }; + assert_eq!(fill.sources.get(&Channel::BaseColor), Some(&Source::image("wood.png"))); +} + #[test] fn brush_presets_apply_save_and_load() { let mut s = session(); @@ -524,3 +585,118 @@ fn curvature_generators_take_a_mode_and_detail_sizes() { assert!(dirt.is_err(), "only curvature generators have a mode"); assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); } + +#[test] +fn generators_take_blur_balance_and_contrast() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "blur": 0.25})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""blur":0.25"#) && inspect.contains(r#""balance":0.75"#), "{inspect}"); + assert!(inspect.contains(r#""contrast":1.0"#), "contrast is clamped to 0..1: {inspect}"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "custom", "customResolution": 512, "resolutionFactor": -9})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""resolution":{"custom":512,"factor":-3,"mode":"Custom"}"#), "the factor is clamped to 1/8: {inspect}"); + assert!(execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "huge"})).is_err(), "unknown resolutions are rejected"); +} + +#[test] +fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"uniform":[0.25,0.25,0.25]}}"#), "{inspect}"); + + let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5})); + assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature"); + let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"})); + assert!(missing_image.is_err(), "the image must be a resource of the project"); + let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true})); + assert!(two_sources.is_err(), "an input takes one source"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputBaked": true})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(!inspect.contains(r#""inputs""#), "the mesh map is read again: {inspect}"); +} + +#[test] +fn changing_generator_kind_keeps_the_effect_identity_and_settings() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut state, "effect.set", &json!({"effect": effect, "name": "Keep me", "opacity": 0.4, "level": 0.2})).unwrap(); + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap(); + let later = execute(&mut state, "effect.add.generator", &json!({"generator": "position"})).unwrap()["effect"].as_u64().unwrap(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "generator": "ambientOcclusion"})).unwrap(); + + let (owner, edited) = state.doc.project.effect(texturecraft_core::LayerId(effect)).unwrap(); + assert!(matches!(&edited.kind, texturecraft_core::EffectKind::Generator(generator) + if generator.kind == texturecraft_core::GeneratorKind::AmbientOcclusion + && generator.level == 0.2 + && matches!(generator.inputs.get(&texturecraft_core::BakedMap::AmbientOcclusion), Some(texturecraft_core::Source::Uniform([0.25, 0.25, 0.25]))))); + assert_eq!(edited.name, "Keep me"); + assert_eq!(edited.opacity, 0.4); + let layer = state.doc.project.layer(owner).unwrap(); + let ids: Vec = layer.mask.as_ref().unwrap().effects.iter().map(|item| item.id.0).collect(); + assert_eq!(ids, vec![effect, later]); +} + +#[test] +fn unparseable_color_param_returns_error() { + let mut s = session(); + let err = execute(&mut s, "layer.add.fill", &json!({"color": "#fff"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "color": "#123"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "mask.add.colorSelection", &json!({"color": "#xyz"})).unwrap_err(); + assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "display.set", &json!({"scatterColor": "#12345"})).unwrap_err(); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let rev_before = s.revision; + let exposure_before = s.doc.project.display.env_exposure; + let err = execute(&mut s, "display.set", &json!({"exposure": 2.0, "scatterColor": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.doc.project.display.env_exposure, exposure_before); + assert_eq!(s.revision, rev_before); + + let mask_before = s.tool.mask_value; + let err = execute(&mut s, "tool.material", &json!({"maskValue": 0.25, "channel": "baseColor", "color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.tool.mask_value, mask_before); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "tool.material", &json!({"color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "layer.add.fill", &json!({"color": [1e40, 0.0, 0.0]})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "noise", "color": "red"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + assert!(execute(&mut s, "tool.cloneSource", &json!({"uv": [0.2, 0.8, 0.4]})).is_err()); + execute(&mut s, "tool.polygonFill", &Value::Null).unwrap(); + let err = execute(&mut s, "tool.click", &json!({"uv": [0.2, 0.8, 0.4]})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.click`: a 2D view point needs `uv` as [u, v]"); +} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 7b458a53..f7053917 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,13 +9,20 @@ license.workspace = true workspace = true [dependencies] +craft-usd.workspace = true +# ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local. +craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "272a095b61257917693da3d09f2f8ecccd7f0295" } +craft-materialx = { workspace = true } +craft-mesh = { workspace = true } +craft-mcmat = { workspace = true } +craft-tcraft = { workspace = true } +craft-zip = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } texturecraft-compose = { workspace = true } image = { workspace = true } gltf = { workspace = true } -tobj = { workspace = true } flate2 = { workspace = true } lz4_flex = { workspace = true } half = { workspace = true } diff --git a/crates/formats/src/icc.rs b/crates/formats/src/icc.rs index 9323f561..f0f16a84 100644 --- a/crates/formats/src/icc.rs +++ b/crates/formats/src/icc.rs @@ -1,63 +1,7 @@ -//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small -//! (about 1.2 KiB) and readable by every colour-managed viewer and editor. -//! -//! The colorants come from the space's primaries adapted to the D50 profile connection space -//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear -//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied -//! from a colour-management library or from another profile. - +//! ICC v2.1 export policy; byte serialization is shared with craft-cms. +use craft_cms_icc_v2::write_v2::{MatrixProfile, ToneCurve, matrix_profile}; use texturecraft_texel::{ColorSpace, srgb_to_linear}; - -/// Samples of the sRGB curve table. const CURVE_POINTS: usize = 1024; -/// The D50 white of the profile connection space. -const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; - -fn s15f16(v: f64) -> [u8; 4] { - ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() -} - -fn xyz_tag(v: [f64; 3]) -> Vec { - let mut b = b"XYZ \0\0\0\0".to_vec(); - for c in v { - b.extend_from_slice(&s15f16(c)); - } - b -} - -fn text_tag(text: &str) -> Vec { - let mut b = b"text\0\0\0\0".to_vec(); - b.extend_from_slice(text.as_bytes()); - b.push(0); - b -} - -/// `textDescriptionType` with the ASCII description only. -fn desc_tag(text: &str) -> Vec { - let mut b = b"desc\0\0\0\0".to_vec(); - b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); - b.extend_from_slice(text.as_bytes()); - b.push(0); - // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. - b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); - b -} - -fn curve_tag(space: ColorSpace) -> Vec { - let mut b = b"curv\0\0\0\0".to_vec(); - if space == ColorSpace::Srgb { - b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes()); - for i in 0..CURVE_POINTS { - let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); - b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); - } - } else { - // One entry is a gamma, u8Fixed8: 1.0 is linear. - b.extend_from_slice(&1u32.to_be_bytes()); - b.extend_from_slice(&0x0100u16.to_be_bytes()); - } - b -} fn description(space: ColorSpace) -> &'static str { match space { @@ -68,64 +12,41 @@ fn description(space: ColorSpace) -> &'static str { } } -/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones). +/// The ICC profile of `space`, or None if its primaries are degenerate. pub fn profile(space: ColorSpace) -> Option> { - let m = space.to_xyz_d50()?; - let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; - let curve = curve_tag(space); - // The green and blue curves are the red one's entry. - let tags: [(&[u8; 4], Vec); 9] = [ - (b"desc", desc_tag(description(space))), - (b"cprt", text_tag("No copyright, generated by TextureCraft")), - (b"wtpt", xyz_tag(D50_XYZ)), - (b"rXYZ", xyz_tag(column(0))), - (b"gXYZ", xyz_tag(column(1))), - (b"bXYZ", xyz_tag(column(2))), - (b"rTRC", curve.clone()), - (b"gTRC", curve.clone()), - (b"bTRC", curve), - ]; - // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. - let table_end = 128 + 4 + 12 * tags.len(); - let mut offsets = Vec::new(); - let mut data: Vec = Vec::new(); - for (i, (_, bytes)) in tags.iter().enumerate() { - let shared = i >= 7; - let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; - offsets.push(at); - if !shared { - data.extend_from_slice(bytes); - while !data.len().is_multiple_of(4) { - data.push(0); - } - } - } - let total = table_end + data.len(); - let mut out = vec![0u8; 128]; - out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); - out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 - out.get_mut(12..16)?.copy_from_slice(b"mntr"); - out.get_mut(16..20)?.copy_from_slice(b"RGB "); - out.get_mut(20..24)?.copy_from_slice(b"XYZ "); - // A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes. - out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]); - out.get_mut(36..40)?.copy_from_slice(b"acsp"); - for (k, v) in D50_XYZ.iter().enumerate() { - out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); - } - out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); - for ((sig, bytes), at) in tags.iter().zip(&offsets) { - out.extend_from_slice(*sig); - out.extend_from_slice(&(*at as u32).to_be_bytes()); - out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); - } - out.extend_from_slice(&data); - Some(out) + let matrix = space.to_xyz_d50()?; + let samples: Vec = if space == ColorSpace::Srgb { + (0..CURVE_POINTS) + .map(|i| { + let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); + (v * 65535.0).round().clamp(0.0, 65535.0) as u16 + }) + .collect() + } else { + Vec::new() + }; + matrix_profile(&MatrixProfile { + matrix, + curve: if samples.is_empty() { ToneCurve::Linear } else { ToneCurve::Samples(&samples) }, + description: description(space), + copyright: "No copyright, generated by TextureCraft", + date: [2026, 1, 1, 0, 0, 0], + }) } +#[cfg(test)] +#[path = "icc_legacy_test.rs"] +mod legacy; + #[cfg(test)] mod tests { use super::*; + #[test] + fn all_spaces_match_legacy_wire_bytes() { + for space in ColorSpace::ALL { + assert_eq!(profile(space), legacy::profile(space), "{space:?}"); + } + } fn u32_at(b: &[u8], i: usize) -> u32 { u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) diff --git a/crates/formats/src/icc_legacy_test.rs b/crates/formats/src/icc_legacy_test.rs new file mode 100644 index 00000000..47b4e600 --- /dev/null +++ b/crates/formats/src/icc_legacy_test.rs @@ -0,0 +1,124 @@ +//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small +//! (about 1.2 KiB) and readable by every colour-managed viewer and editor. +//! +//! The colorants come from the space's primaries adapted to the D50 profile connection space +//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear +//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied +//! from a colour-management library or from another profile. + +use texturecraft_texel::{ColorSpace, srgb_to_linear}; + +/// Samples of the sRGB curve table. +const CURVE_POINTS: usize = 1024; +/// The D50 white of the profile connection space. +const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; + +fn s15f16(v: f64) -> [u8; 4] { + ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() +} + +fn xyz_tag(v: [f64; 3]) -> Vec { + let mut b = b"XYZ \0\0\0\0".to_vec(); + for c in v { + b.extend_from_slice(&s15f16(c)); + } + b +} + +fn text_tag(text: &str) -> Vec { + let mut b = b"text\0\0\0\0".to_vec(); + b.extend_from_slice(text.as_bytes()); + b.push(0); + b +} + +/// `textDescriptionType` with the ASCII description only. +fn desc_tag(text: &str) -> Vec { + let mut b = b"desc\0\0\0\0".to_vec(); + b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); + b.extend_from_slice(text.as_bytes()); + b.push(0); + // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. + b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); + b +} + +fn curve_tag(space: ColorSpace) -> Vec { + let mut b = b"curv\0\0\0\0".to_vec(); + if space == ColorSpace::Srgb { + b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes()); + for i in 0..CURVE_POINTS { + let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); + b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); + } + } else { + // One entry is a gamma, u8Fixed8: 1.0 is linear. + b.extend_from_slice(&1u32.to_be_bytes()); + b.extend_from_slice(&0x0100u16.to_be_bytes()); + } + b +} + +fn description(space: ColorSpace) -> &'static str { + match space { + ColorSpace::Srgb => "sRGB (Rec.709 primaries, sRGB curve)", + ColorSpace::LinearRec709 => "Linear Rec.709 (sRGB primaries, D65)", + ColorSpace::AcesCg => "ACEScg (AP1 primaries, linear)", + ColorSpace::Aces2065 => "ACES2065-1 (AP0 primaries, linear)", + } +} + +/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones). +pub fn profile(space: ColorSpace) -> Option> { + let m = space.to_xyz_d50()?; + let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; + let curve = curve_tag(space); + // The green and blue curves are the red one's entry. + let tags: [(&[u8; 4], Vec); 9] = [ + (b"desc", desc_tag(description(space))), + (b"cprt", text_tag("No copyright, generated by TextureCraft")), + (b"wtpt", xyz_tag(D50_XYZ)), + (b"rXYZ", xyz_tag(column(0))), + (b"gXYZ", xyz_tag(column(1))), + (b"bXYZ", xyz_tag(column(2))), + (b"rTRC", curve.clone()), + (b"gTRC", curve.clone()), + (b"bTRC", curve), + ]; + // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. + let table_end = 128 + 4 + 12 * tags.len(); + let mut offsets = Vec::new(); + let mut data: Vec = Vec::new(); + for (i, (_, bytes)) in tags.iter().enumerate() { + let shared = i >= 7; + let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; + offsets.push(at); + if !shared { + data.extend_from_slice(bytes); + while !data.len().is_multiple_of(4) { + data.push(0); + } + } + } + let total = table_end + data.len(); + let mut out = vec![0u8; 128]; + out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); + out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 + out.get_mut(12..16)?.copy_from_slice(b"mntr"); + out.get_mut(16..20)?.copy_from_slice(b"RGB "); + out.get_mut(20..24)?.copy_from_slice(b"XYZ "); + // A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes. + out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]); + out.get_mut(36..40)?.copy_from_slice(b"acsp"); + for (k, v) in D50_XYZ.iter().enumerate() { + out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); + } + out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); + for ((sig, bytes), at) in tags.iter().zip(&offsets) { + out.extend_from_slice(*sig); + out.extend_from_slice(&(*at as u32).to_be_bytes()); + out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); + } + out.extend_from_slice(&data); + Some(out) +} diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 85590d9d..324c1d26 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -1,6 +1,6 @@ //! Decoding imported image resources (fills, alphas, stencils). -use crate::{FormatError, MAX_IMAGE_SIZE, Result}; +use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result}; /// A decoded image: RGBA as 0..1 floats in the file's own encoding (8/16-bit files stay /// sRGB-encoded; `srgb` says so), row-major, top row first. @@ -15,33 +15,37 @@ pub struct DecodedImage { /// Decode PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR bytes. pub fn decode_image(bytes: &[u8]) -> Result { - decode_image_within(bytes, u64::MAX) + decode_image_within(bytes, MAX_RESOURCE_TEXELS) } /// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the /// header, before any pixel is decoded or allocated. pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result { - let mut reader = - image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })?; // TGA has no magic signature; its decoder validates the header when no format was recognized let format = reader.format().unwrap_or(image::ImageFormat::Tga); reader.set_format(format); - let (width, height) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; + let (width, height) = reader.into_dimensions().map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })?; if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE { return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})"))); } + if u64::from(width) * u64::from(height) > max_texels { return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels"))); } - let image = - crate::guard("image", || image::load_from_memory_with_format(bytes, format).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?; + let image = crate::guard("image", || { + image::load_from_memory_with_format(bytes, format).map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() }) + })?; let srgb = !matches!(image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)); let float_image = image.into_rgba32f(); let (width, height) = float_image.dimensions(); let rgba = float_image.pixels().map(|pixel| pixel.0).collect(); + Ok(DecodedImage { width, height, rgba, srgb }) } @@ -63,15 +67,19 @@ mod tests { #[test] fn decodes_png_and_rejects_garbage() { let mut png = Vec::new(); - let img = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255])); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - let d = decode_image(&png).unwrap(); - assert_eq!((d.width, d.height), (4, 2)); - assert!(d.srgb); - assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3); + let image = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255])); + image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + + let decoded = decode_image(&png).unwrap(); + + assert_eq!((decoded.width, decoded.height), (4, 2)); + assert!(decoded.srgb); + assert!((decoded.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3); assert!(decode_image(b"not an image").is_err()); assert!(decode_image(&png[..png.len() / 2]).is_err()); + let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap(); + assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]); assert!(coverage_png(2, 2, &[0], [255; 3]).is_err()); } @@ -80,11 +88,15 @@ mod tests { fn tga_without_a_magic_signature_decodes_within_the_texel_budget() { let mut bytes = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Tga).unwrap(); + let image = decode_image_within(&bytes, 16).unwrap(); + assert_eq!((image.width, image.height), (4, 4)); assert!((image.rgba[0][1] - 0.2).abs() < 1e-6); assert!(image.srgb); + let header = &bytes[..18]; + assert!(matches!(decode_image_within(header, 15), Err(FormatError::TooLarge(_)))); assert!(decode_image(header).is_err()); } @@ -92,12 +104,25 @@ mod tests { #[test] fn decoding_within_a_texel_limit_refuses_big_images_from_the_header() { let png = { - let mut b = Vec::new(); - image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap(); - b + let mut bytes = Vec::new(); + image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes }; + assert_eq!(decode_image_within(&png, 64).unwrap().width, 8); assert!(matches!(decode_image_within(&png, 63), Err(FormatError::TooLarge(_)))); assert!(decode_image(&png).is_ok()); } + + #[test] + fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() { + // The edge limit permits 16384² but the default resource budget does not + let mut header = [0u8; 18]; + header[2] = 2; + header[12..14].copy_from_slice(&16_384u16.to_le_bytes()); + header[14..16].copy_from_slice(&16_384u16.to_le_bytes()); + header[16] = 24; + + assert!(matches!(decode_image(&header), Err(FormatError::TooLarge(_)))); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 6e57432e..c7309f2e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -95,6 +95,10 @@ pub(crate) fn guard(kind: &'static str, f: impl FnOnce() -> Result) -> Res /// Largest image edge accepted or produced anywhere in this crate. pub const MAX_IMAGE_SIZE: u32 = 16_384; +/// Most texels an imported image resource may decode to by default (8192 × 8192). +/// Larger images are refused from their header before any pixels are decoded. +pub const MAX_RESOURCE_TEXELS: u64 = 1 << 26; + /// Read a whole file, refusing files over `cap` bytes. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { @@ -108,15 +112,64 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { Ok(std::fs::read(path)?) } -/// Write `bytes` to `path` atomically: `.tmp` first, then rename over the target. +/// Create a new temporary file beside `path`, refusing to reuse an existing (possibly symlinked) name. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> { + let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); + let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out"); + + // Bound retries when stale files or concurrent writers occupy candidate names + const MAX_TEMP_ATTEMPTS: u32 = 100; + + for attempt in 0..MAX_TEMP_ATTEMPTS { + let temporary_path = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&temporary_path) { + Ok(file) => return Ok((temporary_path, file)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.into()), + } + } + + Err(FormatError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not create a temporary file"))) +} + +/// Write `bytes` to `path` atomically: a new temporary file first, then rename over the target. #[cfg(not(target_arch = "wasm32"))] pub fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); - let res = std::fs::write(&tmp, bytes).and_then(|_| std::fs::rename(&tmp, path)); - if res.is_err() { - let _ = std::fs::remove_file(&tmp); + use std::io::Write; + + let (temporary_path, mut file) = create_temp(path)?; + let result = file.write_all(bytes).and_then(|_| file.sync_all()); + drop(file); + + let result = result.and_then(|_| std::fs::rename(&temporary_path, path)); + if result.is_err() { + let _ = std::fs::remove_file(&temporary_path); + } + + Ok(result?) +} + +#[cfg(all(test, unix))] +mod atomic_tests { + use super::write_atomic; + + #[test] + fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> { + let directory = std::env::temp_dir().join(format!("tc-atomic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&directory); + std::fs::create_dir_all(&directory)?; + let target = directory.join("out.png"); + let victim = directory.join("victim.txt"); + std::fs::write(&victim, b"safe")?; + std::os::unix::fs::symlink(&victim, directory.join("out.png.tmp"))?; + + write_atomic(&target, b"new").map_err(std::io::Error::other)?; + + assert_eq!(std::fs::read(&victim)?, b"safe"); + assert_eq!(std::fs::read(&target)?, b"new"); + + let _ = std::fs::remove_dir_all(&directory); + Ok(()) } - Ok(res?) } diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs index e7440328..9481ed13 100644 --- a/crates/formats/src/materialx.rs +++ b/crates/formats/src/materialx.rs @@ -1,20 +1,7 @@ -//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification -//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is -//! linked, and nothing is read from any other application. +//! TextureCraft's MaterialX export adapter. //! -//! [`write`] takes a material's name and the texture files an export produced, each tagged with -//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader -//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones -//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a -//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node -//! (OpenGL, +Y up, which is what that node expects). -//! -//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were -//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `` filename token MaterialX defines. -//! Texture file names are relative to the document. - -use std::collections::HashSet; -use std::fmt::Write as _; +//! The shared `craft-materialx` crate owns the MaterialX document writer. This module maps the +//! built-in preset's map names and TextureCraft color spaces to that format-level API. use texturecraft_texel::ColorSpace; @@ -51,7 +38,6 @@ pub const INPUTS: &[(&str, Kind)] = &[ ("height", Kind::Height), ]; -/// The file-name prefix of the built-in OpenPBR preset's maps. const PREFIX: &str = "$mesh_$textureSet_"; /// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`). @@ -59,14 +45,11 @@ const PREFIX: &str = "$mesh_$textureSet_"; pub struct Texture { pub input: String, pub file: String, - /// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...); - /// used for colour inputs only, data maps are always linear. + /// The MaterialX colour space of the file's values; used for color inputs only. pub colorspace: &'static str, } -/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no -/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the -/// specification, which 1.39 readers may not know. +/// The MaterialX colour space of colour maps written in `space`. pub fn colorspace_name(space: ColorSpace) -> &'static str { match space { ColorSpace::Srgb => "srgb_texture", @@ -76,116 +59,28 @@ pub fn colorspace_name(space: ColorSpace) -> &'static str { } } -/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → -/// `base_color`), or None for templates this module has no place for. +/// The OpenPBR input a preset map's file template feeds, or None for unsupported templates. pub fn input_of_template(template: &str) -> Option<&'static str> { let suffix = template.strip_prefix(PREFIX)?; - INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n) -} - -fn kind_of(input: &str) -> Option { - INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k) + INPUTS.iter().find(|(name, _)| *name == suffix).map(|(name, _)| *name) } /// A MaterialX name: letters, digits and underscores, not starting with a digit. -pub fn node_name(s: &str) -> String { - let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); +pub fn node_name(name: &str) -> String { + let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { out.insert(0, '_'); } out } -fn esc(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - c if c.is_control() => out.push(' '), - c => out.push(c), - } - } - out -} - -fn image_name(input: &str) -> String { - format!("image_{}", node_name(input)) -} - -/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes -/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so -/// are repeats of one input (the first wins). +/// The text of a MaterialX OpenPBR document for `name` and the given texture files. pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String { - let base = node_name(name); - let mut seen = HashSet::new(); - let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect(); - let has = |i: &str| tex.iter().any(|(t, _)| t.input == i); - let mut x = String::new(); - let _ = writeln!(x, ""); - let _ = writeln!(x, ""); - - let shader = format!("OPBR_{base}"); - let _ = writeln!(x, " ", esc(&shader)); - for (t, kind) in &tex { - let (ty, node) = match kind { - Kind::Color => ("color3", image_name(&t.input)), - Kind::Float => ("float", image_name(&t.input)), - Kind::Normal => ("vector3", "normalmap".to_owned()), - Kind::Height => continue, - }; - let _ = writeln!(x, " ", t.input); - } - if has("emission_color") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - - for (t, kind) in &tex { - let (ty, space) = match kind { - Kind::Color => ("color3", Some(t.colorspace)), - Kind::Normal => ("vector3", None), - Kind::Float | Kind::Height => ("float", None), - }; - let node = image_name(&t.input); - let _ = writeln!(x, " "); - match space { - Some(space) => { - let _ = writeln!(x, " ", esc(&t.file)); - } - None => { - let _ = writeln!(x, " ", esc(&t.file)); - } - } - let _ = writeln!(x, " "); - } - if has("geometry_normal") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("geometry_normal")); - let _ = writeln!(x, " "); - } - if has("height") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("height")); - let _ = writeln!(x, " "); - let _ = writeln!(x, " "); - } - - let doc = match physical_size_cm { - Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""), - _ => String::new(), - }; - let _ = writeln!(x, " ", esc(&base)); - let _ = writeln!(x, " ", esc(&shader)); - if has("height") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - let _ = writeln!(x, ""); - x + let textures: Vec = textures + .iter() + .map(|texture| craft_materialx::Texture { input: texture.input.clone(), file: texture.file.clone(), colorspace: texture.colorspace.to_owned() }) + .collect(); + craft_materialx::write_open_pbr(name, &textures, physical_size_cm) } #[cfg(test)] @@ -247,7 +142,7 @@ mod tests { assert!(x.contains(want), "missing {want}\n{x}"); } // Data textures carry no colour space, and height is not an OpenPBR input. - assert!(x.contains("value=\"stone_specular_roughness.png\" />")); + assert!(x.contains("value=\"stone_specular_roughness.png\"/>")); assert!(!x.contains("name=\"height\"")); } @@ -265,7 +160,7 @@ mod tests { fn colour_inputs_carry_their_files_space_and_data_inputs_none() { let lin = |input: &str, file: &str| Texture { colorspace: "lin_rec709", ..tex(input, file) }; let x = write("m", &[lin("base_color", "c.exr"), lin("specular_roughness", "r.exr")], None); - assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\" />"), "{x}"); + assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\"/>"), "{x}"); } #[test] @@ -292,7 +187,9 @@ mod tests { assert_eq!(node_name(""), "_"); let x = write("a&\"c", &[tex("base_color", "x\"&<'>..png")], Some([f32::NAN, 1.0])); assert!(balanced(&x.replace("<UDIM>", "UDIM")), "{x}"); - assert!(x.contains("value=\"x"&<'>.<UDIM>.png\"")); + let doc = craft_materialx::Document::parse(x.as_bytes()).unwrap(); + let material = doc.read_material(None).unwrap(); + assert!(material.inputs.iter().any(|(input, value)| input == "base_color" && value == &craft_materialx::Value::Image("x\"&<'>..png".into()))); assert!(!x.contains("doc="), "a non-finite size is left out"); assert!(x.contains("OPBR_a_b___c")); } diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index c8cd8b39..4de6abce 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -1,41 +1,16 @@ -//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF -//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure -//! Rust: no MaterialX library is linked. +//! MaterialX material import adapted to TextureCraft's channel model. //! -//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an -//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft -//! has a channel for into a literal value or an image file: -//! -//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted -//! to linear; a colour given for a scalar channel is averaged); -//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph` -//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and -//! `constant` nodes in between are passed through; -//! - the material's `displacementshader` becomes the height channel; -//! - `uvtiling` of the first tiled image is returned as the UV tiling. -//! -//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning -//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing -//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is. -//! -//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a -//! wiring loop stops at a depth limit, and every failure is an error, never a panic. +//! XML parsing, nodegraph traversal and shader input resolution live in `craft-materialx`. +//! This module maps those format-level values to TextureCraft's channels and color handling. -use std::collections::HashMap; - -use quick_xml::events::{BytesStart, Event}; -use texturecraft_core::Channel; +use texturecraft_core::{Channel, ChannelKind}; use texturecraft_texel::srgb_to_linear; use crate::{FormatError, Result, malformed}; const KIND: &str = "MaterialX document"; /// Largest document read, in bytes. -pub const MAX_BYTES: usize = 16 << 20; -const MAX_DEPTH: usize = 64; -const MAX_ELEMENTS: usize = 200_000; -/// Longest chain of nodes followed from one shader input. -const MAX_HOPS: usize = 16; +pub const MAX_BYTES: usize = craft_materialx::MAX_BYTES; /// What one channel is set from. #[derive(Clone, Debug, PartialEq)] @@ -58,259 +33,40 @@ pub struct Material { pub warnings: Vec, } -// --------------------------------------------------------------------------------------------- -// XML. - -#[derive(Default)] -struct El { - name: String, - attrs: Vec<(String, String)>, - children: Vec, +fn channel(shader: craft_materialx::Shader, input: &str) -> Option { + use craft_materialx::Shader::{GltfPbr, OpenPbr, StandardSurface}; + Some(match (shader, input) { + (OpenPbr, "base_color") | (StandardSurface, "base_color") | (GltfPbr, "base_color") => Channel::BaseColor, + (OpenPbr, "base_metalness") | (StandardSurface, "metalness") | (GltfPbr, "metallic") => Channel::Metallic, + (OpenPbr, "specular_roughness") | (StandardSurface, "specular_roughness") | (GltfPbr, "roughness") => Channel::Roughness, + (OpenPbr, "geometry_normal") | (StandardSurface, "normal") | (GltfPbr, "normal") => Channel::Normal, + (OpenPbr, "geometry_opacity") | (StandardSurface, "opacity") | (GltfPbr, "alpha") => Channel::Opacity, + (OpenPbr, "emission_color") | (StandardSurface, "emission_color") | (GltfPbr, "emission") => Channel::Emissive, + (OpenPbr, "coat_weight") | (StandardSurface, "coat") | (GltfPbr, "clearcoat") => Channel::CoatWeight, + (OpenPbr, "coat_roughness") | (StandardSurface, "coat_roughness") | (GltfPbr, "clearcoat_roughness") => Channel::CoatRoughness, + (OpenPbr, "geometry_coat_normal") | (StandardSurface, "coat_normal") | (GltfPbr, "clearcoat_normal") => Channel::CoatNormal, + (OpenPbr, "fuzz_weight") | (StandardSurface, "sheen") => Channel::SheenWeight, + (OpenPbr, "fuzz_color") | (StandardSurface, "sheen_color") | (GltfPbr, "sheen_color") => Channel::SheenColor, + (OpenPbr, "fuzz_roughness") | (StandardSurface, "sheen_roughness") | (GltfPbr, "sheen_roughness") => Channel::SheenRoughness, + (OpenPbr, "specular_roughness_anisotropy") | (StandardSurface, "specular_anisotropy") => Channel::AnisotropyLevel, + (OpenPbr, "transmission_weight") | (StandardSurface, "transmission") | (GltfPbr, "transmission") => Channel::Transmission, + (OpenPbr, "subsurface_weight") | (StandardSurface, "subsurface") => Channel::ScatterWeight, + (GltfPbr, "occlusion") => Channel::AmbientOcclusion, + _ => return None, + }) } -impl El { - fn attr(&self, k: &str) -> Option<&str> { - self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) +fn constant(channel: Channel, values: &[f32], colorspace: Option<&str>) -> [f32; 3] { + let mut values = values.to_vec(); + if let Some(space) = colorspace + && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) + && values.len() >= 3 + { + values.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); } - - /// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it). - fn input(&self, name: &str) -> Option<&El> { - self.children.iter().find(|c| c.attr("name") == Some(name)) - } -} - -fn element(e: &BytesStart) -> El { - let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); - let attrs = e - .attributes() - .with_checks(false) - .flatten() - .map(|a| { - (text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned())) - }) - .collect(); - El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() } -} - -fn parse_xml(bytes: &[u8]) -> Result { - let mut reader = quick_xml::Reader::from_reader(bytes); - let mut stack = vec![El::default()]; - let mut count = 0usize; - loop { - let event = reader.read_event().map_err(|e| malformed(KIND, e))?; - if matches!(event, Event::Start(_) | Event::Empty(_)) { - count += 1; - if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { - return Err(FormatError::TooLarge(format!( - "the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}" - ))); - } - } - match event { - Event::Start(e) => stack.push(element(&e)), - Event::Empty(e) => { - if let Some(parent) = stack.last_mut() { - parent.children.push(element(&e)); - } - } - Event::End(_) => { - let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?; - if let Some(parent) = stack.last_mut() { - parent.children.push(el); - } - } - Event::Eof => break, - _ => {} - } - } - match (stack.pop(), stack.is_empty()) { - (Some(root), true) => Ok(root), - _ => Err(malformed(KIND, "unclosed elements at the end of the document")), - } -} - -// --------------------------------------------------------------------------------------------- -// Shader input tables: (shader input, channel). `kind` says how to read the value. - -#[derive(Clone, Copy, PartialEq)] -enum Shader { - OpenPbr, - Standard, - Gltf, -} - -const OPEN_PBR: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("base_metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("geometry_normal", Channel::Normal), - ("geometry_opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat_weight", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("geometry_coat_normal", Channel::CoatNormal), - ("fuzz_weight", Channel::SheenWeight), - ("fuzz_color", Channel::SheenColor), - ("fuzz_roughness", Channel::SheenRoughness), - ("specular_roughness_anisotropy", Channel::AnisotropyLevel), - ("transmission_weight", Channel::Transmission), - ("subsurface_weight", Channel::ScatterWeight), -]; - -const STANDARD: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("coat_normal", Channel::CoatNormal), - ("sheen", Channel::SheenWeight), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("specular_anisotropy", Channel::AnisotropyLevel), - ("transmission", Channel::Transmission), - ("subsurface", Channel::ScatterWeight), -]; - -const GLTF: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metallic", Channel::Metallic), - ("roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("alpha", Channel::Opacity), - ("emission", Channel::Emissive), - ("occlusion", Channel::AmbientOcclusion), - ("clearcoat", Channel::CoatWeight), - ("clearcoat_roughness", Channel::CoatRoughness), - ("clearcoat_normal", Channel::CoatNormal), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("transmission", Channel::Transmission), -]; - -// --------------------------------------------------------------------------------------------- -// Resolving what feeds an input. - -struct Doc<'a> { - root: &'a El, - /// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`). - nodes: HashMap, - /// Each nodegraph's outputs: `graph/output` to the node name inside (qualified). - outputs: HashMap, - tiling: Option<[f32; 2]>, - warnings: Vec, -} - -enum Found { - Constant(Vec), - Image(String), - None, -} - -fn numbers(text: &str) -> Option> { - let v: Option> = text.split(',').map(|p| p.trim().parse::().ok().filter(|f| f.is_finite())).collect(); - v.filter(|v| !v.is_empty() && v.len() <= 4) -} - -impl<'a> Doc<'a> { - fn new(root: &'a El) -> Doc<'a> { - let mut nodes = HashMap::new(); - let mut outputs = HashMap::new(); - for c in &root.children { - match (c.name.as_str(), c.attr("name")) { - ("nodegraph", Some(g)) => { - for n in &c.children { - let Some(name) = n.attr("name") else { continue }; - if n.name == "output" { - if let Some(from) = n.attr("nodename") { - outputs.insert(format!("{g}/{name}"), format!("{g}/{from}")); - } - } else { - nodes.insert(format!("{g}/{name}"), n); - } - } - } - (_, Some(name)) => { - nodes.insert(name.to_owned(), c); - } - _ => {} - } - } - Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() } - } - - /// What `input` (an `` element of a node) resolves to; `scope` is the nodegraph the - /// node lives in, if any. - fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found { - if hops > MAX_HOPS { - self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); - return Found::None; - } - if let Some(v) = input.attr("value") { - return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n))); - } - let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) { - (Some(g), out, _) => { - let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned))); - out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned()) - } - (None, _, Some(n)) => { - Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned())) - } - _ => None, - }; - let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None }; - let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned()); - let scope = scope.as_deref(); - match node.name.as_str() { - "tiledimage" | "image" => { - let Some(file) = node.input("file").and_then(|f| f.attr("value")) else { - self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or(""))); - return Found::None; - }; - let prefix = - [node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next(); - if self.tiling.is_none() - && let Some(t) = - node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) - { - // The range a fill's UV scale accepts (`layer.fill.projection`). - self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]); - } - Found::Image(format!("{}{file}", prefix.unwrap_or(""))) - } - "normalmap" | "convert" => match node.input("in") { - Some(i) => self.resolve(i, scope, hops + 1), - None => Found::None, - }, - "constant" => match node.input("value") { - Some(v) => self.resolve(v, scope, hops + 1), - None => Found::None, - }, - other => { - self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or(""))); - Found::None - } - } - } - - /// Literal values tagged with an sRGB colour space are converted to linear. - fn tag(&self, input: &El, mut n: Vec) -> Vec { - let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or(""); - if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 { - n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); - } - n - } -} - -fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { - match (channel.kind(), n) { + match (channel.kind(), values.as_slice()) { (_, [a]) => [*a; 3], - (texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], + (ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], (_, [r, g, b, ..]) => { let mean = (r + g + b) / 3.0; [mean; 3] @@ -319,9 +75,11 @@ fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { } } -/// The literal number of `input`, if it is one. -fn literal(shader: &El, name: &str) -> Option { - shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied()) +fn app_value(channel: Channel, value: craft_materialx::Value) -> Value { + match value { + craft_materialx::Value::Constant { values, colorspace } => Value::Constant(constant(channel, &values, colorspace.as_deref())), + craft_materialx::Value::Image(file) => Value::Image(file), + } } /// Read the material called `material` (default: the first) from a `.mtlx` document. @@ -330,79 +88,30 @@ pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result } fn read_inner(bytes: &[u8], material: Option<&str>) -> Result { - if bytes.len() > MAX_BYTES { - return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20))); - } - let top = parse_xml(bytes)?; - let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no element"))?; - let mut doc = Doc::new(root); - let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect(); - let mat = match material { - Some(name) => materials - .iter() - .copied() - .find(|m| m.attr("name") == Some(name)) - .ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?, - None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?, - }; - let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() }; - let shader = mat - .input("surfaceshader") - .and_then(|i| i.attr("nodename")) - .and_then(|n| doc.nodes.get(n).copied()) - .ok_or_else(|| malformed(KIND, "the material has no surface shader"))?; - let (kind, table) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR), - "standard_surface" => (Shader::Standard, STANDARD), - "gltf_pbr" => (Shader::Gltf, GLTF), - other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))), - }; - // Emission is off by default in OpenPBR and standard_surface. - let emits = match kind { - Shader::OpenPbr => { - shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0)) - } - Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)), - Shader::Gltf => true, - }; - let weight = match kind { - Shader::OpenPbr => literal(shader, "base_weight"), - Shader::Standard => literal(shader, "base"), - Shader::Gltf => None, - }; - if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) { - doc.warnings.push("the base weight isn't 1; it was ignored".into()); - } - for &(input, channel) in table { - let Some(el) = shader.input(input) else { continue }; - if channel == Channel::Emissive && !emits && kind != Shader::Gltf { - doc.warnings.push(format!("{input} was skipped: the shader's emission is 0")); - continue; - } - match doc.resolve(el, None, 0) { - Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))), - Found::Image(f) => out.channels.push((channel, Value::Image(f))), - Found::None => {} + let document = craft_materialx::Document::parse(bytes).map_err(map_error)?; + let shared = document.read_material(material).map_err(map_error)?; + let mut channels = Vec::new(); + for (input, value) in shared.inputs { + if let Some(channel) = channel(shared.shader, &input) { + channels.push((channel, app_value(channel, value))); } } - // The displacement shader's `displacement` input is the height. - if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied()) - && let Some(i) = d.input("displacement") - { - match doc.resolve(i, None, 0) { - Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))), - Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))), - Found::None => {} - } + if let Some(value) = shared.displacement { + channels.push((Channel::Height, app_value(Channel::Height, value))); } - out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]); - out.warnings = doc.warnings; - Ok(out) + Ok(Material { name: shared.name, channels, uv_tiling: shared.uv_tiling, warnings: shared.warnings }) } -fn names(materials: &[&El]) -> String { - let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect(); - if n.is_empty() { "none".into() } else { n.join(", ") } +fn map_error(error: craft_materialx::Error) -> FormatError { + use craft_materialx::Error; + match error { + Error::Xml(xml) if xml.is_limit() => FormatError::TooLarge(xml.to_string()), + Error::MissingMaterial(name) => FormatError::Invalid(format!("no material named {name:?}")), + Error::Unsupported(message) => FormatError::Unsupported(message), + Error::Malformed(message) => malformed(KIND, message), + Error::Root => malformed(KIND, "no element"), + Error::Xml(other) => malformed(KIND, other), + } } #[cfg(test)] @@ -439,6 +148,19 @@ mod tests { m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v) } + #[test] + fn displacement_only_image_supplies_uv_tiling() { + let xml = br#" + + + + + "#; + let material = read_materialx(xml, None).unwrap(); + assert_eq!(get(&material, Channel::Height), Some(&Value::Image("height.png".into()))); + assert_eq!(material.uv_tiling, [4.0, 2.0]); + } + #[test] fn open_pbr_inputs_become_channels() { let m = read_materialx(OPENPBR.as_bytes(), None).unwrap(); @@ -456,6 +178,24 @@ mod tests { assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale"); } + #[test] + fn nodegraph_input_without_output_uses_the_first_output() { + let xml = r#" + + + + + + + + +"#; + for _ in 0..50 { + let material = read_materialx(xml.as_bytes(), None).unwrap(); + assert_eq!(get(&material, Channel::BaseColor), Some(&Value::Image("first.png".into()))); + } + } + #[test] fn emission_is_off_unless_the_shader_emits() { let x = OPENPBR.replace(r#""#, ""); diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 55b6f6ee..5040f320 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -1,11 +1,11 @@ //! MaterialCraft portable materials (`.mcmat`, read only): a zip with `material.json` (the //! manifest: maps by usage, exposed parameters, image inputs, presets), `maps/.png` -//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the source -//! `.mcraft` package. TextureCraft keeps its own reader (the apps share the format, not code). +//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the +//! source package. The shared reader handles the portable container and manifest. //! //! Also the 16-bit PNG encoder that hands baked mesh maps to MaterialCraft as graph inputs. -use std::io::{Cursor, Read}; +use std::io::Cursor; use serde::Deserialize; use texturecraft_core::{LinkParam, LinkPreset}; @@ -16,10 +16,13 @@ use crate::{FormatError, Result}; pub const MCMAT_EXT: &str = "mcmat"; /// MaterialCraft's package extension. pub const MCRAFT_EXT: &str = "mcraft"; -const FORMAT: &str = "craft-material"; -const VERSION: u32 = 1; +const VERSION: u32 = 2; /// Largest entry read (maps are at most 8192² × 16 bits, compressed). const MAX_ENTRY: u64 = 512 << 20; +/// Most map entries one manifest may name (a material has at most nine usages). +const MAX_MAPS: usize = 64; +/// Largest total payload read from one `.mcmat`: maps and source together (audit: TextureCraft #4). +const MAX_TOTAL: u64 = 1 << 30; const KIND: &str = "MaterialCraft material"; #[derive(Clone, Debug, PartialEq, Deserialize)] @@ -66,42 +69,76 @@ fn malformed(msg: impl Into) -> FormatError { FormatError::Malformed { kind: KIND, msg: msg.into() } } -/// Read `.mcmat` bytes. +fn shared_error(error: craft_mcmat::Error) -> FormatError { + match error { + craft_mcmat::Error::Version(version) => FormatError::Unsupported(format!("{KIND} version {version} (this version reads up to {VERSION})")), + craft_mcmat::Error::Limit(message) => malformed(message), + craft_mcmat::Error::Archive(ref archive) if archive.is_limit() => FormatError::TooLarge(error.to_string()), + other => malformed(other.to_string()), + } +} + +/// Read `.mcmat` bytes within TextureCraft's existing per-entry and total payload limits. pub fn read_mcmat(bytes: &[u8]) -> Result { - let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| malformed(e.to_string()))?; - let mut read = |name: &str| -> Result> { - let mut out = Vec::new(); - let f = z.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?; - f.take(MAX_ENTRY + 1).read_to_end(&mut out).map_err(|e| malformed(format!("{name}: {e}")))?; - if out.len() as u64 > MAX_ENTRY { - return Err(FormatError::TooLarge(name.to_string())); - } - Ok(out) + let limits = craft_mcmat::Limits { + min_version: 0, + max_version: VERSION, + max_entries: 100_000, + max_maps: MAX_MAPS, + max_manifest_bytes: MAX_ENTRY, + max_entry_bytes: MAX_ENTRY, + max_total_bytes: MAX_TOTAL, }; - let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|e| malformed(format!("material.json: {e}")))?; - if manifest.format != FORMAT { - return Err(malformed(format!("format `{}`", manifest.format))); - } - if manifest.version > VERSION { - return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version))); - } - let maps = manifest.maps.iter().map(|m| Ok((m.usage.clone(), read(&m.file)?))).collect::>>()?; - let source = read(&manifest.source)?; + let mut archive = craft_mcmat::Material::open(bytes, limits).map_err(shared_error)?; + // Consume the JSON values rather than cloning the entire untrusted manifest into a second tree. + let parameters = std::mem::take(&mut archive.manifest.parameters) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let inputs = std::mem::take(&mut archive.manifest.inputs) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let presets = std::mem::take(&mut archive.manifest.presets) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let shared = &archive.manifest; + let manifest = Manifest { + format: shared.format.clone(), + version: shared.version, + name: shared.name.clone(), + graph: shared.graph.clone(), + size: shared.size, + maps: shared.maps.iter().map(|m| MapEntry { usage: m.usage.clone(), file: m.file.clone() }).collect(), + parameters, + inputs, + presets, + source: shared.source.clone(), + }; + let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), archive.read(&map.file).map_err(shared_error)?))).collect::>>()?; + let source = archive.read_source().map_err(shared_error)?; Ok(PortableMaterial { manifest, maps, source }) } -/// Whether `bytes` are a zip holding `entry` (`material.json`: a portable material, -/// `package.json`: a MaterialCraft package). -fn zip_has(bytes: &[u8], entry: &str) -> bool { - zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(entry).is_ok()) -} - +/// Whether `bytes` contain a portable material manifest within the ZIP entry limit. pub fn is_mcmat(bytes: &[u8]) -> bool { - zip_has(bytes, "material.json") + craft_mcmat::is_material(bytes, 100_000) } pub fn is_mcraft(bytes: &[u8]) -> bool { - zip_has(bytes, "package.json") + let Ok(mut archive) = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 100_000, max_total_bytes: 0 }) else { return false }; + // A portable material may itself contain source.sbs, so it is not a source archive. + if archive.has_duplicate_names() || archive.contains("material.json") { + return false; + } + if archive.contains("package.json") { + return true; + } + (0..archive.len()).any(|i| archive.entry_name(i).ok().flatten().is_some_and(|name| !name.contains('/') && name.to_ascii_lowercase().ends_with(".sbs"))) } /// A baked mesh map (`components` floats per texel, 0..1, rows top first) as a 16-bit PNG @@ -131,13 +168,14 @@ mod tests { /// A `.mcmat` as MaterialCraft writes it (see its `formats/src/material.rs`). pub(crate) fn sample(version: u32) -> Vec { + let source = if version >= 2 { "source.sbs" } else { "source.mcraft" }; let manifest = serde_json::json!({ "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}], "parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0.0, "max": 1.0, "value": {"t": "float", "v": 0.25}}], "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}], - "source": "source.mcraft", "futureField": true + "source": source, "futureField": true }); let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -145,7 +183,7 @@ mod tests { z.write_all(manifest.to_string().as_bytes()).unwrap(); z.start_file("maps/baseColor.png", o).unwrap(); z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); - z.start_file("source.mcraft", o).unwrap(); + z.start_file(source, o).unwrap(); z.write_all(b"pkg").unwrap(); z.finish().unwrap().into_inner() } @@ -153,20 +191,55 @@ mod tests { #[test] fn reads_manifest_maps_and_source() { let bytes = sample(1); + assert!(is_mcmat(&bytes) && !is_mcraft(&bytes)); - let m = read_mcmat(&bytes).unwrap(); - assert_eq!(m.manifest.graph, "Brick_wall"); - assert_eq!(m.manifest.parameters[0].id, "wear"); - assert_eq!(m.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25})); - assert_eq!(m.manifest.presets[0].name, "Worn"); - assert_eq!(m.manifest.inputs[0].identifier, "curvature"); - assert_eq!(m.maps[0].0, "baseColor"); - assert_eq!(crate::decode_image(&m.maps[0].1).unwrap().width, 4); - assert_eq!(m.source, b"pkg"); - assert!(matches!(read_mcmat(&sample(2)), Err(FormatError::Unsupported(_)))); + let material = read_mcmat(&bytes).unwrap(); + + assert_eq!(material.manifest.graph, "Brick_wall"); + assert_eq!(material.manifest.parameters[0].id, "wear"); + assert_eq!(material.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25})); + assert_eq!(material.manifest.presets[0].name, "Worn"); + assert_eq!(material.manifest.inputs[0].identifier, "curvature"); + assert_eq!(material.maps[0].0, "baseColor"); + assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4); + assert_eq!(material.source, b"pkg"); + let current = read_mcmat(&sample(2)).unwrap(); + assert_eq!(current.manifest.source, "source.sbs"); + assert_eq!(current.source, b"pkg"); + assert!(matches!(read_mcmat(&sample(3)), Err(FormatError::Unsupported(_)))); assert!(read_mcmat(b"junk").is_err()); } + #[test] + fn recognizes_both_generations_of_source_archive_without_confusing_portable_materials() { + for entry in ["package.json", "package.sbs"] { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(b"source").unwrap(); + let bytes = zip.finish().unwrap().into_inner(); + assert!(is_mcraft(&bytes), "{entry}"); + } + assert!(!is_mcraft(&sample(2)), "a portable material contains source.sbs too"); + } + + #[test] + fn an_unbounded_map_list_is_refused() { + let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect(); + let manifest = serde_json::json!({"format": craft_mcmat::FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); + let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default(); + archive.start_file("material.json", options).unwrap(); + archive.write_all(manifest.to_string().as_bytes()).unwrap(); + archive.start_file("maps/baseColor.png", options).unwrap(); + archive.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); + archive.start_file("source.mcraft", options).unwrap(); + archive.write_all(b"pkg").unwrap(); + + let result = read_mcmat(&archive.finish().unwrap().into_inner()); + + assert!(matches!(result, Err(FormatError::Malformed { .. }))); + } + #[test] fn mesh_maps_encode_as_16_bit() { let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap(); diff --git a/crates/formats/src/mesh_export/usdc.rs b/crates/formats/src/mesh_export/usdc.rs index 35900e28..b071e215 100644 --- a/crates/formats/src/mesh_export/usdc.rs +++ b/crates/formats/src/mesh_export/usdc.rs @@ -154,7 +154,7 @@ impl Writer { UsdValue::Ints(v) if v.len() >= codec::MIN_COMPRESSED_ARRAY => { let at = self.offset(); self.out.extend_from_slice(&(v.len() as u64).to_le_bytes()); - self.ints(&v.iter().map(|&i| i64::from(i)).collect::>()); + self.ints(&v.iter().map(|&i| i64::from(i)).collect::>())?; rep(ty::INT, codec::IS_ARRAY | codec::IS_COMPRESSED, at) } UsdValue::Ints(v) => self.raw_array(ty::INT, v.len(), v.iter().flat_map(|i| i.to_le_bytes())), @@ -174,10 +174,11 @@ impl Writer { } /// Compressed integers: their compressed size, then the LZ4-framed coding. - fn ints(&mut self, v: &[i64]) { - let comp = codec::compress(&codec::encode_ints(v, 4)); + fn ints(&mut self, v: &[i64]) -> Result<()> { + let comp = codec::compress(&codec::encode_ints(v, 4)?)?; self.out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); self.out.extend_from_slice(&comp); + Ok(()) } fn spec(&mut self, path: usize, kind: i64, fields: Vec<(&str, u64)>) { @@ -303,7 +304,7 @@ impl Writer { self.out.extend_from_slice(&(v as u64).to_le_bytes()); } - fn sections(&mut self) { + fn sections(&mut self) -> Result<()> { let mut toc = Vec::new(); let start = self.offset(); let mut raw = Vec::new(); @@ -311,7 +312,7 @@ impl Writer { raw.extend_from_slice(t.as_bytes()); raw.push(0); } - let comp = codec::compress(&raw); + let comp = codec::compress(&raw)?; self.u64(self.tokens.len()); self.u64(raw.len()); self.u64(comp.len()); @@ -327,9 +328,9 @@ impl Writer { let start = self.offset(); let fields = std::mem::take(&mut self.fields); self.u64(fields.len()); - self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>()); + self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>())?; let reps: Vec = fields.iter().flat_map(|f| f.1.to_le_bytes()).collect(); - let comp = codec::compress(&reps); + let comp = codec::compress(&reps)?; self.u64(comp.len()); self.out.extend_from_slice(&comp); self.section(&mut toc, "FIELDS", start); @@ -337,7 +338,7 @@ impl Writer { let start = self.offset(); let sets = std::mem::take(&mut self.fieldsets); self.u64(sets.len()); - self.ints(&sets); + self.ints(&sets)?; self.section(&mut toc, "FIELDSETS", start); let start = self.offset(); @@ -345,7 +346,7 @@ impl Writer { self.u64(self.paths.len()); self.u64(self.paths.len()); for column in &table { - self.ints(column); + self.ints(column)?; } self.section(&mut toc, "PATHS", start); @@ -353,7 +354,7 @@ impl Writer { let specs = std::mem::take(&mut self.specs); self.u64(specs.len()); for k in 0..3 { - self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>()); + self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>())?; } self.section(&mut toc, "SPECS", start); @@ -371,6 +372,7 @@ impl Writer { if let Some(slot) = self.out.get_mut(16..24) { slot.copy_from_slice(&toc_at.to_le_bytes()); } + Ok(()) } } @@ -400,9 +402,9 @@ impl Writer { Ok(()) } - fn finish(mut self) -> Vec { - self.sections(); - self.out + fn finish(mut self) -> Result> { + self.sections()?; + Ok(self.out) } } @@ -413,7 +415,7 @@ pub(crate) fn write(layer: &UsdLayer) -> Result> { w.add_prim_paths(0, "/", root); w.root_spec(&root.name)?; w.prim_specs(&format!("/{}", root.name), root)?; - Ok(w.finish()) + w.finish() } #[cfg(test)] @@ -504,7 +506,7 @@ mod tests { for (path, value) in attrs.into_iter().zip([points, counts, indices]) { w.spec(path, SPEC_ATTRIBUTE, vec![("default", value)]); } - let bytes = w.finish(); + let bytes = w.finish().unwrap(); let m = crate::import_mesh_bytes("crafted.usdc", &bytes).unwrap().mesh; assert_eq!(m.triangle_count(), 1, "the class prim itself is not drawn"); diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index fd9a7f46..e2abf0be 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -217,7 +217,7 @@ impl<'a> Ogawa<'a> { let value_bytes = match property.pod { 0..=2 => 1, - 3 | 4 => 2, + 3 | 4 | 9 => 2, 5 | 6 | 10 => 4, 7 | 8 | 11 => 8, other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))), @@ -233,6 +233,7 @@ impl<'a> Ogawa<'a> { 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(), 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + 9 => raw.as_chunks::<2>().0.iter().map(|c| half::f16::from_bits(u16::from_le_bytes(*c)).to_f64()).collect(), 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), }) @@ -280,19 +281,30 @@ fn read_inner(bytes: &[u8]) -> Result { if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) { return Err(malformed(KIND, "the archive group does not have the Alembic layout")); } - // Indexed metadata: a u8 length before each string. let block = o.data(root[5])?; - let mut c = Cursor { b: block, pos: 0 }; - while c.pos < block.len() { - let n = c.u8()? as usize; - o.indexed_meta.push(c.string(n)?); - } + read_indexed_meta(block, &mut o.indexed_meta)?; let mut sink = PolygonSink::default(); let mut walk = Walk { o, sink: &mut sink, visits: 0 }; walk.object(root[2], Mat4::IDENTITY, "", 0)?; Ok(sink.finish()) } +/// The most indexed metadata entries that can ever be used: objects and properties refer to one +/// with a single byte, and 0xff already means "stored inline", so only 0 to 254 are reachable. +const MAX_INDEXED_META: usize = 255; + +/// Indexed metadata: a u8 length before each string. `out` starts with the empty entry 0. Reading +/// stops once `out` holds [`MAX_INDEXED_META`] entries, because no later entry can be referred to +/// and an empty one costs a whole `String` in memory for one byte of file. +fn read_indexed_meta(block: &[u8], out: &mut Vec) -> Result<()> { + let mut c = Cursor { b: block, pos: 0 }; + while c.pos < block.len() && out.len() < MAX_INDEXED_META { + let n = c.u8()? as usize; + out.push(c.string(n)?); + } + Ok(()) +} + struct Walk<'a, 'b> { o: Ogawa<'a>, sink: &'b mut PolygonSink, @@ -542,7 +554,7 @@ impl Walk<'_, '_> { Vec2::ZERO } }); - corners.push(Corner { p: *p, n, uv }); + corners.push(Corner { p: *p, n, uv, color: None }); } k = end; if !keep_order { diff --git a/crates/formats/src/mesh_import/abc/tests.rs b/crates/formats/src/mesh_import/abc/tests.rs index dfba3ba9..92f18620 100644 --- a/crates/formats/src/mesh_import/abc/tests.rs +++ b/crates/formats/src/mesh_import/abc/tests.rs @@ -243,6 +243,38 @@ fn strip_alone_keeps_uvs_flipped_to_v_down() { } } +#[test] +fn half_float_uvs_import_without_losing_values() { + let mut a = Abc { w: Writer::new() }; + let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0])); + let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2])); + let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3])); + let uv_bytes: Vec = [0u16, 0, 0x3800, 0x3c00, 0x3c00, 0].iter().flat_map(|x| x.to_le_bytes()).collect(); + let uv = a.array("uv", "", 9, 2, &uv_bytes); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv]); + let mesh = a.object(vec![geom], &[]); + let top = a.object(vec![], &[("m", "", mesh)]); + let imported = crate::import_mesh_bytes("m.abc", &a.archive(top, &["schema=AbcGeom_PolyMesh_v1"])).unwrap(); + assert!(!imported.report.uvs_generated); + for (p, uv) in imported.mesh.positions.iter().zip(&imported.mesh.uvs) { + assert_eq!(*uv, texturecraft_geom::glam::Vec2::new(p.x, 1.0 - p.y)); + } +} + +#[test] +fn half_float_values_preserve_special_values() { + let mut a = Abc { w: Writer::new() }; + let raw: Vec = [0xc000u16, 0x0001, 0x7c00, 0x7e00].iter().flat_map(|x| x.to_le_bytes()).collect(); + let p = a.array("values", "", 9, 1, &raw); + let property = Prop { name: p.name.into(), meta: p.meta, kind: PropKind::Array, pod: 9, extent: 1, group: p.group }; + let mut ogawa = Ogawa { b: &a.w.b, budget: MAX_DECODED_BYTES, indexed_meta: Vec::new() }; + let values = ogawa.values(&property).unwrap(); + assert_eq!(values[0], -2.0); + assert_eq!(values[1], 2f64.powi(-24)); + assert_eq!(values[2], f64::INFINITY); + assert!(values[3].is_nan()); +} + #[test] fn hdf5_and_garbage_are_clear_errors() { let e = read(b"\x89HDF\r\n\x1a\n rest of an hdf5 file").err().unwrap().to_string(); @@ -291,3 +323,29 @@ fn self_referencing_groups_are_bounded() { let bytes = a.archive(at, &[]); assert!(read(&bytes).is_err()); } + +#[test] +fn indexed_metadata_stops_at_the_entries_a_byte_can_index() { + // One real entry followed by a million empty ones: a byte each in the file, a `String` each + // in memory, and no index past 254 can be used anyway. + let mut block = vec![3, b'a', b'b', b'c']; + block.extend(std::iter::repeat_n(0u8, 1_000_000)); + let mut kept = vec![String::new()]; + read_indexed_meta(&block, &mut kept).unwrap(); + assert_eq!(kept.len(), MAX_INDEXED_META); + assert_eq!(kept.get(1).map(String::as_str), Some("abc")); + + // The mesh schema comes from metadata index 1 even when the table has unreachable entries. + let mut a = Abc { w: Writer::new() }; + let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0])); + let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2])); + let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3])); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc]); + let mesh = a.object(vec![geom], &[]); + let top = a.object(vec![], &[("tri", "", mesh)]); + let mut metas = vec!["schema=AbcGeom_PolyMesh_v1"]; + metas.extend(std::iter::repeat_n("", 5_000)); + let raw = read(&a.archive(top, &metas)).unwrap(); + assert_eq!(raw.positions, [Vec3::X, Vec3::Y, Vec3::ZERO]); + assert_eq!(raw.groups, vec![(DEFAULT_MATERIAL.into(), "tri".into(), vec![0, 1, 2])]); +} diff --git a/crates/formats/src/mesh_import/dae.rs b/crates/formats/src/mesh_import/dae.rs index d23ea61b..bb104455 100644 --- a/crates/formats/src/mesh_import/dae.rs +++ b/crates/formats/src/mesh_import/dae.rs @@ -356,6 +356,7 @@ fn add_geometry(d: &mut Doc, sink: &mut PolygonSink, geom: &El, m: Mat4, bind: & p: m.transform_point3(Vec3::from(pos)), n: n.map(|n| nm * Vec3::from(n)), uv: t.map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } next = next.saturating_add(size); diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 5e975ba2..58a01aea 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -1,841 +1,211 @@ -//! FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib-compressed arrays) and -//! ASCII: mesh geometry with normals, UVs and per-polygon materials from the layer elements, every -//! Model's transform and parent hierarchy, and the file's unit and axis system (converted to -//! meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of -//! numbering them and lists properties in `Properties60`; both read into the same scene. -//! Materials bring their diffuse color and, when the file embeds it (a Video's `Content`), the -//! diffuse texture (for high-poly color map bakes); a texture kept as a file beside the FBX comes -//! along when the FBX is packaged with it ([`package`]: a stored zip of the FBX first and the -//! files under their paths below its folder, which [`read`] opens like the FBX). Camera Models become the file's cameras (lens -//! from their camera NodeAttribute, or the Model's own properties in FBX 6). - -use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use std::io::Read as _; - -use base64::Engine as _; -use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; - -use super::external::below; -use super::{ - Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh, check_vertices, lens_fov, zip_entry, -}; +//! FBX scene import through the shared bounded reader. +use super::{Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh}; use crate::{FormatError, Result, malformed}; - +use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; const KIND: &str = "FBX"; -const MAGIC: &[u8] = b"Kaydara FBX Binary \0"; -/// A zip package of an FBX and its texture files ([`package`]). -const ZIP_MAGIC: &[u8] = b"PK\x03\x04"; -/// First FBX version with the object/connection layout read here (6.0). -const MIN_VERSION: i64 = 6000; -/// Deepest node nesting (and Model parent chain) followed. -const MAX_DEPTH: usize = 64; -/// Memory budget for parsed nodes and properties (arrays are held as f64). -const MAX_DECODED_BYTES: usize = 1 << 31; -/// Approximate memory charged per node and per scalar property. -const NODE_COST: usize = 96; -const PROP_COST: usize = 32; - -enum Prop { - I(i64), - F(f64), - S(String), - /// Binary data (`R`), such as an embedded image. - Raw(Vec), - Arr(Vec), -} - -impl Prop { - fn num(&self) -> Option { - match self { - Prop::I(v) => Some(*v as f64), - Prop::F(v) => Some(*v), - _ => None, - } - } -} - -struct Node { - name: String, - props: Vec, - children: Vec, -} - -impl Node { - fn child(&self, name: &str) -> Option<&Node> { - self.children.iter().find(|c| c.name == name) - } - - fn all<'a>(&'a self, name: &'a str) -> impl Iterator { - self.children.iter().filter(move |c| c.name == name) - } - - fn int_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(*v), - _ => None, - } - } - - /// Object id: the number (7.x) or the `Class::Name` string (6.x). - fn id_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(v.to_string()), - Some(Prop::S(s)) if !s.is_empty() => Some(s.clone()), - _ => None, - } - } - - /// An object's name: after its id (7.x) or the id itself (6.x). - fn object_name(&self) -> &str { - clean_name(if self.int_at(0).is_some() { self.str_at(1) } else { self.str_at(0) }) - } - - /// An object's class (`Mesh`, `Camera`, …): after its name. - fn class(&self) -> &str { - self.str_at(if self.int_at(0).is_some() { 2 } else { 1 }) - } - - fn str_at(&self, i: usize) -> &str { - match self.props.get(i) { - Some(Prop::S(s)) => s, - _ => "", - } - } - - fn child_str(&self, name: &str) -> &str { - self.child(name).map_or("", |c| c.str_at(0)) - } - - /// Embedded file bytes of a Video: binary data, or base64 text in ASCII files. - fn content(&self) -> Option> { - let c = self.child("Content")?; - let bytes = match c.props.first()? { - Prop::Raw(b) => b.clone(), - _ => { - let text: String = c.props.iter().filter_map(|p| if let Prop::S(s) = p { Some(s.as_str()) } else { None }).collect(); - base64::engine::general_purpose::STANDARD.decode(text.trim()).ok()? - } - }; - (!bytes.is_empty()).then_some(bytes) - } - - /// Array payload: a binary array, an ASCII `*N { a: ... }` block or a bare value list. - fn arr(&self) -> Cow<'_, [f64]> { - if let Some(Prop::Arr(a)) = self.props.first() { - return Cow::Borrowed(a); - } - if let Some(a) = self.child("a") { - return a.arr(); - } - Cow::Owned(self.props.iter().filter_map(Prop::num).collect()) - } - - /// The numbers of entry `name` in Properties70 (`P: name, type, subtype, flags, values`) or - /// Properties60 (`Property: name, type, flags, values`). - fn property(&self, name: &str) -> Option> { - let list = self.child("Properties70").or_else(|| self.child("Properties60"))?; - list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().filter_map(Prop::num).collect()) - } - - fn vec3(&self, name: &str, default: Vec3) -> Vec3 { - match self.property(name).as_deref() { - Some([x, y, z, ..]) => Vec3::new(*x as f32, *y as f32, *z as f32), - _ => default, - } - } - - fn number(&self, name: &str) -> Option { - self.property(name)?.first().copied() - } -} - -/// Charges parsed data against [`MAX_DECODED_BYTES`]. -struct Budget(usize); - -impl Budget { - fn charge(&mut self, bytes: usize) -> Result<()> { - self.0 = self.0.checked_sub(bytes).ok_or_else(|| FormatError::TooLarge(format!("the FBX file decodes to more than {MAX_DECODED_BYTES} bytes")))?; - Ok(()) - } -} - -// --------------------------------------------------------------------------------------------- -// Binary. - -struct Binary<'a> { - b: &'a [u8], - pos: usize, - /// 64-bit node records (version 7500 and later). - wide: bool, - budget: Budget, -} - -impl<'a> Binary<'a> { - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "unexpected end of file"))?; - self.pos += n; - Ok(s) - } - - fn bytes(&mut self) -> Result<[u8; N]> { - let mut a = [0u8; N]; - a.copy_from_slice(self.take(N)?); - Ok(a) - } - - fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.bytes()?) as usize) - } - - fn uint(&mut self) -> Result { - Ok(if self.wide { u64::from_le_bytes(self.bytes()?) } else { u32::from_le_bytes(self.bytes()?) as u64 }) - } - - /// The next node ending at or before `limit`, or None at a null record / the end. - fn node(&mut self, limit: usize, depth: usize) -> Result> { - let header = if self.wide { 25 } else { 13 }; - if limit.saturating_sub(self.pos) < header { - return Ok(None); - } - let (end, nprops, plen) = (self.uint()?, self.uint()?, self.uint()?); - let [name_len] = self.bytes()?; - if end == 0 { - return Ok(None); - } - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let end = usize::try_from(end).ok().filter(|e| *e > self.pos && *e <= limit).ok_or_else(|| malformed(KIND, "node end offset out of range"))?; - self.budget.charge(NODE_COST)?; - let name = String::from_utf8_lossy(self.take(name_len as usize)?).into_owned(); - let props_end = usize::try_from(plen).ok().and_then(|p| self.pos.checked_add(p)).filter(|e| *e <= end); - let props_end = props_end.ok_or_else(|| malformed(KIND, format!("properties of \"{name}\" overrun the node")))?; - let mut props = Vec::new(); - for _ in 0..nprops { - if self.pos >= props_end { - return Err(malformed(KIND, format!("\"{name}\" claims more properties than it holds"))); - } - props.push(self.prop()?); - } - if self.pos > props_end { - return Err(malformed(KIND, format!("properties of \"{name}\" overrun their list"))); - } - self.pos = props_end; - let mut children = Vec::new(); - while let Some(c) = self.node(end, depth + 1)? { - children.push(c); - } - self.pos = end; - Ok(Some(Node { name, props, children })) - } - - fn prop(&mut self) -> Result { - self.budget.charge(PROP_COST)?; - let [ty] = self.bytes()?; - Ok(match ty { - b'Y' => Prop::I(i16::from_le_bytes(self.bytes()?) as i64), - b'C' | b'B' => Prop::I(self.bytes::<1>()?[0] as i64), - b'I' => Prop::I(i32::from_le_bytes(self.bytes()?) as i64), - b'L' => Prop::I(i64::from_le_bytes(self.bytes()?)), - b'F' => Prop::F(f32::from_le_bytes(self.bytes()?) as f64), - b'D' => Prop::F(f64::from_le_bytes(self.bytes()?)), - b'S' => { - let n = self.u32()?; - Prop::S(String::from_utf8_lossy(self.take(n)?).into_owned()) - } - b'R' => { - let n = self.u32()?; - self.budget.charge(n)?; - Prop::Raw(self.take(n)?.to_vec()) - } - b'f' | b'd' | b'l' | b'i' | b'b' => Prop::Arr(self.array(ty)?), - other => return Err(malformed(KIND, format!("unknown property type 0x{other:02x}"))), - }) - } - - fn array(&mut self, value_type: u8) -> Result> { - let (count, encoding, stored) = (self.u32()?, self.u32()?, self.u32()?); - let value_bytes = match value_type { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - let decoded_bytes = count.checked_mul(value_bytes).ok_or_else(|| malformed(KIND, "array too large"))?; - self.budget.charge(count.saturating_mul(8))?; - - let data = self.take(stored)?; - let raw: Cow<[u8]> = match encoding { - 0 if stored == decoded_bytes => Cow::Borrowed(data), - 1 => { - let mut out = Vec::new(); - flate2::read::ZlibDecoder::new(data) - .take(decoded_bytes as u64 + 1) - .read_to_end(&mut out) - .map_err(|e| malformed(KIND, format!("bad compressed array: {e}")))?; - if out.len() != decoded_bytes { - return Err(malformed(KIND, "compressed array has the wrong length")); - } - - Cow::Owned(out) - } - _ => return Err(malformed(KIND, format!("array encoding {encoding} with {stored} bytes for {count} items"))), - }; - - Ok(match value_type { - b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), - b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), - b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), - b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), - _ => raw.iter().map(|b| *b as f64).collect(), - }) - } -} - -fn parse_binary(b: &[u8]) -> Result<(Vec, i64)> { - let mut r = Binary { b, pos: MAGIC.len(), wide: false, budget: Budget(MAX_DECODED_BYTES) }; - let _reserved: [u8; 2] = r.bytes()?; - let version = u32::from_le_bytes(r.bytes()?); - r.wide = version >= 7500; - let mut nodes = Vec::new(); - while let Some(n) = r.node(b.len(), 0)? { - nodes.push(n); - } - Ok((nodes, version as i64)) -} - -// --------------------------------------------------------------------------------------------- -// ASCII. - -#[derive(Clone, Copy)] -enum Tok<'a> { - /// `name:` - Key(&'a str), - Str(&'a [u8]), - Word(&'a str), - Comma, - Open, - Close, -} - -struct Ascii<'a> { - s: &'a [u8], - pos: usize, - budget: Budget, -} - -impl<'a> Ascii<'a> { - /// The next token and the position after it (the position is not advanced). - fn lex(&self) -> Result, usize)>> { - let mut i = self.pos; - loop { - match self.s.get(i) { - None => return Ok(None), - Some(c) if c.is_ascii_whitespace() => i += 1, - Some(b';') => i += self.s.get(i..).unwrap_or_default().iter().position(|c| *c == b'\n').unwrap_or(self.s.len() - i), - Some(_) => break, - } - } - let rest = self.s.get(i..).unwrap_or_default(); - Ok(Some(match rest.first() { - Some(b',') => (Tok::Comma, i + 1), - Some(b'{') => (Tok::Open, i + 1), - Some(b'}') => (Tok::Close, i + 1), - Some(b'"') => { - let len = rest.get(1..).unwrap_or_default().iter().position(|c| *c == b'"').ok_or_else(|| malformed(KIND, "unterminated string"))?; - (Tok::Str(rest.get(1..1 + len).unwrap_or_default()), i + len + 2) - } - _ => { - let len = rest.iter().position(|c| c.is_ascii_whitespace() || b",{}\":;".contains(c)).unwrap_or(rest.len()); - if len == 0 { - return Err(malformed(KIND, format!("unexpected character at byte {i}"))); - } - let word = std::str::from_utf8(rest.get(..len).unwrap_or_default()).map_err(|_| malformed(KIND, "text is not UTF-8"))?; - if rest.get(len) == Some(&b':') { (Tok::Key(word), i + len + 1) } else { (Tok::Word(word), i + len) } - } - })) - } - - /// Nodes until `}` (left for the caller) or the end. - fn nodes(&mut self, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let mut out = Vec::new(); - while let Some((tok, after)) = self.lex()? { - match tok { - Tok::Close => break, - Tok::Key(name) => { - self.pos = after; - out.push(self.node(name, depth)?); - } - _ => return Err(malformed(KIND, format!("expected a property name at byte {}", self.pos))), - } - } - Ok(out) - } - - fn node(&mut self, name: &str, depth: usize) -> Result { - self.budget.charge(NODE_COST)?; - let mut props = Vec::new(); - // An empty first value (`Content: , "..."`). - if let Some((Tok::Comma, after)) = self.lex()? { - self.pos = after; - } - while let Some((tok, after)) = self.lex()? { - let prop = match tok { - Tok::Str(s) => Some(Prop::S(String::from_utf8_lossy(s).into_owned())), - // `*N` announces an array's length. - Tok::Word(w) if w.starts_with('*') => None, - Tok::Word(w) => Some(w.parse::().map(Prop::I).or_else(|_| w.parse::().map(Prop::F)).unwrap_or_else(|_| Prop::S(w.to_string()))), - _ => break, - }; - self.pos = after; - if let Some(p) = prop { - self.budget.charge(PROP_COST)?; - props.push(p); - } - match self.lex()? { - Some((Tok::Comma, after)) => self.pos = after, - _ => break, - } - } - let mut children = Vec::new(); - if let Some((Tok::Open, after)) = self.lex()? { - self.pos = after; - children = self.nodes(depth + 1)?; - match self.lex()? { - Some((Tok::Close, after)) => self.pos = after, - _ => return Err(malformed(KIND, format!("\"{name}\" is missing its closing brace"))), - } - } - // Long value lists (arrays) are stored compactly. - if props.len() > 1 && props.iter().all(|p| p.num().is_some()) { - props = vec![Prop::Arr(props.iter().filter_map(Prop::num).collect())]; - } - Ok(Node { name: name.to_string(), props, children }) - } -} - -fn parse_ascii(s: &[u8]) -> Result<(Vec, i64)> { - let mut a = Ascii { s, pos: 0, budget: Budget(MAX_DECODED_BYTES) }; - let nodes = a.nodes(0)?; - if a.lex()?.is_some() { - return Err(malformed(KIND, "unbalanced closing brace")); - } - let version = nodes.iter().find(|n| n.name == "FBXHeaderExtension").and_then(|h| h.child("FBXVersion")).and_then(|v| v.int_at(0)); - let version = version.ok_or_else(|| malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)"))?; - Ok((nodes, version)) -} - -// --------------------------------------------------------------------------------------------- -// Scene. - -/// The bytes of the first of a texture's candidate file paths (relative to the FBX's folder) -/// that exists. type Files<'a> = dyn FnMut(&[&str]) -> Option> + 'a; - -/// An FBX, or a package of one and its texture files. -pub(crate) fn read(bytes: &[u8]) -> Result { - if !bytes.starts_with(ZIP_MAGIC) { - return crate::guard(KIND, || read_inner(bytes, &mut |_| None)); +fn limits() -> craft_mesh::Limits { + craft_mesh::Limits { + max_vertices: super::MAX_VERTICES, + max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_face_corners: super::MAX_VERTICES, + max_meshes: super::MAX_VERTICES, + max_parts: super::MAX_VERTICES, + max_materials: super::MAX_VERTICES, + max_nodes: super::MAX_VERTICES, + max_data_bytes: 1 << 31, + max_extras: 100_000, + ..Default::default() } +} + +fn package_limits() -> craft_mesh::fbx::package::PackageLimits { + craft_mesh::fbx::package::PackageLimits { + max_entries: MAX_ZIP_ENTRIES as u64, + max_model_bytes: MAX_MESH_FILE_BYTES, + max_texture_bytes: MAX_TEXTURE_BYTES, + max_total_bytes: MAX_MESH_FILE_BYTES, + } +} + +fn convert(e: craft_mesh::Error) -> FormatError { + match e { + craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), + craft_mesh::Error::Unsupported(s) => FormatError::Unsupported(s), + e => FormatError::Invalid(e.to_string()), + } +} + +pub(crate) fn read(bytes: &[u8]) -> Result { crate::guard(KIND, || { - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| malformed(KIND, format!("FBX package: {e}")))?; - if zip.len() > MAX_ZIP_ENTRIES { - return Err(FormatError::TooLarge(format!("the FBX package has more than {MAX_ZIP_ENTRIES} entries"))); + if !craft_mesh::fbx::package::is_package(bytes) { + return read_inner(bytes, &mut |_| None); } - let name = zip.file_names().flatten().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(Cow::into_owned); - let name = name.ok_or_else(|| malformed(KIND, "the package contains no FBX file"))?; - let fbx = zip_entry(&mut zip, &name, MAX_MESH_FILE_BYTES) - .ok_or_else(|| FormatError::TooLarge("the packaged FBX is unreadable or larger than 2 GiB".into()))?; - if fbx.starts_with(ZIP_MAGIC) { - return Err(malformed(KIND, "the package holds another package")); - } - read_inner(&fbx, &mut |paths| paths.iter().find_map(|p| zip_entry(&mut zip, &below(p)?, MAX_TEXTURE_BYTES))) + let mut package = craft_mesh::fbx::package::Package::open(bytes, package_limits()).map_err(convert)?; + let fbx = package.model().map_err(convert)?; + read_inner(&fbx, &mut |paths| package.texture(paths)) }) } -/// An FBX whose base color textures are files, as a package holding it (first) and the files -/// `found` has, under their paths below its folder; None when it found none (or `bytes` is a -/// package already). Also the texture paths it could not find. pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) -> Option>) -> Result<(Option>, Vec)> { - if bytes.starts_with(ZIP_MAGIC) { + if craft_mesh::fbx::package::is_package(bytes) { return Ok((None, Vec::new())); } crate::guard(KIND, || { - let (mut files, mut missing): (Vec<(String, Vec)>, Vec) = (Vec::new(), Vec::new()); - read_inner(bytes, &mut |paths| { - if let Some((_, data)) = files.iter().find(|(n, _)| paths.iter().any(|p| below(p).as_ref() == Some(n))) { - return Some(data.clone()); - } - for p in paths { - if let (Some(name), Some(data)) = (below(p), found(p).filter(|d| d.len() as u64 <= MAX_TEXTURE_BYTES)) { - files.push((name, data.clone())); - return Some(data); - } - } - // A texture is missing when none of its paths was found; named by its first. - if let Some(first) = paths.first().filter(|f| !missing.iter().any(|m| m == *f)) { - missing.push(first.to_string()); - } - None - })?; - if files.is_empty() { - return Ok((None, missing)); + let limits = limits(); + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let total = files.iter().fold(bytes.len() as u64, |t, (_, d)| t.saturating_add(d.len() as u64)); - if total > MAX_MESH_FILE_BYTES { - return Err(FormatError::TooLarge("the FBX and its textures exceed 2 GiB".into())); - } - let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh.fbx"); - Ok((Some(crate::mesh_export::usd::usdz(leaf, bytes, &files)?), missing)) + doc.scene_with_options( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, + ) + .map_err(convert)?; + craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } fn read_inner(bytes: &[u8], files: &mut Files) -> Result { - let (nodes, version) = if bytes.starts_with(MAGIC) { parse_binary(bytes)? } else { parse_ascii(bytes)? }; - if version < MIN_VERSION { - return Err(FormatError::Unsupported(format!("FBX version {version} (re-export as FBX 2006 / 6.1 or newer)"))); + let limits = limits(); + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let root = |name: &str| nodes.iter().find(|n| n.name == name); - let objects = root("Objects").ok_or_else(|| malformed(KIND, "the file has no Objects"))?; - let (mut geometries, mut models, mut materials) = (HashMap::new(), HashMap::new(), HashMap::new()); - let (mut textures, mut videos, mut attributes) = (HashMap::new(), HashMap::new(), HashMap::new()); - // (geometry, model) instances; an FBX 6 Model holds its geometry itself. - let mut instances: Vec<(String, Option)> = Vec::new(); - for o in &objects.children { - let Some(id) = o.id_at(0) else { continue }; - match o.name.as_str() { - "Geometry" if o.child("Vertices").is_some() => geometries.insert(id, o), - "Model" => { - if o.child("Vertices").is_some() { - geometries.insert(id.clone(), o); - instances.push((id.clone(), Some(id.clone()))); - } - models.insert(id, o) - } - "Material" => materials.insert(id, o), - "Texture" => textures.insert(id, o), - "Video" => videos.insert(id, o), - "NodeAttribute" => attributes.insert(id, o), - _ => None, - }; - } - // Model parents, and each Model's materials in slot order. - let mut parents: HashMap = HashMap::new(); - let mut slots: HashMap> = HashMap::new(); - let mut attribute_of: HashMap = HashMap::new(); - let connections: Vec<&Node> = root("Connections").into_iter().flat_map(|c| c.all("C").chain(c.all("Connect"))).collect(); - for c in &connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if c.str_at(0) != "OO" || child == parent || !models.contains_key(&parent) { - continue; - } - if models.contains_key(&child) { - parents.insert(child, parent); - } else if geometries.contains_key(&child) { - instances.push((child, Some(parent))); - } else if let Some(m) = materials.get(&child) { - slots.entry(parent).or_default().push(material_name(&child, m)); - } else if let Some(a) = attributes.get(&child) { - attribute_of.insert(parent, *a); - } - } - let placed: HashSet<&String> = instances.iter().map(|(g, _)| g).collect(); - let mut unplaced: Vec = geometries.keys().filter(|g| !placed.contains(g)).cloned().collect(); - unplaced.sort_unstable(); - instances.extend(unplaced.into_iter().map(|g| (g, None))); - - let base_colors = base_colors(&materials, &textures, &videos, &connections, files); - let global = global_transform(root("GlobalSettings").or_else(|| objects.child("GlobalSettings"))); + let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; + let (scene, placements) = doc + .scene_with_placements( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, + ) + .map_err(convert)?; + let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); + let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); - let no_slots = Vec::new(); - for (geom, model) in instances { - let Some(g) = geometries.get(&geom) else { continue }; - let m = match model.as_ref().and_then(|m| models.get(m).map(|n| (m, n))) { - Some((id, node)) => { - sink.part = node.object_name().to_string(); - world(&models, &parents, id)? * geometric(node) + let mut cameras = Vec::new(); + cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); + // Bound the stored world matrices and pending node indices together: neither depends on + // copying model names, even when a hierarchy fans out widely. + let placement_bytes = + scene.nodes.len().checked_mul(std::mem::size_of::>()).ok_or_else(|| FormatError::TooLarge("FBX hierarchy size overflow".into()))?; + let remaining = limits.max_data_bytes.checked_sub(placement_bytes).ok_or_else(|| FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into()))?; + let stack_limit = remaining / std::mem::size_of::<(usize, Mat4, usize)>(); + if scene.roots.len() > stack_limit { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); + } + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, 0usize)).collect(); + let mut worlds = vec![None; scene.nodes.len()]; + let mut visited = 0usize; + let mut points = 0usize; + while let Some((id, parent, depth)) = stack.pop() { + visited += 1; + if visited > limits.max_nodes || depth > limits.max_depth { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); + } + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; + let world = parent * to_mat(node.transform); + if let Some(slot) = worlds.get_mut(id) { + *slot = Some(world); + } + for child in node.children.iter().rev() { + if stack.len() >= stack_limit { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } - None => { - sink.part.clear(); - Mat4::IDENTITY + stack.push((*child, world, depth + 1)); + } + if let Some(index) = node.camera + && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) + { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); + } + } + for placement in placements { + let id = placement.node; + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "placement index out of range"))?; + let world = worlds.get(id).copied().flatten().ok_or_else(|| malformed(KIND, "cycle in model hierarchy"))?; + let Some(index) = node.mesh else { continue }; + let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; + points = points.checked_add(mesh.positions.len()).ok_or_else(|| FormatError::TooLarge("FBX instance work overflow".into()))?; + if points > 200_000_000 { + return Err(FormatError::TooLarge("FBX instances exceed the 200000000 control-point work limit".into())); + } + let normal_transform = Mat3::from_mat4(world).inverse().transpose(); + let flip = world.determinant() < 0.0; + sink.part = placement.model.and_then(|i| scene.nodes.get(i)).map_or_else(String::new, |n| n.name.clone()); + let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); + for group in &mesh.parts { + let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); + for face in group.faces() { + let mut corners = Vec::with_capacity(face.len()); + for c in face { + let p = mesh.positions.get(c.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; + let p = world.transform_point3(Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32)); + let n = mesh.normals.get(c.normal as usize).map(|n| normal_transform * Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); + if !mesh.normals.is_empty() && n.is_none() { + bad_normals += 1; + } + let uv = mesh.uv_sets.first().map(|set| match set.get(c.uv as usize) { + Some(v) => Vec2::new(v[0], v[1]), + None => { + bad_uvs += 1; + Vec2::ZERO + } + }); + let color = mesh.colors.get(c.position as usize).copied().map(Vec4::from_array); + corners.push(Corner { p, n, uv, color }); + } + if flip { + corners.reverse(); + } + sink.polygon(material, &corners)?; } - }; - let names = model.as_ref().and_then(|m| slots.get(m)).unwrap_or(&no_slots); - add_geometry(&mut sink, g, global * m, names)?; + } + if bad_normals > 0 { + sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); + } + if bad_uvs > 0 { + sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); + } + } + for warning in scene.warnings { + sink.warn(warning); } let mut raw = sink.finish(); - raw.base_colors = base_colors; - // In file order; FBX 6's built-in "Producer" views are not the scene's cameras. - for o in objects.children.iter().filter(|o| o.name == "Model" && o.class() == "Camera" && !o.object_name().starts_with("Producer ")) { - let Some(id) = o.id_at(0) else { continue }; - if let Ok(m) = world(&models, &parents, &id) { - raw.cameras.push(camera(o, attribute_of.get(&id).copied().unwrap_or(o), global * m)); - } - } + raw.cameras = cameras.into_iter().flatten().collect(); + raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } -/// A camera Model at `m` with its lens in `lens`: FBX cameras look down +X with +Y up. The -/// vertical field of view comes from the focal length (mm) over the film height (inches). -/// shortcut: `OrthoZoom` is taken as the orthographic half view height in scene units; check it -/// against an exporter's orthographic camera when one is at hand. -fn camera(model: &Node, lens: &Node, m: Mat4) -> RawCamera { - let num = |k: &str| lens.number(k).map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0); - let fov = match num("FocalLength") { - Some(f) => lens_fov(f, num("FilmHeight").unwrap_or(0.612) * 25.4), - None => num("FieldOfViewY").or_else(|| num("FieldOfView")).unwrap_or(40.0), - }; - let ortho = (lens.number("CameraProjectionType") == Some(1.0)).then(|| num("OrthoZoom").unwrap_or(1.0)); - RawCamera::placed(model.object_name().to_string(), m, Vec3::X, fov, ortho) +#[cfg(test)] +mod tests { + #[test] + fn incomplete_uv_layer_keeps_other_uvs() { + let bytes = br#"FBXHeaderExtension: { FBXVersion: 7400 } +Objects: { + Geometry: 1, "Geometry::G", "Mesh" { + Vertices: 0,0,0,1,0,0,0,1,0 + PolygonVertexIndex: 0,1,-3 + LayerElementUV: 0 { + MappingInformationType: "ByPolygonVertex" + ReferenceInformationType: "IndexToDirect" + UV: 0.25,0.5, 0.75,0.5 + UVIndex: 0,1 + } + } + Model: 2, "Model::M", "Mesh" {} } - -/// A material's name in the mesh: its object name, or `Material_` when it has none. -fn material_name(id: &str, m: &Node) -> String { - let name = m.object_name(); - if name.is_empty() { format!("Material_{id}") } else { name.to_string() } -} - -/// Preserve material colors independently of textures for ID baking -fn base_colors( - materials: &HashMap, - textures: &HashMap, - videos: &HashMap, - connections: &[&Node], - files: &mut Files, -) -> Vec { - // Texture → its Video, material → its diffuse texture (a property connection wins). - let (mut video_of, mut diffuse) = (HashMap::new(), HashMap::new()); - for c in connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if videos.contains_key(&child) && textures.contains_key(&parent) { - video_of.insert(parent, child); - } else if textures.contains_key(&child) && materials.contains_key(&parent) { - match (c.str_at(0), c.str_at(3)) { - ("OP", "DiffuseColor" | "Maya|baseColor") => { - diffuse.insert(parent, child); - } - ("OO", _) => { - diffuse.entry(parent).or_insert(child); - } - _ => {} - } - } - } - let mut out: Vec = materials - .iter() - .filter_map(|(id, m)| { - let texture = diffuse.get(id); - let (video, tex) = (texture.and_then(|t| video_of.get(t)).and_then(|v| videos.get(v)), texture.and_then(|t| textures.get(t))); - // Embedded content first, then the file the texture (or its video) names. - let image = video.or(tex).and_then(|n| n.content()).or_else(|| [tex, video].into_iter().flatten().find_map(|n| texture_file(n, files))); - let diffuse_color = m.property("DiffuseColor"); - let factor = match diffuse_color.as_deref() { - Some([r, g, b, ..]) => { - let f = m.number("DiffuseFactor").unwrap_or(1.0); - Vec4::new((r * f) as f32, (g * f) as f32, (b * f) as f32, 1.0) - } - _ => Vec4::ONE, - }; - (factor.is_finite() && (image.is_some() || diffuse_color.is_some())).then(|| RawBaseColor { material: material_name(id, m), factor, image }) - }) - .collect(); - out.sort_by(|a, b| a.material.cmp(&b.material)); - out -} - -/// The file a Texture or Video names: its relative path, else its absolute path's file name -/// (looked for in the FBX's folder). -fn texture_file(n: &Node, files: &mut Files) -> Option> { - let relative = n.child_str("RelativeFilename"); - let absolute = [n.child_str("FileName"), n.child_str("Filename")].into_iter().find(|s| !s.is_empty()).unwrap_or_default(); - let leaf = absolute.rsplit(['/', '\\']).next().unwrap_or_default(); - let mut paths: Vec<&str> = Vec::new(); - for p in [relative, leaf] { - if !p.is_empty() && !paths.contains(&p) { - paths.push(p); - } - } - if paths.is_empty() { None } else { files(&paths) } -} - -/// `Name\0\1Class` (binary) or `Class::Name` (ASCII) to `Name`. -fn clean_name(s: &str) -> &str { - match s.split_once("\u{0}\u{1}") { - Some((name, _)) => name, - None => s.split_once("::").map_or(s, |(_, name)| name), +Connections: { C: "OO",1,2 } +"#; + let raw = super::read(bytes).unwrap(); + let uvs = raw.uvs.unwrap(); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::new(0.25, 0.5))); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::ZERO)); + assert!(raw.warnings.iter().any(|w| w.contains("1 polygon corners have no UV"))); } } - -/// Unit scale to meters and the file's axis system to Y up (+Z front, +X right). -fn global_transform(settings: Option<&Node>) -> Mat4 { - let get = |name: &str, default: f64| settings.and_then(|s| s.number(name)).filter(|v| v.is_finite()).unwrap_or(default); - let unit = get("UnitScaleFactor", 1.0); - let unit = if unit > 0.0 { unit / 100.0 } else { 0.01 }; - let axis = |a: &str, s: &str, default: f64| (get(a, default) as i64, if get(s, 1.0) < 0.0 { -1.0 } else { 1.0 }); - let [(right, rs), (up, us), (front, fs)] = - [axis("CoordAxis", "CoordAxisSign", 0.0), axis("UpAxis", "UpAxisSign", 1.0), axis("FrontAxis", "FrontAxisSign", 2.0)]; - let basis = |a: i64| [Vec3::X, Vec3::Y, Vec3::Z].get(a as usize).copied().filter(|_| a >= 0); - let rows = match (basis(right), basis(up), basis(front)) { - (Some(r), Some(u), Some(f)) if r.cross(u).dot(f).abs() > 0.5 => Mat3::from_cols(r * rs, u * us, f * fs).transpose(), - _ => Mat3::IDENTITY, - }; - Mat4::from_mat3(rows) * Mat4::from_scale(Vec3::splat(unit as f32)) -} - -/// Euler rotation in degrees, `order` as FBX RotationOrder (0 = XYZ: X applied first). -fn euler(deg: Vec3, order: i64) -> Mat4 { - use Vec3 as V; - let axes = match order { - 1 => [V::X, V::Z, V::Y], - 2 => [V::Y, V::Z, V::X], - 3 => [V::Y, V::X, V::Z], - 4 => [V::Z, V::X, V::Y], - 5 => [V::Z, V::Y, V::X], - _ => [V::X, V::Y, V::Z], - }; - axes.iter().fold(Mat4::IDENTITY, |m, a| Mat4::from_axis_angle(*a, deg.dot(*a).to_radians()) * m) -} - -/// A Model's local transform: T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹. -fn local(m: &Node) -> Mat4 { - let t = |name: &str| Mat4::from_translation(m.vec3(name, Vec3::ZERO)); - let order = m.number("RotationOrder").unwrap_or(0.0) as i64; - let (rp, sp) = (m.vec3("RotationPivot", Vec3::ZERO), m.vec3("ScalingPivot", Vec3::ZERO)); - t("Lcl Translation") - * t("RotationOffset") - * Mat4::from_translation(rp) - * euler(m.vec3("PreRotation", Vec3::ZERO), 0) - * euler(m.vec3("Lcl Rotation", Vec3::ZERO), order) - * euler(m.vec3("PostRotation", Vec3::ZERO), 0).inverse() - * Mat4::from_translation(-rp) - * t("ScalingOffset") - * Mat4::from_translation(sp) - * Mat4::from_scale(m.vec3("Lcl Scaling", Vec3::ONE)) - * Mat4::from_translation(-sp) -} - -/// The geometry offset of a Model (not inherited by its children). -fn geometric(m: &Node) -> Mat4 { - Mat4::from_translation(m.vec3("GeometricTranslation", Vec3::ZERO)) - * euler(m.vec3("GeometricRotation", Vec3::ZERO), 0) - * Mat4::from_scale(m.vec3("GeometricScaling", Vec3::ONE)) -} - -fn world(models: &HashMap, parents: &HashMap, id: &str) -> Result { - let mut m = Mat4::IDENTITY; - let mut cur = Some(id); - for _ in 0..=MAX_DEPTH { - let Some(node) = cur.and_then(|c| models.get(c)) else { return Ok(m) }; - m = local(node) * m; - cur = cur.and_then(|c| parents.get(c)).map(String::as_str); - } - Err(malformed(KIND, "the Model hierarchy is nested too deeply (or cyclic)")) -} - -#[derive(Clone, Copy)] -enum Mapping { - PolygonVertex, - ControlPoint, - Polygon, - AllSame, -} - -/// One LayerElement's items, optionally through an index array. -struct Layer<'a> { - mapping: Mapping, - data: Cow<'a, [f64]>, - index: Option>, -} - -impl Layer<'_> { - /// Element `index` names the index array (empty: the data is never indexed). - fn read<'a>(geom: &'a Node, element: &str, data: &str, index: &str) -> Option> { - let el = geom.children.iter().filter(|c| c.name == element).min_by_key(|e| e.int_at(0) != Some(0))?; - let mapping = match el.child_str("MappingInformationType") { - "ByPolygonVertex" => Mapping::PolygonVertex, - "ByVertice" | "ByVertex" | "ByControlPoint" => Mapping::ControlPoint, - "ByPolygon" => Mapping::Polygon, - "AllSame" => Mapping::AllSame, - _ => return None, - }; - let indexed = !index.is_empty() && matches!(el.child_str("ReferenceInformationType"), "IndexToDirect" | "Index"); - let index = if indexed { Some(el.child(index)?.arr()) } else { None }; - Some(Layer { mapping, data: el.child(data)?.arr(), index }) - } - - /// The `W` numbers of polygon vertex `k` (control point `cp`, polygon `poly`). - fn get(&self, k: usize, cp: usize, poly: usize) -> Option<[f64; W]> { - let i = match self.mapping { - Mapping::PolygonVertex => k, - Mapping::ControlPoint => cp, - Mapping::Polygon => poly, - Mapping::AllSame => 0, - }; - let i = match &self.index { - Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize, - None => i, - }; - let start = i.checked_mul(W)?; - self.data.get(start..start.checked_add(W)?)?.try_into().ok() - } -} - -fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String]) -> Result<()> { - let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default(); - check_vertices(vertices.len() / 3)?; - let points: Vec = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); - let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); - let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); - let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); - let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); - let normal_transform = Mat3::from_mat4(transform).inverse().transpose(); - let flip = transform.determinant() < 0.0; - let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); - - for (k, &v) in polygon_indices.iter().enumerate() { - // The last corner of each polygon is stored as -(index + 1) - let (control_point, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; - let p = points - .get(control_point as usize) - .filter(|_| control_point.fract() == 0.0) - .ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; - let control_point = control_point as usize; - let n = normals.as_ref().and_then(|l| { - let n = l.get(k, control_point, polygon_index).map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); - bad_normals += usize::from(n.is_none()); - n - }); - - // A UV layer with holes keeps its layout: missing items read as 0, 0 - let uv = uvs.as_ref().map(|l| match l.get(k, control_point, polygon_index) { - Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), - None => { - bad_uvs += 1; - Vec2::ZERO - } - }); - corners.push(Corner { p: *p, n, uv }); - if last || k + 1 == polygon_indices.len() { - if flip { - corners.reverse(); - } - let slot = materials.as_ref().and_then(|l| l.get(polygon_index, polygon_index, polygon_index)).map_or(0.0, |[s]| s); - let name = slots.get(slot as usize).filter(|_| slot >= 0.0).map_or("Default", String::as_str); - sink.polygon(name, &corners)?; - corners.clear(); - polygon_index += 1; - } - } - - if bad_normals > 0 { - sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); - } - if bad_uvs > 0 { - sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); - } - - Ok(()) -} diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 21658033..92e52f72 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -20,8 +20,34 @@ pub(crate) fn read(bytes: &[u8]) -> Result { crate::guard(KIND, || read_inner(bytes)) } +/// Loads and validates the document like `gltf::Gltf::from_slice`, except that a scene without a +/// `nodes` array is an empty scene. The `gltf` crate declares the field as required, but the +/// glTF 2.0 schema lists no required properties for a scene, and exporters write such scenes +/// for scenes that contain no objects. +fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { + let (json, blob) = if bytes.starts_with(b"glTF") { + let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?; + let blob = glb.bin.take().map(std::borrow::Cow::into_owned); + (glb.json, blob) + } else { + (std::borrow::Cow::Borrowed(bytes), None) + }; + let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?; + if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) { + for scene in scenes { + if let Some(scene) = scene.as_object_mut() { + scene.entry("nodes").or_insert_with(|| serde_json::Value::Array(Vec::new())); + } + } + } + // Consume the DOM directly rather than serialising it back to a second full-size buffer. + let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?; + let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?; + Ok((document, blob)) +} + fn read_inner(bytes: &[u8]) -> Result { - let gltf::Gltf { document, blob } = gltf::Gltf::from_slice(bytes).map_err(|e| malformed(KIND, e))?; + let (document, blob) = parse(bytes)?; check_buffer_uris(&document)?; let buffers = gltf::import_buffers(&document, None, blob).map_err(|e| match e { gltf::Error::ExternalReferenceInSliceImport => FormatError::Unsupported( diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 42497364..f0231d11 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -2,7 +2,7 @@ //! world-space [`Mesh`] with one submesh per material and part (glTF node, OBJ object, FBX //! model, COLLADA node, USD Mesh prim, Alembic PolyMesh; unnamed parts take the file stem), materials contiguous, //! glTF UV convention (origin top-left, v down), -//! normals (computed when missing), vertex colors (glTF, OBJ, PLY), UVs (auto-unwrapped when +//! normals (computed when missing), vertex colors (glTF, FBX, OBJ, PLY), UVs (auto-unwrapped when //! missing) and MikkTSpace tangents. glTF, FBX, COLLADA and USD cameras come along as the //! project's camera list. @@ -182,10 +182,11 @@ pub(crate) struct Corner { pub p: Vec3, pub n: Option, pub uv: Option, + pub color: Option, } /// Collects polygons into a [`RawMesh`]: fan triangulation, one vertex per unique corner, and -/// normals / UVs kept only when every corner has them (else computed / unwrapped). +/// normals / UVs / colors kept only when every corner has them (else computed / unwrapped / white). #[derive(Default)] pub(crate) struct PolygonSink { /// Part name of the polygons that follow. @@ -193,10 +194,13 @@ pub(crate) struct PolygonSink { raw: RawMesh, normals: Vec, uvs: Vec, + /// Allocated by the first coloured corner, so a scene without colors pays nothing for them. + colors: Option>, missing_normals: bool, missing_uvs: bool, some_uvs: bool, - ids: HashMap<[u32; 8], u32>, + missing_colors: bool, + ids: HashMap<[u32; 12], u32>, polygon: Vec, triangles: usize, } @@ -213,13 +217,24 @@ impl PolygonSink { self.missing_normals |= c.n.is_none(); self.missing_uvs |= c.uv.is_none(); self.some_uvs |= c.uv.is_some(); + self.missing_colors |= c.color.is_none(); let (n, uv) = (c.n.unwrap_or_default(), c.uv.unwrap_or_default()); + // A corner without a color must not merge with one that has it. + let color_key = c.color.map_or([u32::MAX; 4], |v| v.to_array().map(f32::to_bits)); let key = [c.p.x, c.p.y, c.p.z, n.x, n.y, n.z, uv.x, uv.y].map(f32::to_bits); + let key = [key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], color_key[0], color_key[1], color_key[2], color_key[3]]; let id = match self.ids.entry(key) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { let id = self.raw.positions.len(); check_vertices(id + 1)?; + // White stands in for the corners before the first coloured one. + if c.color.is_some() && self.colors.is_none() { + self.colors = Some(vec![Vec4::ONE; id]); + } + if let Some(colors) = self.colors.as_mut() { + colors.push(c.color.unwrap_or(Vec4::ONE)); + } self.raw.positions.push(c.p); self.normals.push(n); self.uvs.push(uv); @@ -242,8 +257,12 @@ impl PolygonSink { if self.missing_uvs && self.some_uvs { self.warn("some polygons have no UVs; the whole mesh was unwrapped automatically".into()); } + if self.missing_colors && self.colors.is_some() { + self.warn("some polygon corners have no color in the color layer; vertex colors were dropped".into()); + } self.raw.normals = (!self.missing_normals).then_some(self.normals); self.raw.uvs = (!self.missing_uvs).then_some(self.uvs); + self.raw.colors = if self.missing_colors { None } else { self.colors.take() }; self.raw } } diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 2f284704..267aa8ea 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -1,10 +1,9 @@ -//! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn. - +//! Wavefront OBJ through the shared bounded mesh reader. +use super::{MAX_VERTICES, RawMesh, check_vertices}; +use crate::{FormatError, Result, malformed}; +use std::collections::HashMap; use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; -use super::{RawMesh, check_triangles, check_vertices}; -use crate::{Result, malformed}; - const KIND: &str = "OBJ"; pub(crate) fn read(bytes: &[u8]) -> Result { @@ -12,99 +11,77 @@ pub(crate) fn read(bytes: &[u8]) -> Result { } fn read_inner(bytes: &[u8]) -> Result { - let text = String::from_utf8_lossy(bytes); - - // A synthetic library lets tobj assign usemtl names without reading external MTL files - let mut names: Vec<&str> = Vec::new(); - for line in text.lines().map(str::trim) { - if line.split_whitespace().next() == Some("usemtl") - && let Some((_, name)) = line.split_once(' ') - && !name.trim().is_empty() - && !names.contains(&name.trim()) - { - names.push(name.trim()); - } - } - - let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect(); - let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); - - // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates - let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; - let (models, materials) = - tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; - let materials = materials.unwrap_or_default(); - + let limits = craft_mesh::Limits { + max_vertices: MAX_VERTICES, + max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_face_corners: MAX_VERTICES, + max_meshes: MAX_VERTICES, + max_parts: MAX_VERTICES, + max_materials: MAX_VERTICES, + max_data_bytes: super::MAX_MESH_FILE_BYTES as usize, + ..Default::default() + }; + let options = craft_mesh::obj::ReadOptions { strict: true, preserve_runs: true, ignore_material_libraries: true, groups_as_objects: true }; + let scene = craft_mesh::obj::read_with_options(bytes, &limits, &mut craft_mesh::no_external, &options).map_err(|e| match e { + craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), + e => FormatError::Invalid(e.to_string()), + })?; + let any_uvs = scene.meshes.iter().flat_map(|mesh| mesh.parts.iter()).flat_map(|part| part.corners.iter()).any(|c| c.uv != craft_mesh::NONE); + let any_colors = scene.meshes.iter().any(|mesh| !mesh.colors.is_empty()); let mut raw = RawMesh::default(); - let any_uvs = models.iter().any(|m| !m.mesh.indices.is_empty() && m.mesh.texcoords.len() == (m.mesh.positions.len() / 3) * 2); - let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), any_uvs.then(Vec::new), Vec::new()); - let mut partial_uvs = false; - for model in &models { - let mesh = &model.mesh; - if mesh.indices.is_empty() { - continue; - } - let vertex_count = mesh.positions.len() / 3; - check_vertices(raw.positions.len().saturating_add(vertex_count))?; - - // Corners per face; without arities every face is a triangle - let arities: Vec = - if mesh.face_arities.is_empty() { vec![3; mesh.indices.len() / 3] } else { mesh.face_arities.iter().map(|a| *a as usize).collect() }; - check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; - let base = raw.positions.len() as u32; - raw.positions.extend(mesh.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); - if mesh.normals.len() == vertex_count * 3 { - if let Some(v) = &mut normals { - v.extend(mesh.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); - } - } else { - normals = None; - } - if let Some(v) = &mut uvs { - if mesh.texcoords.len() == vertex_count * 2 { - // OBJ UVs have their origin bottom-left - v.extend(mesh.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); - } else { - v.extend(std::iter::repeat_n(Vec2::ZERO, vertex_count)); - partial_uvs = true; - } - } - - // `v x y z r g b`: objects without colors are white - match mesh.vertex_color.len() == vertex_count * 3 { - true => colors.extend(mesh.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), - false => colors.extend(std::iter::repeat_n(Vec4::ONE, vertex_count)), - } - - let name = match mesh.material_id { - Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")), - None => "Default".to_string(), - }; - if let Some(i) = mesh.indices.iter().find(|i| **i as usize >= vertex_count) { - return Err(malformed(KIND, format!("face index {i} out of range"))); - } - - // tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem - let part = if model.name == "unnamed_object" { "" } else { model.name.as_str() }; - let (mut rest, mut corners) = (mesh.indices.as_slice(), Vec::new()); - for arity in arities { - let Some((face, tail)) = rest.split_at_checked(arity) else { break }; - rest = tail; - corners.clear(); - corners.extend(face.iter().map(|i| base + i)); - if arity >= 3 { - raw.polygon(&name, part, &corners); + let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); + let (mut missing_normals, mut missing_uvs) = (false, false); + for mesh in &scene.meshes { + for part in &mesh.parts { + let material = part.material.and_then(|i| scene.materials.get(i)).map_or("Default", |m| m.name.as_str()); + let name = if part.name.is_empty() { mesh.name.as_str() } else { part.name.as_str() }; + // OBJ model/material runs have independent v/vt/vn deduplication. + let mut ids = HashMap::new(); + for face in part.faces() { + let mut polygon = Vec::with_capacity(face.len()); + for corner in face { + let id = if let Some(id) = ids.get(corner) { + *id + } else { + let position = mesh.positions.get(corner.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; + check_vertices(raw.positions.len().saturating_add(1))?; + // Bound both the output pools and the per-run corner map before growth. + let staging = raw + .positions + .len() + .checked_add(1) + .and_then(|n| n.checked_mul(64)) + .and_then(|n| ids.len().checked_add(1).and_then(|m| m.checked_mul(48)).and_then(|m| n.checked_add(m))); + if staging.is_none_or(|n| n > limits.max_data_bytes) { + return Err(FormatError::TooLarge("OBJ mesh exceeds the memory limit".into())); + } + let id = u32::try_from(raw.positions.len()).map_err(|_| FormatError::TooLarge("OBJ vertex count".into()))?; + raw.positions.push(Vec3::new(position[0] as f32, position[1] as f32, position[2] as f32)); + let normal = mesh.normals.get(corner.normal as usize).map(|n| Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); + missing_normals |= normal.is_none(); + normals.push(normal.unwrap_or_default()); + if any_uvs { + let uv = mesh.uv_sets.first().and_then(|set| set.get(corner.uv as usize)).map(|v| Vec2::new(v[0], v[1])); + missing_uvs |= uv.is_none(); + uvs.push(uv.unwrap_or_default()); + } + if any_colors { + colors.push(mesh.colors.get(corner.position as usize).copied().map(Vec4::from_array).unwrap_or(Vec4::ONE)); + } + ids.insert(*corner, id); + id + }; + polygon.push(id); + } + raw.polygon(material, name, &polygon); } } } - - if partial_uvs { + if missing_uvs { raw.warnings.push("some objects have no UVs; default UVs were assigned".into()); } - - raw.normals = normals; - raw.uvs = uvs; - raw.colors = models.iter().any(|model| !model.mesh.vertex_color.is_empty()).then_some(colors); - + raw.normals = (!missing_normals).then_some(normals); + raw.uvs = any_uvs.then_some(uvs); + raw.colors = any_colors.then_some(colors); Ok(raw) } diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index 34e1c1da..fd923ee8 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -10,40 +10,20 @@ const KIND: &str = "PLY"; /// Longest polygon accepted (a list count above this is treated as corruption). const MAX_FACE_VERTICES: usize = 4096; -#[derive(Clone, Copy, PartialEq)] -enum Ty { - I8, - U8, - I16, - U16, - I32, - U32, - F32, - F64, -} +use craft_mesh::ply::{Encoding as SharedEncoding, Header, Rows, Scalar as Ty}; -impl Ty { - fn parse(s: &str) -> Option { - Some(match s { - "char" | "int8" => Ty::I8, - "uchar" | "uint8" => Ty::U8, - "short" | "int16" => Ty::I16, - "ushort" | "uint16" => Ty::U16, - "int" | "int32" => Ty::I32, - "uint" | "uint32" => Ty::U32, - "float" | "float32" => Ty::F32, - "double" | "float64" => Ty::F64, - _ => return None, - }) - } - fn size(self) -> usize { - match self { - Ty::I8 | Ty::U8 => 1, - Ty::I16 | Ty::U16 => 2, - Ty::I32 | Ty::U32 | Ty::F32 => 4, - Ty::F64 => 8, - } - } +fn parse_type(s: &str) -> Option { + Some(match s { + "char" | "int8" => Ty::I8, + "uchar" | "uint8" => Ty::U8, + "short" | "int16" => Ty::I16, + "ushort" | "uint16" => Ty::U16, + "int" | "int32" => Ty::I32, + "uint" | "uint32" => Ty::U32, + "float" | "float32" => Ty::F32, + "double" | "float64" => Ty::F64, + _ => return None, + }) } struct Property { @@ -66,60 +46,36 @@ enum Encoding { Be, } -/// Reads scalars from the body in either encoding. -struct Body<'a> { - data: &'a [u8], - pos: usize, - enc: Encoding, -} - -impl Body<'_> { - fn next_token(&mut self) -> Option<&str> { - let rest = self.data.get(self.pos..)?; - let start = rest.iter().position(|b| !b.is_ascii_whitespace())?; - let len = rest.get(start..)?.iter().position(|b| b.is_ascii_whitespace()).unwrap_or(rest.len() - start); - self.pos += start + len; - std::str::from_utf8(rest.get(start..start + len)?).ok() - } - - fn read(&mut self, ty: Ty) -> Result { - if self.enc == Encoding::Ascii { - let tok = self.next_token().ok_or_else(|| malformed(KIND, "unexpected end of data"))?; - return tok.parse::().map_err(|_| malformed(KIND, format!("bad number \"{tok}\""))); - } - let n = ty.size(); - let bytes = self.data.get(self.pos..self.pos + n).ok_or_else(|| malformed(KIND, "unexpected end of data"))?; - self.pos += n; - let mut b = [0u8; 8]; - b.get_mut(..n).unwrap_or_default().copy_from_slice(bytes); - if self.enc == Encoding::Be { - b.get_mut(..n).unwrap_or_default().reverse(); - } - Ok(match ty { - Ty::I8 => b[0] as i8 as f64, - Ty::U8 => b[0] as f64, - Ty::I16 => i16::from_le_bytes([b[0], b[1]]) as f64, - Ty::U16 => u16::from_le_bytes([b[0], b[1]]) as f64, - Ty::I32 => i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::U32 => u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::F64 => f64::from_le_bytes(b), - }) - } - - fn remaining(&self) -> usize { - self.data.len().saturating_sub(self.pos) - } -} - pub(crate) fn read(bytes: &[u8]) -> Result { let (elements, enc, body_start) = header(bytes)?; - let mut body = Body { data: bytes.get(body_start..).unwrap_or_default(), pos: 0, enc }; + // Keep the strict app header grammar and mesh policy; delegate only wire scalars. + let encoding = match enc { + Encoding::Ascii => SharedEncoding::Ascii, + Encoding::Le => SharedEncoding::Little, + Encoding::Be => SharedEncoding::Big, + }; + let shared_header = Header { encoding, elements: Vec::new(), body: body_start, comments: Vec::new() }; + let mut body = Rows::new(&shared_header, bytes); let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); // Elements may appear in any order, so take the vertex count from the header. let nverts: usize = elements.iter().filter(|e| e.name == "vertex").map(|e| e.count).fold(0, usize::saturating_add); + // The shared ASCII reader counts the delimiter after a value as read; the previous reader + // left it in the remaining bytes. Only an element without properties can notice the difference. + let ascii_slack = usize::from(enc == Encoding::Ascii); for el in &elements { + // An element without properties reads nothing, so its rows are skipped. Its count stays + // bounded by the bytes left, as the previous reader counted them. + if el.props.is_empty() { + if el.count > body.remaining().saturating_add(ascii_slack) { + return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count))); + } + // A vertex element still needs positions, as below. + if el.name == "vertex" { + return Err(malformed(KIND, "vertices have no x, y, z")); + } + continue; + } // Every item takes at least one byte, so the count can never exceed what is left. if el.count > body.remaining() { return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count))); @@ -149,17 +105,17 @@ pub(crate) fn read(bytes: &[u8]) -> Result { match p.list { None => { if let Some(v) = vals.get_mut(k) { - *v = body.read(p.ty)?; + *v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?; } } Some(ct) => { - let len = body.read(ct)?; + let len = body.value(ct).map_err(|e| malformed(KIND, e.to_string()))?; if !(0.0..=MAX_FACE_VERTICES as f64).contains(&len) { return Err(malformed(KIND, format!("bad list length {len}"))); } poly.clear(); for _ in 0..len as usize { - let v = body.read(p.ty)?; + let v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?; if face_list == Some(k) { if !(0.0..nverts as f64).contains(&v) { return Err(malformed(KIND, format!("face index {v} out of range"))); @@ -240,13 +196,13 @@ fn header(bytes: &[u8]) -> Result<(Vec, Encoding, usize)> { } ["property", "list", ct, ty, name] => { let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?; - let (ct, ty) = (Ty::parse(ct), Ty::parse(ty)); + let (ct, ty) = (parse_type(ct), parse_type(ty)); let (Some(ct), Some(ty)) = (ct, ty) else { return Err(malformed(KIND, format!("bad list types in \"{line}\""))) }; el.props.push(Property { name: name.to_string(), ty, list: Some(ct) }); } ["property", ty, name] => { let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?; - let ty = Ty::parse(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?; + let ty = parse_type(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?; el.props.push(Property { name: name.to_string(), ty, list: None }); } ["ply"] | [] | ["comment", ..] | ["obj_info", ..] => {} @@ -256,3 +212,52 @@ fn header(bytes: &[u8]) -> Result<(Vec, Encoding, usize)> { let enc = enc.ok_or_else(|| malformed(KIND, "header has no format line"))?; Ok((elements, enc, pos)) } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod shared_rows_tests { + use super::*; + + #[test] + fn trailing_propertyless_element_after_a_newline_still_opens() { + let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 1\nend_header\n0 0 0\n"; + assert_eq!(read(bytes).unwrap().positions, vec![Vec3::new(0.0, 0.0, 0.0)]); + let huge = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 3\nend_header\n0 0 0\n"; + assert!(read(huge).is_err()); + } + + #[test] + fn propertyless_vertex_element_is_still_rejected() { + let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n3 0 0 0\n"; + let Err(e) = read(bytes) else { panic!("a vertex element without x, y, z must not open") }; + let err = e.to_string(); + assert!(err.contains("vertices have no x, y, z"), "{err}"); + } + + #[test] + fn binary_scalar_endianness_matches_ascii() { + for (format, big) in [("binary_little_endian", false), ("binary_big_endian", true)] { + let mut bytes = + format!("ply\nformat {format} 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n").into_bytes(); + bytes.extend(if big { (-123i16).to_be_bytes() } else { (-123i16).to_le_bytes() }); + bytes.extend(if big { 1.25f32.to_be_bytes() } else { 1.25f32.to_le_bytes() }); + bytes.extend(if big { (-2.5f64).to_be_bytes() } else { (-2.5f64).to_le_bytes() }); + assert_eq!(read(&bytes).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]); + bytes.pop(); + assert!(read(&bytes).is_err()); + } + let ascii = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n -123 \t1.25\r\n -2.5 "; + assert_eq!(read(ascii).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]); + } + + #[test] + fn strict_header_and_invalid_face_policy_remain_local() { + for extra in ["unknown directive\n", "property nonsense x\n"] { + let bytes = format!("ply\nformat ascii 1.0\nelement vertex 1\n{extra}end_header\n0"); + assert!(read(bytes.as_bytes()).is_err()); + } + assert!(read(b"ply\nformat ascii 1.0\ncomment \xff\nend_header\n").is_err()); + let bytes = b"ply\nformat ascii 1.0\nelement face 1\nproperty list uchar int vertex_indices\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nend_header\n3 0 0 1\n0 0 0\n"; + assert!(read(bytes).is_err()); // Do not turn a bad face into a warning/skip. + } +} diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 5c5f4b5a..015724a1 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -3,7 +3,7 @@ use std::io::Write as _; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use super::tests::hammer; use super::*; @@ -298,7 +298,46 @@ fn fbx_binary_32_and_64_bit_compressed_or_not() { } } +/// [`scene`] with a per-polygon-vertex color layer: corner `i` gets `(i/8, 1 - i/8, 0.25, 1)`. +fn colored_scene() -> Vec { + let mut nodes = scene(false); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + let geometry = objects.children.iter_mut().find(|node| node.name == "Geometry").unwrap(); + let colors: Vec = (0..7).flat_map(|i| [i as f64 / 8.0, 1.0 - i as f64 / 8.0, 0.25, 1.0]).collect(); + geometry.children.push(layer( + "LayerElementColor", + "ByPolygonVertex", + "IndexToDirect", + vec![n("Colors", vec![P::Doubles(colors)], vec![]), n("ColorIndex", vec![P::Ints((0..7).collect())], vec![])], + )); + nodes +} + +#[test] +fn fbx_vertex_colors_reach_the_mesh_and_high_polys() { + let nodes = colored_scene(); + let expected: Vec = (0..7).map(|i| Vec4::new(i as f32 / 8.0, 1.0 - i as f32 / 8.0, 0.25, 1.0)).collect(); + for (label, bytes) in [("binary", binary_fbx(&nodes, 7400, false)), ("ascii", ascii_fbx(&nodes).into_bytes())] { + let imported = import_mesh_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(imported.mesh.colors, expected, "{label}: the color layer reaches the mesh"); + let high = import_high_poly_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(high.mesh.colors, expected, "{label}: and the high poly used for ID bakes"); + } +} + /// [`scene`] with a diffuse color on Red and an embedded diffuse texture on Blue. +#[test] +fn fbx_camera_models_are_capped_during_import() { + let mut nodes = scene(false); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + for id in 100..199 { + objects.children.push(n("Model", vec![P::L(id), P::S("Camera\\u{0}\\u{1}Model"), P::S("Camera")], vec![])); + } + + let raw = fbx::read(&binary_fbx(&nodes, 7500, true)).unwrap(); + assert_eq!(raw.cameras.len(), MAX_CAMERAS); +} + fn textured_scene(png: &[u8]) -> Vec { let mut nodes = scene(false); let objects = nodes.iter_mut().find(|n| n.name == "Objects").unwrap(); @@ -415,6 +454,24 @@ fn fbx_ascii_and_z_up() { check_fbx_scene(&import_mesh_bytes("z.fbx", &binary_fbx(&scene(true), 7700, true)).unwrap().mesh, true); } +#[test] +fn fbx_duplicate_geometry_connections_do_not_duplicate_instances() { + let mut nodes = scene(false); + let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap(); + for _ in 0..50 { + connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(21)], vec![])); + } + let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap(); + assert_eq!(imported.report.triangles, 3); + + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + objects.children.push(n("Model", vec![P::L(22), P::S("Other\u{0}\u{1}Model"), P::S("Mesh")], vec![])); + let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap(); + connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(22)], vec![])); + let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap(); + assert_eq!(imported.report.triangles, 6, "a different model must remain a distinct instance"); +} + /// The scene of [`scene`] (Y up) as FBX 6.1 writes it: geometry inside the Model, objects named /// `Class::Name`, `Properties60`, `Connect` records, GlobalSettings inside Objects. const FBX61: &str = r#"; FBX 6.1.0 project file @@ -589,19 +646,55 @@ fn fbx_old_versions_and_garbage_are_errors() { assert!(import_mesh_bytes("h.fbx", &huge).is_err()); } +// Keep these fixtures independently schedulable: one serial test took 24 minutes in +// instrumented coverage. Splitting cases keeps every mutation and assertion intact. #[test] -fn malformed_fbx_and_dae_never_panic() { +fn malformed_fbx_and_dae_never_panic_binary_7400() { hammer("x.fbx", &binary_fbx(&scene(false), 7400, false)); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_binary_7500() { hammer("x.fbx", &binary_fbx(&scene(true), 7500, true)); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_ascii() { hammer("x.fbx", ascii_fbx(&scene(false)).as_bytes()); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_collada() { hammer("x.dae", DAE.as_bytes()); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_binary() { + random_scene_corruptions(0); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_ascii() { + random_scene_corruptions(1); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_collada() { + random_scene_corruptions(2); +} + +fn random_scene_corruptions(selected_fixture: usize) { // Random multi-byte corruptions (a fixed LCG keeps failures reproducible). let mut seed = 0x2545_f491_4f6c_dd1du64; let mut next = move || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) as usize }; - for good in [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()] { + // Replay earlier mutations without parsing them so each fixture receives exactly + // its original LCG stream, not a fresh seed. Fixture sizes and all 1,500 cases + // per fixture stay unchanged; generating these bytes is cheap next to parsing. + let fixtures = [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()]; + for (fixture, good) in fixtures.into_iter().enumerate().take(selected_fixture + 1) { let name = if good.starts_with(b" Result { - let count = bytes.get(80..84).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); - let binary_len = count.and_then(|c| c.checked_mul(50)).and_then(|n| n.checked_add(84)); - let looks_ascii = bytes.iter().position(|b| !b.is_ascii_whitespace()).and_then(|i| bytes.get(i..i + 5)) == Some(b"solid".as_slice()); - let tris = match (count, binary_len) { - // Exact size wins: many binary files also start with "solid". - (Some(c), Some(len)) if len == bytes.len() => binary(bytes, c)?, - _ if looks_ascii => ascii(bytes)?, - (Some(c), Some(len)) if len < bytes.len() => binary(bytes, c)?, - _ => return Err(malformed(KIND, "neither a complete binary STL nor an ascii STL")), - }; + let scene = craft_mesh::stl::read(bytes, &stl_limits()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut raw = RawMesh::default(); - check_triangles(0, tris.len())?; - let mut normals = Vec::with_capacity(tris.len() * 3); - for t in &tris { - let n = (t[1] - t[0]).cross(t[2] - t[0]).try_normalize().unwrap_or(Vec3::Y); - raw.positions.extend_from_slice(t); - normals.extend_from_slice(&[n; 3]); + raw.warnings = scene.warnings; + + let mut tri_count = 0; + let mut vertex_colors = Vec::new(); + let has_colors = !scene.materials.is_empty(); + for mesh in scene.meshes { + // The shared model groups colored facets into parts. Position indices still reflect + // source order, so merge the parts back into STL order for TextureCraft's raw mesh. + let mut triangles = Vec::new(); + for part in mesh.parts { + let material = part.material.and_then(|i| scene.materials.get(i)); + let color = material.map(|m| Vec4::from_array(m.base_color)); + for tri in part.triangles() { + let first_position = tri.iter().map(|c| c.position).min().unwrap_or(u32::MAX); + triangles.push((first_position, tri, color)); + } + } + triangles.sort_by_key(|(first_position, _, _)| *first_position); + for (_, tri, color) in triangles { + check_triangles(tri_count, 1)?; + tri_count += 1; + let mut points = [Vec3::ZERO; 3]; + for (i, corner) in tri.into_iter().enumerate() { + let p = mesh.positions.get(corner.position as usize).ok_or_else(|| FormatError::Invalid(format!("{KIND}: position index out of range")))?; + points[i] = Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32); + } + // Recompute per-facet normals as TextureCraft's old importer did; stored STL + // normals are often zero or disagree with the vertex winding. + let normal = (points[1] - points[0]).cross(points[2] - points[0]).try_normalize().unwrap_or(Vec3::Y); + raw.positions.extend_from_slice(&points); + raw.normals.get_or_insert_with(Vec::new).extend_from_slice(&[normal; 3]); + if has_colors { + // The shared reader normalizes STL's color extensions to linear RGBA. + // Uncolored facets alongside colored ones receive its neutral gray material. + let color = color.unwrap_or(Vec4::new(0.6, 0.6, 0.6, 1.0)); + vertex_colors.extend_from_slice(&[color; 3]); + } + } + } + if raw.positions.is_empty() { + return Err(crate::malformed(KIND, "no facets")); + } + if has_colors { + raw.colors = Some(vertex_colors); } - raw.normals = Some(normals); raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); Ok(raw) } -fn binary(bytes: &[u8], count: usize) -> Result> { - check_triangles(0, count)?; - let mut out = Vec::with_capacity(count); - for i in 0..count { - let f = |k: usize| -> Result { - let o = 84 + i * 50 + 12 + k * 4; - let b = bytes.get(o..o + 4).ok_or_else(|| malformed(KIND, "truncated facet"))?; - Ok(f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - }; - let v = |c: usize| -> Result { Ok(Vec3::new(f(c * 3)?, f(c * 3 + 1)?, f(c * 3 + 2)?)) }; - out.push([v(0)?, v(1)?, v(2)?]); - } - Ok(out) +/// STL stores three positions per facet; retain the app's established triangle capacity. +fn stl_limits() -> craft_mesh::Limits { + craft_mesh::Limits { max_vertices: MAX_VERTICES, ..craft_mesh::Limits::default() } } -fn ascii(bytes: &[u8]) -> Result> { - let text = std::str::from_utf8(bytes).map_err(|_| malformed(KIND, "ascii STL is not text"))?; - let mut out = Vec::new(); - let mut facet: Vec = Vec::new(); - let mut words = text.split_whitespace(); - while let Some(w) = words.next() { - match w { - "vertex" => { - let mut c = [0.0f32; 3]; - for v in &mut c { - let tok = words.next().ok_or_else(|| malformed(KIND, "truncated vertex"))?; - *v = tok.parse().map_err(|_| malformed(KIND, format!("bad number \"{tok}\"")))?; - } - facet.push(Vec3::from(c)); - } - "endfacet" => { - for i in 1..facet.len().saturating_sub(1) { - check_triangles(out.len(), 1)?; - out.push([facet[0], facet[i], facet[i + 1]]); - } - facet.clear(); - } - _ => {} - } +#[cfg(test)] +mod tests { + #[test] + fn shared_reader_accepts_the_app_vertex_limit() { + let limits = super::stl_limits(); + assert_eq!(limits.max_vertices, super::MAX_VERTICES); + assert_eq!(limits.max_triangles, texturecraft_geom::MAX_TRIANGLES); } - if out.is_empty() { - return Err(malformed(KIND, "no facets")); - } - Ok(out) } diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index e55f8eae..88509a05 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -118,6 +118,48 @@ fn glb_two_materials_mirrored_node() { m.validate().unwrap(); } +/// A scene without a `nodes` array is legal glTF (Blender writes one for a scene with no exported +/// objects); it must not stop the default scene from importing. +#[test] +fn gltf_scene_without_nodes_imports_the_default_scene() { + let mut json: serde_json::Value = serde_json::from_slice(&embedded_gltf()).unwrap(); + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]); + json["scene"] = 1.into(); + let im = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap(); + assert_eq!(im.report.triangles, 2); + // Only an empty scene: nothing to import, but a clear error rather than a parse failure. + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }]); + json["scene"] = 0.into(); + let err = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap_err(); + assert!(!err.to_string().contains("missing field"), "{err}"); +} + +#[test] +fn glb_scene_without_nodes_keeps_binary_mesh_in_default_scene() { + let original = glb(true, true); + let jlen = u32::from_le_bytes(original[12..16].try_into().unwrap()) as usize; + let mut json: serde_json::Value = serde_json::from_slice(&original[20..20 + jlen]).unwrap(); + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]); + json["scene"] = 1.into(); + let mut js = serde_json::to_vec(&json).unwrap(); + while !js.len().is_multiple_of(4) { + js.push(b' '); + } + let bin_chunk = &original[20 + jlen..]; + let mut glb = Vec::new(); + glb.extend(b"glTF"); + glb.extend(2u32.to_le_bytes()); + glb.extend(((20 + js.len() + bin_chunk.len()) as u32).to_le_bytes()); + glb.extend((js.len() as u32).to_le_bytes()); + glb.extend(b"JSON"); + glb.extend(js); + glb.extend(bin_chunk); + let im = import_mesh_bytes("scene.glb", &glb).unwrap(); + assert_eq!(im.report.triangles, 2); + assert_eq!(im.mesh.materials, ["Red", "Material_1"]); + assert_outward(&im.mesh); +} + #[test] fn gltf_embedded_buffers_and_missing_attributes() { let im = import_mesh_bytes("scene.gltf", &embedded_gltf()).unwrap(); @@ -372,6 +414,43 @@ fn stl_ascii_and_binary() { assert_eq!(import_mesh_bytes("c.stl", &b).unwrap().mesh.triangle_count(), 2); } +#[test] +fn stl_shared_reader_keeps_flat_normals_and_surfaces_shared_repairs_and_colors() { + let mut bytes = stl_binary(); + // VisCAM/SolidView: bit 15 marks a facet color; red occupies bits 10..14. + bytes[132..134].copy_from_slice(&0xfc00u16.to_le_bytes()); + // A third facet repeats that color after an uncolored facet. The shared reader groups its + // parts by color, so the adapter must restore the source facet order. + bytes.extend([0.0f32; 3].iter().flat_map(|v| v.to_le_bytes())); + for v in [[0.0f32, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]] { + bytes.extend(v.iter().flat_map(|x| x.to_le_bytes())); + } + bytes.extend(0xfc00u16.to_le_bytes()); + // Some exporters leave the header count at zero despite having facets. + bytes[80..84].copy_from_slice(&0u32.to_le_bytes()); + let imported = import_mesh_bytes("colored.stl", &bytes).unwrap(); + assert_eq!(imported.mesh.triangle_count(), 3); + assert_eq!(imported.mesh.submeshes.len(), 1); + assert_eq!(imported.mesh.submeshes[0].name, "colored"); + assert_eq!( + imported.mesh.positions, + vec![ + Vec3::ZERO, + Vec3::X, + Vec3::new(1.0, 1.0, 0.0), + Vec3::ZERO, + Vec3::new(1.0, 1.0, 0.0), + Vec3::Y, + Vec3::Z, + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 1.0, 1.0) + ] + ); + assert_eq!(imported.mesh.normals, vec![Vec3::Z; 9]); + assert!(imported.mesh.colors.iter().any(|c| c.x > 0.99 && c.y < 0.01 && c.z < 0.01)); + assert!(imported.report.warnings.iter().any(|w| w.contains("counts no facets"))); +} + /// Every prefix and some corruptions of a valid file: errors, never panics (and never an /// error from the panic guard, which would mean a parser panicked). pub(crate) fn hammer(name: &str, good: &[u8]) { diff --git a/crates/formats/src/mesh_import/usd/codec.rs b/crates/formats/src/mesh_import/usd/codec.rs index a336db33..4221e390 100644 --- a/crates/formats/src/mesh_import/usd/codec.rs +++ b/crates/formats/src/mesh_import/usd/codec.rs @@ -104,35 +104,13 @@ pub(crate) fn numeric(t: u8) -> Option<(Scalar, usize)> { /// Decompress Crate's LZ4 framing into at most `max_out` bytes. pub(crate) fn decompress(input: &[u8], max_out: usize) -> Result> { - let bad = |e: lz4_flex::block::DecompressError| malformed(KIND, format!("LZ4 data: {e}")); - let (&chunks, mut rest) = input.split_first().ok_or_else(|| malformed(KIND, "empty compressed block"))?; - // LZ4 expands at most ~255×: never allocate more than the input can produce. - let mut out = vec![0u8; max_out.min(input.len().saturating_mul(256).saturating_add(64))]; - let written = if chunks == 0 { - lz4_flex::block::decompress_into(rest, &mut out).map_err(bad)? - } else { - if chunks > 127 { - return Err(malformed(KIND, "bad LZ4 chunk count")); - } - let mut total = 0usize; - for _ in 0..chunks { - let size = rest.get(..4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?; - let size = usize::try_from(size).map_err(|_| malformed(KIND, "negative LZ4 chunk size"))?; - let chunk = rest.get(4..4usize.saturating_add(size)).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?; - rest = rest.get(4 + size..).unwrap_or_default(); - total += lz4_flex::block::decompress_into(chunk, out.get_mut(total..).unwrap_or_default()).map_err(bad)?; - } - total - }; - out.truncate(written); - Ok(out) + craft_usd::decompress(input, max_out).map_err(|e| malformed(KIND, e.to_string())) } /// Crate's LZ4 framing for one chunk (inputs are far below LZ4's ~2 GB chunk limit). -pub(crate) fn compress(input: &[u8]) -> Vec { - let mut out = vec![0u8]; - out.extend_from_slice(&lz4_flex::block::compress(input)); - out +pub(crate) fn compress(input: &[u8]) -> Result> { + // Keep one compressed output reservation within the app's decoded-data ceiling. + craft_usd::compress::compress(input, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } /// Upper bound of the encoded size of `n` integers of `width` bytes. @@ -140,89 +118,24 @@ pub(crate) fn encoded_ints_len(n: usize, width: usize) -> usize { if n == 0 { 0 } else { width.saturating_add(n.saturating_mul(2).saturating_add(7) / 8).saturating_add(n.saturating_mul(width)) } } -fn read_signed(b: &[u8], at: usize, width: usize) -> Option { - let s = b.get(at..at.checked_add(width)?)?; - Some(match width { - 1 => i64::from(i8::from_le_bytes(s.try_into().ok()?)), - 2 => i64::from(i16::from_le_bytes(s.try_into().ok()?)), - 4 => i64::from(i32::from_le_bytes(s.try_into().ok()?)), - _ => i64::from_le_bytes(s.try_into().ok()?), - }) -} - -/// Decode `n` integers of `width` (4 or 8) bytes; 32-bit values are sign-extended (reinterpret -/// as u32 for unsigned data). +/// Decode packed integers after the caller charges its aggregate decoded-byte budget. pub(crate) fn decode_ints(data: &[u8], n: usize, width: usize) -> Result> { - let err = || malformed(KIND, "truncated integer array"); - if n == 0 { - return Ok(Vec::new()); - } - let common = read_signed(data, 0, width).ok_or_else(err)?; - let codes_at = width; - let mut at = codes_at + n.div_ceil(4); - let mut out = Vec::with_capacity(n); - let mut prev = 0i64; - for i in 0..n { - let code = (data.get(codes_at + i / 4).ok_or_else(err)? >> (2 * (i % 4))) & 3; - let delta = match code { - 0 => common, - c => { - let w = (width >> (3 - c as usize)).max(1); - let v = read_signed(data, at, w).ok_or_else(err)?; - at += w; - v - } - }; - prev = if width == 4 { i64::from((prev as i32).wrapping_add(delta as i32)) } else { prev.wrapping_add(delta) }; - out.push(prev); - } - Ok(out) + let width = match width { + 4 => craft_usd::integers::Width::I32, + 8 => craft_usd::integers::Width::I64, + _ => return Err(malformed(KIND, "unsupported integer width")), + }; + craft_usd::integers::decode(data, n, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } -/// Encode integers of `width` (4 or 8) bytes (values must fit the width). -pub(crate) fn encode_ints(values: &[i64], width: usize) -> Vec { - if values.is_empty() { - return Vec::new(); - } - let wrap = |v: i64| if width == 4 { i64::from(v as i32) } else { v }; - let mut prev = 0i64; - let deltas: Vec = values - .iter() - .map(|&v| { - let d = wrap(v.wrapping_sub(prev)); - prev = v; - d - }) - .collect(); - let mut counts = std::collections::HashMap::new(); - for d in &deltas { - *counts.entry(*d).or_insert(0usize) += 1; - } - let common = counts.into_iter().max_by_key(|&(v, c)| (c, v)).map_or(0, |(v, _)| v); - let mut out = Vec::with_capacity(encoded_ints_len(values.len(), width)); - out.extend_from_slice(&common.to_le_bytes()[..width]); - let codes_at = out.len(); - out.resize(codes_at + values.len().div_ceil(4), 0); - for (i, &d) in deltas.iter().enumerate() { - let small = |bits: u32| d >= -(1i64 << (bits - 1)) && d < (1i64 << (bits - 1)); - let code: u8 = if d == common { - 0 - } else if small(width as u32 * 2) { - 1 - } else if small(width as u32 * 4) { - 2 - } else { - 3 - }; - if code > 0 { - let w = (width >> (3 - code as usize)).max(1); - out.extend_from_slice(&d.to_le_bytes()[..w]); - } - if let Some(b) = out.get_mut(codes_at + i / 4) { - *b |= code << (2 * (i % 4)); - } - } - out +/// Encode packed integers with a combined scratch/output reservation cap. +pub(crate) fn encode_ints(values: &[i64], width: usize) -> Result> { + let width = match width { + 4 => craft_usd::integers::Width::I32, + 8 => craft_usd::integers::Width::I64, + _ => return Err(malformed(KIND, "unsupported integer width")), + }; + craft_usd::integers::encode(values, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } /// Error for counts that cannot be real (more items than bytes left could describe). diff --git a/crates/formats/src/mesh_import/usd/mod.rs b/crates/formats/src/mesh_import/usd/mod.rs index e7f9d0fe..9f6f6d41 100644 --- a/crates/formats/src/mesh_import/usd/mod.rs +++ b/crates/formats/src/mesh_import/usd/mod.rs @@ -576,6 +576,7 @@ impl<'a> Stage<'a> { p: m.transform_point3(Vec3::from(p)), n: normals.as_ref().and_then(|pv| pv.get::<3>(at)).map(|v| nm * Vec3::from(v)), uv: uvs.as_ref().and_then(|pv| pv.get::<2>(at)).map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } if flip { diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 1797093b..c8a8cf25 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -408,18 +408,50 @@ fn usd_extension_detects_the_encoding() { fn integer_coding_round_trips() { let values: Vec = vec![0, 1, 2, 3, 3, 3, -5, 1000, -70000, i64::from(i32::MAX), i64::from(i32::MIN), 7, 7, 7, 8]; for width in [4, 8] { - let enc = codec::encode_ints(&values, width); + let enc = codec::encode_ints(&values, width).unwrap(); assert!(enc.len() <= codec::encoded_ints_len(values.len(), width)); assert_eq!(codec::decode_ints(&enc, values.len(), width).unwrap(), values); assert!(codec::decode_ints(&enc[..enc.len() - 1], values.len(), width).is_err()); } let wide = vec![i64::MAX, i64::MIN, 0, 1 << 40]; - assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8), 4, 8).unwrap(), wide); + assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8).unwrap(), 4, 8).unwrap(), wide); let big: Vec = (0..5000u32).flat_map(|i| (i % 7).to_le_bytes()).collect(); - assert_eq!(codec::decompress(&codec::compress(&big), big.len()).unwrap(), big); + assert_eq!(codec::decompress(&codec::compress(&big).unwrap(), big.len()).unwrap(), big); assert!(codec::decompress(&[0, 0xF0], 10).is_err()); } +#[test] +fn shared_crate_lz4_writer_preserves_bytes() { + for len in [0, 1, 15, 16, 255, 4096] { + let data: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + let mut previous = vec![0]; + previous.extend(lz4_flex::block::compress(&data)); + assert_eq!(codec::compress(&data).unwrap(), previous); + } +} + +#[test] +fn shared_integer_decoder_rejects_unsupported_width_and_oversized_output() { + assert!(codec::decode_ints(&[], 1, 3).is_err()); + assert!(codec::decode_ints(&[], super::MAX_DECODED_BYTES / 8 + 1, 8).is_err()); + assert!(codec::decode_ints(&[], 0, 4).unwrap().is_empty()); +} + +#[test] +fn shared_crate_lz4_retains_chunk_and_budget_policy() { + let mut frame = vec![2]; + for raw in [b"abc".as_slice(), b"def".as_slice()] { + let block = lz4_flex::block::compress(raw); + frame.extend((block.len() as i32).to_le_bytes()); + frame.extend(block); + } + frame.extend(b"old reader ignores this tail"); + assert_eq!(codec::decompress(&frame, 6).unwrap(), b"abcdef"); + assert!(codec::decompress(&frame, 5).is_err()); + assert!(codec::decompress(&[1, 255, 255, 255, 255], 64).is_err()); + assert!(codec::decompress(&[128], 64).is_err()); +} + #[test] fn malformed_usd_never_panics() { // A small two-material mesh keeps the byte loops fast. @@ -477,3 +509,10 @@ fn loose_layer_textures_are_packaged() { assert_eq!((f.name, f.bytes == out.bytes, f.warnings.len()), (format!("t.{ext}"), true, 1), "{ext}"); } } + +#[test] +fn shared_integer_writer_preserves_tie_wire_and_rejects_invalid_width() { + assert_eq!(codec::encode_ints(&[1, 3, 4, 6], 4).unwrap(), vec![2, 0, 0, 0, 17, 1, 1]); + assert!(codec::encode_ints(&[1], 3).is_err()); + assert!(codec::encode_ints(&[], 8).unwrap().is_empty()); +} diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 221c7b4a..fb925765 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -15,6 +15,9 @@ const MIN_VERSION: (u8, u8, u8) = (0, 4, 0); const MAX_SECTIONS: usize = 64; /// Items in one table or array. const MAX_ITEMS: usize = 1 << 28; +/// Entries in the PATHS table. The declared count is tiny in the file but each entry is a +/// materialised path, so it needs its own ceiling as well as the decoded-byte budget. +const MAX_PATHS: usize = 4_000_000; /// Spec types. const SPEC_ATTRIBUTE: i64 = 1; @@ -242,58 +245,73 @@ impl<'a> Crate<'a> { /// Paths are stored as a pre-order tree: element token (negative for properties) and a /// jump per node (-2 leaf, -1 child only, 0 sibling only, >0 child and sibling at +jump). - fn read_paths(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> { - let total = s.count(0)?; - let n = s.count(0)?; - let index = s.ints(n, 4, budget)?; - let elements = s.ints(n, 4, budget)?; - let jumps = s.ints(n, 4, budget)?; - budget.take(total.saturating_mul(64))?; - self.paths = vec![None; total]; - let mut work: Vec<(usize, Option)> = vec![(0, None)]; - let mut steps = 0usize; - let bad = || malformed(KIND, "corrupt path table"); - while let Some((mut i, mut parent)) = work.pop() { + fn read_paths(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let path_count = section.count(0)?; + let encoded_count = section.count(0)?; + let path_indices = section.ints(encoded_count, 4, budget)?; + let elements = section.ints(encoded_count, 4, budget)?; + let jumps = section.ints(encoded_count, 4, budget)?; + if path_count > MAX_PATHS { + return Err(FormatError::TooLarge(format!("the USD path table has {path_count} entries (limit {MAX_PATHS})"))); + } + + // Charge slot storage before allocating the table + budget.take(path_count.saturating_mul(std::mem::size_of::>()))?; + self.paths = vec![None; path_count]; + let mut pending_branches: Vec<(usize, Option)> = vec![(0, None)]; + let mut visited_count = 0usize; + let path_error = || malformed(KIND, "corrupt path table"); + while let Some((mut cursor_index, mut parent)) = pending_branches.pop() { loop { - steps += 1; - if steps > n { - return Err(bad()); + visited_count += 1; + if visited_count > encoded_count { + return Err(path_error()); } - let this = i; - i += 1; - let at = index.get(this).map(|v| *v as u32 as usize).filter(|p| *p < total).ok_or_else(bad)?; - let el = match parent { + + let node_index = cursor_index; + cursor_index += 1; + let path_index = + path_indices.get(node_index).map(|v| *v as u32 as usize).filter(|parent_index| *parent_index < path_count).ok_or_else(path_error)?; + let path_element = match parent { None => PathEl { text: "/".into(), parent: None, name: String::new(), prop: false }, - Some(p) => { - let e = *elements.get(this).ok_or_else(bad)?; - let name = self.token(e.unsigned_abs())?.to_string(); - let base = self.paths.get(p).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(bad)?; - let text = match (e < 0, base) { - (true, _) => format!("{base}.{name}"), - (false, _) if name.starts_with('{') => format!("{base}{name}"), + Some(parent_index) => { + let element_token = *elements.get(node_index).ok_or_else(path_error)?; + let name = self.token(element_token.unsigned_abs())?; + let parent_path = self.paths.get(parent_index).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(path_error)?; + let separator_bytes = usize::from(element_token < 0 || (!name.starts_with('{') && parent_path != "/")); + let text_bytes = parent_path.len().saturating_add(name.len()).saturating_add(separator_bytes); + + // Charge both retained strings before allocating either one + budget.take(text_bytes.saturating_add(name.len()))?; + let name = name.to_string(); + let text = match (element_token < 0, parent_path) { + (true, _) => format!("{parent_path}.{name}"), + (false, _) if name.starts_with('{') => format!("{parent_path}{name}"), (false, "/") => format!("/{name}"), - (false, _) => format!("{base}/{name}"), + (false, _) => format!("{parent_path}/{name}"), }; - budget.take(text.len())?; - PathEl { text, parent: Some(p), name, prop: e < 0 } + PathEl { text, parent: Some(parent_index), name, prop: element_token < 0 } } }; - if let Some(slot) = self.paths.get_mut(at) { - *slot = Some(el); + + if let Some(slot) = self.paths.get_mut(path_index) { + *slot = Some(path_element); } - let jump = *jumps.get(this).ok_or_else(bad)?; + + let jump = *jumps.get(node_index).ok_or_else(path_error)?; let (child, sibling) = (jump > 0 || jump == -1, jump >= 0); if child { if sibling { - work.push((this.checked_add(usize::try_from(jump).map_err(|_| bad())?).ok_or_else(bad)?, parent)); + pending_branches.push((node_index.checked_add(usize::try_from(jump).map_err(|_| path_error())?).ok_or_else(path_error)?, parent)); } - parent = Some(at); + parent = Some(path_index); } if !child && !sibling { break; } } } + Ok(()) } @@ -642,11 +660,47 @@ mod tests { } fn compressed_ints(out: &mut Vec, v: &[i64]) { - let comp = codec::compress(&codec::encode_ints(v, 4)); + let comp = codec::compress(&codec::encode_ints(v, 4).unwrap()).unwrap(); out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); out.extend_from_slice(&comp); } + #[test] + fn repeated_path_names_count_toward_the_decode_budget() { + let name = "long_name_reused"; + let mut section = Vec::new(); + section.extend_from_slice(&3u64.to_le_bytes()); + section.extend_from_slice(&3u64.to_le_bytes()); + compressed_ints(&mut section, &[0, 1, 2]); + compressed_ints(&mut section, &[0, 0, 0]); + compressed_ints(&mut section, &[-1, 0, -2]); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + + let decoded_arrays_bytes = 3 * 3 * std::mem::size_of::(); + let path_slots_bytes = 3 * std::mem::size_of::>(); + let path_text_bytes = 2 * (1 + name.len()); + let one_name_budget = decoded_arrays_bytes + path_slots_bytes + path_text_bytes + name.len(); + let mut insufficient_budget = Budget(one_name_budget); + + let rejected = crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut insufficient_budget); + + assert!(matches!(rejected, Err(FormatError::TooLarge(_))), "two path names cannot fit a one-name budget"); + drop(crate_data); + + let mut complete_budget = Budget(one_name_budget + name.len()); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut complete_budget).unwrap(); + + assert_eq!(complete_budget.0, 0); + assert_eq!(crate_data.path(1).unwrap().text, format!("/{name}")); + assert_eq!(crate_data.path(2).unwrap().text, format!("/{name}")); + let retained_name_bytes: usize = crate_data.paths.iter().filter_map(Option::as_ref).map(|path| path.name.capacity()).sum(); + assert!(retained_name_bytes >= 2 * name.len()); + println!("retained names: 2, buffer capacity: {retained_name_bytes} bytes"); + } + #[test] fn compressed_float_and_int_arrays() { let n = 20usize; @@ -667,7 +721,7 @@ mod tests { compressed_ints(&mut b, &idx); let i64_at = b.len() as u64; b.extend_from_slice(&(n as u64).to_le_bytes()); - let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8)); + let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8).unwrap()).unwrap(); b.extend_from_slice(&(comp.len() as u64).to_le_bytes()); b.extend_from_slice(&comp); let c = crate_over(&b, (0, 8, 0)); diff --git a/crates/formats/src/project_file/load_budget.rs b/crates/formats/src/project_file/load_budget.rs index 284c4d64..a183336a 100644 --- a/crates/formats/src/project_file/load_budget.rs +++ b/crates/formats/src/project_file/load_budget.rs @@ -13,14 +13,18 @@ impl LoadBudget { self.limit_bytes - self.used_bytes } + pub(super) fn exceeded_message(&self) -> String { + format!( + "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", + self.limit_bytes, + self.limit_bytes as f64 / (1u64 << 30) as f64, + ) + } + /// Reserve bytes before retaining decoded data so entries share one allocation budget. pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> { if bytes > self.remaining() { - return Err(format!( - "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", - self.limit_bytes, - self.limit_bytes as f64 / (1u64 << 30) as f64, - )); + return Err(self.exceeded_message()); } self.used_bytes += bytes; diff --git a/crates/formats/src/project_file/metadata_reader.rs b/crates/formats/src/project_file/metadata_reader.rs deleted file mode 100644 index 7e82825c..00000000 --- a/crates/formats/src/project_file/metadata_reader.rs +++ /dev/null @@ -1,81 +0,0 @@ -use std::cell::Cell; -use std::io::{self, Read, Seek, SeekFrom}; - -/// Restrict ZIP indexing to a bounded tail and read allowance before enabling payload access. -pub(super) struct MetadataReader<'a, R> { - reader: R, - metadata_only: &'a Cell, - metadata_start: u64, - remaining_bytes: u64, - position: u64, -} - -impl<'a, R: Read + Seek> MetadataReader<'a, R> { - pub(super) fn new(mut reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> io::Result { - let end = reader.seek(SeekFrom::End(0))?; - Ok(Self { reader, metadata_only, metadata_start: end.saturating_sub(metadata_bytes), remaining_bytes: metadata_bytes.saturating_mul(2), position: end }) - } -} - -impl Read for MetadataReader<'_, R> { - fn read(&mut self, bytes: &mut [u8]) -> io::Result { - if bytes.is_empty() { - return Ok(0); - } - - let metadata_only = self.metadata_only.get(); - if metadata_only && (self.position < self.metadata_start || self.remaining_bytes == 0) { - return Err(io::Error::new(io::ErrorKind::InvalidData, "project ZIP metadata exceeds the indexing limit")); - } - - let length = if metadata_only { bytes.len().min(usize::try_from(self.remaining_bytes).unwrap_or(usize::MAX)) } else { bytes.len() }; - let read = self.reader.read(bytes.get_mut(..length).unwrap_or_default())?; - self.position = self.position.saturating_add(read as u64); - if metadata_only { - self.remaining_bytes -= read as u64; - } - - Ok(read) - } -} - -impl Seek for MetadataReader<'_, R> { - fn seek(&mut self, position: SeekFrom) -> io::Result { - self.position = self.reader.seek(position)?; - Ok(self.position) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Cursor; - - #[test] - fn indexing_cannot_read_payloads_outside_the_metadata_window() { - let metadata_only = Cell::new(true); - let mut reader = MetadataReader::new(Cursor::new(vec![7; 100]), &metadata_only, 8).unwrap(); - reader.seek(SeekFrom::Start(91)).unwrap(); - - assert!(reader.read(&mut [0; 1]).is_err()); - reader.seek(SeekFrom::Start(92)).unwrap(); - reader.read_exact(&mut [0; 8]).unwrap(); - - metadata_only.set(false); - reader.seek(SeekFrom::Start(0)).unwrap(); - reader.read_exact(&mut [0; 100]).unwrap(); - } - - #[test] - fn repeated_metadata_scans_share_one_read_allowance() { - let metadata_only = Cell::new(true); - let mut reader = MetadataReader::new(Cursor::new(vec![7; 8]), &metadata_only, 8).unwrap(); - for _ in 0..2 { - reader.seek(SeekFrom::Start(0)).unwrap(); - reader.read_exact(&mut [0; 8]).unwrap(); - } - reader.seek(SeekFrom::Start(0)).unwrap(); - - assert!(reader.read(&mut [0; 1]).is_err()); - } -} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 8390220a..e1d98196 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -18,7 +18,6 @@ //! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture //! set cover its whole atlas (`resolution` per tile, see `TileGrid`). -use std::cell::Cell; use std::collections::{BTreeMap, HashSet}; use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; @@ -31,21 +30,21 @@ use zip::{CompressionMethod, ZipArchive, ZipWriter}; use self::entries::Entry; use self::load_budget::LoadBudget; -use self::metadata_reader::MetadataReader; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; mod load_budget; -mod metadata_reader; mod project_open_limit; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources}; pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; const KIND: &str = "project file"; +#[cfg(test)] const MAGIC: &[u8; 4] = b"TCTX"; -/// Version of the `.bin` layout. +#[cfg(test)] const BIN_VERSION: u32 = 1; +#[cfg(test)] const BIN_HEADER_BYTES: usize = 24; const MAX_JSON: u64 = 256 << 20; const MAX_THUMBNAIL: u64 = 64 << 20; @@ -98,23 +97,23 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result> { Ok(out.into_inner()) } -/// Save atomically: `.tmp` first, then rename over `path`. +/// Save atomically through a newly created temporary file beside `path`. #[cfg(not(target_arch = "wasm32"))] -pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); - let res = (|| -> Result<()> { - let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?); - write_project(&mut file, pf)?; - file.into_inner().map_err(|e| e.into_error())?.sync_all()?; - std::fs::rename(&tmp, path)?; +pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Result<()> { + let (temporary_path, file) = crate::create_temp(path)?; + let result = (|| -> Result<()> { + let mut file = std::io::BufWriter::new(file); + write_project(&mut file, project_file)?; + file.into_inner().map_err(|error| error.into_error())?.sync_all()?; + std::fs::rename(&temporary_path, path)?; Ok(()) })(); - if res.is_err() { - let _ = std::fs::remove_file(&tmp); + + if result.is_err() { + let _ = std::fs::remove_file(&temporary_path); } - res + + result } fn zip_err(e: zip::result::ZipError) -> FormatError { @@ -124,6 +123,7 @@ fn zip_err(e: zip::result::ZipError) -> FormatError { } } +#[cfg(test)] fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { let mut b = MAGIC.to_vec(); for v in [BIN_VERSION, w, h, comps as u32, count as u32] { @@ -132,19 +132,18 @@ fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { b } -fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { - w.write_all(&header(img.width(), img.height(), img.comps(), img.allocated_count()))?; - let mut buf = Vec::with_capacity(TILE_AREA * img.comps() * 2 + 8); - for (tx, ty) in img.allocated() { - buf.clear(); - buf.extend_from_slice(&tx.to_le_bytes()); - buf.extend_from_slice(&ty.to_le_bytes()); - for v in img.tile(tx, ty).unwrap_or_default() { - buf.extend_from_slice(&v.to_le_bytes()); - } - w.write_all(&buf)?; +fn codec_write_error(error: craft_tcraft::Error) -> std::io::Error { + match error { + craft_tcraft::Error::Io(error) => error, + other => std::io::Error::other(other), } - Ok(()) +} + +fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { + let layout = craft_tcraft::Layout { width: img.width(), height: img.height(), components: img.comps() }; + let count = u32::try_from(img.allocated_count()).map_err(std::io::Error::other)?; + let tiles = img.allocated().map(|(x, y)| (x, y, img.tile(x, y).unwrap_or_default())); + craft_tcraft::write_tiles(w, layout, count, tiles).map_err(codec_write_error) } /// Keep `[a-z0-9]`, at most 8 characters (the mesh entry's extension). @@ -169,18 +168,12 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet) -> Strin entry } -/// Floats converted to bytes at a time when a baked map streams into the compressor. +#[cfg(test)] const BAKED_CHUNK: usize = 1 << 16; fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> { - w.write_all(&header(res, h, comps, 0))?; - let mut buf = Vec::with_capacity(BAKED_CHUNK * 4); - for chunk in data.chunks(BAKED_CHUNK) { - buf.clear(); - buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); - w.write_all(&buf)?; - } - Ok(()) + let layout = craft_tcraft::Layout { width: res, height: h, components: comps }; + craft_tcraft::write_baked(w, layout, data).map_err(codec_write_error) } /// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. @@ -304,110 +297,34 @@ fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &st Ok(out) } -/// Decode bounded chunks so a false header cannot allocate an entire missing map. -fn read_f32s(reader: &mut impl Read, count: usize, what: &str) -> Result> { - let mut values = Vec::new(); - let mut bytes = vec![0u8; BAKED_CHUNK.min(count) * 4]; - let mut remaining = count; - while remaining > 0 { - let chunk_values = BAKED_CHUNK.min(remaining); - let chunk = bytes.get_mut(..chunk_values * 4).ok_or_else(|| malformed(KIND, format!("{what}: invalid float chunk")))?; - read_exact(reader, chunk, what)?; - values.try_reserve(chunk_values).map_err(|_| FormatError::TooLarge(format!("{what}: not enough memory for {count} values")))?; - values.extend(chunk.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes))); - remaining -= chunk_values; - } - - Ok(values) -} - -fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> { - r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}"))) -} - -fn u32_at(b: &[u8], i: usize) -> u32 { - b.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).unwrap_or(0) -} - -/// Read and check a `.bin` header: returns (width, height, comps, count). -fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> { - let mut h = [0u8; BIN_HEADER_BYTES]; - read_exact(r, &mut h, what)?; - if h.get(..4) != Some(MAGIC.as_slice()) { - return Err(malformed(KIND, format!("{what}: bad magic"))); - } - let v = u32_at(&h, 1); - if v > BIN_VERSION { - return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION }); - } - Ok((u32_at(&h, 2), u32_at(&h, 3), u32_at(&h, 4) as usize, u32_at(&h, 5) as usize)) -} - -/// Error unless the entry has no bytes left (also makes the zip reader verify the CRC). -fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { - let mut b = [0u8; 1]; - match r.read(&mut b) { - Ok(0) => Ok(()), - Ok(_) => Err(malformed(KIND, format!("{what}: trailing data"))), - Err(e) => Err(malformed(KIND, format!("{what}: {e}"))), - } +/// Transfer the bytes charged by the shared codec to this project's one load budget. +fn codec_result(result: std::result::Result, shared: &craft_zip::Budget, budget: &mut LoadBudget, what: &str) -> Result { + budget.take(shared.used()).map_err(FormatError::TooLarge)?; + result.map_err(|error| match error { + craft_tcraft::Error::Budget(_) => FormatError::TooLarge(budget.exceeded_message()), + craft_tcraft::Error::Limit(message) => FormatError::TooLarge(format!("{what}: {message}")), + craft_tcraft::Error::NewerVersion(found) => FormatError::NewerVersion { found, supported: craft_tcraft::VERSION }, + other => malformed(KIND, format!("{what}: {other}")), + }) } fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result { - budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; - let (width, height, stored_components, count) = read_header(reader, what)?; - if (width, height) != size || stored_components != components { - return Err(malformed( - KIND, - format!("{what}: {width}×{height}×{stored_components} does not match the texture set ({}×{}×{components})", size.0, size.1), - )); - } - - let mut image = TileImage::new(width, height, components); - if count > (image.tiles_x() as usize) * (image.tiles_y() as usize) { - return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds"))); - } - - let mut bytes = vec![0u8; TILE_AREA * components * 2]; - let mut position_bytes = [0u8; 8]; - for _ in 0..count { - budget.take((position_bytes.len() + bytes.len()) as u64).map_err(FormatError::TooLarge)?; - read_exact(reader, &mut position_bytes, what)?; - let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1)); - if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) { - return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})"))); - } - - read_exact(reader, &mut bytes, what)?; - let data: Vec = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect(); - image.set_tile(tx, ty, Some(Arc::new(data))); - } - - expect_end(reader, what)?; - - Ok(image) + let layout = craft_tcraft::Layout { width: size.0, height: size.1, components }; + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let mut image = None; + let result = craft_tcraft::read_tiles(reader, layout, MAX_TEXELS, &mut shared, |x, y, values| { + image.get_or_insert_with(|| TileImage::new(size.0, size.1, components)).set_tile(x, y, Some(Arc::new(values))); + Ok(()) + }); + codec_result(result, &shared, budget, what)?; + Ok(image.unwrap_or_else(|| TileImage::new(size.0, size.1, components))) } -/// A baked map: (width, height, data). fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec)> { - budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; - let (width, height, stored_components, _) = read_header(reader, what)?; - if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components { - return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}"))); - } - - let value_count = u64::from(width) * u64::from(height) * components as u64; - let payload_bytes = value_count * 4; - if declared_bytes != BIN_HEADER_BYTES as u64 + payload_bytes { - return Err(malformed(KIND, format!("{what}: {declared_bytes} bytes for a {width}×{height}×{components} map"))); - } - - budget.take(payload_bytes).map_err(FormatError::TooLarge)?; - let value_count = usize::try_from(value_count).map_err(|_| FormatError::TooLarge(format!("{what}: too many values for this platform")))?; - let data = read_f32s(reader, value_count, what)?; - expect_end(reader, what)?; - - Ok((width, height, data)) + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let result = craft_tcraft::read_baked(reader, declared_bytes, components, MAX_TEXELS, &mut shared); + let (layout, values) = codec_result(result, &shared, budget, what)?; + Ok((layout.width, layout.height, values)) } /// Texture set holding a paint layer, a content effect or a mask effect id. @@ -422,47 +339,31 @@ fn load(reader: R) -> Result { } fn check_archive(zip: &mut ZipArchive, limit_bytes: u64) -> Result<()> { - if zip.len() > MAX_ENTRIES { - return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); - } - - // Count every declared payload, including ignored entries, before any decompression - let mut declared_budget = LoadBudget::new(limit_bytes); - for index in 0..zip.len() { - let entry = zip.by_index_raw(index).map_err(zip_err)?; - declared_budget.take(entry.size()).map_err(FormatError::TooLarge)?; - } - - // Shared compressed ranges can amplify one payload into many apparent files - if zip.has_overlapping_entries().map_err(zip_err)? { - return Err(malformed(KIND, "overlapping ZIP entries are not supported")); - } - - Ok(()) + craft_zip::inspect_seekable(zip, MAX_ENTRIES, limit_bytes).map_err(|error| match error { + craft_zip::InspectError::TooManyEntries { .. } => FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")), + craft_zip::InspectError::DeclaredBytesExceeded { .. } => FormatError::TooLarge(LoadBudget::new(limit_bytes).exceeded_message()), + craft_zip::InspectError::OverlappingEntries => malformed(KIND, "overlapping ZIP entries are not supported"), + craft_zip::InspectError::Zip(error) => zip_err(error), + }) } -fn open_archive<'a, R: Read + Seek>(reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> Result>> { - let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?; +fn open_archive(reader: R, metadata_bytes: u64) -> Result>> { + let (reader, indexing) = craft_zip::MetadataReader::new(reader, metadata_bytes)?; // Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?; - metadata_only.set(false); + indexing.finish(); Ok(archive) } fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result { - let metadata_only = Cell::new(true); - let mut zip = open_archive(reader, &metadata_only, MAX_ZIP_METADATA_BYTES)?; + let mut zip = open_archive(reader, MAX_ZIP_METADATA_BYTES)?; check_archive(&mut zip, budget.remaining())?; let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; - #[derive(serde::Deserialize)] - struct Version { - format_version: u32, - } - let v: Version = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; - if v.format_version > FORMAT_VERSION { - return Err(FormatError::NewerVersion { found: v.format_version, supported: FORMAT_VERSION }); + let version = craft_tcraft::project_version(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; + if version > FORMAT_VERSION { + return Err(FormatError::NewerVersion { found: version, supported: FORMAT_VERSION }); } let (project, mut recovered) = recovery::read_project(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 93a58a9a..4fcc0aed 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -82,6 +82,15 @@ fn round_trip_is_identical_and_deterministic() { assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap()); } +#[test] +fn shared_project_schema_round_trips_the_app_document() { + let project = sample().pf.project; + let original = serde_json::to_value(&project).unwrap(); + let document: craft_tcraft::ProjectDocument = serde_json::from_value(original.clone()).unwrap(); + assert_eq!(document.format_version, project.format_version); + assert_eq!(serde_json::to_value(document).unwrap(), original); +} + #[test] fn legacy_bakes_load_as_is_without_layout_conversion() { let mut sample = sample(); @@ -803,13 +812,17 @@ fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() { #[test] fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() { let values: Vec = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect(); - let bytes: Vec = values.iter().flat_map(|bits| bits.to_le_bytes()).collect(); + let mut bytes = header(values.len() as u32, 1, 1, 0); + bytes.extend(values.iter().flat_map(|bits| bits.to_le_bytes())); + let declared = bytes.len() as u64; let mut reader = Cursor::new(bytes); + let mut budget = LoadBudget::new(declared); - let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap(); + let (_, _, decoded) = read_baked(&mut reader, declared, 1, &mut budget, "baked map").unwrap(); assert_eq!(decoded.into_iter().map(f32::to_bits).collect::>(), values); - assert_eq!(reader.position(), (values.len() * 4) as u64); + assert_eq!(reader.position(), declared); + assert_eq!(budget.remaining(), 0); } #[test] @@ -818,23 +831,19 @@ fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() { writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); writer.write_all(&vec![7; 1 << 20]).unwrap(); let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - let mut archive = open_archive(Cursor::new(bytes), &metadata_only, 4096).unwrap(); + let mut archive = open_archive(Cursor::new(bytes), 4096).unwrap(); let mut first_byte = [0; 1]; archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap(); assert_eq!(first_byte, [7]); - assert!(!metadata_only.get()); let mut writer = ZipWriter::new(Cursor::new(Vec::new())); writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap(); writer.write_all(&[7]).unwrap(); let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - assert!(open_archive(Cursor::new(bytes), &metadata_only, 4096).is_err()); - assert!(metadata_only.get(), "failed indexing must not enable payload access"); + assert!(open_archive(Cursor::new(bytes), 4096).is_err()); } #[test] @@ -845,9 +854,8 @@ fn zip64_entry_counts_remain_supported_and_bounded() { writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); } let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - let mut archive = open_archive(Cursor::new(bytes), &metadata_only, MAX_ZIP_METADATA_BYTES).unwrap(); + let mut archive = open_archive(Cursor::new(bytes), MAX_ZIP_METADATA_BYTES).unwrap(); let result = check_archive(&mut archive, 0); assert_eq!(archive.len(), count); diff --git a/crates/geom/src/gbuffer.rs b/crates/geom/src/gbuffer.rs index e26b923f..f18ee092 100644 --- a/crates/geom/src/gbuffer.rs +++ b/crates/geom/src/gbuffer.rs @@ -20,7 +20,7 @@ pub struct UvGBuffer { pub tri: Vec, /// Barycentric weights of the triangle's second and third vertices. pub bary: Vec<[f32; 2]>, - /// Texels written by more than one triangle (overlapping UVs). + /// Covers past the first on texels where any cover has the texel center strictly inside (overlapping UVs; an edge two neighbours share is no overlap) pub overlaps: u32, } @@ -41,74 +41,95 @@ fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) } +/// Twice-areas (in texels²) below this are degenerate triangles, which cover nothing +const MIN_DOUBLE_AREA: f32 = 1e-12; + +/// How far outside a triangle (as a share of its double area) a texel center may sit and still count as covered, so shared edges leave no gaps +const EDGE_TOLERANCE: f32 = 1e-6; + impl UvGBuffer { - /// Rasterize the triangles of material `material` at `width × height`. + /// Rasterize the triangles of material `material` at `width × height` pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer { - let (w, h) = (width.max(1), height.max(1)); - let size = Vec2::new(w as f32, h as f32); - let bands = h.div_ceil(BAND) as usize; - let mut bins: Vec> = vec![Vec::new(); bands]; - for t in mesh.triangles_of(material) { - let Some([a, b, c]) = mesh.tri(t) else { continue }; - let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; - let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; - let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; - if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + let (width, height) = (width.max(1), height.max(1)); + let size = Vec2::new(width as f32, height as f32); + let corner_uvs = |triangle: usize| { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) + }; + + // Sort triangles into bands of rows so each band rasterizes on its own thread + let mut bands: Vec> = vec![Vec::new(); height.div_ceil(BAND) as usize]; + for triangle in mesh.triangles_of(material) { + let Some(uvs) = corner_uvs(triangle) else { continue }; + let top = (uvs.iter().map(|uv| uv.y).fold(f32::INFINITY, f32::min) * size.y).floor().max(0.0) as i64; + let bottom = (uvs.iter().map(|uv| uv.y).fold(f32::NEG_INFINITY, f32::max) * size.y).ceil().min(size.y) as i64; + if bottom <= top || !uvs.iter().all(|uv| uv.is_finite()) { continue; } - let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize); - for bin in bins.iter_mut().take(b1 + 1).skip(b0) { - bin.push(t as u32); + + let (first_band, last_band) = ((top / BAND as i64) as usize, ((bottom - 1).max(0) / BAND as i64) as usize); + for band in bands.iter_mut().take(last_band + 1).skip(first_band) { + band.push(triangle as u32); } } - let n = w as usize * h as usize; - let mut tri = vec![NO_TRI; n]; - let mut bary = vec![[0.0f32; 2]; n]; - let band_len = (BAND * w) as usize; + + let texel_count = width as usize * height as usize; + let mut tri = vec![NO_TRI; texel_count]; + let mut bary = vec![[0.0f32; 2]; texel_count]; + let band_texels = (BAND * width) as usize; let overlaps: u32 = tri - .par_chunks_mut(band_len) - .zip(bary.par_chunks_mut(band_len)) + .par_chunks_mut(band_texels) + .zip(bary.par_chunks_mut(band_texels)) .enumerate() - .map(|(bi, (tri, bary))| { - let mut overlaps = 0u32; - let row0 = bi as u32 * BAND; - let rows = (tri.len() as u32) / w; - for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { - let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; - let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; - let (pa, pb, pc) = (ua * size, ub * size, uc * size); - let area = edge(pa, pb, pc); - if area.abs() < 1e-12 { + .map(|(band_index, (band_tri, band_bary))| { + // Keep cover counts and strict interiors independent of triangle order + let mut covers = vec![0u32; band_tri.len()]; + let mut strict_cover = vec![false; band_tri.len()]; + let first_row = band_index as u32 * BAND; + let band_rows = (band_tri.len() as u32) / width; + for &triangle in bands.get(band_index).map(Vec::as_slice).unwrap_or(&[]) { + let Some(uvs) = corner_uvs(triangle as usize) else { continue }; + let [a, b, c] = uvs.map(|uv| uv * size); + let double_area = edge(a, b, c); + if double_area.abs() < MIN_DOUBLE_AREA { continue; } - let eps = -1e-6 * area.abs(); - let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; - let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); - let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); - let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); - for y in y0..y1 { - for x in x0..x1 { - let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); - let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); - if w0 < eps || w1 < eps || w2 < eps { + + let tolerance = EDGE_TOLERANCE * double_area.abs(); + let (sign, inverse_area) = (double_area.signum(), 1.0 / double_area.abs()); + let left = a.x.min(b.x).min(c.x).floor().max(0.0) as u32; + let right = (a.x.max(b.x).max(c.x).ceil().min(width as f32) as u32).min(width); + let top = (a.y.min(b.y).min(c.y).floor().max(first_row as f32) as u32).max(first_row); + let bottom = (a.y.max(b.y).max(c.y).ceil() as u32).min(first_row + band_rows); + for y in top..bottom { + for x in left..right { + let center = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let weights = [edge(b, c, center) * sign, edge(c, a, center) * sign, edge(a, b, center) * sign]; + if weights.iter().any(|weight| *weight < -tolerance) { continue; } - let i = ((y - row0) * w + x) as usize; - if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { - if *slot != NO_TRI { - overlaps += 1; - } - *slot = t; - let inv = 1.0 / area.abs(); - *bw = [w1 * inv, w2 * inv]; - } + + let index = ((y - first_row) * width + x) as usize; + let (Some(slot), Some(slot_bary), Some(cover_count), Some(strict)) = + (band_tri.get_mut(index), band_bary.get_mut(index), covers.get_mut(index), strict_cover.get_mut(index)) + else { + continue; + }; + + *cover_count += 1; + *strict |= weights.iter().all(|weight| *weight > tolerance); + *slot = triangle; + *slot_bary = [weights[1] * inverse_area, weights[2] * inverse_area]; } } } - overlaps + + // Every cover past the first overlaps, unless all of them only touch the texel center with an edge (neighbours sharing it) + covers.iter().zip(&strict_cover).filter(|(_, strict)| **strict).map(|(count, _)| count.saturating_sub(1)).sum::() }) .sum(); - UvGBuffer { width: w, height: h, tri, bary, overlaps } + + UvGBuffer { width, height, tri, bary, overlaps } } pub fn covered(&self, i: usize) -> bool { @@ -157,7 +178,7 @@ mod tests { #[test] fn half_triangle_covers_texels_with_centers_inside() { - // One triangle covering the lower-left half of UV space (v down: y = v·H). + // UV v increases down, so this triangle covers the lower-left half let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], vec![0, 1, 2], "m") .unwrap(); @@ -171,6 +192,28 @@ mod tests { assert_eq!(g.overlaps, 0); } + #[test] + fn neighbours_sharing_an_edge_through_texel_centers_do_not_overlap() { + // An 8×8 grid of quads at 512 texels: each quad's diagonal runs through 64 texel centers + let grid = primitives::plane(1.0, 8); + let gbuffer = UvGBuffer::new(&grid, 0, 512, 512); + assert_eq!(gbuffer.covered_count(), 512 * 512); + assert_eq!(gbuffer.overlaps, 0); + } + + #[test] + fn an_edge_through_a_covered_texel_center_counts_both_edge_covers() { + // The texel center (0.5, 0.5) lies inside the first triangle and on the diagonal the other two share + let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.2), Vec2::new(0.2, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)]; + let positions = vec![Vec3::ZERO; uv.len()]; + + // In either order: the inside cover first, or the two edge covers first + for indices in [vec![0, 1, 2, 0, 3, 4, 0, 5, 3], vec![0, 3, 4, 0, 5, 3, 0, 1, 2]] { + let m = Mesh::from_parts(positions.clone(), None, uv.clone(), indices.clone(), "m").unwrap(); + assert_eq!(UvGBuffer::new(&m, 0, 1, 1).overlaps, 2, "{indices:?}"); + } + } + #[test] fn overlapping_and_degenerate_triangles() { let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)]; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 5680a499..b0d311df 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -7,6 +7,9 @@ use crate::{GeomError, Result}; /// An edge by the bits of its two end positions, the lower one first type EdgePositions = ([u32; 3], [u32; 3]); +/// Normals closer than about one degree are the same normal: the edge between them is smooth +const SAME_NORMAL_MIN_COSINE: f32 = 0.9998; + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -85,36 +88,37 @@ impl Mesh { /// split it from its twin), per material in `0..materials.len().max(1)`. pub fn wire_edges(&self) -> Vec> { (0..self.materials.len().max(1)) - .map(|m| { - // Edge → (real in some triangle, triangles using it), in first-seen order. + .map(|material| { + // Keep first-seen edge order while counting its triangle uses let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); - let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); - for t in self.triangles_of(m) { - let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue }; - let hidden = self.diagonals.get(t).copied().unwrap_or(0); - for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() { - let key = (a.min(b), a.max(b)); - let real = hidden >> i & 1 == 0; - let e = *at.entry(key).or_insert_with(|| { + let mut edge_indices: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); + for triangle in self.triangles_of(material) { + let Some(vertices) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + let hidden = self.diagonals.get(triangle).copied().unwrap_or(0); + for (side, (from, to)) in [(vertices[0], vertices[1]), (vertices[1], vertices[2]), (vertices[2], vertices[0])].into_iter().enumerate() { + let key = (from.min(to), from.max(to)); + let is_polygon_edge = hidden >> side & 1 == 0; + let edge_index = *edge_indices.entry(key).or_insert_with(|| { edges.push((key, false, 0)); edges.len() - 1 }); - if let Some((_, r, n)) = edges.get_mut(e) { - *r |= real; - *n = n.saturating_add(1); + if let Some((_, edge_is_polygon_side, triangle_count)) = edges.get_mut(edge_index) { + *edge_is_polygon_side |= is_polygon_edge; + *triangle_count = triangle_count.saturating_add(1); } } } - edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + edges.into_iter().filter(|(_, is_polygon_edge, triangle_count)| *is_polygon_edge || *triangle_count == 1).map(|(edge, ..)| edge).collect() }) .collect() } - /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` - pub fn uv_seam_edges(&self) -> Vec> { + /// Hard edges the UV layout does not split, which bake visible lines into the normal map: two triangles meet there with different normals but the same UVs, per material in `0..materials.len().max(1)` + pub fn missing_seam_edges(&self) -> Vec> { // Signed zero denotes the same position on either side of an imported seam let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); let mut seams = vec![Vec::new(); self.materials.len().max(1)]; + // Match across materials before grouping the lines for texture-set visibility let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); for material in 0..seams.len() { @@ -132,10 +136,19 @@ impl Mesh { } let uv = |index: u32| self.uvs.get(index as usize).copied(); + + // Imported normals need not be unit length; two missing normals agree + let direction = |index: u32| self.normals.get(index as usize).map_or(Vec3::ZERO, |normal| normal.normalize_or_zero()); + let same_normal = |a: u32, b: u32| { + let (a, b) = (direction(a), direction(b)); + a == b || a.dot(b) >= SAME_NORMAL_MIN_COSINE + }; for pairs in sides.into_values() { let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; - if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { + let uv_split = pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))); + let hard = pairs.iter().any(|&(from, to, _)| !same_normal(from, first_from) || !same_normal(to, first_to)); + if hard && !uv_split { for (from, to, material) in pairs { if let Some(edges) = seams.get_mut(material) { edges.push((from.min(to), from.max(to))); @@ -471,67 +484,77 @@ mod tests { fn wire_edges_leave_out_polygon_diagonals() { let mut m = quad(); assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); - // Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad. + + // Hide the quad's shared diagonal m.diagonals = vec![0b100, 0b001]; assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); - // A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays. + + // Keep the diagonal when a seam splits its twin let mut seam = m.clone(); seam.indices[3] = 4; assert_eq!(seam.wire_edges()[0].len(), 6); - // Appending keeps each side's diagonals on its own triangles. + + // Appending preserves each side's own diagonals let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap(); a.append(&m); assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } - #[test] - fn uv_seams_are_where_the_uv_layout_splits() { - let mesh = quad(); - assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); - - // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut - let mut seam = mesh.clone(); - seam.positions.push(seam.positions[0]); - seam.normals.push(seam.normals[0]); - seam.tangents.push(seam.tangents[0]); - seam.uvs.push(Vec2::new(0.9, 0.9)); - seam.indices[3] = 4; - assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); - - // The same split with the same UV is a hard edge, not a seam - let mut hard = seam.clone(); - hard.uvs[4] = hard.uvs[0]; - assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); - } - - #[test] - fn uv_seams_join_positions_with_opposite_signed_zero() { - let mut mesh = quad(); - mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0)); - mesh.normals.push(mesh.normals[0]); - mesh.tangents.push(mesh.tangents[0]); - mesh.uvs.push(Vec2::new(0.9, 0.9)); - mesh.indices[3] = 4; - assert_eq!(mesh.positions[0], mesh.positions[4]); - assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); - } - - #[test] - fn uv_seams_between_materials_belong_to_both_materials() { + /// `quad` with vertex 4 a copy of vertex 0 at `uv` with `normal`, used by the second triangle: the diagonal (0, 2) / (4, 2) has two sides + fn split_quad(uv: Vec2, normal: Vec3) -> Mesh { let mut mesh = quad(); mesh.positions.push(mesh.positions[0]); - mesh.normals.push(mesh.normals[0]); + mesh.normals.push(normal); mesh.tangents.push(mesh.tangents[0]); - mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.uvs.push(uv); mesh.indices[3] = 4; + mesh + } + + #[test] + fn missing_seams_are_hard_edges_the_uv_layout_does_not_split() { + let none = vec![Vec::<(u32, u32)>::new()]; + assert_eq!(quad().missing_seam_edges(), none, "a smooth quad has no hard edge"); + + let shared_uv = quad().uvs[0]; + let smooth_split = split_quad(shared_uv, Vec3::Z); + assert_eq!(smooth_split.missing_seam_edges(), none, "the same normal on both sides is a smooth edge"); + + let hard = split_quad(shared_uv, Vec3::new(1.0, 0.0, 1.0).normalize()); + assert_eq!(hard.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]], "a hard edge inside one UV island"); + + let seamed = split_quad(Vec2::new(0.9, 0.9), hard.normals[4]); + assert_eq!(seamed.missing_seam_edges(), none, "a hard edge on a UV seam is fine"); + + let mut short_normals = quad(); + short_normals.normals.iter_mut().for_each(|normal| *normal *= 0.5); + assert_eq!(short_normals.missing_seam_edges(), none, "normals shorter than unit length point the same way"); + assert_eq!(split_quad(shared_uv, Vec3::Z * 0.5).missing_seam_edges(), none, "normals of different lengths point the same way"); + + let mut no_normals = quad(); + no_normals.normals.fill(Vec3::ZERO); + assert_eq!(no_normals.missing_seam_edges(), none, "two missing normals agree"); + } + + #[test] + fn missing_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = split_quad(quad().uvs[0], Vec3::X); + mesh.positions[4] = Vec3::new(-0.0, 0.0, 0.0); + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn missing_seams_between_materials_belong_to_both_materials() { + let mut mesh = split_quad(quad().uvs[0], Vec3::X); mesh.materials.push("second".into()); mesh.submeshes[0].count = 3; mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); - assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); - mesh.uvs[4] = mesh.uvs[0]; - assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.normals[4] = mesh.normals[0]; + assert_eq!(mesh.missing_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a hard edge"); } #[test] diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 5bb3f911..2cde78c8 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -353,6 +353,13 @@ impl Default for BrushSettings { } impl BrushSettings { + /// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the + /// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it. + pub fn uv_stamp_radius(&self, pressure: f32) -> f32 { + let p = pressure.clamp(0.0, 1.0); + self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 } + } + /// Clamp every value into its valid range (input from UI, CLI or agents) pub fn sanitized(&self) -> BrushSettings { let clamp_finite = |value: f32, min: f32, max: f32, default: f32| if value.is_finite() { value.clamp(min, max) } else { default }; @@ -392,6 +399,15 @@ impl BrushSettings { #[cfg(test)] mod tests { + #[test] + fn uv_stamp_radius_follows_pen_pressure() { + let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() }; + assert!((b.uv_stamp_radius(1.0) - 0.2).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.5) - 0.15).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.0) - 0.1).abs() < 1e-6); + assert!((b.uv_stamp_radius(7.0) - 0.2).abs() < 1e-6, "pressure clamps to 1"); + } + use super::*; #[test] diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 080f12ba..ee15b556 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,6 +19,7 @@ bytemuck = { workspace = true } half = { workspace = true } log = { workspace = true } rayon = { workspace = true } +serde = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = "0.4" diff --git a/crates/render/src/bake_overlay.rs b/crates/render/src/bake_overlay.rs new file mode 100644 index 00000000..31d8135d --- /dev/null +++ b/crates/render/src/bake_overlay.rs @@ -0,0 +1,24 @@ +//! One overlay of bake mode's 3D view: whether it shows, its color and its opacity + +/// Whether a part of the bake setup shows in the 3D view, and in which color and opacity +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct BakeOverlay { + pub shown: bool, + /// Linear RGB + pub color: [f32; 3], + /// 0 transparent, 1 opaque; the matching error mixes into the high poly by it + pub opacity: f32, +} + +impl BakeOverlay { + /// A hidden overlay in `color`, fully opaque + pub const fn hidden(color: [f32; 3]) -> Self { + Self { shown: false, color, opacity: 1.0 } + } + + /// The overlay's shader globals: rgb its color, a its opacity (0 while hidden) + pub(crate) fn globals(&self) -> [f32; 4] { + let [red, green, blue] = self.color; + [red, green, blue, if self.shown { self.opacity.clamp(0.0, 1.0) } else { 0.0 }] + } +} diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs index 8dbc4927..a03fbfd1 100644 --- a/crates/render/src/bake_visualization.rs +++ b/crates/render/src/bake_visualization.rs @@ -1,12 +1,58 @@ -//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the missing seams and the low poly -/// Which parts of the bake setup the 3D view draws +use crate::bake_overlay::BakeOverlay; +use crate::neutral_material::NeutralMaterial; + +/// Default overlay colors, linear RGB +const HIGH_POLY_COLOR: [f32; 3] = [0.0, 0.216, 0.521]; +const MATCHING_ERROR_COLOR: [f32; 3] = [1.0, 0.0, 0.0]; +const CAGE_SURFACE_COLOR: [f32; 3] = [0.604, 0.451, 0.216]; +const CAGE_WIRE_COLOR: [f32; 3] = [0.604, 0.604, 0.604]; +const MISSING_SEAM_COLOR: [f32; 3] = [0.451, 0.0, 0.451]; +const LOW_POLY_COLOR: [f32; 3] = [0.216, 0.216, 0.216]; + +/// Which parts of the bake setup the 3D view draws, and how #[derive(Clone, Copy, Debug, PartialEq)] pub struct BakeVisualization { - pub high_poly: bool, - pub cage: bool, - pub uv_seams: bool, - pub low_poly: bool, - /// Draw the cage, seams and low poly of only this texture set + pub high_poly: BakeOverlay, + /// Tints the high poly where the bake's rays miss it + pub matching_error: BakeOverlay, + pub cage_surface: BakeOverlay, + pub cage_wire: BakeOverlay, + /// The low poly's hard edges that are not UV seams + pub missing_seams: BakeOverlay, + /// The low poly; its color is the neutral material's color + pub low_poly: BakeOverlay, + /// Shade the low poly with this plain material instead of its painted one + pub neutral: Option, + /// Draw the cage and high poly of only this texture set (the high poly's vertices of other sets come marked hidden) pub only_set: Option, } + +impl Default for BakeVisualization { + /// Every part hidden, in its default color, the low poly with its painted material + fn default() -> Self { + Self { + high_poly: BakeOverlay::hidden(HIGH_POLY_COLOR), + matching_error: BakeOverlay::hidden(MATCHING_ERROR_COLOR), + cage_surface: BakeOverlay::hidden(CAGE_SURFACE_COLOR), + cage_wire: BakeOverlay::hidden(CAGE_WIRE_COLOR), + missing_seams: BakeOverlay::hidden(MISSING_SEAM_COLOR), + low_poly: BakeOverlay::hidden(LOW_POLY_COLOR), + neutral: None, + only_set: None, + } + } +} + +impl BakeVisualization { + /// Whether any part of the cage shows + pub fn cage_shown(&self) -> bool { + self.cage_surface.shown || self.cage_wire.shown + } + + /// The neutral material while the low poly shows with it + pub fn shown_neutral(&self) -> Option { + self.neutral.filter(|_| self.low_poly.shown) + } +} diff --git a/crates/render/src/cage_geometry.rs b/crates/render/src/cage_geometry.rs new file mode 100644 index 00000000..95b0ec6f --- /dev/null +++ b/crates/render/src/cage_geometry.rs @@ -0,0 +1,13 @@ +//! A texture set's cage as the renderer takes it + +use texturecraft_geom::glam::Vec3; + +/// A cage for [`crate::Renderer::set_bake_cage`]: three corners per low-poly triangle, and lines as corner pairs +#[derive(Clone, Copy, Debug)] +pub struct CageGeometry<'a> { + pub corners: &'a [Vec3], + /// The low poly's polygon edges, for the wireframe + pub edges: &'a [[u32; 2]], + /// The low poly's hard edges without a UV seam + pub missing_seams: &'a [[u32; 2]], +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs index 3ed4f13f..98b7b15e 100644 --- a/crates/render/src/cage_gpu.rs +++ b/crates/render/src/cage_gpu.rs @@ -6,4 +6,7 @@ pub(crate) struct CageGpu { pub(crate) corner_count: u32, pub(crate) edges: wgpu::Buffer, pub(crate) edge_index_count: u32, + /// Corner pairs along the low poly's hard edges without a UV seam + pub(crate) missing_seams: wgpu::Buffer, + pub(crate) missing_seam_index_count: u32, } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 649d9988..fc777e80 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,7 +13,9 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_overlay; pub mod bake_visualization; +pub mod cage_geometry; mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] @@ -24,15 +26,19 @@ pub mod headless; mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; +mod missing_seam_gpu; +pub mod neutral_material; pub mod overlay_quad; pub mod readback; pub mod renderer; pub mod set_highlight; mod subdivide; pub mod trace; -mod uv_seam_gpu; +pub use bake_overlay::BakeOverlay; pub use bake_visualization::BakeVisualization; +pub use cage_geometry::CageGeometry; +pub use neutral_material::NeutralMaterial; pub use overlay_quad::OverlayQuad; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; pub use set_highlight::SetHighlight; diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/missing_seam_gpu.rs similarity index 63% rename from crates/render/src/uv_seam_gpu.rs rename to crates/render/src/missing_seam_gpu.rs index 0ac80dc9..07a69168 100644 --- a/crates/render/src/uv_seam_gpu.rs +++ b/crates/render/src/missing_seam_gpu.rs @@ -1,5 +1,5 @@ -/// The low poly's UV seams as a line list over its vertex buffer -pub(crate) struct UvSeamGpu { +/// The low poly's hard edges without a UV seam, as a line list over its vertex buffer +pub(crate) struct MissingSeamGpu { /// The low-poly mesh the lines belong to pub(crate) mesh_id: u64, pub(crate) lines: wgpu::Buffer, diff --git a/crates/render/src/neutral_material.rs b/crates/render/src/neutral_material.rs new file mode 100644 index 00000000..d3331185 --- /dev/null +++ b/crates/render/src/neutral_material.rs @@ -0,0 +1,75 @@ +//! The plain material bake mode can show the low poly with, so the bake reads without the painted colours + +/// The highest Quality: reflection samples per pixel +pub const MAX_SAMPLES_PER_PIXEL: u32 = 256; + +/// A plain material for the low poly in bake mode: its color comes from the low poly's overlay; its normal and occlusion are the texture set's as shown (the bake under any painted normal, height or AO) +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct NeutralMaterial { + pub roughness: f32, + pub metallic: f32, + /// How much the texture set's ambient occlusion (baked × painted) darkens the material (0 none, 1 fully) + pub ao_intensity: f32, + /// Environment reflection samples per pixel, taken by every frame so a moving view looks like a still one + pub samples_per_pixel: u32, + /// Light the material along the baked bent normal: the open direction above each point + pub bent_normal: bool, + /// How far the diffuse light turns to the bent normal, and how much reflections facing away from it dim (0..1) + pub bent_normal_diffuse: f32, + pub bent_normal_specular: f32, +} + +impl Default for NeutralMaterial { + /// Low quality (16 samples per pixel), a slightly rough half metal, most of the baked occlusion, no bent normal + fn default() -> Self { + Self { + roughness: 0.3, + metallic: 0.6, + ao_intensity: 0.75, + samples_per_pixel: 16, + bent_normal: false, + bent_normal_diffuse: 1.0, + bent_normal_specular: 1.0, + } + } +} + +impl NeutralMaterial { + /// The material's shader globals: x roughness, y metallic, z AO intensity, w 1 (on) + pub(crate) fn globals(&self) -> [f32; 4] { + [self.roughness, self.metallic, self.ao_intensity, 1.0] + } + + /// Reflection samples each frame takes: the whole quality, from 1 to [`MAX_SAMPLES_PER_PIXEL`] (a damaged settings file can't stall the GPU) + pub(crate) fn samples_per_frame(&self) -> u32 { + self.samples_per_pixel.clamp(1, MAX_SAMPLES_PER_PIXEL) + } + + /// The bent normal's shader globals: x diffuse amount, y specular amount (both 0 while off), zw - + pub(crate) fn bent_normal_globals(&self) -> [f32; 4] { + if self.bent_normal { [self.bent_normal_diffuse, self.bent_normal_specular, 0.0, 0.0] } else { [0.0; 4] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_frame_takes_the_whole_quality() { + let quality = |samples_per_pixel| NeutralMaterial { samples_per_pixel, ..NeutralMaterial::default() }; + assert_eq!(quality(16).samples_per_frame(), 16); + assert_eq!(quality(256).samples_per_frame(), 256); + assert_eq!(quality(u32::MAX).samples_per_frame(), MAX_SAMPLES_PER_PIXEL, "a damaged file is held to the highest quality"); + assert_eq!(quality(0).samples_per_frame(), 1); + } + + #[test] + fn the_bent_normal_reaches_the_shader_only_when_on() { + let off = NeutralMaterial::default(); + assert_eq!(off.bent_normal_globals(), [0.0; 4]); + let on = NeutralMaterial { bent_normal: true, bent_normal_diffuse: 0.5, bent_normal_specular: 0.25, ..off }; + assert_eq!(on.bent_normal_globals(), [0.5, 0.25, 0.0, 0.0]); + } +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1636f1ad..4c62d450 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -31,14 +31,15 @@ use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; use crate::bake_visualization::BakeVisualization; +use crate::cage_geometry::CageGeometry; use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; +use crate::missing_seam_gpu::MissingSeamGpu; use crate::overlay_quad::OverlayQuad; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; -use crate::uv_seam_gpu::UvSeamGpu; pub const MSAA: u32 = 4; pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; @@ -84,6 +85,14 @@ struct GlobalsRaw { refr: [f32; 4], highlight: [f32; 4], highlight_shift: [f32; 4], + bake_high: [f32; 4], + bake_matching_error: [f32; 4], + bake_cage: [f32; 4], + bake_cage_wire: [f32; 4], + bake_missing_seam: [f32; 4], + bake_neutral_color: [f32; 4], + bake_neutral: [f32; 4], + bake_bent_normal: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -548,7 +557,10 @@ pub struct Renderer { bake_high_pipeline: wgpu::RenderPipeline, cage_pipeline: wgpu::RenderPipeline, cage_wire_pipeline: wgpu::RenderPipeline, - uv_seam_pipeline: wgpu::RenderPipeline, + missing_seam_pipeline: wgpu::RenderPipeline, + /// The missing seams along the cage, and in the 2D view + cage_missing_seam_pipeline: wgpu::RenderPipeline, + uv_missing_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -585,7 +597,7 @@ pub struct Renderer { bake_high: Option, /// Each texture set's cage, by set index cages: Vec>, - uv_seams: Option, + missing_seams: Option, sets: Vec, /// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least /// as reduced as the device's texture limit needs). @@ -872,8 +884,10 @@ impl Renderer { fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)), ], ); + // The display textures, the aux texture, the sampler let textures = DisplayKind::ALL.len() as u32 + 1; + // Displacement reads the height (and the sampler) in the vertex shader let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32; let set_entries: Vec<_> = (0..textures) @@ -910,7 +924,7 @@ impl Renderer { attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2], })]; - // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter + // RGBA8 fallback clips bright highlights and dark gradients let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT }; let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend)); let always = || Some(depth_state(false, wgpu::CompareFunction::Always)); @@ -1001,8 +1015,30 @@ impl Renderer { MSAA, wire3d_depth.clone(), ); - let uv_seam_pipeline = - pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); + let cage_missing_seam_pipeline = pipeline( + device, + "tc_cage_missing_seam", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_cage_missing_seam", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_missing_seam_pipeline = + pipeline(device, "tc_uv_missing_seam", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire_missing_seam", blend), MSAA, always()); + let missing_seam_pipeline = pipeline( + device, + "tc_missing_seam", + &layout, + &module, + "vs_wire3d", + &vertex_layout, + hdr_target("fs_wire_missing_seam", blend), + MSAA, + wire3d_depth.clone(), + ); let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); let overlay_pipeline = pipeline(device, "tc_overlay", &background_layout, &module, "vs_overlay", &vertex_layout, hdr_target("fs_overlay", blend), MSAA, wire3d_depth); @@ -1135,7 +1171,9 @@ impl Renderer { bake_high_pipeline, cage_pipeline, cage_wire_pipeline, - uv_seam_pipeline, + missing_seam_pipeline, + cage_missing_seam_pipeline, + uv_missing_seam_pipeline, bg_pipeline, blit_pipeline, post_pipeline, @@ -1162,7 +1200,7 @@ impl Renderer { mesh: None, bake_high: None, cages: Vec::new(), - uv_seams: None, + missing_seams: None, sets: Vec::new(), display_shift: 0, material_sets: Vec::new(), @@ -1223,6 +1261,7 @@ impl Renderer { if self.mesh.as_ref().is_some_and(|m| m.id == id) { return; } + let verts = subdivide::vertices(mesh); let mk = |label: &str, data: &[u8], usage: wgpu::BufferUsages| upload_buffer(device, queue, label, data, usage); let mut idx_bytes = bytemuck::cast_slice::(&mesh.indices).to_vec(); @@ -1230,7 +1269,8 @@ impl Renderer { let vb = mk("tc_vb", bytemuck::cast_slice(&verts), wgpu::BufferUsages::VERTEX); let ib = mk("tc_ib", &idx_bytes, wgpu::BufferUsages::INDEX); let draws: Vec<(u32, u32, usize)> = mesh.submeshes.iter().map(|s| (s.start, s.count, s.material)).collect(); - // Mesh edges per material (polygons, not their triangles), for the wireframes. + + // Use polygon edges for each material's wireframe let mut line_idx: Vec = Vec::new(); let mut line_draws = Vec::new(); for (m, edges) in mesh.wire_edges().into_iter().enumerate() { @@ -1289,8 +1329,8 @@ impl Renderer { self.content_rev += 1; } - /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners - pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) { + /// Texture set `texture_set`'s cage; `None` removes it. The same `topology` as before only rewrites the corners + pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option>, topology: u64) { if self.cages.len() <= texture_set { self.cages.resize_with(texture_set + 1, || None); } @@ -1298,16 +1338,18 @@ impl Renderer { match (cage, slot.as_mut()) { (None, _) => *slot = None, - (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => { - queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners)); + (Some(cage), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == cage.corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(cage.corners)); } - (Some((corners, edges)), _) => { + (Some(cage), _) => { *slot = Some(CageGpu { topology, - corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX), - corner_count: corners.len() as u32, - edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX), - edge_index_count: (edges.len() * 2) as u32, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(cage.corners), wgpu::BufferUsages::VERTEX), + corner_count: cage.corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(cage.edges), wgpu::BufferUsages::INDEX), + edge_index_count: (cage.edges.len() * 2) as u32, + missing_seams: upload_buffer(device, queue, "tc_cage_seam_ib", bytemuck::cast_slice(cage.missing_seams), wgpu::BufferUsages::INDEX), + missing_seam_index_count: (cage.missing_seams.len() * 2) as u32, }); } } @@ -1322,8 +1364,8 @@ impl Renderer { } } - /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id` - pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { + /// The low poly's hard edges without a UV seam as vertex pairs per material ([`Mesh::missing_seam_edges`]) for mesh `mesh_id` + pub fn set_missing_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { let mut line_indices: Vec = Vec::new(); let mut line_draws = Vec::new(); for (material, edges) in seams.iter().enumerate() { @@ -1332,8 +1374,8 @@ impl Renderer { line_draws.push((start, line_indices.len() as u32 - start, material)); } - let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); - self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws }); + let lines = upload_buffer(device, queue, "tc_missing_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.missing_seams = Some(MissingSeamGpu { mesh_id, lines, line_draws }); self.content_rev += 1; } @@ -1858,10 +1900,11 @@ impl Renderer { if sample >= TAA_SAMPLES { return; } + let aspect = frame.size[0].max(1) as f32 / frame.size[1].max(1) as f32; let mut vp = frame.camera.view_proj(aspect); if sample > 0 { - // Sub-pixel jitter in clip space: a box filter over the pixel once averaged. + // Sub-pixel jitter averages into a box filter let (jx, jy) = (halton(sample, 2) - 0.5, halton(sample, 3) - 0.5); vp = Mat4::from_translation(Vec3::new(2.0 * jx / frame.size[0].max(1) as f32, 2.0 * jy / frame.size[1].max(1) as f32, 0.0)) * vp; } @@ -1873,13 +1916,13 @@ impl Renderer { (1.0, [sx, sy, pan[0], pan[1]]) } }; - // Data views (channels, mesh maps, UV checker, the 2D view) show values as they are: no - // exposure, tone mapping, effects or shadows. + + // Data views bypass exposure, tone mapping, effects and shadows let data = uv_view > 0.5 || s.view_mode != 0; let fx = |v: f32| if s.post_effects && !data { v.clamp(0.0, 1.0) } else { 0.0 }; let bloom = fx(s.bloom) > 0.0; - // The key light lives in the environment: turn it with it (the inverse of env_rotate in - // mesh.wgsl maps environment directions to world directions). + + // Turn the key light with the environment let (sin, cos) = s.env_rotation_deg.to_radians().sin_cos(); let [lx, ly, lz, lw] = s.light; let light = Vec3::new(cos * lx + sin * lz, ly, cos * lz - sin * lx); @@ -1888,19 +1931,19 @@ impl Renderer { self.ensure_dense(device, queue); } let disp = match self.mesh.as_ref().filter(|_| displace) { - // Height-to-normal's slope: strength 1 tilts 45° for a height change of 1 over 1/16 of - // the UV square; the vertex shader samples the mip whose texels match the vertex spacing. + // A unit height across 1/16 of UV space tilts 45°; use the mip nearest vertex spacing Some(m) => [1.0, m.world_per_uv / 16.0, 1.0 / (m.dense.as_ref().unwrap_or(&m.geo).triangles.max(1) as f32 * 0.5).sqrt(), 0.0], None => [0.0; 4], }; let shadow_disp = [disp[0], disp[1] * s.height_strength, disp[2], 0.0]; let shadow_vp = if !data && s.shadows && lw > 0.0 { self.update_shadow(device, queue, encoder, light, shadow_disp, &frame.visible) } else { None }; let radius = self.mesh.as_ref().map_or(1.0, |m| m.radius); - // Background rays come from a perspective camera even in orthographic views (an ortho - // ray grid would show a single flat environment color). + + // Perspective background rays prevent flat color in orthographic views let bg_vp = OrbitCamera { ortho: false, ..frame.camera }.view_proj(aspect); let e = frame.camera.eye(); - // Scene effects (3D material view; they need float targets for depths and signed light). + + // Scene effects need float targets for depths and signed light let scene_fx = !data && frame.kind == ViewKind::Scene && self.hdr_format == HDR_FORMAT && self.mesh.is_some(); let dof = s.dof.filter(|_| scene_fx); let sss = s.sss_blur.filter(|m| scene_fx && m.iter().any(|v| *v > 0.0)); @@ -1909,7 +1952,8 @@ impl Renderer { let cam = &frame.camera; let half_h = (cam.fov.clamp(5.0, 150.0).to_radians() * 0.5).tan(); let height = frame.size[1].max(1) as f32; - // Pixels per world unit at view depth z: k / z in perspective, k in orthographic views. + + // Perspective pixels per world unit vary with depth let k = if cam.ortho { height / (2.0 * cam.distance.max(1e-6) * half_h) } else { height / (2.0 * half_h) }; let ppw = |z: f32| if cam.ortho { k } else { k / z.max(1e-6) }; let dof_c = dof.map_or([0.0; 4], |[focus, aperture]| { @@ -1929,7 +1973,7 @@ impl Renderer { uv_xform, light: [light.x, light.y, light.z, lw], light_vp: shadow_vp.unwrap_or(Mat4::IDENTITY).to_cols_array_2d(), - // Normal offset: 1.5 shadow texels of the light frustum (2 × radius wide). + // Offset by 1.5 shadow texels to avoid self-shadowing shadow: [if shadow_vp.is_some() { 1.0 } else { 0.0 }, 1.0 / SHADOW_SIZE as f32, radius * 3.0 / SHADOW_SIZE as f32, 0.0], material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior], scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }], @@ -1938,6 +1982,7 @@ impl Renderer { refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], highlight: highlight_globals(s, data), highlight_shift: highlight_shift(frame.size), + ..bake_globals(s.bake) }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; let post = PostRaw { @@ -1961,9 +2006,7 @@ impl Renderer { } let weight = 1.0 / f64::from(sample + 1); match v.fx.as_ref().filter(|_| fx_on) { - // The effects run on every frame before it joins the average, so idle accumulation - // also smooths the depth of field's sampling pattern (turned each frame). Their - // G-buffer (unjittered) stays valid while the view accumulates. + // Effects run before averaging; the unjittered G-buffer remains valid Some(f) => { self.scene_pass(encoder, v, &v.hdr, globals_bg, frame); if sample == 0 { @@ -2099,7 +2142,8 @@ impl Renderer { None => (&self.mesh_pipeline, frame.shade.wireframe_3d.then_some(&self.wire3d_pipeline)), Some(_) => (&self.uv_pipeline, frame.shade.wireframe.then_some(&self.wire_pipeline)), }; - // Transmissive surfaces refract what the behind pass rendered this frame. + + // Transmissive surfaces refract the current behind pass let refr = v.behind.as_ref().filter(|_| frame.shade.refraction).map_or(&self.refr_black, |b| &b.bg); let highlight = frame.shade.highlight.filter(|_| uv_ts.is_none()).map(|highlight| (&self.highlight_pipeline, highlight.set)); self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); @@ -2148,14 +2192,13 @@ impl Renderer { pass.set_bind_group(2, refraction_source, &[]); let geometry = self.geometry(mesh, frame); let bake = frame.shade.bake.filter(|_| uv_set.is_none()); - let low_poly_shown = bake.is_none_or(|bake| bake.low_poly); - let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set); - let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip(); + let low_poly_shown = bake.is_none_or(|bake| bake.low_poly.shown); + let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_set.is_none_or(|only| only == *set)).unzip(); // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) let passes = [ - (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1), - (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1), + (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1), + (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1), (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), ]; for (pipeline, vertices, indices, ranges, only_set, instances) in passes { @@ -2173,6 +2216,18 @@ impl Renderer { if let Some(bake) = bake { self.draw_bake(&mut pass, mesh, frame, bake); } + if let Some(texture_set) = uv_set + && frame.shade.bake.is_some_and(|bake| bake.missing_seams.shown) + && let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == mesh.id) + { + pass.set_pipeline(&self.uv_missing_seam_pipeline); + pass.set_vertex_buffer(0, mesh.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..1); + } + } // Overlay quads last, so the mesh's depth hides what is behind it if uv_set.is_none() @@ -2184,9 +2239,9 @@ impl Renderer { } } - /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` + /// Bake mode's high poly, missing seams and cages over the low poly `low_poly` fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) { - if bake.high_poly + if bake.high_poly.shown && let Some(high) = &self.bake_high { pass.set_pipeline(&self.bake_high_pipeline); @@ -2196,35 +2251,46 @@ impl Renderer { pass.draw_indexed(0..high.index_count, 0, 0..1); } - if bake.uv_seams - && let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + if bake.missing_seams.shown + && let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) { - pass.set_pipeline(&self.uv_seam_pipeline); + pass.set_pipeline(&self.missing_seam_pipeline); pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) { + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } } - if !bake.cage { - return; - } - let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true); let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref()); + // The translucent faces first, then the wireframe over them - pass.set_pipeline(&self.cage_pipeline); - for cage in cages() { - pass.set_vertex_buffer(0, cage.corners.slice(..)); - pass.draw(0..cage.corner_count, 0..1); + if bake.cage_surface.shown { + pass.set_pipeline(&self.cage_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.draw(0..cage.corner_count, 0..1); + } } - pass.set_pipeline(&self.cage_wire_pipeline); - for cage in cages() { - pass.set_vertex_buffer(0, cage.corners.slice(..)); - pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); - pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + + if bake.cage_wire.shown { + pass.set_pipeline(&self.cage_wire_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + } + } + + if bake.missing_seams.shown && bake.cage_shown() { + pass.set_pipeline(&self.cage_missing_seam_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.missing_seams.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.missing_seam_index_count, 0, 0..1); + } } } @@ -2336,6 +2402,26 @@ fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { [r, g, b, HIGHLIGHT_OPACITY] } +/// The globals of bake mode's overlays and neutral material for `bake` (all zero without it) +fn bake_globals(bake: Option) -> GlobalsRaw { + let Some(bake) = bake else { return GlobalsRaw::zeroed() }; + + let [red, green, blue] = bake.low_poly.color; + let neutral = bake.shown_neutral(); + let samples_per_frame = neutral.map_or(0, |neutral| neutral.samples_per_frame()); + GlobalsRaw { + bake_high: bake.high_poly.globals(), + bake_matching_error: bake.matching_error.globals(), + bake_cage: bake.cage_surface.globals(), + bake_cage_wire: bake.cage_wire.globals(), + bake_missing_seam: bake.missing_seams.globals(), + bake_neutral_color: [red, green, blue, samples_per_frame as f32], + bake_neutral: neutral.map_or([0.0; 4], |neutral| neutral.globals()), + bake_bent_normal: neutral.map_or([0.0; 4], |neutral| neutral.bent_normal_globals()), + ..GlobalsRaw::zeroed() + } +} + /// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target fn highlight_shift(size: [u32; 2]) -> [f32; 4] { let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5; diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl index 1985f980..0720e318 100644 --- a/crates/render/src/shaders/bake_view.wgsl +++ b/crates/render/src/shaders/bake_view.wgsl @@ -1,19 +1,46 @@ -// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams +// Bake mode's 3D view: the high poly, the cage around the low poly, the missing seams and the neutral material struct BakeViewOut { @builtin(position) clip: vec4, @location(0) world_position: vec3, @location(1) normal: vec3, - // 1 where the bake's rays miss the high poly, 0 where they reach it + // 1 where the bake's rays miss the high poly, 0 where they reach it, negative where another texture set owns it (hidden) @location(2) missed: f32, }; -const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56); -const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01); -const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26); -const CAGE_OPACITY: f32 = 0.16; -const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7); -const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0); +// Reflectance of the neutral material's dielectric part facing the camera +const NEUTRAL_F0: f32 = 0.04; + +// Lowest roughness the neutral material shades with: below it the GGX lobe is too narrow for its samples +const MIN_NEUTRAL_ROUGHNESS: f32 = 0.045; + +// How fast reflections fade as they dip below the mesh surface (larger = sooner) +const HORIZON_FADE: f32 = 1.3; + +// Floor of the cosines that divide the reflection terms, so grazing angles stay finite +const MIN_COSINE: f32 = 1e-4; + +// A normal closer than this to +-Z builds its tangent frame from X, where the cross product with Z would vanish +const TANGENT_HELPER_MAX_Z: f32 = 0.999; + +// One mip coarser than each sample's share of the lobe: hides the gaps between few samples (filtered importance sampling) +const FILTERED_SAMPLING_LOD_BIAS: f32 = 1.0; + +// A packed bent normal shorter than this is the unbaked gray, not a direction +const BENT_NORMAL_MIN_LENGTH: f32 = 0.5; + +// Cosines between a reflection and the bent normal over which the reflection goes from occluded to open +const BENT_OCCLUSION_START: f32 = -0.25; +const BENT_OCCLUSION_END: f32 = 0.75; + +// Floor of the GGX distribution's denominator, which reaches 0 at the peak of a mirror-like lobe +const MIN_GGX_DENOMINATOR: f32 = 1e-6; + +// Fractional part of the golden ratio: shifts each accumulated frame's samples around the lobe +const GOLDEN_RATIO_FRACTION: f32 = 0.618034; + +// High-poly surface where the interpolated `missed` falls below this belongs to a hidden texture set +const HIDDEN_BELOW: f32 = -0.5; // Brightness of surfaces seen edge-on; facing the camera adds the rest const HEADLIGHT_AMBIENT: f32 = 0.3; @@ -45,7 +72,11 @@ fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3 @fragment fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 { - let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed); + if (surface.missed < HIDDEN_BELOW) { + discard; + } + + let color = mix(g.bake_high.rgb, g.bake_matching_error.rgb, max(surface.missed, 0.0) * g.bake_matching_error.a); return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0); } @@ -63,7 +94,7 @@ fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut { @fragment fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position))); - return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY); + return vec4(headlight(g.bake_cage.rgb, face_normal, surface.world_position), g.bake_cage.a); } // Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces @@ -79,10 +110,112 @@ fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut { @fragment fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { - return CAGE_WIRE_COLOR; + return g.bake_cage_wire; } @fragment -fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 { - return UV_SEAM_COLOR; +fn fs_wire_missing_seam(surface: VOut) -> @location(0) vec4 { + return g.bake_missing_seam; +} + +// The missing seams along the cage, whose vertices carry the bake view's outputs +@fragment +fn fs_wire_cage_missing_seam(surface: BakeViewOut) -> @location(0) vec4 { + return g.bake_missing_seam; +} + +// Shade the neutral material using the texture set's normal, occlusion and optional bent normal +fn neutral_color(n: vec3, n_geo: vec3, v: vec3, world_position: vec3, ao_channel: f32, packed_bent: vec3) -> vec4 { + let albedo = g.bake_neutral_color.rgb; + let rough = clamp(g.bake_neutral.x, MIN_NEUTRAL_ROUGHNESS, 1.0); + let metal = g.bake_neutral.y; + let ao = mix(1.0, ao_channel, g.bake_neutral.z); + let f0 = mix(vec3(NEUTRAL_F0), albedo, metal); + let diffuse_col = albedo * (1.0 - metal); + let nov = clamp(abs(dot(n, v)), MIN_COSINE, 1.0); + + // An unbaked bent normal reads as the neutral gray (length 0): the surface normal stands in + var bent = packed_bent * 2.0 - 1.0; + bent = select(n, normalize(bent), dot(bent, bent) > BENT_NORMAL_MIN_LENGTH * BENT_NORMAL_MIN_LENGTH); + let diffuse = sh_irradiance(normalize(mix(n, bent, g.bake_bent_normal.x)), vec3(0.0)) * diffuse_col * ao; + let r = reflect(-v, n); + let horizon = clamp(1.0 + HORIZON_FADE * dot(r, n_geo), 0.0, 1.0); + + // Reflections pointing away from the open direction are occluded + let bent_occlusion = mix(1.0, smoothstep(BENT_OCCLUSION_START, BENT_OCCLUSION_END, dot(bent, r)), g.bake_bent_normal.y); + let spec = sampled_reflection(n, v, rough, f0, nov) * ao * bent_occlusion * horizon * horizon; + + var direct = vec3(0.0); + if (g.light.w > 0.0) { + let l = normalize(g.light.xyz); + let h = normalize(l + v); + let nol = clamp(dot(n, l), 0.0, 1.0); + let f = f0 + (vec3(1.0) - f0) * pow(1.0 - clamp(dot(v, h), 0.0, 1.0), 5.0); + direct = ((vec3(1.0) - f) * diffuse_col / PI + ggx_dv(rough * rough, nov, nol, clamp(dot(n, h), 0.0, 1.0)) * f) * nol * g.light.w; + if (g.shadow.x > 0.5 && nol > 0.0) { + direct *= shadow_factor(world_position, n_geo); + } + } + let color = diffuse + spec + direct; + return vec4(select(color, vec3(0.0), any(color != color)), 1.0); +} + +// Importance sample the environment's GGX reflection with a new sequence each frame +fn sampled_reflection(n: vec3, v: vec3, rough: f32, f0: vec3, nov: f32) -> vec3 { + let count = max(u32(g.bake_neutral_color.w), 1u); + let a = rough * rough; + let a2 = a * a; + let env_size = vec2(textureDimensions(env_tex)); + let texel_solid_angle = 4.0 * PI / (env_size.x * env_size.y); + let side = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), abs(n.z) < TANGENT_HELPER_MAX_Z); + let tangent = normalize(cross(side, n)); + let bitangent = cross(n, tangent); + let frame_offset = u32(g.material.z) * count; + + // Schlick-GGX geometry term at k = a / 2 + let k = a * 0.5; + let view_visibility = nov / (nov * (1.0 - k) + k); + + var sum = vec3(0.0); + for (var index = 0u; index < count; index++) { + let xi = vec2(fract((f32(index) + 0.5) / f32(count) + f32(g.material.z) * GOLDEN_RATIO_FRACTION), radical_inverse(index + frame_offset)); + let phi = 2.0 * PI * xi.x; + + // Clamp cosine before computing its sine to avoid NaN near zero roughness + let cos_theta = clamp(sqrt((1.0 - xi.y) / (1.0 + (a2 - 1.0) * xi.y)), 0.0, 1.0); + let sin_theta = sqrt(1.0 - cos_theta * cos_theta); + let h = normalize(tangent * (cos(phi) * sin_theta) + bitangent * (sin(phi) * sin_theta) + n * cos_theta); + let l = reflect(-v, h); + let nol = min(dot(n, l), 1.0); + if (nol <= 0.0) { + continue; + } + + // Capped at 1: a dot product rounding past it makes pow(1 - voh, 5) NaN on GPUs that compute pow through log2 + let noh = clamp(dot(n, h), MIN_COSINE, 1.0); + let voh = clamp(dot(v, h), MIN_COSINE, 1.0); + let denominator = max(noh * noh * (a2 - 1.0) + 1.0, MIN_GGX_DENOMINATOR); + let pdf = a2 / (PI * denominator * denominator) * noh / (4.0 * voh); + + // Filtered importance sampling: each sample reads the mip that covers its share of the lobe + let lod = clamp(0.5 * log2(1.0 / (f32(count) * pdf * texel_solid_angle)) + FILTERED_SAMPLING_LOD_BIAS, 0.0, g.env.y); + let light = textureSampleLevel(env_tex, env_samp, env_uv(l), lod).rgb; + let fresnel = f0 + (vec3(1.0) - f0) * pow(1.0 - voh, 5.0); + let visibility = view_visibility * nol / (nol * (1.0 - k) + k); + let contribution = light * fresnel * (visibility * voh / (noh * nov)); + + // Drop NaN samples before they contaminate the frame average + sum += select(contribution, vec3(0.0), any(contribution != contribution)); + } + return sum / f32(count); +} + +// Van der Corput: the bits of `index` mirrored behind the binary point (swapped by hand: WebGL2 lacks a bit reverse) +fn radical_inverse(index: u32) -> f32 { + var bits = (index << 16u) | (index >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return f32(bits) / 4294967296.0; } diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 23c4bd64..aac1d147 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -26,6 +26,14 @@ struct Globals { refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - + bake_high: vec4, // bake mode: rgb high poly color, a - + bake_matching_error: vec4, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden) + bake_cage: vec4, // rgb cage surface color, a opacity + bake_cage_wire: vec4, // rgb cage wireframe color, a opacity + bake_missing_seam: vec4, // rgb color of hard edges without a UV seam, a opacity + bake_neutral_color: vec4, // rgb the neutral material's color, a its reflection samples this frame + bake_neutral: vec4, // x roughness, y metallic, z AO intensity of the neutral material, w on (1) + bake_bent_normal: vec4, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw - }; @group(0) @binding(0) var g: Globals; @@ -403,8 +411,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let hu = textureSample(t_height, samp, uv - vec2(0.0, ts.y)).r; let hd = textureSample(t_height, samp, uv + vec2(0.0, ts.y)).r; - // Tangent-space normal: height gradient (+Y = up the image) combined with the normal channel. - // Same slope rule as texture export: strength 1 tilts 45° for a height change of 1 over 1/16 of the width. + // Match export: a unit height over 1/16 of the width tilts 45° + // Combine the height gradient with the tangent-space normal let k = g.mode.z * dims.x / 16.0 * tile_scale(uv); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); var n_detail = snorm8(nrm_s); @@ -418,6 +426,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { if (ch >= 11) { return unlit(lobe_view(ch, lobes, sheen_t, nrm_t.a, emis_t.a, extra)); } + switch ch { case 0: { return unlit(data_out(base_s.rgb)); } case 1: { return unlit(data_out(vec3(orm.b))); } @@ -435,6 +444,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { if (mode == 2) { return unlit(raw_out(aux.rgb)); } + if (mode == 3) { let c = floor(uv * 32.0); let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5); @@ -446,7 +456,11 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { return unlit(data_out((col + tint) * diff)); } - // Opacity: dithered alpha test (a new pattern per accumulated frame, so it averages out). + if (g.bake_neutral.w > 0.5) { + return Shaded(neutral_color(n, n_geo, v, i.wpos, orm.r, aux.rgb), vec3(0.0)); + } + + // Change the alpha dither each frame so accumulation smooths it if (base_s.a < hash12(i.clip.xy + g.material.z * vec2(17.0, 59.0))) { discard; } @@ -459,25 +473,27 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { var f0 = mix(vec3(0.08 * orm.a), albedo, metal); var diffuse_col = albedo * (1.0 - metal); if (g.material.x > 0.5) { - // Specular/glossiness: the Specular color is F0 and base color the diffuse color, with - // the energy the specular takes removed (roughness already is 1 - glossiness). + // Specular color gives F0; remove its energy from diffuse f0 = hgt.gba; diffuse_col = albedo * (1.0 - max(f0.r, max(f0.g, f0.b))); } - // Transmission: that part of the dielectric base refracts instead of reflecting diffusely. + + // Transmission removes energy from the dielectric diffuse base let trans = extra.b * (1.0 - metal); diffuse_col *= 1.0 - trans; - // The extra lobes; their defaults (weights 0) leave the base shading as it is. + // Zero lobe weights preserve the base shading let coat_w = lobes.r; let coat_rough = clamp(lobes.g, 0.045, 1.0); let aniso = lobes.b; let sheen_col = sheen_t.rgb * sheen_t.a; let sheen_max = max3(sheen_col); let sheen_rough = clamp(nrm_t.a, 0.07, 1.0); - // Subsurface scattering: wrapped diffuse, wider for the channels the scatter color carries further. + + // Scatter color controls each channel's diffuse wrap let wrap = emis_t.a * g.scatter.xyz; - // Anisotropy: GGX roughness stretched along the mesh tangent turned by the angle (0..1 → 0..π). + + // Stretch GGX along the tangent rotated by 0..π let a = rough * rough; let at = max(a * (1.0 + aniso), 0.002); let ab = max(a * (1.0 - aniso), 0.002); @@ -486,8 +502,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let ta1 = ta0 - n * dot(n, ta0); let ta = ta1 * inverseSqrt(max(dot(ta1, ta1), 1e-8)); let ba = cross(n, ta); - // The clear coat follows the mesh normal (not the normal and height channels), turned by the - // coat normal channel where it is painted (the flat default keeps the mesh normal exactly). + + // Coat normals perturb the geometric normal independently of base detail var n_c = n_geo; let cn = coat_normal_ts(extra); if (coat_w > 0.0 && max(abs(cn.x), abs(cn.y)) > 0.004) { @@ -495,7 +511,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { } let nov_c = clamp(abs(dot(n_c, v)), 1e-4, 1.0); let coat_t = 1.0 - coat_w * schlick(0.04, nov_c); - // What reaches the layers below: the coat's transmission and the sheen albedo scaling. + + // Coat transmission and sheen albedo limit energy reaching the base var base_scale = coat_t; var sheen_e = 0.0; if (sheen_max > 0.0) { @@ -506,12 +523,13 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let diffuse = sh_irradiance(n, wrap) * diffuse_col * ao; var r = reflect(-v, n); if (aniso > 0.0) { - // Bent reflection vector: the standard real-time approximation of anisotropic IBL. + // Bend the reflection to approximate anisotropic IBL let bent = cross(cross(ba, v), ba); r = reflect(-v, normalize(mix(n, bent, aniso * clamp(5.0 * rough, 0.0, 1.0)))); } let pre = textureSampleLevel(env_tex, env_samp, env_uv(r), rough * g.env.y).rgb; - // Horizon fading: reflections that point below the geometric surface are dimmed. + + // Fade reflections below the geometric surface let horizon = clamp(1.0 + 1.3 * dot(r, n_geo), 0.0, 1.0); let spec = pre * env_brdf(f0, rough, nov) * ao * horizon * horizon; var layers = vec3(0.0); @@ -525,16 +543,14 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { } if (trans > 0.0) { - // shortcut: one refraction interface (no exit); the path tracer refracts through the - // whole mesh. + // Approximate one refraction interface; the path tracer also handles the exit var td = refract(-v, n, 1.0 / max(g.material.w, 1.0)); if (dot(td, td) < 1e-6) { td = reflect(-v, n); } var behind = textureSampleLevel(env_tex, env_samp, env_uv(td), rough * g.env.y).rgb; if (g.refr.x > 0.5) { - // Screen-space refraction: the opaque scene where the refracted ray lands on screen, - // over the environment where that shows nothing (or the ray leaves the view). + // Composite the refracted screen sample over the environment fallback let p = g.view_proj * vec4(i.wpos + td * g.refr.z, 1.0); let s = p.xy / max(p.w, 1e-6); let suv = vec2(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5); @@ -563,7 +579,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { dv = ggx_dv(a, nov, nol, noh); } let f = f0 + (vec3(1.0) - f0) * pow(1.0 - voh, 5.0); - // Energy-conserving wrapped Lambert (plain Lambert where nothing scatters). + + // Normalize wrapped Lambert to conserve energy let diff_nol = max((nol_raw + wrap) / ((1.0 + wrap) * (1.0 + wrap)), vec3(0.0)); direct_diffuse = (vec3(1.0) - f) * diffuse_col / PI * diff_nol * (g.light.w * base_scale); direct = ((vec3(1.0) - f) * diffuse_col / PI * diff_nol + dv * f * nol) * (g.light.w * base_scale); diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 3b5b3938..f6c25615 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -3,7 +3,7 @@ use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; -use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind}; +use texturecraft_render::{BakeOverlay, BakeVisualization, CageGeometry, Frame, NeutralMaterial, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -226,6 +226,92 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +/// `overlay` shown +fn shown(overlay: BakeOverlay) -> BakeOverlay { + BakeOverlay { shown: true, ..overlay } +} + +#[test] +fn bake_neutral_material_shades_the_low_poly_in_its_settings() { + const COLOR_LEAD: i32 = 30; + let Some((mut h, frame)) = setup() else { return }; + + let neutral = NeutralMaterial { roughness: 0.5, metallic: 0.0, ao_intensity: 1.0, samples_per_pixel: 16, ..NeutralMaterial::default() }; + let low_poly = BakeOverlay { color: [0.0, 0.0, 0.8], ..shown(BakeVisualization::default().low_poly) }; + let painted_parts = BakeVisualization { low_poly, ..BakeVisualization::default() }; + let neutral_parts = BakeVisualization { neutral: Some(neutral), ..painted_parts }; + let painted = render(&mut h, &shaded(&frame, |s| s.bake = Some(painted_parts)), "bake_neutral_off"); + let blue = render(&mut h, &shaded(&frame, |s| s.bake = Some(neutral_parts)), "bake_neutral_blue"); + let center = (frame.size[0] / 2, frame.size[1] / 2); + let [red, green, blue_channel] = blue.at(center.0, center.1).map(i32::from); + assert!( + blue_channel > red + COLOR_LEAD && blue_channel > green + COLOR_LEAD, + "the neutral material takes the project mesh's color: {:?}", + [red, green, blue_channel] + ); + assert_ne!(blue.px, painted.px, "the painted material is replaced"); + + let metal = BakeVisualization { neutral: Some(NeutralMaterial { metallic: 1.0, roughness: 0.1, ..neutral }), ..neutral_parts }; + assert_ne!(render(&mut h, &shaded(&frame, |s| s.bake = Some(metal)), "bake_neutral_metal").px, blue.px, "roughness and metallic reach the shader"); + + let hidden_low_poly = BakeVisualization { low_poly: BakeOverlay { shown: false, ..low_poly }, ..neutral_parts }; + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_neutral_background"); + assert_same( + &render(&mut h, &shaded(&frame, |s| s.bake = Some(hidden_low_poly)), "bake_neutral_hidden"), + &background, + "a hidden project mesh draws nothing", + ); +} + +#[test] +fn bake_neutral_material_looks_the_same_moving_as_still() { + // Full quality keeps the first frame near settled; one sample missed by 6.6 levels + const MAX_MEAN_LEVELS: f32 = 4.0; + let Some((mut h, frame)) = setup() else { return }; + + let neutral = NeutralMaterial { roughness: 0.5, metallic: 1.0, ..NeutralMaterial::default() }; + let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() }; + let still = shaded(&frame, |s| { + s.taa = true; + s.bake = Some(parts); + }); + let first = render(&mut h, &still, "bake_neutral_first_frame"); + for _ in 1..TAA_SAMPLES { + render(&mut h, &still, "bake_neutral_settling"); + } + let settled = render(&mut h, &still, "bake_neutral_settled"); + + // Compared on the ball in the middle of the view, where the reflections are + let (width, height) = (frame.size[0], frame.size[1]); + let ball = (width * 3 / 8..width * 5 / 8).flat_map(|x| (height / 4..height / 2).map(move |y| (x, y))); + let differences: Vec = ball.map(|(x, y)| (first.luma(x, y) - settled.luma(x, y)).abs()).collect(); + let mean_difference = differences.iter().sum::() / differences.len() as f32; + assert!(mean_difference < MAX_MEAN_LEVELS, "the first frame is {mean_difference} levels off the settled one on average"); +} + +#[test] +fn bake_neutral_material_stays_lit_at_any_roughness_once_settled() { + // Near roughness 0 a bad sample gave NaN, and the settled average of all frames went black + const MIN_BALL_LUMA: f32 = 20.0; + let Some((mut h, frame)) = setup() else { return }; + + for roughness in [0.0, 0.05, 0.1] { + let neutral = NeutralMaterial { roughness, ..NeutralMaterial::default() }; + let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() }; + let still = shaded(&frame, |s| { + s.taa = true; + s.bake = Some(parts); + }); + for _ in 0..TAA_SAMPLES { + render(&mut h, &still, "bake_neutral_mirror_settling"); + } + let settled = render(&mut h, &still, "bake_neutral_mirror_settled"); + let (width, height) = (frame.size[0], frame.size[1]); + let ball = settled.mean(width * 3 / 8, height / 4, width * 5 / 8, height / 2); + assert!(ball > MIN_BALL_LUMA, "roughness {roughness}: the settled ball is black ({ball})"); + } +} + #[test] fn bake_visualization_draws_the_high_poly_and_the_cage() { // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color @@ -246,15 +332,17 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() { } h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap(); let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect(); - h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY); - let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None }; + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &corners, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY); + let bake = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), ..BakeVisualization::default() }; let center = (frame.size[0] / 2, frame.size[1] / 2); let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name); let low_only = only(&mut h, bake, "bake_low_only"); - let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden"); - let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly"); - let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage"); + let high_only = BakeVisualization { high_poly: shown(bake.high_poly), matching_error: shown(bake.matching_error), ..BakeVisualization::default() }; + let caged_parts = BakeVisualization { cage_surface: shown(bake.cage_surface), cage_wire: shown(bake.cage_wire), ..bake }; + let hidden = only(&mut h, BakeVisualization::default(), "bake_low_hidden"); + let high_poly = only(&mut h, high_only, "bake_high_poly"); + let caged = only(&mut h, caged_parts, "bake_cage"); assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly"); let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background"); assert_same(&hidden, &background, "without the low poly only the background is left"); @@ -270,26 +358,63 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() { // Vertices the bake's rays miss turn red h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]); - let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed"); + let missed = only(&mut h, high_only, "bake_high_missed"); let [red, green, blue] = missed.at(center.0, center.1).map(i32::from); assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]); + let no_error = only(&mut h, BakeVisualization { matching_error: bake.matching_error, ..high_only }, "bake_high_missed_hidden"); + assert_same(&no_error, &high_poly, "with the matching error hidden the missed vertices keep the high poly's color"); + let green_error = BakeOverlay { color: [0.0, 1.0, 0.0], ..high_only.matching_error }; + let [red, green, blue] = + only(&mut h, BakeVisualization { matching_error: green_error, ..high_only }, "bake_high_missed_green").at(center.0, center.1).map(i32::from); + assert!(green > red + COLOR_LEAD && green > blue + COLOR_LEAD, "the matching error's color reaches the shader: {:?}", [red, green, blue]); - // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out - let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set"); - let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set"); - assert_ne!(first_set.px, caged.px, "the second set's low poly is left out"); - assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out"); - assert_ne!(first_set.px, second_set.px); + // Show for selected texture set only filters the cage (only set 0 has one here), never the low poly + let first_set = only(&mut h, BakeVisualization { only_set: Some(0), ..caged_parts }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { only_set: Some(1), ..caged_parts }, "bake_only_second_set"); + assert_same(&first_set, &caged, "set 0's cage stays and both sets' low poly draws"); + assert_same(&second_set, &low_only, "set 0's cage drops out, the low poly stays"); - // UV seams draw over the low poly - h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges()); - let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams"); + // The cage's surface and wireframe show apart, in their own color and opacity + let surface_only = only(&mut h, BakeVisualization { cage_surface: shown(bake.cage_surface), ..bake }, "bake_cage_surface"); + let wire_only = only(&mut h, BakeVisualization { cage_wire: shown(bake.cage_wire), ..bake }, "bake_cage_wire"); + assert!(surface_only.px != low_only.px && wire_only.px != low_only.px && surface_only.px != wire_only.px, "each part of the cage draws on its own"); + let opaque_blue = BakeOverlay { color: [0.0, 0.0, 1.0], opacity: 1.0, ..caged_parts.cage_surface }; + let [red, green, blue] = + only(&mut h, BakeVisualization { cage_surface: opaque_blue, ..bake }, "bake_cage_surface_blue").at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green + COLOR_LEAD, "an opaque blue cage hides the ball: {:?}", [red, green, blue]); + let clear = only(&mut h, BakeVisualization { cage_surface: BakeOverlay { opacity: 0.0, ..opaque_blue }, ..bake }, "bake_cage_surface_clear"); + assert_same(&clear, &low_only, "a fully transparent cage leaves the ball as it is"); + + // High-poly vertices another set owns are left out + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![-1.0; high.positions.len()]); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_high_hidden_background"); + assert_same(&only(&mut h, high_only, "bake_high_other_set"), &background, "a high poly owned by other sets draws nothing"); + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![0.0; high.positions.len()]); + + // The missing seams draw over the low poly in their color + h.renderer.set_missing_seams(&h.device, &h.queue, MESH_ID, &ball.wire_edges()); + let seams = only(&mut h, BakeVisualization { missing_seams: shown(bake.missing_seams), ..bake }, "bake_missing_seams"); assert_ne!(seams.px, low_only.px, "the seams show"); + let green_seams = BakeOverlay { color: [0.0, 1.0, 0.0], ..shown(bake.missing_seams) }; + assert_ne!( + only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_green").px, + seams.px, + "the seams' color reaches the shader" + ); + let uv = Frame { view_id: 2, kind: ViewKind::Uv { ts: 0, zoom: 1.0, pan: [0.0, 0.0] }, ..frame.clone() }; + let uv_plain = render(&mut h, &shaded(&uv, |s| s.bake = Some(bake)), "bake_missing_seams_uv_off"); + let uv_seams = render(&mut h, &shaded(&uv, |s| s.bake = Some(BakeVisualization { missing_seams: green_seams, ..bake })), "bake_missing_seams_uv"); + assert_ne!(uv_seams.px, uv_plain.px, "the seams show in the 2D view too"); + let caged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..caged_parts }, "bake_missing_seams_cage"); + let uncaged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_no_cage"); + let caged_plain = only(&mut h, caged_parts, "bake_cage_no_seams"); + assert_ne!(caged_seams.px, caged_plain.px, "the seams show with the cage"); + assert_ne!(caged_seams.px, uncaged_seams.px); // A new distance with the same topology only moves the corners let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect(); - h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY); - let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown"); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &grown, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY); + let bigger = only(&mut h, caged_parts, "bake_cage_grown"); assert_ne!(caged.px, bigger.px, "the cage grew"); } @@ -300,6 +425,7 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() { let high = primitives::sphere(0.5, 16, 8); headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap(); let limit = headless.device.limits().max_buffer_size; + // The viewport vertex contains position, normal, tangent and UV: twelve f32 values let vertex_count = limit as usize / (12 * std::mem::size_of::()) + 1; let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() }; @@ -307,7 +433,7 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() { assert!(error.contains("GPU buffer limit"), "{error}"); headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]); - let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let bake = BakeVisualization { high_poly: shown(BakeVisualization::default().high_poly), ..BakeVisualization::default() }; let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared"); let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background"); assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible"); @@ -317,10 +443,10 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() { } #[test] -fn bake_low_poly_visibility_also_filters_its_wireframe() { +fn bake_low_poly_visibility_also_filters_its_wireframe_but_not_by_selected_set() { let Some((mut headless, frame)) = setup() else { return }; - let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let bake = BakeVisualization::default(); let hidden = shaded(&frame, |shade| { shade.bake = Some(bake); shade.wireframe_3d = true; @@ -332,13 +458,13 @@ fn bake_low_poly_visibility_also_filters_its_wireframe() { for texture_set in [0, 1] { let selected = shaded(&hidden, |shade| { - shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake }); + shade.bake = Some(BakeVisualization { low_poly: shown(bake.low_poly), only_set: Some(texture_set), ..bake }); shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] }); }); - let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() }; + let expected = shaded(&selected, |shade| shade.bake = Some(BakeVisualization { only_set: None, ..shade.bake.unwrap_or(bake) })); let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}")); let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}")); - assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set"); + assert_same(&actual, &expected, "the selected-set filter leaves the low poly, its wireframe and highlight alone"); } } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 738ceaec..322d3297 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -13,7 +13,7 @@ use std::path::PathBuf; /// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB). const MANIFESTS: &[(&str, Faces, Faces)] = &[ ("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]), - // The interface font, regular and semibold (0.8 MB). + // The interface font has regular and semibold faces (LATIN_MANIFEST, LATIN, LATIN), ]; /// The Arabic face (0.8 MB, so the web build has it too). @@ -38,6 +38,7 @@ fn main() { Err(e) => println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {e}", dir.display()), } } + src.push_str("];\n"); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); if let Err(e) = std::fs::write(&out, src) { @@ -52,6 +53,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: if rel == LATIN_MANIFEST && !manifest.exists() { return Ok(String::new()); } + let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); let wanted = if wasm { web } else { desktop }; @@ -61,9 +63,11 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let [family, style, file, scripts, ..] = f.as_slice() else { return Err(format!("malformed manifest line: {line}")); }; + if !wanted.contains(&(*family, *style)) { continue; } + let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); if rel == LATIN_MANIFEST { @@ -72,6 +76,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: std::fs::write(&out, without_private_use(&bytes).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{}: {e}", out.display()))?; path = out; } + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, @@ -80,6 +85,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: path.display().to_string(), ); } + Ok(out) } diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs index 6d0cd6e4..cf6ba7e4 100644 --- a/crates/ui-egui/i18n_build.rs +++ b/crates/ui-egui/i18n_build.rs @@ -13,9 +13,11 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { source.push_str("];\n"); return Ok(source); }; + if !dir.is_absolute() { return Err("CRAFT_I18N_DIR must be an absolute path".into()); } + let locales = dir.join("locales"); let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?; println!("cargo::rerun-if-changed={}", locales.display()); @@ -26,23 +28,26 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { paths.push(entry.path()); } } + paths.sort(); let mut count = 0; let mut catalogs = Vec::new(); for path in paths { - // Watch directories too: adding/removing an app catalog must rebuild the embedding. + // Watch directories so adding or removing an app catalog rebuilds the embedding println!("cargo::rerun-if-changed={}", path.display()); let app = path.join("texturecraft.tsv"); if !app.is_file() { continue; } + let locale = path.file_name().and_then(|n| n.to_str()).ok_or("non-UTF-8 locale")?; let common = path.join("common.tsv"); let embed = |file: &Path| -> Result<(String, &'static str), String> { let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; let name = file.to_str().ok_or("non-UTF-8 catalog path")?; println!("cargo::rerun-if-changed={name}"); - // The shared runtime requires static inputs; this short-lived build process owns them. + + // The shared runtime needs static inputs for this short-lived build process Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str()))) }; let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") }; @@ -55,12 +60,14 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { if required && count == 0 { return Err("no TextureCraft translation catalogs found".into()); } - // Reject the same rows the runtime would skip, before required builds can ship English fallbacks. + + // Reject rows the runtime would skip before required builds can ship English fallbacks let (runtime, mut problems) = craft_i18n::I18n::new(Box::leak(catalogs.into_boxed_slice()), &[]); problems.extend(runtime.check_all()); if !problems.is_empty() { return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; "))); } + source.push_str("];\n"); Ok(source) } @@ -83,6 +90,7 @@ pub fn embed() { "pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into() } }; + let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs"); if let Err(error) = std::fs::write(&out, source) { println!("cargo::error=writing {}: {error}", out.display()); diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index f585d326..4b60f6f0 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -5,4 +5,6 @@ pub struct BakeJob { pub queue: Vec, pub current: Option, pub total: usize, + /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. + pub mesh_id: u64, } diff --git a/crates/ui-egui/src/bake_mode/bake_checks.rs b/crates/ui-egui/src/bake_mode/bake_checks.rs new file mode 100644 index 00000000..36b91298 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_checks.rs @@ -0,0 +1,223 @@ +//! Problems the next bake would have, listed above the bake bar before Bake is pressed + +use std::sync::{Arc, Weak}; + +use egui_phosphor::regular as icon; +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; + +use crate::TextureCraftApp; +use crate::i18n::trf; +use crate::theme::Tokens; + +/// Share of a texture set's UV layout that may overlap before it is listed (as mesh import warns) +const UV_OVERLAP_WARNING: f32 = 0.01; + +/// How many part names a warning spells out before "and N more" +const NAMES_SHOWN: usize = 3; + +/// The warnings' gap above the bake bar +const WARNINGS_GAP: f32 = 8.0; + +/// The warnings above bake mode's bake bar in the 3D view `viewport`, until a bake starts +pub(crate) fn bake_warnings(app: &TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { + if app.bake_progress().is_some() { + return; + } + + let warnings = cached_warnings(ctx, &app.session); + if warnings.is_empty() { + return; + } + + let tokens = Tokens::get(ctx); + let above_bar = super::BAKE_BAR_MARGIN + ctx.global_style().spacing.interact_size.y + WARNINGS_GAP; + egui::Area::new(egui::Id::unique("bake_warnings")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -above_bar)).show( + ctx, + |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| { + for warning in warnings.iter() { + ui.label(egui::RichText::new(format!("{} {warning}", icon::WARNING)).color(tokens.warning)); + } + }); + }, + ); +} + +/// The warnings for the texture sets the next bake includes, worked out again only when what they read changes +pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc> { + let id = egui::Id::unique("bake_check_warnings"); + let key = inputs_key(session); + + // A handle, not an address: a rebuilt high poly could reuse a dropped one's address + let high = session.bake_meshes.merged_high().map_or_else(Weak::new, |high| Arc::downgrade(&high.mesh)); + if let Some((cached_key, cached_high, cached)) = ctx.data(|data| data.get_temp::<(String, Weak, Arc>)>(id)) + && cached_key == key + && cached_high.ptr_eq(&high) + { + return cached; + } + + let fresh = Arc::new(warnings(session)); + ctx.data_mut(|data| data.insert_temp(id, (key, high, fresh.clone()))); + fresh +} + +/// Everything the warnings read or show apart from the high poly (cached as a handle): the low poly, the UI language, and per included set its name, material, high-poly settings, UV tile resolutions and the tiles left out of the bake +fn inputs_key(session: &Session) -> String { + let sets: Vec<_> = baked_sets(session) + .filter_map(|index| { + let set = session.doc.project.texture_sets.get(index)?; + Some((index, &set.name, set.material, &set.bake.high_poly, &set.tile_resolutions, &set.bake_excluded_tiles)) + }) + .collect(); + + format!("{}|{}|{sets:?}", session.mesh_id, crate::i18n::current().code) +} + +/// The texture sets the next bake includes +fn baked_sets(session: &Session) -> impl Iterator + '_ { + session.doc.project.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.common.is_enabled && set.has_enabled_bake_tiles()).map(|(index, _)| index) +} + +/// Overlapping UVs per included set, its low-poly parts "By Mesh Name" pairs with nothing, then the high-poly parts no included set bakes from +pub(crate) fn warnings(session: &Session) -> Vec { + let mut lines = Vec::new(); + let included: Vec = baked_sets(session).collect(); + for &index in &included { + let Some(set) = session.doc.project.texture_sets.get(index) else { continue }; + + let overlap = session.bake_uv_overlap(index).unwrap_or(0.0); + if overlap > UV_OVERLAP_WARNING { + let percent = format!("{:.1}", overlap * 100.0); + lines.push(trf( + "{set}: {percent}% of the UV layout overlaps, so those texels bake one place for several", + &[("set", &set.name), ("percent", &percent)], + )); + } + + let Ok(Some(pairs)) = session.bake_name_pairs(index) else { continue }; + + let unpaired_low: Vec<&str> = pairs.iter().filter(|pair| pair.high.is_none()).filter_map(|pair| pair.low.as_deref()).collect(); + if !unpaired_low.is_empty() { + lines.push(trf("{set}: no high poly part matches {names}", &[("set", &set.name), ("names", &listed(&unpaired_low))])); + } + } + + let unpaired_high = session.bake_unpaired_high_parts(&included).unwrap_or_default(); + if !unpaired_high.is_empty() { + let names: Vec<&str> = unpaired_high.iter().map(String::as_str).collect(); + lines.push(trf("No low poly part matches {names}", &[("names", &listed(&names))])); + } + + lines +} + +/// `names` joined, the first few spelled out and the rest counted +fn listed(names: &[&str]) -> String { + let shown = names.iter().take(NAMES_SHOWN).copied().collect::>().join(", "); + match names.len().checked_sub(NAMES_SHOWN).filter(|more| *more > 0) { + Some(more) => trf("{names} and {count} more", &[("names", &shown), ("count", &more)]), + None => shown, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::MeshMatchMode; + + /// Part `index` named `name` (an OBJ object): a quad at x offset `x` whose UVs span `u` to `u` + 0.2 + fn quad(name: &str, index: usize, x: f32, u: f32) -> String { + let first = index * 4 + 1; + format!( + "o {name}\nv {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\nvt {u} 0\nvt {} 0\nvt {} 1\nvt {u} 1\nf {first}/{first} {}/{} {}/{} {}/{}\n", + x + 1.0, + x + 1.0, + u + 0.2, + u + 0.2, + first + 1, + first + 1, + first + 2, + first + 2, + first + 3, + first + 3 + ) + } + + fn session(overlapping: bool) -> Session { + let names = ["Box_low", "Lid_low", "Bolt_low", "Nut_low", "Pin_low"]; + let obj: String = + names.iter().enumerate().map(|(index, name)| quad(name, index, index as f32 * 2.0, if overlapping { 0.0 } else { index as f32 * 0.2 })).collect(); + Session::from_mesh_bytes("parts.obj", obj.as_bytes(), 128, "parts").unwrap() + } + + #[test] + fn a_clean_setup_lists_nothing() { + let mut session = session(false); + assert_eq!(warnings(&session), Vec::::new()); + session.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + assert_eq!(warnings(&session), Vec::::new(), "\"Always\" pairs every part"); + } + + #[test] + fn renaming_a_set_refreshes_the_cached_warnings() { + let mut session = session(true); + let ctx = egui::Context::default(); + let before = cached_warnings(&ctx, &session); + assert!(before.iter().any(|line| line.starts_with(&session.doc.project.texture_sets[0].name)), "{before:?}"); + + session.doc.project.texture_sets[0].name = "Renamed".into(); + let after = cached_warnings(&ctx, &session); + assert!(after.iter().any(|line| line.starts_with("Renamed:")), "{after:?}"); + } + + #[test] + fn swapping_the_high_poly_refreshes_the_cached_warnings() { + let mut session = session(false); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + session.add_high_poly_bytes("spare.obj", b"o Spare_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let ctx = egui::Context::default(); + assert!(cached_warnings(&ctx, &session).contains(&"No low poly part matches Spare_high".to_owned())); + + // The new high poly's mesh may take the dropped one's address + drop(session.remove_high_poly(0).unwrap()); + session.add_high_poly_bytes("box.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let after = cached_warnings(&ctx, &session); + assert!(!after.iter().any(|line| line.contains("Spare_high")), "{after:?}"); + } + + #[test] + fn leaving_the_overlapping_tile_out_refreshes_the_cached_warnings() { + // One quad in tile 1001, two on the same UVs in tile 1002 + let obj = [quad("First_low", 0, 0.0, 0.0), quad("Second_low", 1, 2.0, 1.0), quad("Third_low", 2, 4.0, 1.0)].concat(); + let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap(); + let ctx = egui::Context::default(); + assert_eq!(cached_warnings(&ctx, &session).len(), 1, "tile 1002 overlaps"); + + session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002); + assert_eq!(*cached_warnings(&ctx, &session), Vec::::new(), "tile 1001 alone has no overlap"); + } + + #[test] + fn overlapping_uvs_and_unpaired_parts_are_listed() { + let mut session = session(true); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Spare_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let set = session.doc.project.texture_sets[0].name.clone(); + + assert_eq!( + warnings(&session), + [ + format!("{set}: 100.0% of the UV layout overlaps, so those texels bake one place for several"), + format!("{set}: no high poly part matches Lid_low, Bolt_low, Nut_low and 1 more"), + "No low poly part matches Spare_high".to_owned(), + ] + ); + + session.doc.project.texture_sets[0].bake.common.is_enabled = false; + assert_eq!(warnings(&session), Vec::::new(), "a set the bake leaves out is not checked"); + } +} diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs index 42da4393..5c4d02cc 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -1,58 +1,191 @@ use egui::collapsing_header::CollapsingState; use egui::{Rect, Ui, vec2}; use egui_phosphor::regular as icon; +use texturecraft_render::BakeOverlay; +use super::BakeVisualizationToggles; +use super::section_opening::SectionOpening; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{n_, tr, trf}; +use crate::screen_color_pick::eyedropper; use crate::theme::Tokens; -use crate::widgets::{icon_button_without_tooltip, section_chevron}; +use crate::widgets::{color_swatch, combo, icon_button, section_chevron, slider}; /// The panel's width and its gap from the 3D view's top-left corner const PANEL_WIDTH: f32 = 280.0; const PANEL_MARGIN: f32 = 12.0; -/// Size of the panel's eye buttons +/// Opacity of the panel's backing +const PANEL_OPACITY: f32 = 0.92; + +/// Size of the panel's eye button, and of the smaller buttons on its rows const EYE_BUTTON_SIZE: f32 = 22.0; +const ROW_BUTTON_SIZE: f32 = 18.0; + +/// Width of an overlay's color swatch +const SWATCH_WIDTH: f32 = 44.0; + +/// The neutral material's quality steps: samples per pixel and their names +const QUALITIES: [(u32, &str); 6] = [ + (4, n_("Very Low (4 spp)")), + (16, n_("Low (16 spp)")), + (32, n_("Medium (32 spp)")), + (64, n_("High (64 spp)")), + (128, n_("Very High (128 spp)")), + (256, n_("Ultra (256 spp)")), +]; /// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { let toggles = &mut app.ui.bake_visualization; + let tokens = Tokens::get(ui.ctx()); egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( ui.ctx(), |ui| { - ui.set_width(PANEL_WIDTH); - let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true); - let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open())); - if header.clicked() { - collapsing_state.toggle(ui); - } + // Its own backing, so the panel reads in every theme over whatever the 3D view shows + egui::Frame::popup(ui.style()).fill(tokens.panel.gamma_multiply(PANEL_OPACITY)).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); - collapsing_state.show_body_unindented(ui, |ui| { - ui.add_enabled_ui(toggles.on, |ui| { - ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); - eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None); - eye_row(ui, &mut toggles.cage, tr("Cage"), None); - eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None); - eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None); - }); + // Ids renamed with the reference defaults, so open/closed states saved by earlier builds don't carry over + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("baking_visualization_open"), true); + if header(ui, toggles, collapsing_state.is_open()).clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles)); }); }, ); } -/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response -fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response { +/// The panel's sections below its header +fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { + ui.horizontal(|ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(egui::RichText::new(icon::INFO).color(Tokens::get(ui.ctx()).text_dim)) + .on_hover_text(tr("Only the cage and the high poly meshes of the selected texture set show.")); + }); + }); + + // The eye greys what it hides, and holds the project mesh shown + let meshes_editable = !toggles.hide_baking_meshes; + if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| { + overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh); + overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error); + }) { + toggles.reset_high_poly(); + } + + if collapsible(ui, "cage", tr("Cage"), SectionOpening::Open, true, meshes_editable, |ui| { + overlay_row(ui, "bake_cage_surface_color", tr("Cage Surface"), &mut toggles.cage_surface); + ui.add_enabled_ui(toggles.cage_surface.shown, |ui| slider(ui, tr("Cage Surface Opacity"), &mut toggles.cage_surface.opacity, 0.0..=1.0, 2)); + overlay_row(ui, "bake_cage_wire_color", tr("Cage Wireframe"), &mut toggles.cage_wire); + ui.add_enabled_ui(toggles.cage_wire.shown, |ui| slider(ui, tr("Cage Wireframe Opacity"), &mut toggles.cage_wire.opacity, 0.0..=1.0, 2)); + }) { + toggles.reset_cage(); + } + + if collapsible(ui, "seams", tr("UV Seams"), SectionOpening::Closed, true, true, |ui| { + overlay_row(ui, "bake_missing_seam_color", tr("Missing Seams on Hard Edges"), &mut toggles.missing_seams); + }) { + toggles.reset_seams(); + } + + if collapsible(ui, "project_mesh", tr("Project Mesh (LP)"), SectionOpening::Closed, true, true, |ui| { + ui.add_enabled_ui(meshes_editable, |ui| overlay_row(ui, "bake_project_mesh_color", tr("Project Mesh"), &mut toggles.project_mesh)); + ui.add_enabled_ui(toggles.project_mesh.shown, |ui| { + collapsible(ui, "neutral_material", tr("Neutral Material"), SectionOpening::Open, false, true, |ui| neutral_material(ui, toggles)) + }); + }) { + toggles.reset_project_mesh(); + } +} + +/// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal +fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { + ui.add_enabled_ui(toggles.neutral_shown, |ui| { + let neutral = &mut toggles.neutral; + let selected = QUALITIES.iter().find(|(samples, _)| *samples == neutral.samples_per_pixel).map_or("", |(_, name)| tr(name)); + combo(ui, tr("Quality"), selected, |ui| { + for (samples, name) in QUALITIES { + ui.selectable_value(&mut neutral.samples_per_pixel, samples, tr(name)); + } + }); + slider(ui, tr("Roughness"), &mut neutral.roughness, 0.0..=1.0, 2); + slider(ui, tr("Metallic"), &mut neutral.metallic, 0.0..=1.0, 2); + slider(ui, tr("AO intensity"), &mut neutral.ao_intensity, 0.0..=1.0, 2); + ui.checkbox(&mut neutral.bent_normal, tr("Bent Normal")); + ui.add_enabled_ui(neutral.bent_normal, |ui| { + slider(ui, tr("Bent Normal Diffuse Amount"), &mut neutral.bent_normal_diffuse, 0.0..=1.0, 2); + slider(ui, tr("Bent Normal Specular Amount"), &mut neutral.bent_normal_specular, 0.0..=1.0, 2); + }); + }); +} + +/// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked +fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool { + let tokens = Tokens::get(ui.ctx()); + let mut collapsing_state = + CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open); + let (header, reset) = ui + .horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = egui::RichText::new(format!("{} {title}", section_chevron(ui, collapsing_state.is_open()).text())).strong().color(tokens.text_strong); + let header = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); + + // Dimmed while the section is closed, as the reference draws it + let reset = resettable.then(|| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(collapsing_state.is_open() && editable, |ui| { + icon_button(ui, icon::CLOCK_COUNTER_CLOCKWISE, &trf("Reset {section}", &[("section", &title)]), false, ROW_BUTTON_SIZE) + }) + .inner + }) + .inner + }); + (header, reset) + }) + .inner; + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_indented(&header, ui, |ui| { + ui.add_enabled_ui(editable, body); + }); + reset.is_some_and(|reset| reset.clicked()) +} + +/// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right +fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) { + ui.horizontal(|ui| { + ui.checkbox(&mut overlay.shown, label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(overlay.shown, |ui| { + eyedropper( + ui, + ui.make_persistent_id(id), + &mut overlay.color, + &trf("Pick the {overlay} Color from the Screen", &[("overlay", &label)]), + ROW_BUTTON_SIZE, + ); + color_swatch(ui, id, &mut overlay.color, SWATCH_WIDTH); + }); + }); + }); +} + +/// The panel's title with a chevron showing whether the panel is `open`, and the eye that hides the baking meshes; returns the title's response +fn header(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, open: bool) -> egui::Response { let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.set_min_height(EYE_BUTTON_SIZE); - let text = match open { - Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())), - None => egui::RichText::new(label), - }; - let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click())); + let text = egui::RichText::new(format!("{} {}", section_chevron(ui, open).text(), tr("Baking Visualization"))).color(tokens.text_strong); + let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() { - *shown = !*shown; + if icon_button(ui, icon::EYE_SLASH, tr("Hide Baking Meshes"), toggles.hide_baking_meshes, EYE_BUTTON_SIZE).clicked() { + toggles.toggle_hiding(); } }); response diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs index 0603c523..bb99e09b 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -1,34 +1,140 @@ use serde::{Deserialize, Serialize}; -use texturecraft_render::BakeVisualization; +use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial}; -/// The Baking Visualization panel's switches in bake mode's 3D view +/// Opacity of the cage's surface and wireframe until changed +const CAGE_OPACITY: f32 = 0.4; + +/// The Baking Visualization panel's settings for bake mode's 3D view (view state, not saved in the project) #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct BakeVisualizationToggles { - /// The panel's eye: the whole visualization on or off - pub on: bool, + /// The panel's eye: hides the high poly and the cage, whatever their own switches say + pub hide_baking_meshes: bool, pub selected_set_only: bool, - pub high_poly: bool, - pub cage: bool, - pub uv_seams: bool, - pub low_poly: bool, + pub high_poly_mesh: BakeOverlay, + pub matching_error: BakeOverlay, + pub cage_surface: BakeOverlay, + pub cage_wire: BakeOverlay, + pub missing_seams: BakeOverlay, + pub project_mesh: BakeOverlay, + /// Show the project mesh with [`Self::neutral`] instead of its painted material + pub neutral_shown: bool, + pub neutral: NeutralMaterial, } impl Default for BakeVisualizationToggles { fn default() -> Self { - Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true } + let parts = BakeVisualization::default(); + let shown = |overlay: BakeOverlay| BakeOverlay { shown: true, ..overlay }; + Self { + hide_baking_meshes: false, + selected_set_only: false, + high_poly_mesh: shown(parts.high_poly), + matching_error: shown(parts.matching_error), + cage_surface: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_surface) }, + cage_wire: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_wire) }, + missing_seams: shown(parts.missing_seams), + project_mesh: shown(parts.low_poly), + neutral_shown: true, + neutral: NeutralMaterial::default(), + } } } impl BakeVisualizationToggles { - /// What the renderer draws with these switches while texture set `selected_set` is selected - pub fn visualization(&self, selected_set: usize) -> Option { - self.on.then_some(BakeVisualization { - high_poly: self.high_poly, - cage: self.cage, - uv_seams: self.uv_seams, - low_poly: self.low_poly, + /// What the renderer draws with these settings while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> BakeVisualization { + let unless_hidden = |overlay: BakeOverlay| BakeOverlay { shown: overlay.shown && !self.hide_baking_meshes, ..overlay }; + BakeVisualization { + high_poly: unless_hidden(self.high_poly_mesh), + matching_error: self.matching_error, + cage_surface: unless_hidden(self.cage_surface), + cage_wire: unless_hidden(self.cage_wire), + missing_seams: self.missing_seams, + low_poly: self.project_mesh, + neutral: self.neutral_shown.then_some(self.neutral), only_set: self.selected_set_only.then_some(selected_set), - }) + } + } + + /// Whether the project mesh shows the neutral material lit along the bent normal, which the 3D view then reads in place of a mesh map + pub fn bent_normal_shown(&self) -> bool { + self.project_mesh.shown && self.neutral_shown && self.neutral.bent_normal + } + + /// Switch the panel's eye; hiding the baking meshes shows the project mesh, so the view never goes empty + pub fn toggle_hiding(&mut self) { + self.hide_baking_meshes = !self.hide_baking_meshes; + self.project_mesh.shown |= self.hide_baking_meshes; + } + + /// Put the High Definition Mesh section back to its defaults + pub fn reset_high_poly(&mut self) { + let defaults = Self::default(); + (self.high_poly_mesh, self.matching_error) = (defaults.high_poly_mesh, defaults.matching_error); + } + + /// Put the Cage section back to its defaults + pub fn reset_cage(&mut self) { + let defaults = Self::default(); + (self.cage_surface, self.cage_wire) = (defaults.cage_surface, defaults.cage_wire); + } + + /// Put the UV Seams section back to its defaults + pub fn reset_seams(&mut self) { + self.missing_seams = Self::default().missing_seams; + } + + /// Put the Project Mesh section back to its defaults + pub fn reset_project_mesh(&mut self) { + let defaults = Self::default(); + (self.project_mesh, self.neutral_shown, self.neutral) = (defaults.project_mesh, defaults.neutral_shown, defaults.neutral); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn panel_settings_saved_by_earlier_builds_start_over_from_the_defaults() { + let mut saved = serde_json::to_value(crate::state::UiState::default()).unwrap(); + let fields = saved.as_object_mut().unwrap(); + fields.remove("baking_visualization"); + fields.insert( + "bake_visualization".into(), + serde_json::json!({"hide_baking_meshes": false, "missing_seams": {"shown": false, "color": [1, 0, 0], "opacity": 1}}), + ); + let state: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(state.bake_visualization, BakeVisualizationToggles::default()); + } + + #[test] + fn the_settings_reach_the_renderer() { + let mut toggles = BakeVisualizationToggles::default(); + toggles.cage_wire.color = [0.1, 0.2, 0.3]; + toggles.neutral_shown = false; + let visualization = toggles.visualization(2); + assert_eq!(visualization.cage_wire, toggles.cage_wire); + assert_eq!(visualization.neutral, None); + assert_eq!(visualization.only_set, None); + toggles.selected_set_only = true; + assert_eq!(toggles.visualization(2).only_set, Some(2)); + } + + #[test] + fn the_eye_hides_the_baking_meshes_and_keeps_the_project_mesh() { + let mut toggles = BakeVisualizationToggles::default(); + let shown = toggles.visualization(0); + assert!(shown.high_poly.shown && shown.cage_surface.shown && shown.cage_wire.shown, "the eye starts off, as in the reference"); + + toggles.project_mesh.shown = false; + toggles.toggle_hiding(); + let hidden = toggles.visualization(0); + assert!(!hidden.high_poly.shown && !hidden.cage_surface.shown && !hidden.cage_wire.shown); + assert!(hidden.low_poly.shown, "hiding the baking meshes brings the project mesh back"); + + toggles.toggle_hiding(); + assert!(toggles.visualization(0).high_poly.shown, "the eye switches back"); } } diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index 02d712a0..1953d2d3 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -1,6 +1,7 @@ use super::controls::{choice, hint, integer, number, section, text_input}; use crate::TextureCraftApp; use crate::i18n::tr; +use crate::theme::Tokens; use crate::widgets::icon_button; use egui::Ui; use egui_phosphor::regular as icon; @@ -9,7 +10,16 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -/// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage) +/// How many rows the high poly list box is tall +const HIGH_POLY_LIST_ROWS: f32 = 5.0; + +/// Space between the panel's sections, in points +const SECTION_GAP: f32 = 8.0; + +/// Widest dilation the slider offers, in texels (the bake settings command accepts the same) +const MAX_DILATION_WIDTH: u32 = 128; + +/// The output and high-poly sections, then cage and skew, greyed with the reason when they can't apply pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { let mut reset = Map::new(); ui.push_id("common", |ui| { @@ -28,7 +38,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe (BakeAntialiasing::Subsampling8x8, tr("Subsampling 8x8")), ], ); - integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=128); + integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); }) { settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; @@ -40,12 +50,14 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }); - ui.add_space(8.0); + // Without a high poly the reference shows everything that needs one greyed, not hidden + let has_high = !app.session.bake_meshes.high.is_empty(); + ui.add_space(SECTION_GAP); ui.push_id("high_poly", |ui| { if section(ui, tr("High-Poly Parameters"), |ui| { ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); - high_poly_files(app, ui); - if !app.session.bake_meshes.high.is_empty() { + high_poly_scene(app, ui); + ui.add_enabled_ui(has_high, |ui| { ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); choice( ui, @@ -56,67 +68,89 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); - } + }); }) { settings.high_poly = Default::default(); reset.insert("high_poly".into(), json!(settings.high_poly)); } }); - if !app.session.bake_meshes.high.is_empty() { - ui.add_space(8.0); - ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), |ui| { + ui.add_space(SECTION_GAP); + ui.push_id("cage", |ui| { + if section(ui, tr("Cage"), |ui| { + // The cage steers rays toward a separate high poly, so it has nothing to do without one + let cage_applies = has_high && !settings.high_poly.use_low_as_high; + if !has_high { + hint(ui, tr("The cage applies once a high poly mesh is loaded.")); + } else if !cage_applies { + hint(ui, tr("The cage is not used while the low poly mesh is used as the high poly mesh.")); + } + ui.add_enabled_ui(cage_applies, |ui| { choice( ui, tr("Cage Type"), &mut settings.cage.kind, &[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))], ); - match settings.cage.kind { - CageType::DistanceBased => { - paint_brush(app, ui, BakePaintTarget::Cage); - number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); - number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); - ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); - ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); - } - CageType::CustomFile => cage_file(app, ui), - } - }) { - settings.cage = Default::default(); - reset.insert("cage".into(), json!(settings.cage)); - } - }); - - if settings.cage.kind == CageType::DistanceBased { - ui.add_space(8.0); - ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), |ui| { - choice( - ui, - tr("Skew Correction Method"), - &mut settings.skew.method, - &[ - (SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), - (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based")), - ], - ); - paint_brush(app, ui, BakePaintTarget::Skew); - ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); - number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); - number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); - }) { - settings.skew = Default::default(); - reset.insert("skew".into(), json!(settings.skew)); + if settings.cage.kind == CageType::DistanceBased { + paint_brush(app, ui, BakePaintTarget::Cage); + number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); + number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); + ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); + ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); } }); + if settings.cage.kind == CageType::CustomFile { + cage_file(app, ui, cage_applies); + } + }) { + settings.cage = Default::default(); + reset.insert("cage".into(), json!(settings.cage)); } - } + }); + + // Shown greyed when it can't apply, as the reference does, with the reason on top + let skew_applies = has_high && settings.skew_applies(); + ui.add_space(SECTION_GAP); + ui.push_id("skew", |ui| { + if section(ui, tr("Skew Correction"), |ui| { + if !skew_applies { + hint(ui, skew_unavailable_reason(settings, has_high)); + } + ui.add_enabled_ui(skew_applies, |ui| { + choice( + ui, + tr("Skew Correction Method"), + &mut settings.skew.method, + &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], + ); + paint_brush(app, ui, BakePaintTarget::Skew); + ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); + number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); + number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + }); + }) { + settings.skew = Default::default(); + reset.insert("skew".into(), json!(settings.skew)); + } + }); (!reset.is_empty()).then_some(Value::Object(reset)) } +/// Why Skew Correction can't apply: no high poly (`has_high` false), or `settings` rule it out (see [`BakeSettings::skew_applies`]) +fn skew_unavailable_reason(settings: &BakeSettings, has_high: bool) -> &'static str { + if !has_high { + tr("Skew Correction applies once a high poly mesh is loaded.") + } else if settings.high_poly.use_low_as_high { + tr("Skew Correction is not available while the low poly mesh is used as the high poly mesh.") + } else if settings.cage.kind == CageType::CustomFile { + tr("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself.") + } else { + tr("Skew Correction needs Average Normals turned on in the cage settings.") + } +} + fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { ui.label(tr("Output Size")); ui.horizontal(|ui| { @@ -144,42 +178,65 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { }); } -fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("High Poly Scene")); - let meshes: Vec<_> = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); - let mut remove = None; - for (index, name) in meshes.iter().enumerate() { - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - let label_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); - ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name); - if icon_button(ui, icon::TRASH, tr("Remove"), false, button_size).clicked() { - remove = Some(index); - } - }); - } +/// The high poly meshes as a list box, with + to add some and − to remove the selected one +fn high_poly_scene(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let names: Vec = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); + let selected_id = ui.make_persistent_id("high_poly_selected"); + let mut selected = ui.data(|data| data.get_temp::(selected_id)).filter(|index| *index < names.len()); - if meshes.is_empty() { - hint(ui, tr("No High-Poly Meshes")); - } - if let Some(index) = remove { + ui.label(tr("High Poly Scene")); + let (mut add, mut remove) = (false, false); + ui.horizontal_top(|ui| { + let button_size = ui.spacing().interact_size.y; + let list_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); + let list_height = HIGH_POLY_LIST_ROWS * ui.spacing().interact_size.y; + egui::Frame::NONE.fill(tokens.field).stroke(egui::Stroke::new(1.0, tokens.field_border)).corner_radius(tokens.cr()).show(ui, |ui| { + ui.set_min_size(egui::vec2(list_width, list_height)); + ui.set_max_width(list_width); + egui::ScrollArea::both().id_salt("high_poly_list").max_height(list_height).auto_shrink([false; 2]).show(ui, |ui| { + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(selected == Some(index), name).on_hover_text(name).clicked() { + selected = Some(index); + } + } + }); + }); + ui.vertical(|ui| { + add = icon_button(ui, icon::PLUS, tr("Add High-Poly Meshes"), false, button_size).clicked(); + remove = ui.add_enabled_ui(selected.is_some(), |ui| icon_button(ui, icon::MINUS, tr("Remove"), false, button_size)).inner.clicked(); + }); + }); + + if let (true, Some(index)) = (remove, selected) { app.run("bake.highPoly.remove", json!({ "index": index })); + selected = None; } - if ui.button(tr("Add High-Poly Meshes")).clicked() { + ui.data_mut(|data| { + if let Some(index) = selected { + data.insert_temp(selected_id, index); + } else { + data.remove_temp::(selected_id); + } + }); + if add { crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false); } } -fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("Cage Scene")); +/// The cage file row; while the cage can't `apply` only removing a loaded one stays available, so a saved cage can still be dropped +fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui, apply: bool) { + ui.add_enabled(apply, egui::Label::new(tr("Cage Scene"))); let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0); - ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { - crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); - } + ui.add_enabled_ui(apply, |ui| { + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { + crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); + } + }); if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() { app.run("bake.cage.clear", json!({})); } diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 9013be73..2ae7f095 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -1,10 +1,13 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands +mod bake_checks; mod bake_paint_brush; mod bake_visualization_panel; mod bake_visualization_toggles; mod breadcrumb; mod common_settings; +mod section_opening; +pub(crate) use bake_checks::bake_warnings; pub use bake_paint_brush::BakePaintBrush; pub(crate) use bake_visualization_panel::bake_visualization_panel; pub use bake_visualization_toggles::BakeVisualizationToggles; @@ -47,18 +50,23 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), format!("{resolution} × {resolution}"), resolution, None) - && selected != resolution - { - app.start_resize(set_index, selected); - } - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - if ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()).on_hover_text(&name).clicked() { - app.run("textureSet.select", json!({ "ts": set_index })); - } - }); + + // The name takes the room the resolution leaves, so it only shortens when the row is too narrow + let resolution_text = format!("{resolution}x{resolution}"); + let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0); + let name_size = egui::vec2(name_width, ui.spacing().interact_size.y); + let name_button = ui.allocate_ui_with_layout(name_size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(name_width); + ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()) }); + if name_button.inner.on_hover_text(&name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + } + if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), resolution_text, resolution, None) + && selected != resolution + { + app.start_resize(set_index, selected); + } }); if !tiles.is_empty() { @@ -71,7 +79,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { app.run("bake.tile.set", json!({"ts": set_index, "tile": tile, "enabled": enabled})); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let text = override_resolution.map(|value| format!("{value} × {value}*")).unwrap_or_default(); + let text = override_resolution.map(|value| format!("{value}x{value}*")).unwrap_or_default(); let label = trf("UV tile {tile} resolution", &[("tile", &tile.to_string())]); if let Some(selected) = resolution_menu( ui, @@ -93,12 +101,17 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { }); } +/// How wide [`resolution_menu`] draws `text`, with a button's padding on both sides +fn resolution_menu_width(ui: &Ui, text: &str) -> f32 { + let font = egui::TextStyle::Button.resolve(ui.style()); + ui.painter().layout_no_wrap(text.to_owned(), font, ui.visuals().text_color()).size().x + ui.spacing().button_padding.x * 2.0 +} + fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option) -> Option { - let effective_size = format!("{resolution} × {resolution}"); + let effective_size = format!("{resolution}x{resolution}"); let measured = if text.is_empty() { &effective_size } else { &text }; let font = egui::TextStyle::Button.resolve(ui.style()); - let text_width = ui.painter().layout_no_wrap(measured.clone(), font.clone(), ui.visuals().text_color()).size().x; - let width = text_width + ui.spacing().button_padding.x * 2.0; + let width = resolution_menu_width(ui, measured); let response = ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new("").frame(false)); let popup_id = response.id.with("resolution_menu"); let open = egui::Popup::is_id_open(ui.ctx(), popup_id) || response.clicked(); @@ -115,7 +128,7 @@ fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inhe ui.separator(); } for candidate in [128, 256, 512, 1024, 2048, 4096, 8192] { - if ui.selectable_label(candidate == resolution, format!("{candidate} × {candidate}")).clicked() { + if ui.selectable_label(candidate == resolution, format!("{candidate}x{candidate}")).clicked() { selected = Some(candidate); } } @@ -228,10 +241,27 @@ fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// How many maps baking `texture_sets` makes, counted as the reference's Bake button counts them: checked maps × included UV tiles, per set +fn maps_to_bake(app: &TextureCraftApp, texture_sets: &[usize]) -> usize { + texture_sets + .iter() + .filter_map(|index| app.session.doc.project.texture_sets.get(*index)) + .map(|set| { + let tiles = if set.uv_tiles.is_empty() { 1 } else { set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).count() }; + set.bake.maps.enabled().count() * tiles + }) + .sum() +} + +/// The bake bar's gap from the bottom of the 3D view, in points (the pre-bake warnings sit above it) +pub(super) const BAKE_BAR_MARGIN: f32 = 16.0; + pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { - egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( - ctx, - |ui| { + egui::Area::new(egui::Id::unique("bake_bar")) + .constrain_to(viewport) + .anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -BAKE_BAR_MARGIN)) + .default_width(0.0) + .show(ctx, |ui| { if let Some(status) = app.bake_status() { ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong())); } @@ -253,8 +283,9 @@ pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: .filter(|(_, texture_set)| texture_set.bake.common.is_enabled && texture_set.has_enabled_bake_tiles()) .map(|(index, _)| index) .collect(); - let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); - if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { + let maps = maps_to_bake(app, &texture_sets); + let label = trf("Bake ({n})", &[("n", &maps)]); + if ui.add_enabled(maps > 0, primary_button(ui, &label)).clicked() { app.start_bake(texture_sets); } } @@ -263,6 +294,5 @@ pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: app.ui.mode = Mode::Painting; } }); - }, - ); + }); } diff --git a/crates/ui-egui/src/bake_mode/section_opening.rs b/crates/ui-egui/src/bake_mode/section_opening.rs new file mode 100644 index 00000000..8428a7f7 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/section_opening.rs @@ -0,0 +1,6 @@ +/// Whether a Baking Visualization section starts open, as the reference shows the panel at first launch (HP and Cage open, UV seams and Project mesh closed) +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SectionOpening { + Open, + Closed, +} diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs index b9cecaa9..766a43c2 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -11,7 +11,7 @@ use super::reach_link::ReachLink; use super::shared_handle::SharedHandle; use crate::gpu::SceneSync; -/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams +/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the missing seams #[derive(Default)] pub struct BakeSceneLink { /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) @@ -51,7 +51,7 @@ impl BakeSceneLink { let Some(visualization) = visualization else { return }; - if visualization.high_poly { + if visualization.high_poly.shown { let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); let handle = SharedHandle::of(high.as_ref()); if handle != self.high { @@ -64,14 +64,19 @@ impl BakeSceneLink { self.high_sent = true; } self.reach.sync(session, self.high_id, visualization.only_set, out); + } else if self.high_sent { + // Drop the hidden GPU mesh but keep its id so its reach can be reused + out.bake_high = Some((None, self.high_id)); + self.high_sent = false; + self.reach.resend(); } - if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) { + if visualization.missing_seams.shown && self.seams_mesh_id != Some(session.mesh_id) { self.seams_mesh_id = Some(session.mesh_id); - out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges())); + out.missing_seams = Some((session.mesh_id, session.mesh.missing_seam_edges())); } - if visualization.cage { + if visualization.cage_shown() { self.sync_cages(session, out); } } @@ -85,6 +90,7 @@ impl BakeSceneLink { } self.cages.truncate(set_count); self.cages.resize_with(set_count, || None); + let mut shared_edges = None; for (texture_set, link) in self.cages.iter_mut().enumerate() { let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue }; @@ -95,11 +101,26 @@ impl BakeSceneLink { if link.max_frontal == max_frontal { continue; } + link.max_frontal = max_frontal; } _ => { self.next_topology += 1; - let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new); + let shell = session + .bake_cage_inputs(texture_set) + .ok() + .flatten() + .and_then(|inputs| { + let result = if inputs.uses_mesh(&session.mesh) { + let (wire_edges, missing_seam_edges) = + shared_edges.get_or_insert_with(|| (session.mesh.wire_edges(), session.mesh.missing_seam_edges())); + inputs.cage_shell_with_edges(wire_edges, missing_seam_edges) + } else { + inputs.cage_shell() + }; + result.ok() + }) + .map(Arc::new); *link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal }); } } @@ -117,7 +138,20 @@ mod tests { use super::*; use serde_json::json; - const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + /// Every part of the visualization shown + fn everything() -> BakeVisualization { + let parts = BakeVisualization::default(); + let shown = |overlay: texturecraft_render::BakeOverlay| texturecraft_render::BakeOverlay { shown: true, ..overlay }; + BakeVisualization { + high_poly: shown(parts.high_poly), + matching_error: shown(parts.matching_error), + cage_surface: shown(parts.cage_surface), + cage_wire: shown(parts.cage_wire), + missing_seams: shown(parts.missing_seams), + low_poly: shown(parts.low_poly), + ..parts + } + } /// How long a test waits for the reach worker: frames, and the pause between them const WAIT_FRAMES: usize = 2000; @@ -165,41 +199,62 @@ mod tests { #[test] fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() { let (mut session, mut link) = (session(), BakeSceneLink::default()); - let first = sync(&mut link, &session, EVERYTHING); - assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); + let first = sync(&mut link, &session, everything()); + assert!(first.bake_high.is_some() && first.missing_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; - let unchanged = sync(&mut link, &session, EVERYTHING); - assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent"); + let unchanged = sync(&mut link, &session, everything()); + assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.missing_seams.is_none(), "nothing changed, nothing is sent"); set_distances(&mut session, 0.03); - let moved = sync(&mut link, &session, EVERYTHING); + let moved = sync(&mut link, &session, everything()); let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; assert_eq!(moved_topology, topology, "a distance only moves the corners"); assert_ne!(moved_cage.corners, cage.corners); texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); - let rebuilt = sync(&mut link, &session, EVERYTHING); + let rebuilt = sync(&mut link, &session, everything()); assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts - red_share(&mut link, &session, EVERYTHING); + red_share(&mut link, &session, everything()); link.resend(); - let resent = sync(&mut link, &session, EVERYTHING); - assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); + let resent = sync(&mut link, &session, everything()); + assert!(resent.bake_high.is_some() && resent.missing_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len()); assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame"); assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id"); assert!(!link.busy(), "a lost frame doesn't work out the reach again"); } + #[test] + fn a_hidden_high_poly_leaves_the_gpu_and_comes_back_without_a_new_reach() { + let (session, mut link) = (session(), BakeSceneLink::default()); + let sent = |out: SceneSync| out.bake_high.map(|(high, id)| (high.is_some(), id)); + let hidden = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() }; + let first = sent(sync(&mut link, &session, everything())); + red_share(&mut link, &session, everything()); + let dropped = sent(sync(&mut link, &session, hidden)); + assert!(sync(&mut link, &session, hidden).bake_high.is_none(), "dropped once"); + let back = sync(&mut link, &session, everything()); + assert!(!link.busy(), "showing it again starts no new reach"); + assert!(back.bake_high_missed.is_some(), "its colours are sent again with it"); + + let (Some((true, first_id)), Some((false, dropped_id)), Some((true, back_id))) = (first, dropped, sent(back)) else { + panic!("the high poly is sent, dropped, then sent again") + }; + + assert_eq!((dropped_id, back_id), (first_id, first_id)); + } + #[test] fn a_reach_finishes_while_nothing_is_drawn() { let session = session(); - let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING }; + let no_high_poly = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() }; for hidden in [None, Some(no_high_poly)] { let mut link = BakeSceneLink::default(); - sync(&mut link, &session, EVERYTHING); + sync(&mut link, &session, everything()); assert!(link.busy(), "the first frame starts working out the reach"); let finished = (0..WAIT_FRAMES).any(|_| { @@ -215,11 +270,11 @@ mod tests { fn the_red_follows_the_distances_and_the_selected_set() { let (mut session, mut link) = (session(), BakeSceneLink::default()); set_distances(&mut session, 0.0); - let at_zero = red_share(&mut link, &session, EVERYTHING); + let at_zero = red_share(&mut link, &session, everything()); assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}"); set_distances(&mut session, 0.05); - let covered = red_share(&mut link, &session, EVERYTHING); + let covered = red_share(&mut link, &session, everything()); assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}"); set_distances(&mut session, 0.0); @@ -230,10 +285,11 @@ mod tests { } }; by_name(&mut session, "_no_such_suffix"); - let by_name_red = red_share(&mut link, &session, EVERYTHING); + let by_name_red = red_share(&mut link, &session, everything()); assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}"); - let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING }; - assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing"); + let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..everything() }; + let hidden = texturecraft_engine::bake::HIDDEN_HIGH_POLY_VERTEX; + assert_eq!(red_share(&mut link, &session, no_set), hidden, "a filter that keeps no set hides the whole high poly"); } } diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs index c8a181f5..f94ed3d5 100644 --- a/crates/ui-egui/src/bake_scene/reach_link.rs +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -64,7 +64,11 @@ impl ReachLink { .enumerate() .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) .collect(); + if keys != self.keys || high_id != self.high_id { + // The GPU keeps displayed colors; stale CPU arrays need not overlap the rebuild + self.reach.clear(); + let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect(); self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || { inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect() @@ -99,8 +103,31 @@ mod tests { use texturecraft_engine::core::BakePaintTarget; use texturecraft_engine::geom::primitives; + #[test] + fn rebuilding_reach_releases_previous_vertex_arrays_before_starting_work() { + const PREVIOUS_SET_COUNT: usize = 2; + const PREVIOUS_VERTEX_COUNT: usize = 64; + + let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap(); + session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap(); + let mut link = ReachLink { + reach: (0..PREVIOUS_SET_COUNT).map(|_| Some(HighPolyReach { vertices: vec![None; PREVIOUS_VERTEX_COUNT], ..Default::default() })).collect(), + ..Default::default() + }; + let mut out = SceneSync::default(); + + link.sync(&session, 1, None, &mut out); + + let retained_slots: usize = link.reach.iter().flatten().map(|reach| reach.vertices.capacity()).sum(); + assert_eq!(retained_slots, 0, "obsolete CPU arrays must not overlap their replacements"); + assert!(out.bake_high_missed.is_none(), "the GPU keeps its displayed colors until the replacement arrives"); + } + #[test] fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() { + const WAIT_FRAMES: usize = 2000; + const WAIT_FRAME_PAUSE: Duration = Duration::from_millis(5); + let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap(); session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap(); let (sender, receiver) = mpsc::channel(); @@ -113,6 +140,7 @@ mod tests { link.sync(&session, 2, None, &mut out); assert!(out.bake_high_missed.is_none()); } + assert!(sender.send(Vec::new()).is_ok(), "input changes must keep the running job's receiver"); link.poll(); @@ -123,13 +151,15 @@ mod tests { assert!(link.busy()); assert!(out.bake_high_missed.is_none()); - for _ in 0..2000 { + for _ in 0..WAIT_FRAMES { link.poll(); if !link.busy() { break; } - std::thread::sleep(Duration::from_millis(5)); + + std::thread::sleep(WAIT_FRAME_PAUSE); } + assert!(!link.busy(), "the latest reach must finish"); link.sync(&session, 2, None, &mut out); let (high_id, missed) = out.bake_high_missed.unwrap(); diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs new file mode 100644 index 00000000..f8d76d78 --- /dev/null +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -0,0 +1,138 @@ +//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab + +use egui::Ui; +use serde_json::json; +use std::path::Path; +use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// The preset name field's width in points +const NAME_WIDTH: f32 = 110.0; + +/// A name field and a button that saves the current brush under that name +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { + let dir = crate::user_dir("brushes"); + let name_id = ui.make_persistent_id("brush_preset_name"); + let confirm_id = ui.make_persistent_id("brush_preset_overwrite"); + let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); + let mut pending_path: Option = ui.data_mut(|data| data.get_temp(confirm_id)); + + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH)); + + if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { + let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim()))); + match std::fs::symlink_metadata(&path) { + Ok(_) => pending_path = Some(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + } + Err(_) => pending_path = Some(path), + } + } + }); + + if let Some(path) = pending_path.clone() { + let mut replace = false; + let mut cancel = false; + egui::Window::new(tr("Replace")) + .id(ui.make_persistent_id("brush_preset_replace_dialog")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ui.ctx(), |ui| { + ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default()); + ui.horizontal(|ui| { + replace = ui.button(tr("Replace")).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + if replace { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + pending_path = None; + } else if cancel { + pending_path = None; + } + } + + ui.data_mut(|data| { + data.insert_temp(name_id, new_name); + data.insert_temp(confirm_id, pending_path); + }); +} + +/// Preserve Unicode names and encode filename punctuation without collisions +fn preset_file_stem(name: &str) -> String { + let mut stem = String::new(); + + // Six digits cover every Unicode scalar and separate adjacent escapes + for character in name.chars() { + if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' { + stem.push(character); + } else { + stem.push_str(&format!("~{:06X}", character as u32)); + } + } + let uppercase = stem.to_ascii_uppercase(); + if matches!( + uppercase.as_str(), + "CON" + | "PRN" + | "AUX" + | "NUL" + | "COM1" + | "COM2" + | "COM3" + | "COM4" + | "COM5" + | "COM6" + | "COM7" + | "COM8" + | "COM9" + | "LPT1" + | "LPT2" + | "LPT3" + | "LPT4" + | "LPT5" + | "LPT6" + | "LPT7" + | "LPT8" + | "LPT9" + ) { + stem.insert_str(0, "brush-"); + } + stem +} + +/// Save a preset and invalidate cached tiles only when the write succeeds +fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool { + // A folder that cannot be made is reported by the save command + let _ = std::fs::create_dir_all(dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() { + return false; + } + + app.brushes = None; + app.thumbs.forget_saved_files(); + true +} + +#[cfg(test)] +mod tests { + use super::preset_file_stem; + + #[test] + fn distinct_unicode_brush_names_have_distinct_safe_file_stems() { + assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画")); + assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb")); + assert_eq!(preset_file_stem("水彩"), "水彩"); + assert!(!preset_file_stem("a/b").contains('/')); + assert_eq!(preset_file_stem("CON"), "brush-CON"); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1d266ee1..2d0bbdd4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,8 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, - LinkParam, MaterialLink, ProceduralKind, Projection, Source, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, + Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; @@ -141,9 +141,10 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - // Wraps in a narrow column instead of widening the rows below past the panel. + + // Wrap in a narrow column so rows stay within the panel ui.horizontal_wrapped(|ui| { - // The menu buttons as compact as the icon buttons beside them. + // Keep menu buttons as compact as the adjacent icon buttons ui.spacing_mut().button_padding.x = 4.0; ui.spacing_mut().item_spacing.x = 4.0; let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); @@ -185,7 +186,8 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { for id in stack { layer_tree(app, ui, id, 0, &mut count); } - // Click on empty space deselects nothing; the space below the rows drops at the bottom. + + // Empty space keeps the selection and drops below the rows let free = ui.available_height(); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if free.is_finite() { free.max(24.0) } else { 24.0 }), Sense::hover()); if let Some(dragged) = dnd_release::(&resp) { @@ -262,21 +264,107 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } /// Layer rows alternate between two shades so neighbours read as separate items. -fn row_shade(tk: &Tokens, index: usize) -> Color32 { - if index.is_multiple_of(2) { tk.row } else { tk.row.lerp_to_gamma(tk.row_hover, 0.45) } +fn row_shade(tokens: &Tokens, index: usize) -> Color32 { + if index.is_multiple_of(2) { tokens.row } else { tokens.row.lerp_to_gamma(tokens.row_hover, ALTERNATE_LAYER_SHADE) } } /// Width of the blend mode / opacity column at the right of a layer row. const RIGHT_COLUMN: f32 = 58.0; /// Indent per folder level, and per level of the effect tree. const INDENT: f32 = 14.0; +/// Edge of the small icon buttons in the properties panel. +const ICON_BUTTON_SIZE: f32 = 22.0; +/// Height of a blend mode menu or opacity field in a stack row, and the rounding of its hover fill. +const ROW_CONTROL_HEIGHT: f32 = 17.0; +const ROW_CONTROL_ROUNDING: f32 = 2.0; +/// Gap between the controls at the right of a stack row, and between them and the row's edge. +const ROW_CONTROL_GAP: f32 = 4.0; +/// Space before an effect row's eye and after its name. +const ROW_LEFT_PADDING: f32 = 7.0; +const ROW_RIGHT_PADDING: f32 = 6.0; +/// Width of the selected row's accent edge. +const SELECTED_EDGE_WIDTH: f32 = 3.0; +/// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. +const THUMBNAIL_ROUNDING: f32 = 2.0; +const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; +const HIDDEN_STRIKE_WIDTH: f32 = 1.5; +const DROP_LINE_WIDTH: f32 = 2.0; +/// The eye's size and the column it sits in (the eye and a gap before the thumbnail). +const EYE_SIZE: f32 = 16.0; +const EYE_COLUMN_WIDTH: f32 = 22.0; +/// Gap between an effect's thumbnail and its name, and the narrowest name worth showing. +const THUMBNAIL_GAP: f32 = 8.0; +const MIN_NAME_WIDTH: f32 = 20.0; +/// Font sizes in an effect row: the eye, the name, the blend mode and its caret. +const EYE_FONT_SIZE: f32 = 12.0; +const EFFECT_NAME_FONT_SIZE: f32 = 11.5; +const ROW_SMALL_FONT_SIZE: f32 = 11.0; +const CARET_FONT_SIZE: f32 = 8.0; +/// Room for the caret at the right of the blend mode's name. +const CARET_WIDTH: f32 = 10.0; +/// The blend mode menu's width, wide enough for the longest mode name. +const BLEND_MENU_MIN_WIDTH: f32 = 190.0; +/// Padding inside a row's opacity field, and the percent it moves per point dragged. +const ROW_FIELD_PADDING: f32 = 4.0; +const OPACITY_DRAG_SPEED: f64 = 0.5; +/// A layer row's eye: its hit area, its glyph size and the column it sits in. +const LAYER_EYE_SIZE: f32 = 18.0; +const LAYER_EYE_FONT_SIZE: f32 = 13.0; +const LAYER_EYE_COLUMN_WIDTH: f32 = 20.0; +/// A folder's caret: its size (the space it takes before the thumbnail) and its center from where it starts. +const FOLDER_CARET_SIZE: f32 = 14.0; +const FOLDER_CARET_CENTER: f32 = 6.0; +/// A thumbnail's border while it is the layer's target, and how far outside it the mask-view and drop outlines sit. +const TARGET_BORDER_WIDTH: f32 = 1.5; +const HIGHLIGHT_OUTSET: f32 = 2.0; +/// The gap between a layer row's stacked blend mode and opacity, either side of the row's middle. +const ROW_STACK_GAP: f32 = 1.0; +/// Width of a layer's colour tag beside the accent edge. +const TAG_WIDTH: f32 = 3.0; +/// Space between a layer's content and mask thumbnails, and the size of the empty mask slot. +const THUMBNAIL_SPACING: f32 = 4.0; +const MASK_SLOT_SIZE: f32 = 18.0; +/// Grays of a white or black mask before its thumbnail arrives. +const WHITE_MASK_GRAY: u8 = 225; +const BLACK_MASK_GRAY: u8 = 18; +/// A layer's name and subtitle font sizes, and their distance from the row's middle. +const LAYER_NAME_FONT_SIZE: f32 = 12.5; +const LAYER_SUBTITLE_FONT_SIZE: f32 = 10.0; +const NAME_LINE_GAP: f32 = 2.0; +/// Folder lines: their width, how faded they are, how far an indent must reach past one, and where the branch starts. +const FOLDER_LINE_WIDTH: f32 = 1.0; +const FOLDER_LINE_FADE: f32 = 0.6; +const FOLDER_LINE_CLEARANCE: f32 = 8.0; +const FOLDER_BRANCH_OFFSET: f32 = 15.0; +/// The share of a folder row's height, either side of its middle, where a drop goes inside it. +const FOLDER_DROP_ZONE: f32 = 0.25; +/// How far each alternating effect row shade goes from the panel towards the hover colour. +const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; +/// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. +const EFFECT_BLEND_WIDTH: f32 = 82.0; +const EFFECT_OPACITY_WIDTH: f32 = 36.0; /// Height of the "Content effects" / "Mask effects" header rows. const GROUP_HEADER_H: f32 = 20.0; +// Group header spacing leaves room for the label and effect count +const GROUP_HEADER_CARET_OFFSET: f32 = 15.0; +const GROUP_HEADER_LABEL_GAP: f32 = 10.0; +const GROUP_HEADER_LABEL_RESERVE: f32 = 28.0; +const GROUP_HEADER_COUNT_PADDING: f32 = 8.0; +const GROUP_HEADER_LABEL_FONT_SIZE: f32 = 10.5; +/// Hover tint of alternating layer rows +const ALTERNATE_LAYER_SHADE: f32 = 0.45; +/// Maximum layer-tree nesting shown by the dock +const MAX_LAYER_TREE_DEPTH: usize = 12; +/// Checkerboard cells along each thumbnail edge +const THUMB_CHECKER_CELLS: usize = 4; +/// Keep the group label and count readable when the panel is narrow +const GROUP_HEADER_MIN_REMAINING_WIDTH: f32 = 90.0; + /// Keep both thumbnail targets inside the row before spending space on indentation fn layer_thumbnail_layout(width: f32, depth: usize, folder: bool, preferred_size: f32) -> (f32, f32) { - let controls = 7.0 + 20.0 + if folder { 14.0 } else { 0.0 }; - let thumbnail_space = (width - controls - 4.0 - 4.0).max(0.0); + let controls = ROW_LEFT_PADDING + LAYER_EYE_COLUMN_WIDTH + if folder { FOLDER_CARET_SIZE } else { 0.0 }; + let thumbnail_space = (width - controls - THUMBNAIL_SPACING - ROW_CONTROL_GAP).max(0.0); let size = preferred_size.min(thumbnail_space * 0.5); let indent = (depth as f32 * INDENT).min((thumbnail_space - size * 2.0).max(0.0)); (indent, size) @@ -284,359 +372,357 @@ fn layer_thumbnail_layout(width: f32, depth: usize, folder: bool, preferred_size /// Drop secondary controls before allowing them to cover thumbnail targets or the name fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { - let right = rect.right() - 4.0; - let show_blend = right - RIGHT_COLUMN - 4.0 - left >= 20.0; - let name_right = if show_blend { right - RIGHT_COLUMN - 4.0 } else { right }; + let right = rect.right() - ROW_CONTROL_GAP; + let show_blend = right - RIGHT_COLUMN - ROW_CONTROL_GAP - left >= MIN_NAME_WIDTH; + let name_right = if show_blend { right - RIGHT_COLUMN - ROW_CONTROL_GAP } else { right }; (Rect::from_min_max(pos2(left, rect.top() + 4.0), pos2(name_right.max(left), rect.bottom() - 4.0)), show_blend) } /// Preserve the effect eye, preview and a readable name before spending space on nesting. fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { - (level as f32 * INDENT).min((width - 7.0 - 22.0 - preview - 8.0 - 20.0 - 6.0).max(0.0)) + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) } /// X of the centre of the eye column at indent `level` in a row spanning from `left`. fn level_x(left: f32, level: usize) -> f32 { - left + 7.0 + level as f32 * INDENT + 8.0 + left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5 } fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) { let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; + let index = *count; *count += 1; layer_row(app, ui, &layer, depth, index); - let mask_effects = layer.mask.as_ref().map_or(0, |m| m.effects.len()); + 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); } - // A line under the layer and its effects separates it from the next layer. - let tk = Tokens::get(ui.ctx()); - let r = ui.available_rect_before_wrap(); - ui.painter().hline(r.x_range(), r.top() - 0.5, Stroke::new(1.0, tk.separator)); + + // A line under the layer and its effects separates it from the next layer + let tokens = Tokens::get(ui.ctx()); + let available = ui.available_rect_before_wrap(); + ui.painter().hline(available.x_range(), available.top() - 0.5, Stroke::new(1.0, tokens.separator)); if let LayerKind::Group { children, collapsed } = &layer.kind && !collapsed - && depth < 12 + && depth < MAX_LAYER_TREE_DEPTH { - for c in children.iter().rev() { - layer_tree(app, ui, *c, depth + 1, count); + for child in children.iter().rev() { + layer_tree(app, ui, *child, depth + 1, count); } } } /// The picture for `target` inside `rect` (drawn over the well), whether there is one yet. fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool) -> bool { - let tk = Tokens::get(ui.ctx()); - let p = ui.painter(); - p.rect_filled(rect, 2.0, tk.field); - // A checkerboard shows through where the layer has nothing (transparent texels). - let cells = 4; - let cell = rect.width() / cells as f32; - let check = tk.field.lerp_to_gamma(tk.row_hover, 0.6); - for y in 0..cells { - for x in (0..cells).filter(|x| (x + y) % 2 == 0) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(x as f32 * cell, y as f32 * cell), vec2(cell, cell)), 0.0, check); + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter(); + painter.rect_filled(rect, THUMBNAIL_ROUNDING, tokens.field); + + // A checkerboard shows through where the layer has nothing (transparent texels) + let cell_size = rect.width() / THUMB_CHECKER_CELLS as f32; + let check = tokens.field.lerp_to_gamma(tokens.row_hover, 0.6); + for y in 0..THUMB_CHECKER_CELLS { + for x in (0..THUMB_CHECKER_CELLS).filter(|x| (x + y) % 2 == 0) { + painter.rect_filled(Rect::from_min_size(rect.min + vec2(x as f32 * cell_size, y as f32 * cell_size), vec2(cell_size, cell_size)), 0.0, check); } } - // Only rows on screen ask for a picture. + + // Only rows on screen ask for a picture if ui.is_rect_visible(rect) - && let Some(tex) = app.layer_panel.texture(ui.ctx(), &app.session, target) + && 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 }; - ui.painter().image(tex, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); + painter.image(texture, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); return true; } + false } +/// The row of `layer` at folder depth `depth`, the `index`th row of the stack (rows alternate shades). fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); let content_target = selected && targets_content(app); - let size = layer_preview_size(app); - let h = layer_row_height(size); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); - let p = ui.painter().clone(); - let bg = if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover + let preferred_size = layer_preview_size(app); + let row_height = layer_row_height(preferred_size); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); + + // Background, folder lines, the selected row's accent edge and the colour tag + let painter = ui.painter().clone(); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover } else { - row_shade(&tk, index) + row_shade(&tokens, index) }; - p.rect_filled(rect, 0.0, bg); - let (indent, size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), size); + painter.rect_filled(rect, 0.0, background); + let (indent, thumbnail_size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), preferred_size); // Folder contents hang off lines down the left without crossing compact row controls - let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6)); + let line = Stroke::new(FOLDER_LINE_WIDTH, tokens.button_border.gamma_multiply(FOLDER_LINE_FADE)); for level in 0..depth { - let x = level_x(rect.left(), level); - if level as f32 * INDENT + 8.0 < indent { - p.vline(x, rect.y_range(), line); + if level as f32 * INDENT + FOLDER_LINE_CLEARANCE < indent { + painter.vline(level_x(rect.left(), level), rect.y_range(), line); } } if depth > 0 && indent >= INDENT { - let x = rect.left() + 15.0 + indent - INDENT; - p.hline(x..=x + INDENT * 0.5, rect.center().y, line); + let x = rect.left() + FOLDER_BRANCH_OFFSET + indent - INDENT; + painter.hline(x..=x + INDENT * 0.5, rect.center().y, line); } if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, row_height)), 0.0, tokens.accent); } - if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag); + if let Some(tag) = layer.color_tag.and_then(|tag| TAG_COLORS.get(tag as usize)) { + painter.rect_filled(Rect::from_min_size(rect.min + vec2(SELECTED_EDGE_WIDTH, 0.0), vec2(TAG_WIDTH, row_height)), 0.0, *tag); } - let x0 = rect.left() + 7.0 + indent; - // Eye. - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); - let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); - p.text( + + // The eye + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(LAYER_EYE_SIZE, LAYER_EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); + painter.text( eye.center(), egui::Align2::CENTER_CENTER, if layer.visible { ic::EYE } else { ic::EYE_SLASH }, - egui::FontId::proportional(13.0), - if layer.visible { tk.text } else { tk.text_dim }, + egui::FontId::proportional(LAYER_EYE_FONT_SIZE), + if layer.visible { tokens.text } else { tokens.text_dim }, ); - if eye_resp.clicked() { + if eye_response.clicked() { app.run("layer.visible", json!({"layer": layer.id.0})); } - // Group caret. - let mut x = x0 + 20.0; + + // A folder's caret + let mut x = content_left + LAYER_EYE_COLUMN_WIDTH; if let LayerKind::Group { collapsed, .. } = layer.kind { - let caret = Rect::from_center_size(pos2(x + 6.0, rect.center().y), vec2(14.0, 14.0)); - let cr = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); - p.text( + let caret = Rect::from_center_size(pos2(x + FOLDER_CARET_CENTER, rect.center().y), vec2(FOLDER_CARET_SIZE, FOLDER_CARET_SIZE)); + let caret_response = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); + painter.text( caret.center(), egui::Align2::CENTER_CENTER, if collapsed { ic::CARET_RIGHT } else { ic::CARET_DOWN }, - egui::FontId::proportional(11.0), - tk.text_dim, + egui::FontId::proportional(ROW_SMALL_FONT_SIZE), + tokens.text_dim, ); - if cr.clicked() - && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|l| &mut l.kind) + if caret_response.clicked() + && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|edited| &mut edited.kind) { *collapsed = !*collapsed; } - x += 14.0; + + x += FOLDER_CARET_SIZE; } - // Content thumbnail: the layer's own result in the displayed channel. - let ch = app.ui.layer_channel; - let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible); - if !drawn { - content_glyph(&p, &tk, thumb, layer); + + // 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); } - p.rect_stroke( - thumb, - 2.0, - Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); - if content_resp.clicked() { + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); + let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); } - x = thumb.right() + 4.0; - // An instance draws its source's content, blending and (unless it has its own) mask. + x = thumbnail.right() + THUMBNAIL_SPACING; + + // An instance draws its source's content, blending and (unless it has its own) mask let project = &app.session.doc.project; - let source = layer.instance_source().map(|src| { - let set = project.locate(src).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(|t| t.name.as_str()).unwrap_or("?"); - project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) + let source = layer.instance_source().map(|source| { + let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); + project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name)) }); - let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch)); - // Mask thumbnail, selectable on its own; or the slot that adds one. + let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); + let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); + + // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; - if let Some(m) = &mask { - let mask_sel = selected && !targets_content(app); - mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled); - if !drawn { - p.rect_filled( - mask_rect, - 2.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim); + if let Some(mask) = &mask { + let mask_target = selected && !targets_content(app); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask.enabled) { + let white = mask.background == texturecraft_engine::core::MaskBackground::White; + painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); + if !mask.effects.is_empty() { + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(LAYER_EYE_FONT_SIZE), tokens.text_dim); } } - p.rect_stroke( - mask_rect, - 2.0, - Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - if !m.enabled { - p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); + if !mask.enabled { + painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } - let mr = ui + let mask_response = ui .interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()) .on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)")); - if mr.clicked() { + if mask_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); - if ui.input(|i| i.modifiers.alt) { + if ui.input(|input| input.modifiers.alt) { let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); - let p = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; - app.run("viewport.view", p); + let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; + app.run("viewport.view", view); } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); + painter.rect_stroke( + mask_rect.expand(HIGHLIGHT_OUTSET), + THUMBNAIL_ROUNDING, + Stroke::new(TARGET_BORDER_WIDTH, tokens.warning), + egui::StrokeKind::Outside, + ); } - x = mask_rect.right() + 8.0; } else { - // The empty slot adds a mask to this layer. - let slot_size = size.min(18.0); + // The empty slot adds a mask to this layer + let slot_size = thumbnail_size.min(MASK_SLOT_SIZE); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + let slot_color = if slot.hovered() { tokens.accent } else { tokens.field_border }; + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, slot_color), egui::StrokeKind::Inside); if slot.hovered() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text); } egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); - x = mask_rect.right() + 8.0; } - // Blend mode and opacity of the displayed channel, stacked at the right. - let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0)); - // Name (or rename editor) with the quieter subtitle under it. + x = mask_rect.right() + THUMBNAIL_GAP; + + // Name (or rename editor) with the quieter subtitle under it let (name_rect, show_blend) = layer_name_layout(rect, x); - let show_name = name_rect.width() >= 20.0; + let show_name = name_rect.width() >= MIN_NAME_WIDTH; if !show_name { - resp.clone().on_hover_text(&layer.name); + row.clone().on_hover_text(&layer.name); if app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0) { app.ui.rename = None; } } - let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); + let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0); if renaming { - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); - if let Some((_, buf)) = app.ui.rename.as_mut() { - // Escape reaches us instead of just unfocusing the field, so it can cancel. + let mut editor_ui = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + if let Some((_, text)) = app.ui.rename.as_mut() { + // Escape reaches us instead of just unfocusing the field, so it can cancel let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; - let r = child.add(egui::TextEdit::singleline(buf).desired_width(name_rect.width()).event_filter(filter)); - if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + let editor = editor_ui.add(egui::TextEdit::singleline(text).desired_width(name_rect.width()).event_filter(filter)); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; - } else if r.lost_focus() { - // Enter or a click elsewhere. - let name = buf.trim().to_string(); + } else if editor.lost_focus() { + // Enter or a click elsewhere + let name = text.trim().to_string(); app.ui.rename = None; if !name.is_empty() && name != layer.name { app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); } - } else if !r.has_focus() { - // Only until the field has focus: requesting it every frame kept it from ever - // losing focus, which trapped the editor open and blocked every shortcut. - r.request_focus(); + } else if !editor.has_focus() { + // Only until the field has focus: asking every frame trapped the editor open and blocked every shortcut + editor.request_focus(); } } } else if show_name { - let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text); + let name_color = if layer.visible { tokens.text_strong } else { tokens.text_dim }; + let galley = elided(&painter, layer.name.clone(), LAYER_NAME_FONT_SIZE, name_color, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y - NAME_LINE_GAP - galley.size().y), galley, tokens.text); let kind = tr(match &layer.kind { LayerKind::Paint => "Paint layer", LayerKind::Fill(_) => "Fill layer", LayerKind::Group { .. } => "Folder", LayerKind::Instance { .. } => "Instance", }); - let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len()); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |mask| mask.effects.len()); let subtitle = match (source, effects) { - (Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE), + (Some(source), _) => format!("{kind} · {} {source}", ic::LINK_SIMPLE), (None, 0) => kind.to_string(), (None, 1) => format!("{kind} · {}", tr("1 effect")), - (None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])), + (None, count) => format!("{kind} · {}", trf("{count} effects", &[("count", &count)])), }; - let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim); + 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); } - if let Some(b) = blend.filter(|_| show_blend) { - let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); - if br.hovered() { - p.rect_filled(blend_rect, 2.0, tk.row_hover); + + // Blend mode and opacity of the displayed channel, stacked at the right + let mode_rect = Rect::from_min_size( + pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y - ROW_CONTROL_HEIGHT - ROW_STACK_GAP), + vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT), + ); + let opacity_rect = + Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y + ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT)); + if let Some(channel_blend) = blend.filter(|_| show_blend) { + let id = ui.scope_id().with(("blend", layer.id.0)); + let (mode, opacity) = blend_controls( + ui, + id, + (mode_rect, opacity_rect), + (channel_blend.mode, channel_blend.opacity), + (tr("Blending mode of the displayed channel"), &layer.name), + ); + if let Some(mode) = mode { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "mode": format!("{mode:?}")})); } - p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); - egui::Popup::menu(&br).show(|ui| { - ui.set_min_width(190.0); - for m in BlendMode::MENU { - match m { - Some(m) => { - if ui.selectable_label(m == b.mode, tr(m.label())).clicked() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "mode": format!("{m:?}")})); - ui.close(); - } - } - None => { - ui.separator(); - } - } - } - }); - let mut op = (b.opacity * 100.0).round(); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); - // As tall as its slot in the row (the style's fields are taller), in the row's small print. - child.spacing_mut().interact_size.y = op_rect.height(); - child.spacing_mut().button_padding = vec2(4.0, 0.0); - child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%")); - if r.changed() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); + if let Some((opacity, merge)) = opacity { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "opacity": opacity, "merge": merge})); } } else if show_blend { - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(ROW_SMALL_FONT_SIZE), tokens.text_dim); } - // Interaction: select, rename, drag & drop, context menu. - let on_control = eye_resp.clicked() || content_resp.clicked(); - if resp.clicked() && !on_control && !renaming { + + // Interaction: select, rename, drag & drop, context menu + let on_control = eye_response.clicked() || content_response.clicked(); + if row.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() && !on_control && !renaming && show_name { + if row.double_clicked() && !on_control && !renaming && show_name { app.ui.rename = Some((layer.id.0, layer.name.clone())); } - if resp.drag_started() && !renaming { - resp.dnd_set_drag_payload(layer.id.0); + if row.drag_started() && !renaming { + row.dnd_set_drag_payload(layer.id.0); } - // Drops: a layer or a shelf material lands above this row (inside a folder when dropped on - // its middle); a shelf smart mask replaces this layer's mask. - let inside = layer.is_group() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| (p.y - rect.center().y).abs() < h * 0.25); - let shelf = resp.dnd_hover_payload::().map(|d| d.asset.clone()); - let moving = resp.dnd_hover_payload::().is_some_and(|src| *src != layer.id.0); + + // Drops: a layer or a shelf material lands above this row (inside a folder on its middle); a shelf smart mask replaces the mask + let inside = layer.is_group() + && ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| (pointer.y - rect.center().y).abs() < row_height * FOLDER_DROP_ZONE); + let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); + let moving = row.dnd_hover_payload::().is_some_and(|dragged| *dragged != layer.id.0); + let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); if moving || shelf.as_ref().is_some_and(Asset::is_material) { if inside { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } else { - p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); + painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } } else if matches!(shelf, Some(Asset::SmartMask(_))) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Outside); + 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() { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } - if let Some(src) = dnd_release::(&resp) - && *src != layer.id.0 + if let Some(dragged) = dnd_release::(&row) + && *dragged != layer.id.0 { - app.run("layer.move", json!({"layer": *src, "above": layer.id.0, "inside": inside})); + app.run("layer.move", json!({"layer": *dragged, "above": layer.id.0, "inside": inside})); } - match dnd_release::(&resp).map(|d| d.asset.clone()) { - Some(Asset::Material(m)) => { - app.run("material.apply", json!({"material": m, "above": layer.id.0, "inside": inside})); + match dnd_release::(&row).map(|drag| drag.asset.clone()) { + Some(Asset::Material(material)) => { + app.run("material.apply", json!({"material": material, "above": layer.id.0, "inside": inside})); } Some(Asset::Library(path)) => { app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside})); } - Some(Asset::SmartMask(m)) => { - app.run("mask.smart.apply", json!({"name": m, "layer": layer.id.0})); + Some(Asset::SmartMask(smart_mask)) => { + app.run("mask.smart.apply", json!({"name": smart_mask, "layer": layer.id.0})); } - Some(Asset::Filter(f)) => { + Some(Asset::Filter(filter)) => { app.run("layer.select", json!({"layer": layer.id.0})); - app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": f, "target": "content"})); + app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": filter, "target": "content"})); } Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {} } - resp.context_menu(|ui| layer_context_menu(app, ui, layer)); + row.context_menu(|ui| layer_context_menu(app, ui, layer)); +} + +/// The border of a content or mask thumbnail: the accent while it is the layer's target. +fn target_stroke(tokens: &Tokens, target: bool) -> Stroke { + if target { Stroke::new(TARGET_BORDER_WIDTH, tokens.accent) } else { Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border) } } /// What a content thumbnail shows until its picture arrives (or where the layer has none). @@ -665,37 +751,50 @@ 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 tk = Tokens::get(ui.ctx()); - let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |m| &m.effects) } else { &layer.content_effects }; + 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, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click()); + 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") }; - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); - let p = ui.painter().clone(); - p.rect_filled(rect, 0.0, if resp.hovered() { tk.row_hover } else { tk.panel }); - let indent = ((depth + 1) as f32 * INDENT).min((rect.width() - 90.0).max(0.0)); - tree_lines(&p, &tk, rect, indent, &[], more_below); - let x = rect.left() + 15.0 + indent; - p.text( + 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(10.0), - tk.text_dim, + egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE), + tokens.text_dim, ); - let galley = elided(&p, label.to_string(), 10.5, tk.text_dim, (rect.right() - 28.0 - x - 10.0).max(0.0)); - p.galley(pos2(x + 10.0, rect.center().y - galley.size().y * 0.5), galley, tk.text_dim); - p.text(pos2(rect.right() - 8.0, rect.center().y), egui::Align2::RIGHT_CENTER, stack.len().to_string(), egui::FontId::proportional(10.0), tk.text_dim); - if resp.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) { + 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 { return; } + let trunks: Vec = if more_below { vec![depth] } else { Vec::new() }; - for (i, e) in stack.iter().rev().enumerate() { - effect_row(app, ui, layer, stack, e, depth + 2, &trunks, i + 1 == stack.len(), mask); + 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); } } @@ -721,97 +820,203 @@ fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: & /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +/// A stack row's blend mode menu and opacity field (percent, named after row `row_name`): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. +fn blend_controls( + ui: &mut Ui, + id: egui::Id, + (mode_rect, opacity_rect): (Rect, Rect), + (mode, opacity): (BlendMode, f32), + (hover, row_name): (&str, &str), +) -> (Option, Option<(f32, bool)>) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter().clone(); + + let mut picked = None; + let menu = ui.interact(mode_rect, id, Sense::click()).on_hover_text(hover); + if menu.hovered() { + painter.rect_filled(mode_rect, ROW_CONTROL_ROUNDING, tokens.row_hover); + } + let mode_font = egui::FontId::proportional(ROW_SMALL_FONT_SIZE); + painter.text(mode_rect.right_center() - vec2(CARET_WIDTH, 0.0), egui::Align2::RIGHT_CENTER, mode.short(), mode_font, tokens.text); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_FONT_SIZE), tokens.text_dim); + egui::Popup::menu(&menu).show(|ui| { + ui.set_min_width(BLEND_MENU_MIN_WIDTH); + for item in BlendMode::MENU { + match item { + Some(item) => { + if ui.selectable_label(item == mode, tr(item.label())).clicked() { + picked = Some(item); + ui.close(); + } + } + None => { + ui.separator(); + } + } + } + }); + + let mut percent = (opacity * 100.0).round(); + let mut field_ui = ui.new_child(egui::UiBuilder::new().max_rect(opacity_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); + // As tall as its slot in the row (the style's fields are taller), in the row's small print + field_ui.spacing_mut().interact_size.y = opacity_rect.height(); + field_ui.spacing_mut().button_padding = vec2(ROW_FIELD_PADDING, 0.0); + field_ui.style_mut().override_text_style = Some(egui::TextStyle::Small); + + // Plain text like the blend mode beside it: no field box, only the hover fill + let widgets = &mut field_ui.visuals_mut().widgets; + for state in [&mut widgets.inactive, &mut widgets.noninteractive] { + state.weak_bg_fill = Color32::TRANSPARENT; + state.bg_fill = Color32::TRANSPARENT; + state.bg_stroke = Stroke::NONE; + } + for state in [&mut widgets.hovered, &mut widgets.active] { + state.weak_bg_fill = tokens.row_hover; + state.bg_stroke = Stroke::NONE; + } + let field = field_ui.add(egui::DragValue::new(&mut percent).range(0.0..=100.0).speed(OPACITY_DRAG_SPEED).max_decimals(0).suffix("%")); + field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, true, trf("Opacity of {name}", &[("name", &row_name)]))); + + // A drag's first change starts an undo step and its later changes continue it (a drag can start without a change) + let drag_changed_id = id.with("opacity_drag_changed"); + let drag_changed = !field.drag_started() && ui.data(|data| data.get_temp::(drag_changed_id)).unwrap_or(false); + let merge = field.dragged() && drag_changed; + if field.changed() || field.drag_started() { + ui.data_mut(|data| data.insert_temp(drag_changed_id, field.changed() && field.dragged())); + } + (picked, field.changed().then_some((percent / 100.0, merge))) +} + +/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. #[allow(clippy::too_many_arguments)] -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) { - let tk = Tokens::get(ui.ctx()); - let (eid, visible) = (e.id, e.visible); - let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let size = effect_preview_size(layer_preview_size(app)); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); - let p = ui.painter().clone(); - p.rect_filled( - rect, - 0.0, - if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover - } else { - tk.panel - }, - ); - let indent = effect_row_indent(rect.width(), level, size); - tree_lines(&p, &tk, rect, indent, trunks, !last); +fn effect_row( + app: &mut TextureCraftApp, + ui: &mut Ui, + layer: &Layer, + stack: &[Effect], + effect: &Effect, + row_index: usize, + level: usize, + trunks: &[usize], + last: bool, + in_mask: bool, +) { + let tokens = Tokens::get(ui.ctx()); + let (effect_id, visible) = (effect.id, effect.visible); + let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id); + let layer_preview = layer_preview_size(app); + let preview_size = effect_preview_size(layer_preview); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview)), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name)); + + // Background, tree lines and the selected row's accent edge + let painter = ui.painter().clone(); + + // Effect rows alternate two shades just above the panel, counted from the top of their list + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover + } else { + tokens.panel.lerp_to_gamma(tokens.row_hover, EFFECT_ROW_SHADES[row_index % EFFECT_ROW_SHADES.len()]) + }; + painter.rect_filled(rect, 0.0, background); + let indent = effect_row_indent(rect.width(), level, preview_size); + tree_lines(&painter, &tokens, rect, indent, trunks, !last); if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent); } - let x0 = rect.left() + 7.0 + indent; - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); - let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); - p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - // The stack as it is up to and including this effect; a hidden one shows what it bypasses. - let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size)); - let ch = app.ui.layer_channel; - if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) { + + // The eye, then the stack as it is up to and including this effect (a hidden one shows what it bypasses) + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(EYE_SIZE, EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eff_eye", effect_id.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); + let eye_glyph = if visible { ic::EYE } else { ic::EYE_SLASH }; + painter.text(eye.center(), egui::Align2::CENTER_CENTER, eye_glyph, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text_dim); + let thumbnail = Rect::from_min_size(pos2(content_left + EYE_COLUMN_WIDTH, rect.center().y - preview_size * 0.5), vec2(preview_size, preview_size)); + let channel = app.ui.layer_channel; + if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) { let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; - p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim); + painter.text(thumbnail.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(preview_size * 0.5), tokens.text_dim); } - p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside); + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border), egui::StrokeKind::Outside); if !visible { - p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim)); + painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - let name_x = thumb.right() + 8.0; - let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0)); - p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text); - if er.clicked() { - app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); - } else if resp.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + + // The name, then the blend mode and opacity side by side at the right when the name keeps room to be read + let name_left = thumbnail.right() + THUMBNAIL_GAP; + let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; + let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; + let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; + let name_color = if visible { tokens.text } else { tokens.text_dim }; + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); + painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + if show_blend { + let mode_width = EFFECT_BLEND_WIDTH - ROW_CONTROL_GAP - EFFECT_OPACITY_WIDTH; + let mode_rect = Rect::from_center_size(pos2(controls_left + mode_width * 0.5, rect.center().y), vec2(mode_width, ROW_CONTROL_HEIGHT)); + let opacity_center = pos2(mode_rect.right() + ROW_CONTROL_GAP + EFFECT_OPACITY_WIDTH * 0.5, rect.center().y); + let opacity_rect = Rect::from_center_size(opacity_center, vec2(EFFECT_OPACITY_WIDTH, ROW_CONTROL_HEIGHT)); + let id = ui.scope_id().with(("eff_blend", effect_id.0)); + let (mode, opacity) = + blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), (tr("Blending mode of the effect"), &effect.name)); + if let Some(mode) = mode { + app.run("effect.set", json!({"effect": effect_id.0, "blend": format!("{mode:?}")})); + } + if let Some((opacity, merge)) = opacity { + app.run("effect.set", json!({"effect": effect_id.0, "opacity": opacity, "merge": merge})); + } } - // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. - if resp.drag_started() { - resp.dnd_set_drag_payload(EffectDrag(eid.0)); + + if eye_response.clicked() { + app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if row.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); } - let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); - let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); - if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half + if row.drag_started() { + row.dnd_set_drag_payload(EffectDrag(effect_id.0)); + } + let position = |id: u64| stack.iter().position(|other| other.id.0 == id); + let below = ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| pointer.y > rect.center().y); + if row.dnd_hover_payload::().is_some_and(|dragged| dragged.0 != effect_id.0 && position(dragged.0).is_some()) { let y = if below { rect.bottom() } else { rect.top() }; - p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + painter.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(DROP_LINE_WIDTH, tokens.accent)); } - if let Some(src) = dnd_release::(&resp) - && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + if let Some(dragged) = dnd_release::(&row) + && let (Some(from), Some(to)) = (position(dragged.0), position(effect_id.0)) && from != to { - // Rows list the stack top first, so above this row is the next index up. + // Rows list the stack top first, so above this row is the next index up let index = match (from < to, below) { (true, false) | (false, true) => to, (true, true) => to - 1, (false, false) => to + 1, }; - app.run("effect.move", json!({"effect": src.0, "index": index})); + app.run("effect.move", json!({"effect": dragged.0, "index": index})); } - resp.context_menu(|ui| { + + row.context_menu(|ui| { let keymap = app.ui.keymap.clone(); - // The row is selected before the paste runs, so a copied effect is all it needs. + // The row is selected before the paste runs, so a copied effect is all it needs let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); - // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. - for (label, id, keys, enabled) in [ + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect + for (label, command, keys, enabled) in [ (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), (tr("Duplicate effect"), "effect.duplicate", None, true), (tr("Remove effect"), "effect.remove", None, true), ] { - let mut b = egui::Button::new(label); - if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { - b = b.shortcut_text(sc); + let mut button = egui::Button::new(label); + if let Some(shortcut) = keys.and_then(|key| crate::keymap::shortcut_of(&keymap, key)) { + button = button.shortcut_text(shortcut); } - if ui.add_enabled(enabled, b).clicked() { - // Selected first: a paste lands above it, a duplicate takes the selection. - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); - app.run(id, json!({"effect": eid.0})); + if ui.add_enabled(enabled, button).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); + app.run(command, json!({"effect": effect_id.0})); ui.close(); } } @@ -878,7 +1083,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.close(); } }; - // An instance without a mask of its own edits its source's; adding one overrides it. + // An instance edits its source mask until it gets its own let project = &app.session.doc.project; let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.is_some()); run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": lid}), layer.mask.is_none()); @@ -965,7 +1170,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { app.run("textureSet.uvTiles", json!({"ts": ts, "enabled": tiled})); } ui.end_row(); - // Each tile's own size (per-tile resolution). + // Each tile's own size (per-tile resolution) for &udim in &set.uv_tiles { let r = set.tile_resolution(udim); ui.label(RichText::new(format!(" {udim}")).color(tk.text_dim)); @@ -1045,7 +1250,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { .color(tk.text_dim), ); }); - // An image resource instead of a bake, or no map. + // An image resource instead of a bake, or no map ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { if let Some(name) = image_menu(app, ui) { @@ -1059,7 +1264,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { }); }); }); - // A shelf image dropped on the row becomes this mesh map. + // A shelf image dropped on the row becomes this mesh map let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); if let Some(name) = image_drop(ui, &resp) { app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); @@ -1069,10 +1274,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } /// Menu items listing the image resources, then Import...: the image picked, if any. -fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { +pub(crate) fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { ui.label(caption(tr("Images"))); let mut picked = None; - // Bounded, so Import... and the items after it stay on screen with many images. + // Bounded so Import... and later items stay on screen with many images egui::ScrollArea::vertical().id_salt("image_menu").max_height(240.0).show(ui, |ui| { for name in app.session.doc.resources.keys() { if ui.button(name.as_str()).clicked() { @@ -1092,7 +1297,7 @@ fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { /// An image from the Assets panel dropped on `resp`, outlined while one hovers it. Other assets /// are left for the drop targets around it. -fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { +pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { if !resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { return None; } @@ -1103,7 +1308,7 @@ fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } } -fn mesh_map_color(map: BakedMap) -> Color32 { +pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 { match map { BakedMap::Normal => Color32::from_rgb(128, 128, 255), BakedMap::WorldNormal => Color32::from_rgb(120, 200, 140), @@ -1121,17 +1326,21 @@ fn mesh_map_color(map: BakedMap) -> Color32 { // --------------------------------------------------------------------------------------------- // Properties -/// The Properties tab title: what the panel edits. +/// The Properties tab title: what the panel edits pub(crate) fn properties_title(app: &TextureCraftApp) -> String { let project = &app.session.doc.project; + let tool = app.session.tool.tool; + let tool_usable = app.session.tool_usable(tool); let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { - // Polygon fill keeps its own properties whatever is selected - _ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(), + // Polygon fill keeps its own properties wherever it can fill + _ if tool == Tool::PolygonFill && tool_usable => tr(tool.label()).to_string(), (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(), - _ => tr(app.session.tool.tool.label()).to_string(), + (Some(_), StackTarget::Mask) if !tool_usable => tr("Mask").to_string(), + (None, _) if !tool_usable => return tr("Properties").to_string(), + _ => tr(tool.label()).to_string(), }; format!("{} - {what}", tr("Properties")) } @@ -1142,14 +1351,16 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } -/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool +/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder, instance or mask, else the tool (or a hint to select a layer when it can't act) pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); + let tool = app.session.tool.tool; + let tool_usable = app.session.tool_usable(tool); match (&selected, app.session.target) { - // Polygon fill shows its own settings and says what it fills into, whatever is selected - _ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui), + // Polygon fill shows its own settings and says what it fills into, wherever it can fill + _ if tool == Tool::PolygonFill && tool_usable => polygon_fill_properties(app, ui), (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => { @@ -1158,8 +1369,13 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => instance_properties(app, ui, layer), (Some(layer), StackTarget::Mask) => { height_mask_section(app, ui, layer); - ui.separator(); - tool_properties(app, ui); + if tool_usable { + ui.separator(); + tool_properties(app, ui); + } + } + (None, _) if !tool_usable => { + ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); } _ => tool_properties(app, ui), } @@ -1583,6 +1799,10 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { } *brush = brush.sanitized(); + + // Presets are files, which the browser doesn't have + #[cfg(not(target_arch = "wasm32"))] + section(ui, "sec_brush_preset", tr("Preset"), false, |ui| crate::brush_preset_save::row(app, ui)); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. @@ -1828,7 +2048,8 @@ fn link_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, link: app.cook_link(layer); } if ui.button(tr("Open in MaterialCraft")).clicked() { - let path = std::env::temp_dir().join(format!("{}.mcraft", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let ext = texturecraft_engine::link_cmds::source_extension(&link.package); + let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); let opened = app .session .link_package(layer) @@ -1910,7 +2131,7 @@ fn with(base: &Value, extra: Value) -> Value { } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). -fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { +pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { let p = &app.session.doc.project; let Some((ts, _, _)) = p.locate(reader) else { return Vec::new() }; p.walk(ts) @@ -1922,7 +2143,7 @@ fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String .collect() } -fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { +pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } @@ -2214,37 +2435,23 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu } } }); - // A shelf image dropped on the channel becomes its source. + // A shelf image dropped on the channel becomes its source if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { app.run("layer.fill.set", set(json!({"image": name}))); } } } -fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { - let tk = Tokens::get(ui.ctx()); - let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; +/// The properties of effect `effect_id` of `layer`: each kind's own settings. +fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { + let tokens = Tokens::get(ui.ctx()); + let Some(effect) = app.session.doc.project.effect(effect_id).map(|(_, effect)| effect.clone()) else { return }; - let id = eid.0; - ui.horizontal(|ui| { - ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { - for mode in BlendMode::all() { - if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); - } - } - }); - }); - let mut opacity = effect.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); - } - ui.separator(); + let id = effect_id.0; match &effect.kind { - EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), - EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, eid, levels), + EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), + EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); let anchors = anchors_below(app, layer.id); @@ -2280,12 +2487,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } }); - ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } _ => {} } if anchors.is_empty() { - ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); } } EffectKind::Material(fill) => { @@ -2297,27 +2504,29 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(caption(tr("Anchor point"))); ui.label( RichText::new(tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|content| content.id == eid) { + let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { tr("Paint on the mesh to edit the layer content.") } else { tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") }; - ui.label(RichText::new(hint).color(tk.text_dim)); - tool_properties(app, ui); + ui.label(RichText::new(hint).color(tokens.text_dim)); + if app.session.tool_usable(app.session.tool.tool) { + tool_properties(app, ui); + } } EffectKind::Path(paths) => { ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); let editing = app.session.tool.path.editing; for index in 0..paths.len() { ui.horizontal(|ui| { - let selected = editing == Some((eid, index)); + let selected = editing == Some((effect_id, index)); if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { if selected { app.run("tool.path", json!({"clear": true})); @@ -2325,94 +2534,23 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: app.run("path.edit", json!({"effect": id, "index": index})); } } - if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { app.run("path.remove", json!({"effect": id, "index": index})); } }); } - tool_properties(app, ui); + if app.session.tool_usable(app.session.tool.tool) { + tool_properties(app, ui); + } } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), - EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, eid, colors, *tolerance), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), other => { - ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); + ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); } } } -/// The settings of generator effect `id`. -fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { - for kind in GeneratorKind::ALL { - if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); - } - } - }); - - let (mut level, mut softness, mut noise, mut noise_scale, mut offset, mut invert) = - (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset, generator.invert); - let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); - let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); - let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); - let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); - if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit).or(invert_edit) { - app.run( - "effect.set", - json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "invert": invert, "merge": merge}), - ); - } - - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); - } -} - -/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). -fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { - let tk = Tokens::get(ui.ctx()); - let shown = detail.cloned().unwrap_or_default(); - combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { - for mode in CurvatureMode::ALL { - if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { - app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); - } - } - }); - - ui.label(caption(tr("Detail sizes"))); - let mut weights = shown.weights; - let mut edit = None; - for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { - edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); - } - if detail.is_none() { - ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); - } -} - -/// The translated name of curvature mode `mode`. -fn curvature_mode_label(mode: CurvatureMode) -> &'static str { - match mode { - CurvatureMode::Edges => tr("Edges"), - CurvatureMode::Cavities => tr("Cavities"), - CurvatureMode::Both => tr("Edges and cavities"), - CurvatureMode::Raw => tr("Raw curvature"), - } -} - /// The filter slot and the parameters of filter effect `id` fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 5bebfd98..62bfa427 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -133,17 +133,28 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node Workspace { use Panel::*; + + // The Assets split keeps four tiles visible at the reference window width + const ASSETS_SPLIT_RATIO: f32 = 0.16; + const VIEWPORT_SPLIT_RATIO: f32 = 0.80; + const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; + const LAYERS_SPLIT_RATIO: f32 = 0.57; + let column = split( SplitAxis::Vertical, - SplitSize::Ratio(0.125), + SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO), tabs(&[TextureSetList]), - split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + ); + let root = split( + SplitAxis::Horizontal, + SplitSize::Ratio(ASSETS_SPLIT_RATIO), + tabs(&[Assets]), + split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column), ); - let root = - split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { @@ -215,8 +226,11 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { // --------------------------------------------------------------------------------------------- // The live dock -/// Width of the bake layout's texture set and mesh map bakers column, in points -const BAKERS_COLUMN_WIDTH: f32 = 200.0; +/// Height of a panel group's tab strip, in points +pub(crate) const TAB_HEIGHT: f32 = 30.0; + +/// Width of the bake layout's texture set and mesh map bakers column in points: the reference's scaled to our larger font +const BAKERS_COLUMN_WIDTH: f32 = 232.0; /// Width of the bake layout's common and mesh map settings column, in points const SETTINGS_COLUMN_WIDTH: f32 = 330.0; /// Height of the log under the bake layout's columns, in points @@ -367,29 +381,42 @@ fn area_id() -> Id { Id::unique("texturecraft-docking") } -/// The dock look: every panel group is a card on the window's frame colour, its tab strip -/// without hard lines, the shown tab a pill. -fn style(ui: &Ui, t: &Tokens) -> DockStyle { - let mut s = DockStyle::from_ui(ui); - s.gap = f32::from(crate::theme::GUTTER); - // Smallest panel extent a divider drag leaves. - s.min_pane = 60.0; - s.background = t.panel; - s.tab_background = t.panel; - s.active_background = t.button; - s.text = t.text_strong; - s.inactive_text = t.text_dim; - s.border = egui::Stroke::NONE; - s.accent = t.accent; - s.floating_background = t.panel; - s.floating_stroke = egui::Stroke::new(1.0, t.button_border); - s.font = egui::FontId::proportional(12.5); - s.min_tab_width = 54.0; - s.tab_height = 30.0; - // Panels arrange in a split tree around the viewport; floating title bars only move windows. - s.new_dock_zones = false; - s.title_bar_docks = false; - s +/// Smallest panel extent a divider drag leaves, in points +const MIN_PANE_EXTENT: f32 = 60.0; + +/// Border width of a floating panel, in points +const FLOATING_BORDER_WIDTH: f32 = 1.0; + +/// Text size of the panel tabs, in points +const TAB_TEXT_SIZE: f32 = 12.5; + +/// Narrowest panel tab, in points +const MIN_TAB_WIDTH: f32 = 54.0; + +/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill +fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { + let mut dock_style = DockStyle::from_ui(ui); + dock_style.gap = f32::from(crate::theme::GUTTER); + dock_style.min_pane = MIN_PANE_EXTENT; + + dock_style.background = tokens.panel; + dock_style.tab_background = tokens.panel; + dock_style.active_background = tokens.button; + dock_style.text = tokens.text_strong; + dock_style.inactive_text = tokens.text_dim; + dock_style.border = egui::Stroke::NONE; + dock_style.accent = tokens.accent; + dock_style.floating_background = tokens.panel; + dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border); + + dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE); + dock_style.min_tab_width = MIN_TAB_WIDTH; + dock_style.tab_height = TAB_HEIGHT; + + // Panels arrange in a split tree around the viewport; floating title bars only move windows + dock_style.new_dock_zones = false; + dock_style.title_bar_docks = false; + dock_style } /// Whether a modal layer or update dialog holds the input, so the panels, floating ones included, diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs new file mode 100644 index 00000000..63fe8008 --- /dev/null +++ b/crates/ui-egui/src/generator_panel.rs @@ -0,0 +1,394 @@ +//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs. + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source}; + +use crate::TextureCraftApp; +use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::theme::{Tokens, caption}; +use crate::widgets::{combo, section, slider_edit}; + +/// Random seeds stay below this, short enough to read and type. +const SEED_RANGE: u32 = 10_000; +/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range. +const SEED_MIX: u32 = 2_654_435_761; + +/// Font size of the notes under a control. +const NOTE_FONT_SIZE: f32 = 10.5; + +/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. +const INPUT_TILE_SIZE: f32 = 32.0; +const INPUT_TILE_ROUNDING: f32 = 2.0; +const INPUT_TILE_ICON_SIZE: f32 = 16.0; + +/// Width of the names in the Attributes section, so their values line up. +const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; + +/// The settings of generator effect `id`. +pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() && kind != generator.kind { + app.run("effect.set", json!({"effect": id, "generator": format!("{kind:?}")})); + } + } + }); + + section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); + section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); + section(ui, "generator_parameters", tr("Parameters"), true, |ui| { + global_adjustments(app, ui, id, generator); + ramp_parameters(app, ui, id, generator); + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + app.run("effect.set", defaults_of(id, generator.kind)); + } + }); + }); + }); + if !generator.kind.inputs().is_empty() { + section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + for map in generator.kind.inputs() { + input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); + } + }); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label( + RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tokens.warning), + ); + } +} + +/// What a generator kind makes, its category and its tags (read only). +fn attributes(ui: &mut Ui, kind: GeneratorKind) { + let tokens = Tokens::get(ui.ctx()); + let (description, tags) = match kind { + GeneratorKind::EdgeWear => ( + tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::Dirt => ( + tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")], + ), + GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), + GeneratorKind::Curvature => ( + tr("Convex edges, cavities or both from the curvature map, at several detail sizes."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::AmbientOcclusion => { + (tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) + } + GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + }; + + // Wrapped rows: a long line must not widen the panel past its edge + let tags = tags.join(", "); + for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] { + ui.horizontal_top(|ui| { + ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); + ui.add(egui::Label::new(value).wrap()); + }); + } +} + +/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to. +fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) { + let tokens = Tokens::get(ui.ctx()); + combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| { + for mode in ResolutionMode::ALL { + if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")})); + } + } + }) + .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); + if resolution.mode == ResolutionMode::Custom { + combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| { + for size in OutputResolution::CUSTOM_SIZES { + if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() { + app.run("effect.set", json!({"effect": id, "customResolution": size})); + } + } + }); + } + combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| { + for factor in OutputResolution::FACTORS { + if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() { + app.run("effect.set", json!({"effect": id, "resolutionFactor": factor})); + } + } + }) + .on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up.")); + + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return }; + + let (smallest, largest) = texture_set + .uv_tiles + .iter() + .map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution)) + .fold((u32::MAX, 0), |(smallest, largest), size| (smallest.min(size), largest.max(size))); + let (smallest, largest) = if largest == 0 { + let size = resolution.output_size(texture_set.resolution, texture_set.resolution); + (size, size) + } else { + (smallest, largest) + }; + let size_label = if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") }; + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label)); + }) + .response + .on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution.")); +} + +/// The most powers of two a resolution factor scales by, either way. +const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); + +/// "Same as context", or the fraction or multiple a resolution factor stands for. +fn factor_label(factor: i8) -> String { + match factor { + 0 => tr("Same as context").to_string(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + } +} + +/// Global invert, blur, balance and contrast: what every generator applies to its finished value. +fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut invert, mut global) = (generator.invert, generator.global); + let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); + let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); + let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); + if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) { + app.run( + "effect.set", + json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), + ); + } +} + +/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. +fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), + ); + } + seed_row(app, ui, id, generator.seed); +} + +/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference. +fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { + let typing_id = ui.make_persistent_id(("generator_seed_typing", id)); + let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); + ui.horizontal(|ui| { + ui.label(tr("Seed")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { + typing = !typing; + } + if typing { + let mut typed = seed; + let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); + if field.changed() { + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge})); + } + } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() { + app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)})); + } + }); + }); + ui.data_mut(|data| data.insert_temp(typing_id, typing)); +} + +/// A seed different from `current`, from the clock. +fn random_seed(current: u32) -> u32 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); + let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; + if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } +} + +/// The `effect.set` params that put generator effect `id` back to the defaults of its kind. +fn defaults_of(id: u64, kind: GeneratorKind) -> Value { + let defaults = Generator::new(kind); + let mut params = json!({ + "effect": id, + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + "seed": defaults.seed, + "direction": defaults.direction, + "invert": defaults.invert, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + if let Some(detail) = defaults.detail { + params["mode"] = json!(format!("{:?}", detail.mode)); + params["sizes"] = json!(detail.weights); + } + params +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tokens = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + +/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { + let tokens = Tokens::get(ui.ctx()); + let input = map.id(); + let current = match source { + None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), + Some(Source::Uniform(_)) => tr("Uniform value").to_string(), + Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel), + Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + }; + let group = ui.group(|ui| { + ui.horizontal(|ui| { + input_tile(app, ui, map, source); + ui.vertical(|ui| { + ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + }); + }); + combo(ui, tr("Source"), current.clone(), |ui| { + let anchors = anchors_below(app, layer); + if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + } + for (anchor, label) in &anchors { + if ui + .selectable_label( + matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), + trf("Anchor: {name}", &[("name", label)]), + ) + .clicked() + { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + }); + if let Some(Source::Uniform(value)) = source { + let mut value = value[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); + } + } + if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + ui.label( + RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) + .size(NOTE_FONT_SIZE) + .color(tokens.text_dim), + ); + } + }); + if let Some(name) = image_drop(ui, &group.response) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } +} + +/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); + let painter = ui.painter(); + let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + match source { + Some(Source::Image { name, .. }) => match app.session.images.get(name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), name, image); + painter.image(texture.id(), rect, whole, egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + } + }, + Some(Source::Uniform(value)) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + } + Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); + } + None => { + let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); + painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); + } + } + painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside); +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 944a8ecd..ef362d63 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -11,7 +11,7 @@ use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::Mesh; -use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu}; +use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu}; use crate::bake_scene::{BakeSceneLink, CageUpload}; @@ -27,8 +27,8 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); -/// The low poly's UV seam edges (vertex pairs) per material -pub type UvSeamEdges = Vec>; +/// The low poly's hard edges without a UV seam (vertex pairs) per material +pub type MissingSeamEdges = Vec>; /// What the renderer must catch up with before drawing. #[derive(Default)] @@ -49,8 +49,8 @@ pub struct SceneSync { pub bake_cages: Vec<(usize, Option, u64)>, /// Texture sets left after some were removed: their cages go too pub bake_cage_count: Option, - /// The low poly's UV seams per material, for mesh id - pub uv_seams: Option<(u64, UvSeamEdges)>, + /// The low poly's hard edges without a UV seam per material, for mesh id + pub missing_seams: Option<(u64, MissingSeamEdges)>, } /// Lives in egui's callback resources. @@ -366,11 +366,15 @@ impl CallbackTrait for ViewCallback { gpu.renderer.truncate_bake_cages(count); } for (texture_set, cage, topology) in &sync.bake_cages { - let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice())); + let cage = cage.as_ref().map(|upload| CageGeometry { + corners: &upload.corners, + edges: &upload.shell.edges, + missing_seams: &upload.shell.missing_seams, + }); gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); } - if let Some((mesh_id, seams)) = &sync.uv_seams { - gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams); + if let Some((mesh_id, seams)) = &sync.missing_seams { + gpu.renderer.set_missing_seams(device, queue, *mesh_id, seams); } } @@ -384,6 +388,7 @@ impl CallbackTrait for ViewCallback { reports.memory.push(texture_set); } } + // This frame's report drain already ran: the next frame shows the toast gpu.ctx.request_repaint(); } diff --git a/crates/ui-egui/src/grid_tile.rs b/crates/ui-egui/src/grid_tile.rs new file mode 100644 index 00000000..45fd9bf6 --- /dev/null +++ b/crates/ui-egui/src/grid_tile.rs @@ -0,0 +1,9 @@ +//! A grid tile's measurements in the shelf's small, medium and large views + +/// A grid tile's size and its thumbnail's size and center below the tile's top, in points +pub(crate) struct GridTile { + pub(crate) width: f32, + pub(crate) height: f32, + pub(crate) thumbnail_size: f32, + pub(crate) thumbnail_center_y: f32, +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 90a1db04..f1aaa9b8 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -158,35 +158,36 @@ mod tests { fn catalog_keys() -> Vec<&'static str> { use texturecraft_engine::core::{BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind}; use texturecraft_engine::filter_lib::{FILTERS, build, scalar_params}; - let mut k: Vec<&'static str> = Vec::new(); - k.extend(crate::menus::TOP); - for i in crate::menus::CATALOG.iter().filter(|i| i.label != "-") { - k.push(i.label); - k.extend(i.sub); + let mut keys: Vec<&'static str> = Vec::new(); + keys.extend(crate::menus::TOP); + for item in crate::menus::CATALOG.iter().filter(|item| item.label != "-") { + keys.push(item.label); + keys.extend(item.sub); } - k.extend(crate::docking::VIEWS.iter().map(|(_, p)| p.name())); - for b in crate::keymap::bindings() { - k.push(b.label); - k.push(b.group); + keys.extend(crate::docking::VIEWS.iter().map(|(_, panel)| panel.name())); + for binding in crate::keymap::bindings() { + keys.push(binding.label); + keys.push(binding.group); } - k.extend(crate::shelf::TABS.iter().map(|t| t.2)); - k.extend(Channel::ALL.iter().flat_map(|c| [c.label(), c.short()])); - k.extend(BlendMode::all().map(|m| m.label())); - k.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|m| m.label())); - k.extend(texturecraft_engine::Tool::ALL.iter().map(|t| t.label())); - k.extend(ProceduralKind::ALL.iter().map(|p| p.label())); - k.extend(GeneratorKind::ALL.iter().map(|g| g.label())); - k.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|a| a.label())); - k.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, l)| *l)); - for f in FILTERS { - k.extend([f.label, f.group]); - if let Ok(EffectKind::Filter(x)) = build(f.id, &serde_json::Value::Null) { - k.push(x.label()); - k.extend(scalar_params(&x).into_iter().map(|p| p.1)); + keys.extend(crate::shelf::TABS.iter().map(|tab| tab.2)); + keys.extend(Channel::ALL.iter().flat_map(|channel| [channel.label(), channel.short()])); + keys.extend(BlendMode::all().map(|mode| mode.label())); + keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label())); + keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label())); + keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); + keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); + keys.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|alpha| alpha.label())); + keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label)); + for filter in FILTERS { + keys.extend([filter.label, filter.group]); + if let Ok(EffectKind::Filter(effect)) = build(filter.id, &serde_json::Value::Null) { + keys.push(effect.label()); + keys.extend(scalar_params(&effect).into_iter().map(|parameter| parameter.1)); } } - // Effect, view and camera names the engine gives. - k.extend([ + + // Include effect, view and camera names supplied by the engine + keys.extend([ "Paint", "Path", "Fill", @@ -199,8 +200,8 @@ mod tests { texturecraft_engine::camera_cmds::DEFAULT_CAMERA, crate::dock::SOLO_HINT, ]); - k.retain(|s| !s.is_empty() && !UNTRANSLATED.contains(s)); - k + keys.retain(|key| !key.is_empty() && !UNTRANSLATED.contains(key)); + keys } /// String literals passed straight to `tr(` or `trf(` in `src`. @@ -254,7 +255,8 @@ mod tests", for &(locale, common, app) in CRAFT_I18N { let Some(lang) = I18N.from_code(locale) else { continue }; let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect(); - // Decode TSV escapes for comparison with the literal source strings. + + // Decode TSV escapes to compare with literal source strings let mut rows = HashMap::new(); for text in [common, app] { for line in text.lines().filter(|l| !l.starts_with('#')) { @@ -335,17 +337,18 @@ mod tests", let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let keys = keys(); set_language("ja"); - let t = std::time::Instant::now(); - let mut n = 0usize; + let started = std::time::Instant::now(); + let mut total_chars = 0usize; for _ in 0..100 { - for k in &keys { - n += tr(k).len(); + for key in &keys { + total_chars += tr(key).len(); } } - let per = t.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64; + let ns_per_lookup = started.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64; set_language("en"); - assert!(n > 0); - // A frame looks up a few hundred strings: well under a microsecond each. - assert!(per < 1000.0, "{per:.0} ns per lookup"); + assert!(total_chars > 0); + + // A frame looks up a few hundred strings, each expected below one microsecond + assert!(ns_per_lookup < 1000.0, "{ns_per_lookup:.0} ns per lookup"); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs new file mode 100644 index 00000000..b63df18c --- /dev/null +++ b/crates/ui-egui/src/i18n/ar.rs @@ -0,0 +1,1148 @@ +//! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "جارٍ خبز {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "جارٍ خبز {map} ({n}/{total})، مجموعة الخامات {set} من {sets}"), + ("Follow Newest Map", "تتبّع أحدث خريطة"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "الرسم متوقف مؤقتًا أثناء عرض عملية الخبز. ألغِ الخبز أو انتظر حتى ينتهي.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ما يعرضه العرض ثلاثي الأبعاد أثناء الخبز: أحدث خريطة مكتملة، أو أي خريطة مكتملة تختارها، أو الخامة. الخرائط التي لم تُخبز بعد تعرض قيمة محايدة.", + ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), + ("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"), + ("2D view only", "عرض ثنائي الأبعاد فقط"), + ("32 bits (float)", "32 بت (فاصلة عائمة)"), + ("3D mesh", "مجسم ثلاثي الأبعاد"), + ("3D meshes", "مجسمات ثلاثية الأبعاد"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "رسم الخامات ثلاثية الأبعاد: طبقات، أقنعة، مواد ذكية، خبز خرائط المجسم والتصدير.", + ), + ("3D view only", "عرض ثلاثي الأبعاد فقط"), + ("3D/2D views", "عرض 3D/2D"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "المجلد يدمج عناصره الفرعية (تمرير مباشر). حدد عتامة كل قناة في صفوف الطبقات.", + ), + ("ACES filmic", "ACES سينمائي"), + ("Ambient", "المحيط"), + ("AO intensity", "شدة الانسداد المحيطي (AO)"), + ("About TextureCraft", "حول TextureCraft"), + ("About TextureCraft...", "حول TextureCraft..."), + ("Add an anchor point to a layer below to use its stack as a mask.", "أضف نقطة ارتكاز إلى طبقة سفلية لاستخدام مكدسها كقناع."), + ("Add anchor point", "إضافة نقطة ارتكاز"), + ("Add as decal (view center)", "إضافة كملصق (مركز العرض)"), + ("Add black mask", "إضافة قناع أسود"), + ("Add channel", "إضافة قناة"), + ("Add color", "إضافة لون"), + ("Add compare mask", "إضافة قناع مقارنة"), + ("Add effect", "إضافة تأثير"), + ("Add fill", "إضافة تعبئة"), + ("Add fill layer", "إضافة طبقة تعبئة"), + ("Add filter", "إضافة مرشح"), + ("Add folder", "إضافة مجلد"), + ("Add generator", "إضافة مولّد"), + ("Add levels", "إضافة مستويات"), + ("Add mask", "إضافة قناع"), + ("Add mask with color selection", "إضافة قناع مع تحديد لوني"), + ("Add output", "إضافة مخرج"), + ("Add paint", "إضافة رسم"), + ("Add paint layer", "إضافة طبقة رسم"), + ("Add smart material from the shelf", "إضافة مادة ذكية من الرف"), + ("Add to the layer content", "إضافة إلى محتوى الطبقة"), + ("Add to the mask", "إضافة إلى القناع"), + ("Add white mask", "إضافة قناع أبيض"), + ("Adjustments", "تعديلات"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "محاذاة: يُحتفظ بالإزاحة المحددة بالضربة الأولى. V + النقر يحدد مصدراً جديداً.", + ), + ("Alignment", "محاذاة"), + ("Alignment and culling", "المحاذاة والاستبعاد"), + ("All layers", "كل الطبقات"), + ("Alpha", "ألفا"), + ("Alphas", "أقنعة ألفا"), + ("Also bound to {item} ({menu})", "مرتبط أيضاً بـ {item} ({menu})"), + ("Alt + LMB drag", "سحب بـ Alt + زر الفأرة الأيسر"), + ("Always", "دائماً"), + ("Ambient Occlusion", "الانسداد المحيطي (AO)"), + ("Ambient occlusion", "الانسداد المحيطي (AO)"), + ("Amount", "المقدار"), + ("Anchor point", "نقطة ارتكاز"), + ("Anchor: {name}", "نقطة ارتكاز: {name}"), + ("Anchor: {name} ({channel})", "نقطة ارتكاز: {name} ({channel})"), + ("Angle", "الزاوية"), + ("Angle (degrees)", "الزاوية (بالدرجات)"), + ("Angle fade from", "تلاشي الزاوية من"), + ("Angle fade to", "تلاشي الزاوية إلى"), + ("Angle jitter", "اضطراب الزاوية"), + ("Anisotropy angle", "زاوية تباين الخواص"), + ("Anisotropy level", "مستوى تباين الخواص"), + ("Antialiasing", "تنعيم الحواف"), + ("Aperture", "فتحة العدسة"), + ("Apply", "تطبيق"), + ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), + ("Assets", "الأصول"), + ("Auto", "تلقائي"), + ("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"), + ("Autosave every", "حفظ تلقائي كل"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "تُحفظ النسخ التلقائية والمواد الذكية والإعدادات المسبقة والقوالب وتخطيطات الواجهة في مجلد البيانات. يُطبَّق المجلد الجديد عند إعادة التشغيل، وتبقى الملفات المحفوظة في مكانها.", + ), + ("Axis", "المحور"), + ("Back to painting", "العودة إلى الرسم"), + ("Backface culling", "استبعاد الوجوه الخلفية"), + ("Bake an ID map (F8) to pick colors from the mesh.", "اخبز خريطة المعرّفات ID (F8) لالتقاط الألوان من الشبكة."), + ("Bake Mesh Maps", "خبز خرائط المجسم"), + ("Bake mesh maps", "خبز خرائط المجسم"), + ( + "Bake mesh maps (F8) for curvature, AO and thickness based generators.", + "اخبز خرائط المجسم (F8) للمولدات المعتمدة على الانحناء والانسداد المحيطي والسماكة.", + ), + ("Baked Lighting", "إضاءة مخبوزة"), + ("Baking", "الخبز"), + ("Base color", "اللون الأساسي"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "اللون الأساسي هو اللون المنتشر، واللمعان هو لون F0، والصفاء هو 1 - الخشونة (أضف هذه القنوات في إعدادات مجموعة الخامات).", + ), + ("Base color, Metallic, Roughness and Specular level.", "اللون الأساسي، المعدنية، الخشونة ومستوى اللمعان."), + ("Based on each texture set's size", "بناءً على حجم كل مجموعة خامات"), + ("Basic settings", "الإعدادات الأساسية"), + ("Bent Normals", "النواظم المنحنية"), + ("Bevel", "شطف الحواف"), + ("Black", "أسود"), + ("Blending", "الدمج"), + ("Blending mode of the displayed channel", "نمط الدمج للقناة المعروضة"), + ("Blur", "تمويه"), + ("Blur Directional", "تمويه اتجاهي"), + ("Blur and sharpen", "تمويه وتوضيح"), + ("Bounces", "الارتدادات"), + ("Bricks", "طوب"), + ("Brush", "فرشاة"), + ("Brush size", "حجم الفرشاة"), + ("Brush size down / up", "تصغير / تكبير حجم الفرشاة"), + ("Brushed lines", "خطوط مصقولة بالفرشاة"), + ("Built-in (read-only): duplicate it to edit", "مدمج (للقراءة فقط): انسخه لتعديله"), + ("Built-in templates are read-only: duplicate one to edit it", "القوالب المدمجة للقراءة فقط: انسخ قالباً لتعديله"), + ("Built-in: {mesh}", "مدمج: {mesh}"), + ("Cage: {name}", "القفص (Cage): {name}"), + ("Camera", "الكاميرا"), + ("Colors", "الألوان"), + ("Go to camera 1", "الانتقال إلى الكاميرا 1"), + ("Go to camera 2", "الانتقال إلى الكاميرا 2"), + ("Go to camera 3", "الانتقال إلى الكاميرا 3"), + ("Go to camera 4", "الانتقال إلى الكاميرا 4"), + ("Go to camera 5", "الانتقال إلى الكاميرا 5"), + ("Go to camera 6", "الانتقال إلى الكاميرا 6"), + ("Go to camera 7", "الانتقال إلى الكاميرا 7"), + ("Go to camera 8", "الانتقال إلى الكاميرا 8"), + ("Go to camera 9", "الانتقال إلى الكاميرا 9"), + ("Camera settings", "إعدادات الكاميرا"), + ("Cancel", "إلغاء"), + ("Cancel the stroke", "إلغاء ضربة الفرشاة"), + ("Cell size (texels at 2K)", "حجم الخلية (تكسل بدقة 2K)"), + ("Cells", "خلايا"), + ("Channel", "القناة"), + ("Channel source: uniform value, procedural, image or anchor", "مصدر القناة: قيمة موحدة، إجرائي، صورة أو نقطة ارتكاز"), + ("Channels", "القنوات"), + ("Check for Updates...", "التحقق من وجود تحديثات..."), + ("Checker", "رقعة شطرنج"), + ("Clamp", "تقييد القيم"), + ("Clear", "مسح"), + ("Clear mask", "مسح القناع"), + ("Clear recent projects", "مسح المشاريع الأخيرة"), + ("Click a mesh part to show or hide the selected layer on it.", "انقر على جزء من المجسم لإظهار أو إخفاء الطبقة المحددة عليه."), + ("Click the mesh to pick its material into the brush", "انقر على المجسم لالتقاط مادته إلى الفرشاة"), + ("Click the mesh to place the decal", "انقر على المجسم لوضع الملصق"), + ("Click, then press the new shortcut (Esc cancels)", "انقر، ثم اضغط الاختصار الجديد (Esc للإلغاء)"), + ("Clone", "استنساخ"), + ("Close", "إغلاق"), + ("Closed path", "مسار مغلق"), + ("Cloud", "سحابة"), + ("Clouds", "سحب"), + ("Coat normal", "ناظم الطبقة الشفافة"), + ("Coat roughness", "خشونة الطبقة الشفافة"), + ("Coat weight", "وزن الطبقة الشفافة"), + ("Color", "اللون"), + ("Color Balance", "توازن الألوان"), + ("Color burn", "حرق لوني (Color Burn)"), + ("Color dodge", "تفتيح لوني (Color Dodge)"), + ("Color of the light that travels under the surface (each channel goes as far as its value)", "لون الضوء المنتقل تحت السطح (تصل كل قناة بقدر قيمتها)"), + ("Color picker", "منتقي الألوان"), + ("Color selection", "تحديد لوني"), + ("Color to replace", "اللون المراد استبداله"), + ("Colors near the first shift towards the second, keeping their shading.", "الألوان القريبة من الأولى تتحول نحو الثانية مع الحفاظ على تظليلها."), + ("Colors read as gray. Add a levels or blur effect above to shape the result.", "تُقرأ الألوان كرمادي. أضف تأثير مستويات أو تمويه في الأعلى لتشكيل النتيجة."), + ("Combine with the layer's height", "الدمج مع ارتفاع الطبقة"), + ("Compare mask", "قناع مقارنة"), + ("Compositing", "التركيب"), + ("Constant", "ثابت"), + ("Constants", "ثوابت"), + ("Contrast", "التباين"), + ("Contrast/Luminosity", "التباين / الإضاءة"), + ("Converted maps", "الخرائط المحوّلة"), + ("Copy RGB values", "نسخ قيم RGB"), + ("Copy effect", "نسخ التأثير"), + ("Copy from", "نسخ من"), + ("Copy layer(s)", "نسخ الطبقة (الطبقات)"), + ("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"), + ("Copy to all texture sets", "نسخ إلى جميع مجموعات الخامات"), + ("Copy what the texture set shows", "نسخ ما تعرضه مجموعة الخامات"), + ("Couldn't encode the render", "تعذر ترميز التصيير"), + ("Couldn't export textures: {error}", "تعذر تصدير الخامات: {error}"), + ("Couldn't export the mesh: {error}", "تعذر تصدير المجسم: {error}"), + ("Couldn't export the template: {error}", "تعذر تصدير القالب: {error}"), + ("Couldn't import {name}: {error}", "تعذر استيراد {name}: {error}"), + ("Couldn't open {name}: {error}", "تعذر فتح {name}: {error}"), + ("Couldn't read the render back from the GPU", "تعذرت قراءة التصيير من وحدة معالجة الرسوميات (GPU)"), + ("Couldn't save the render: {error}", "تعذر حفظ التصيير: {error}"), + ("Couldn't save {name}: {error}", "تعذر حفظ {name}: {error}"), + ("Count per stamp", "العدد لكل طبعة"), + ("Crate", "صندوق"), + ("Create", "إنشاء"), + ("Create smart material", "إنشاء مادة ذكية"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+السحب بالزر الأيمن في عرض يضبط الحجم والصلابة، وCtrl+السحب بالزر الأيسر يضبط التدفق والزاوية.", + ), + ("Cube", "مكعب"), + ("Current layer", "الطبقة الحالية"), + ("Curvature", "الانحناء"), + ("Cut effect", "قص التأثير"), + ("Cut layer(s)", "قص الطبقة (الطبقات)"), + ("Cyan / red", "سماوي / أحمر"), + ("Cylinder", "أسطوانة"), + ("Cylindrical projection", "إسقاط أسطواني"), + ("Dark to light: the content's luminance picks a color along these stops.", "من الداكن إلى الفاتح: تحدد إضاءة المحتوى لوناً على طول نقاط التوقف هذه."), + ("Darken (Min)", "تغميق (الحد الأدنى)"), + ("Data folder", "مجلد البيانات"), + ("Decal", "ملصق"), + ("Decal projection", "إسقاط الملصق"), + ("Default", "افتراضي"), + ("Default camera", "الكاميرا الافتراضية"), + ("Delete the selected template", "حذف القالب المحدد"), + ("Delete this camera", "حذف هذه الكاميرا"), + ("Deleted template \"{name}\"", "تم حذف القالب \"{name}\""), + ("Denoise", "إزالة الضوضاء"), + ("Depth", "العمق"), + ("Depth of field", "عمق الميدان"), + ("Depth of field (viewport and Rendering mode)", "عمق الميدان (منفذ العرض ونمط التصيير)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "عمق المستوى الحاد على طول خط النظر (0: مركز المدار)"), + ("Details saved to {file}", "حُفظت التفاصيل في {file}"), + ("Difference", "الفرق"), + ("Dilation + default background color", "تمديد + لون الخلفية الافتراضي"), + ("Dilation + transparent", "تمديد + شفاف"), + ("Dilation infinite", "تمديد لا نهائي"), + ("DirectX normal map", "خريطة نواظم DirectX"), + ("Dirt", "أوساخ"), + ("Disable", "تعطيل"), + ("Dismiss", "تجاهل"), + ("Displacement (height channel)", "إزاحة (قناة الارتفاع)"), + ("Display Settings", "إعدادات العرض"), + ("Display material", "عرض المادة"), + ("Display next channel", "عرض القناة التالية"), + ("Display next mesh map", "عرض خريطة المجسم التالية"), + ("Display previous channel", "عرض القناة السابقة"), + ("Display previous mesh map", "عرض خريطة المجسم السابقة"), + ("Distance", "المسافة"), + ("Distort", "تشويه"), + ("Divide", "قسمة"), + ("Document resolution", "دقة المستند"), + ("Documentation...", "التوثيق..."), + ("Done on CPU: {n} / {max} samples, {s} s", "اكتمل على المعالج (CPU): {n} / {max} عينة، {s} ث"), + ("Done on GPU: {n} / {max} samples, {s} s", "اكتمل على المعالج الرسومي (GPU): {n} / {max} عينة، {s} ث"), + ("Double-click to rename", "انقر نقراً مزدوجاً لإعادة التسمية"), + ("Download as", "تنزيل باسم"), + ("Downloaded {name}", "تم تنزيل {name}"), + ("Drag onto an output channel", "اسحب إلى قناة إخراج"), + ("Drags the layer stack's values along the stroke into the selected layer.", "يسحب قيم مكدس الطبقات على طول الضربة إلى الطبقة المحددة."), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "يرسم {name} لمجموعة الخامات \"{set}\". التعديلات على المصدر تظهر في كل نسخة.", + ), + ( + "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", + "اسحب الإطار لتحريك الملصق، أو الزاوية لتغيير حجمه، أو المقبض الدائري لتدويره", + ), + ("Drop an image from the Assets panel here to use it as this mesh map", "أفلت صورة من لوحة الأصول هنا لاستخدامها كخريطة المجسم هذه"), + ("Dry streaks", "خطوط جافة"), + ("Duplicate effect", "تكرار التأثير"), + ("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"), + ("Duplicate the selected template", "تكرار القالب المحدد"), + ("Edge Detect", "اكتشاف الحواف"), + ("Edit", "تحرير"), + ("Edit keyboard shortcuts...", "تعديل اختصارات لوحة المفاتيح..."), + ("Edit quick mask", "تحرير القناع السريع"), + ("Editing quick mask: paint where painting is allowed (U to finish)", "تحرير القناع السريع: ارسم حيث يُسمح بالرسم (اضغط U للإنهاء)"), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "تحرير القناع السريع: ترسم الضربات حيث يُسمح بالرسم. اضغط U للإنهاء.", + ), + ("Emissive", "إشعاع"), + ("Enable or disable the effect", "تمكين أو تعطيل التأثير"), + ("Enable quick mask", "تمكين القناع السريع"), + ("Environment blur", "تمويه البيئة"), + ("Environment exposure (EV)", "تعريض البيئة (EV)"), + ("Environment map", "خريطة البيئة"), + ("Environment opacity", "عتامة البيئة"), + ("Environment rotation", "دوران البيئة"), + ("Environment settings", "إعدادات البيئة"), + ("Environment: {name}", "البيئة: {name}"), + ("Environments", "البيئات"), + ("Eraser", "ممحاة"), + ("Exclusion", "استبعاد (Exclusion)"), + ("Expand or collapse the folder", "توسيع المجلد أو طيه"), + ("Export", "تصدير"), + ("Export Mesh...", "تصدير المجسم..."), + ("Export Textures...", "تصدير الخامات..."), + ("Export mesh", "تصدير المجسم"), + ("Export template", "تصدير القالب"), + ("Export templates", "تصدير القوالب"), + ("Export textures", "تصدير الخامات"), + ("Export the selected template (.json)", "تصدير القالب المحدد (.json)"), + ("Exported mesh to {path}", "تم تصدير المجسم إلى {path}"), + ("Exported template \"{name}\" to {path}", "تم تصدير القالب \"{name}\" إلى {path}"), + ("Exported {n} textures to {folder}", "تم تصدير {n} خامة إلى {folder}"), + ("F0 from specular level", "F0 من مستوى اللمعان"), + ("Fabric weave", "نسيج قماش"), + ("Field of view (deg)", "مجال الرؤية (بالدرجات)"), + ("File", "ملف"), + ("File name without extension; variables insert names", "اسم الملف بدون الامتداد؛ تُدرج المتغيرات الأسماء"), + ("File type", "نوع الملف"), + ("Fill", "تعبئة"), + ("Fill the closed path (lasso)", "تعبئة المسار المغلق (حبل التحديد)"), + ("Fill the path (close it first)", "تعبئة المسار (أغلقه أولاً)"), + ("Filter", "مرشح"), + ("Filter the remaining noise while keeping edges and texture detail", "تصفية الضوضاء المتبقية مع الحفاظ على الحواف وتفاصيل الخامة"), + ("Filters", "مرشحات"), + ("Fine noise", "ضوضاء دقيقة"), + ("Fingerprints", "بصمات أصابع"), + ("Enter a finite number", "أدخل عددًا محدودًا"), + ("Double-click or press Enter to edit", "انقر نقرًا مزدوجًا أو اضغط Enter للتعديل"), + ("Fit the input range to the histogram", "ملاءمة نطاق الإدخال مع المدرج التكراري"), + ("Flatten layer", "تسطيح الطبقة"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "يقلب القناة الخضراء للصورة، لخرائط النواظم المصنوعة ومحور Y يشير إلى الأسفل", + ), + ("Flow", "التدفق"), + ("Flow and opacity", "التدفق والعتامة"), + ("Flow jitter", "اضطراب التدفق"), + ("Focus distance", "مسافة التركيز"), + ("Folder", "مجلد"), + ("Folders", "مجلدات"), + ("Follow path", "اتباع المسار"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "للمشروع كله: طريقة قراءة صور خرائط النواظم المعيَّنة كخرائط للمجسم (أعد تعيينها بعد التغيير) والقيمة الافتراضية للتصدير", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "مجاني ومفتوح المصدر (MIT أو Apache-2.0)، كُتب بلغة Rust."), + ("From template", "من قالب"), + ("From template / project", "من قالب / مشروع"), + ("Full", "كامل"), + ("GPU error: {error}", "خطأ في GPU: {error}"), + ("Geometry mask", "قناع هندسي"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "لمعان GGX مع رؤية سميث المرتبطة بالارتفاع، وانتشار لامبرت، وإضاءة معتمدة على الصور بمجموع مقسم مع إشعاع توافقيات كروية وتلاشي الأفق.", + ), + ("Gamma", "غاما (Gamma)"), + ("General export parameters", "معلمات التصدير العامة"), + ("General properties", "الخصائص العامة"), + ("Generator", "مولّد"), + ("Geometry and UVs only", "الهندسة وإحداثيات UV فقط"), + ("Glossiness", "الصفاء (Glossiness)"), + ("Glossiness from roughness", "الصفاء من الخشونة"), + ("Glow", "توهج"), + ("Gradient", "تدرج لوني"), + ("Gradient Map", "خريطة التدرج"), + ("Gravity", "الجاذبية"), + ("Gray", "رمادي"), + ("Gray + A", "رمادي + A"), + ("Gray 50%", "رمادي 50%"), + ("Grayscale", "تدرج رمادي"), + ("Group layer(s)", "تجميع الطبقة (الطبقات)"), + ("Grunge", "تعتيق (Grunge)"), + ("HDR environments", "بيئات HDR"), + ("High Pass", "تمرير عالي (High Pass)"), + ("HSL Perceptive", "HSL إدراكي"), + ("Half", "نصف"), + ("Hammered", "مطروق"), + ("Hard light", "ضوء ساطع (Hard Light)"), + ("Hardness", "الصلابة"), + ("Height", "الارتفاع"), + ("Height offset", "إزاحة الارتفاع"), + ("Height to normal strength", "قوة تحويل الارتفاع إلى ناظم"), + ("Help", "مساعدة"), + ("Hide UI", "إخفاء واجهة المستخدم"), + ("High", "عالي"), + ("High poly: {name}", "عالي الدقة: {name}"), + ("Highlights", "المناطق المضيئة"), + ("Histogram Range", "نطاق المدرج التكراري"), + ("Histogram Scan", "مسح المدرج التكراري"), + ("Histogram Shift", "إزاحة المدرج التكراري"), + ("History", "السجل"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "استمر بالضغط على S: السحب بالزر الأيسر يدوّر، والأيمن يغيّر الحجم، والأوسط يحرّك الستنسل.", + ), + ("Hold V and click the mesh to set the clone source", "استمر بالضغط على V وانقر على المجسم لتعيين مصدر الاستنساخ"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "استمر بالضغط على V وانقر على المجسم لتعيين المصدر، ثم ارسم في مكان آخر لنسخه.", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "المسافة التي ينتقل بها الضوء تحت السطح، كنسبة من حجم المجسم (حيث تُرسَم قناة وزن التشتت)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "مدى انكسار الضوء في الأسطح النافذة (حيث تُرسَم قناة النفاذية): ماء 1.33، زجاج 1.5، ألماس 2.42", + ), + ("Hue shift (degrees)", "إزاحة تدرج اللون (بالدرجات)"), + ("ID", "المُعرّف (ID)"), + ("Image: {name}", "صورة: {name}"), + ("Images", "صور"), + ("Import HDR...", "استيراد HDR..."), + ("Import a template (.json)", "استيراد قالب (.json)"), + ("Import an image (File > Import resources) to project it onto the mesh.", "استورد صورة (ملف > استيراد الموارد) لإسقاطها على المجسم."), + ("Import resources...", "استيراد الموارد..."), + ("Import MaterialX material...", "استيراد مادة MaterialX..."), + ("MaterialX materials", "مواد MaterialX"), + ("Import...", "استيراد..."), + ("Imported template \"{name}\"", "تم استيراد القالب \"{name}\""), + ("Imported {name}", "تم استيراد {name}"), + ("Index of refraction", "معامل الانكسار"), + ("Input high", "المدخل العالي"), + ("Input low", "المدخل المنخفض"), + ("Input maps", "خرائط المدخلات"), + ("Insert a variable", "إدراج متغير"), + ("Instance", "نسخة مرتبطة (Instance)"), + ("Instantiate across texture sets", "إنشاء نسخ مرتبطة عبر مجموعات الخامات"), + ("Intensity (texels at 2K)", "الشدة (تكسل بدقة 2K)"), + ("Interface", "الواجهة"), + ("Interface scale", "مقياس الواجهة"), + ("Inverse Subtract", "طرح عكسي"), + ("Inverse divide", "قسمة عكسية"), + ("Invert", "عكس"), + ("Invert mask", "عكس القناع"), + ("Invert mask background", "عكس خلفية القناع"), + ("Invert mask value", "عكس قيمة القناع"), + ("Invert quick mask", "عكس القناع السريع"), + ("Jitters", "اضطرابات (Jitters)"), + ("Join the ArtCraft community on Discord", "انضم إلى مجتمع ArtCraft على Discord"), + ("Join the community (Discord)...", "الانضمام إلى المجتمع (Discord)..."), + ("Key light (shadow-casting light, direct only)", "الضوء الرئيسي (ضوء ملقي للظلال، مباشر فقط)"), + ("Keyboard", "لوحة المفاتيح"), + ("Keyboard shortcuts", "اختصارات لوحة المفاتيح"), + ("Light azimuth (degrees)", "سمت الضوء (بالدرجات)"), + ("Light elevation (degrees)", "ارتفاع الضوء (بالدرجات)"), + ("Light intensity", "شدة الضوء"), + ("LMB", "زر الفأرة الأيسر"), + ("Language", "اللغة"), + ("Layer mask", "قناع الطبقة"), + ("Layer memory: {mb} MB", "ذاكرة الطبقات: {mb} ميغابايت"), + ("Layers", "الطبقات"), + ("Lazy mouse", "الفأرة الكسولة (Lazy mouse)"), + ("Lazy mouse distance", "مسافة الفأرة الكسولة"), + ("Leather grain", "حبيبات جلدية"), + ("Lens size: how quickly things blur away from the focus distance", "حجم العدسة: سرعة تمويه العناصر البعيدة عن مسافة التركيز"), + ("Level", "المستوى"), + ("Levels", "المستويات"), + ("Lifetime (steps)", "عمر الجسيم (بالخطوات)"), + ("Light / direction", "الضوء / الاتجاه"), + ("Lighten (Max)", "تفتيح (الحد الأقصى)"), + ("Lightness", "الإضاءة"), + ("Linear", "خطي"), + ("Linear burn", "حرق خطي (Linear Burn)"), + ("Linear dodge (Add)", "تفتيح خطي (إضافة)"), + ("Linear light", "ضوء خطي (Linear Light)"), + ("List of exports", "قائمة الصادرات"), + ("Load UI Layout", "تحميل تخطيط الواجهة"), + ("Loaded UI layout {path}", "تم تحميل تخطيط الواجهة {path}"), + ("Log", "السجل"), + ("Low", "منخفض"), + ("Luminosity", "اللمعان (Luminosity)"), + ("MMB drag / Alt + MMB", "سحب بزر الفأرة الأوسط / Alt + زر الفأرة الأوسط"), + ("Made by the ArtCraft team and community.", "صُنع بواسطة فريق ArtCraft والمجتمع."), + ("Magenta / green", "أرجواني / أخضر"), + ("Main shader", "المظلل الرئيسي"), + ("Marble veins", "عروق الرخام"), + ("Mask", "قناع"), + ("Mask Editor: Edge wear", "محرر الأقنعة: تآكل الحواف"), + ("Mask value (gray)", "قيمة القناع (رمادي)"), + ("Mask with height", "قناع بالارتفاع"), + ("MatFinish Grind", "إنهاء المادة: جلخ"), + ("MatFinish Hammered", "إنهاء المادة: مطروق"), + ("MatFinish Raw", "إنهاء المادة: خام"), + ("MatFinish Sanded", "إنهاء المادة: مصنفر"), + ("Material", "المادة"), + ("Material ball", "كرة المادة"), + ("Material finish", "إنهاء المادة"), + ("Materials", "المواد"), + ("Maximum", "الحد الأقصى"), + ("Mesh fill", "تعبئة المجسم"), + ("Mesh map: {map}", "خريطة المجسم: {map}"), + ("Mesh maps", "خرائط المجسم"), + ("Mesh maps baked", "تم خبز خرائط المجسم"), + ("Meshes", "المجسمات"), + ("Metallic", "معدنية"), + ("Midtones", "درجات الإضاءة المتوسطة"), + ("Minimum", "الحد الأدنى"), + ("Minimum size (%)", "الحد الأدنى للحجم (%)"), + ("Missing (bake to create)", "مفقود (اخبز للإنشاء)"), + ("Mixed AO", "انسداد محيطي مختلط"), + ("Mode", "النمط"), + ("More in Assets > Alphas: click one, or drag it here", "المزيد في الأصول > أقنعة ألفا: انقر على واحد، أو اسحبه إلى هنا"), + ("Mosaic", "فسيفساء"), + ("Move down", "تحريك لأسفل"), + ("Move up", "تحريك لأعلى"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "يحرك السطح وفق قناة الارتفاع على نسخة أدق من المجسم، بقوة تحويل الارتفاع إلى ناظم (منفذ العرض فقط: الرسم يتبع السطح الأساسي)", + ), + ("Multiply", "ضرب"), + ("My smart materials", "موادي الذكية"), + ("Name", "الاسم"), + ("New project", "مشروع جديد"), + ("New project...", "مشروع جديد..."), + ("New template", "قالب جديد"), + ("No GPU renderer available", "لا يتوفر مصيّر GPU"), + ("No font on this system can show this language", "لا يوجد خط على هذا النظام يمكنه عرض هذه اللغة"), + ("No outputs yet: add one above, then drag input maps onto its channels.", "لا توجد مخرجات بعد: أضف مخرجاً بالأعلى، ثم اسحب خرائط المدخلات إلى قنواته."), + ("No padding (passthrough)", "بدون حشو (تمرير مباشر)"), + ("Noise amount", "كمية الضوضاء"), + ("Noise scale", "مقياس الضوضاء"), + ("None", "بلا"), + ("Normal", "عادي"), + ("Normal DirectX", "ناظم DirectX"), + ("Normal Invert", "عكس الناظم"), + ("Normal OpenGL", "ناظم OpenGL"), + ("Normal from height", "ناظم من الارتفاع"), + ("Normal map combine", "دمج خرائط النواظم"), + ("Normal map detail", "تفاصيل خريطة النواظم"), + ("Color space", "فضاء الألوان"), + ("Normal map format", "صيغة خريطة النواظم"), + ("Normal map inverse detail", "عكس تفاصيل خريطة النواظم"), + ("Normal: painting uses the flat normal", "عادي: يستخدم الرسم الناظم المسطح"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "لا توجد ذاكرة GPU كافية لعرض مجموعة الخامات \"{name}\" كاملة: خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "لا توجد ذاكرة GPU كافية لعرض {count} من مجموعات الخامات كاملة ({names}): خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", + ), + ("Not exported: no source in this texture set", "لم يتم التصدير: لا يوجد مصدر في مجموعة الخامات هذه"), + ("Not saved: {error}", "لم يتم الحفظ: {error}"), + ("Off", "معطل"), + ("Offset", "إزاحة"), + ("Offset right", "إزاحة لليمين"), + ("Offset up", "إزاحة لأعلى"), + ("Offset {axis}", "إزاحة {axis}"), + ("Offsets the textures by the height channel, at the height to normal strength", "يزيح الخامات وفق قناة الارتفاع، بقوة تحويل الارتفاع إلى ناظم"), + ("On", "مفعل"), + ("Opacity", "العتامة"), + ("Open sample project...", "فتح مشروع نموذجي..."), + ("Open...", "فتح..."), + ("Opened {name}", "تم فتح {name}"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "تضيف القنوات الاختيارية طبقة طلاء شفافة (وزن الطلاء، خشونة الطلاء، ناظم الطلاء)، ولمعاناً (وزن اللمعان، لونه، خشونته)، وتباين الخواص (مستوى التباين، زاويته)، وتشتتاً تحت السطح (وزن التشتت)، ونفاذية (النفاذية).", + ), + ("Orbit", "مدار"), + ("Orthographic", "متوازي (إملائي)"), + ("Perspective", "منظوري"), + ("Output directory", "دليل الإخراج"), + ("Output high", "المخرج العالي"), + ("Output low", "المخرج المنخفض"), + ("Output template", "قالب الإخراج"), + ("Output templates", "قوالب الإخراج"), + ("Overlay", "تراكب (Overlay)"), + ("Overlay opacity", "عتامة التراكب"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - خشونة ومعدنية (TextureCraft)"), + ("Pick color", "التقاط لون"), + ("PNG image", "صورة PNG"), + ("Padding", "الحشو (Padding)"), + ("Paint", "رسم"), + ("Paint chips", "قشور الطلاء"), + ("Paint on the mesh to edit the layer content.", "ارسم على المجسم لتعديل محتوى الطبقة."), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "ارسم على المجسم لتعديل هذا القناع. استخدم قيمة القناع في لسان تبويب المادة للتدرج الرمادي.", + ), + ("Paint with the current tool", "الرسم بالأداة الحالية"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "بكسلات الطبقات المرسومة {pixels} ميغابايت، القنوات المركبة {composites} ميغابايت، ذاكرة التخزين المؤقت للتركيب {cache} ميغابايت", + ), + ("Painting", "الرسم"), + ("Pan", "تحريك العرض (Pan)"), + ("Parallax occlusion (height channel)", "إزاحة المنظور (قناة الارتفاع)"), + ("Partial mask values follow the layer's height: high parts show first", "قيم القناع الجزئية تتبع ارتفاع الطبقة: تظهر الأجزاء المرتفعة أولاً"), + ("Particle brush (slides down the surface)", "فرشاة الجسيمات (تنزلق على السطح)"), + ("Particle brush: particles slide down the surface", "فرشاة الجسيمات: تنزلق الجسيمات على السطح"), + ("Particles", "جسيمات"), + ("Passthrough", "تمرير مباشر (Passthrough)"), + ("Paste as instance", "لصق كنسخة مرتبطة (Instance)"), + ("Paste effect", "لصق التأثير"), + ("Paste layer(s)", "لصق الطبقة (الطبقات)"), + ("Path", "مسار"), + ("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "المسار: النقر يضيف نقطة، والنقر على المنحنى يُدرج نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي", + ), + ("Pattern scale", "مقياس النمط"), + ("Perlin noise", "ضوضاء بيرلن (Perlin)"), + ("Pick focus in the viewport", "اختر نقطة التركيز في منفذ العرض"), + ("Pin light", "ضوء مثبت (Pin Light)"), + ("Place on the surface", "وضع على السطح"), + ("Place path points on the mesh", "وضع نقاط المسار على المجسم"), + ("Planar projection", "إسقاط مستوٍ"), + ("Plane", "مستوٍ"), + ("Polygon fill", "تعبئة مضلع"), + ("Pores", "مسام"), + ("Position", "الموضع"), + ("Position gradient", "تدرج الموضع"), + ("Position jitter", "اضطراب الموضع"), + ("Posterize", "تبسيط الألوان (Posterize)"), + ("Press a key...", "اضغط على مفتاح..."), + ("Project", "المشروع"), + ("Project Configuration...", "تكوين المشروع..."), + ("Project opened", "تم فتح المشروع"), + ("Project template", "قالب المشروع"), + ("Projection", "الإسقاط"), + ("Projects and meshes", "المشاريع والمجسمات"), + ("Properties", "الخصائص"), + ("Quarter", "ربع"), + ("Quick mask", "قناع سريع"), + ("Quit", "إنهاء"), + ("Radius (texels at 2K)", "نصف القطر (تكسل بدقة 2K)"), + ("RENDERING", "التصيير"), + ("Range", "النطاق"), + ("Rebind any menu item, tool or command", "إعادة ربط أي عنصر قائمة، أو أداة أو أمر"), + ("Recent projects", "المشاريع الأخيرة"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "يسجل المكدس حتى هذه الطبقة. يمكن لتأثيرات التعبئة في الأقنعة (وطبقات التعبئة) بالأعلى قراءته كمصدر.", + ), + ("Redo", "إعادة"), + ("Reimport mesh", "إعادة استيراد المجسم"), + ("Remove", "إزالة"), + ("Remove channel", "إزالة القناة"), + ("Remove effect", "إزالة التأثير"), + ("Remove last", "إزالة الأخير"), + ("Remove layer", "إزالة الطبقة"), + ("Remove layer(s)", "إزالة الطبقة (الطبقات)"), + ("Remove mask", "إزالة القناع"), + ("Remove point", "إزالة النقطة"), + ("Remove resource", "إزالة المورد"), + ("Remove the shortcut", "إزالة الاختصار"), + ("Remove this output", "إزالة هذا المخرج"), + ("Remove unused resources...", "إزالة الموارد غير المستخدمة..."), + ("Rename the selected template", "إعادة تسمية القالب المحدد"), + ("Render on the CPU", "التصيير على المعالج (CPU)"), + ("Rendering", "التصيير"), + ("Rendering (path traced)", "التصيير (بتتبع المسار)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "التصيير على المعالج (CPU): {n} / {max} عينة، {s} ث"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "التصيير على المعالج الرسومي (GPU): {n} / {max} عينة، {s} ث"), + ("Rendering, path traced", "التصيير، بتتبع المسار"), + ("Replace", "استبدال"), + ("Replace Color", "استبدال اللون"), + ("Replacement color", "لون الاستبدال"), + ("Report a bug...", "الإبلاغ عن خطأ..."), + ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), + ("Reset", "إعادة تعيين"), + ("Reset UI", "إعادة ضبط واجهة المستخدم"), + ("Reset all", "إعادة ضبط الكل"), + ("Reset to defaults", "إعادة الضبط إلى الإعدادات الافتراضية"), + ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), + ("Resizing", "تغيير الحجم"), + ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), + ("Return to this step", "العودة إلى هذه الخطوة"), + ("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"), + ("Rotation", "التدوير"), + ("Rotation (degrees)", "التدوير (بالدرجات)"), + ("Roughness", "الخشونة"), + ("Roughness from glossiness", "الخشونة من الصفاء"), + ("Round", "دائري"), + ("Rounded cube", "مكعب مدور الزوايا"), + ("Samples", "العينات"), + ("Saturation", "التشبع"), + ("Save", "حفظ"), + ("Save UI Layout", "حفظ تخطيط الواجهة"), + ("Save a copy...", "حفظ نسخة..."), + ("Save as...", "حفظ باسم..."), + ("Save current layout...", "حفظ التخطيط الحالي..."), + ("Save render...", "حفظ التصيير..."), + ("Save view as camera", "حفظ المنظور ككاميرا"), + ("Saved UI layout {path}", "تم حفظ تخطيط الواجهة {path}"), + ("Saved {path}", "تم الحفظ في {path}"), + ("Saving UI layouts to files is available in the desktop app", "حفظ تخطيطات الواجهة إلى ملفات متاح في تطبيق سطح المكتب"), + ("Scale", "المقياس"), + ("Scale / tiling", "المقياس / التكرار"), + ("Scatter color", "لون التشتت"), + ("Scatter radius", "نصف قطر التشتت"), + ("Scattering weight", "وزن التشتت"), + ("Scratches", "خدوش"), + ("Screen", "شاشة (Screen)"), + ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), + ("Search", "بحث"), + ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), + ("Seed", "البذرة العشوائية (Seed)"), + ("Select a layer", "تحديد طبقة"), + ("Select an output template", "تحديد قالب إخراج"), + ("Select source", "تحديد المصدر"), + ("Select the mask (Alt+click: show it in the viewport)", "تحديد القناع (Alt+نقر: عرضه في منفذ العرض)"), + ("Select...", "تحديد..."), + ("Settings", "الإعدادات"), + ("Settings...", "الإعدادات..."), + ("Shader Settings", "إعدادات المظلل"), + ("Shader instance", "نسخة المظلل"), + ("Shadows", "الظلال"), + ("Sharpen", "توضيح الحواف (Sharpen)"), + ("Sheen color", "لون اللمعان"), + ("Sheen color × weight", "لون اللمعان × الوزن"), + ("Sheen roughness", "خشونة اللمعان"), + ("Sheen weight", "وزن اللمعان"), + ("Shift + wheel", "Shift + عجلة الفأرة"), + ("Shortcuts list...", "قائمة الاختصارات..."), + ("Show on all parts", "إظهار على جميع الأجزاء"), + ("Show UV wireframe in the 2D view", "إظهار الهيكل السلكي لـ UV في العرض ثنائي الأبعاد"), + ("Show entire mesh", "إظهار المجسم كاملاً"), + ("Show log...", "إظهار السجل..."), + ("Show or hide the layer", "إظهار أو إخفاء الطبقة"), + ("Show or hide the texture set", "إظهار أو إخفاء مجموعة الخامات"), + ("Show wireframe in the 3D view", "إظهار الهيكل السلكي في العرض ثلاثي الأبعاد"), + ("Signed addition (AddSub)", "جمع ذو إشارة (AddSub)"), + ("Size", "الحجم"), + ("Size in screen space", "الحجم في فضاء الشاشة"), + ("Size jitter", "اضطراب الحجم"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "حجم الخامات التي يعرضها منفذ العرض: الحجم الأصغر يستهلك ذاكرة GPU أقل مع مجموعات الخامات الكبيرة. يحتفظ الرسم والتصدير بالدقة الكاملة.", + ), + ("Slope Blur", "تمويه المنحدر (Slope Blur)"), + ("Slope scale", "مقياس المنحدر"), + ("Smart masks", "أقنعة ذكية"), + ("Smart material saved to {path}", "تم حفظ المادة الذكية في {path}"), + ("Smart materials", "مواد ذكية"), + ("Smudge", "تلطيخ (Smudge)"), + ("Soft light", "ضوء خافت (Soft Light)"), + ("Softness", "النعومة"), + ("Source", "المصدر"), + ("Source U {u} V {v}", "المصدر U {u} V {v}"), + ("Spacing", "التباعد"), + ("Specular", "اللمعان (Specular)"), + ("Specular level", "مستوى اللمعان"), + ("Sphere", "كرة"), + ("Spherical projection", "إسقاط كروي"), + ("Spray", "رش (Spray)"), + ("Square", "مربع"), + ("Stamp depth", "عمق الطبعة"), + ("Star", "نجمة"), + ("Starting render...", "بدء التصيير..."), + ("Stencil", "ستنسل (Stencil)"), + ("Steps", "الخطوات"), + ("Streaks", "خطوط"), + ("Strength", "القوة"), + ("Stripes", "أشرطة"), + ("Stroke opacity", "عتامة الضربة"), + ("Subsampling 2x2", "استعيان فرعي 2×2"), + ("Subsampling 4x4", "استعيان فرعي 4×4"), + ("Subsampling 8x8", "استعيان فرعي 8×8"), + ("Subsurface scattering", "تشتت تحت السطح (SSS)"), + ("Subtract", "طرح"), + ("Tangent | Wrap", "مماس | التفاف"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "تنعيم حواف زمني (يحسّن العرض ثلاثي الأبعاد أثناء ثباته)"), + ("Texture Sets", "مجموعات الخامات"), + ("Texture Set Settings", "إعدادات مجموعة الخامات"), + ("Texture resolution", "دقة الخامة"), + ("Texture set channels", "قنوات مجموعة الخامات"), + ("Texture sets", "مجموعات الخامات"), + ("TextureCraft had to close:", "اضطر TextureCraft إلى الإغلاق:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - خشونة ومعدنية"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - لمعان وصفاء"), + ("TextureCraft project", "مشروع TextureCraft"), + ("TextureCraft project or mesh", "مشروع أو مجسم TextureCraft"), + ("Textures", "الخامات"), + ("Textures embedded; for game engines and most viewers", "الخامات مدمجة؛ لمحركات الألعاب ومعظم برامج العرض"), + ("Textures packaged; for USD tools and AR Quick Look", "الخامات محزومة؛ لأدوات USD وميزة المعاينة السريعة للواقع المعزز"), + ("The GPU couldn't render this scene: {error}", "تعذر على معالج الرسوميات (GPU) تصيير هذا المشهد: {error}"), + ("The bake worker stopped", "توقف عامل الخبز"), + ("The eraser removes paint from the enabled channels.", "تزيل الممحاة الطلاء من القنوات الممكنة."), + ("The first stroke sets the offset from the source.", "تحدد الضربة الأولى الإزاحة عن المصدر."), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "تقطع ألفا الصورة شكل الملصق؛ وتبقى الوجوه المتجهة بعيداً والأسطح التي تتجاوز عمقها واضحة.", + ), + ("The next click in the 3D view moves the decal there", "النقر التالي في العرض ثلاثي الأبعاد ينقل الملصق إلى هناك"), + ("The resize worker stopped", "توقف عامل تغيير الحجم"), + ("Thickness", "السماكة"), + ("Thin areas", "المناطق الرقيقة"), + ("Threshold", "العتبة (Threshold)"), + ("Tile", "تكرار (Tile)"), + ("Tiles", "بلاطات"), + ("Tint", "صبغة"), + ("Toggle mask", "تبديل القناع"), + ("Tolerance", "التفاوت (Tolerance)"), + ("Tone mapping", "مطابقة درجات الألوان (Tone mapping)"), + ("Tools", "الأدوات"), + ("Torus", "طارة (Torus)"), + ("Transmission", "النفاذية (Transmission)"), + ("Tri-planar projection", "إسقاط ثلاثي المستويات (Tri-planar)"), + ("Triangle fill", "تعبئة مثلث"), + ("UDIM plane", "مستوي UDIM"), + ("UDIM tiles painted by this texture set, each at the set's size", "بلاطات UDIM المرسومة بمجموعة الخامات هذه، كل منها بحجم المجموعة"), + ("UI layout", "تخطيط الواجهة"), + ("UI layout: {error}", "تخطيط الواجهة: {error}"), + ("UI layouts", "تخطيطات الواجهة"), + ("UI {ms} ms", "واجهة المستخدم {ms} مللي ثانية"), + ("USD binary, textures alongside", "USD ثنائي، الخامات بجانبه"), + ("USD text, textures alongside", "USD نصي، الخامات بجانبه"), + ("USDZ with textures", "USDZ مع الخامات"), + ("UV checker", "رقعة فحص UV"), + ("UV island fill", "تعبئة جزيرة UV"), + ("UV transformations", "تحويلات UV"), + ("UV projection", "إسقاط UV"), + ("UV tiles", "بلاطات UV"), + ("UV tiles (UDIM)", "بلاطات UV (UDIM)"), + ("Undo", "تراجع"), + ("Uniform value", "قيمة موحدة"), + ("Use an equirectangular .hdr or .exr image as the environment", "استخدم صورة .hdr أو .exr متساوية المستطيلات كبيئة"), + ("Use the control channel or `texturecraft-cli render` for screenshots", "استخدم قناة التحكم أو الأمر `texturecraft-cli render` لالتقاط لقطات الشاشة"), + ("Value", "القيمة"), + ("Version {version}", "الإصدار {version}"), + ("Version: {version} ({gpu})", "الإصدار: {version} ({gpu})"), + ("View through this camera", "الرؤية من خلال هذه الكاميرا"), + ("Viewer settings", "إعدادات العارض"), + ("Viewport", "منفذ العرض"), + ("Viewport and brush (fixed)", "منفذ العرض والفرشاة (ثابت)"), + ("Views", "طرق العرض"), + ("Vivid light", "ضوء ساطع (Vivid Light)"), + ("Voronoi", "فورونوي (Voronoi)"), + ("Warp", "التواء (Warp)"), + ("Warp Directional", "التواء اتجاهي"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ مع MTL، والخامات بجانبه"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "WebGPU غير متاح في هذا المتصفح، لذا يعمل TextureCraft على WebGL2: نمط التصيير يتتبع المسار على المعالج (أبطأ) ومجموعات الخامات الكبيرة تظهر بدقة مخفضة. يتوفر WebGPU في الإصدارات الحديثة من Chrome وEdge وSafari.", + ), + ("Wheel / Alt + RMB drag", "العجلة / سحب بـ Alt + زر الفأرة الأيمن"), + ("White", "أبيض"), + ("Width", "العرض"), + ("Width (texels at 2K)", "العرض (تكسل بدقة 2K)"), + ("Window", "نافذة"), + ("Wood grain", "حبيبات الخشب"), + ("Works in texture space, like the blur: it does not cross UV seams.", "يعمل في فضاء الخامات، مثل التمويه: لا يعبر درزات UV."), + ("World Space Normal", "ناظم الفضاء العالمي"), + ("Yellow / blue", "أصفر / أزرق"), + ("Zoom", "تكبير/تصغير"), + ("a missing layer", "طبقة مفقودة"), + ("aniso", "تباين"), + ("aniso angle", "زاوية التباين"), + ("ao", "انسداد محيطي"), + ("coat", "طلاء"), + ("coat nrm", "ناظم الطلاء"), + ("coat rough", "خشونة الطلاء"), + ("color", "لون"), + ("emiss", "إشعاع"), + ("glTF binary with textures", "glTF ثنائي مع الخامات"), + ("gloss", "صفاء"), + ("height", "ارتفاع"), + ("metal", "معدن"), + ("min", "د"), + ("missing", "مفقود"), + ("missing source", "مصدر مفقود"), + ("no GPU", "بدون GPU"), + ("none", "بلا"), + ("nrm", "ناظم"), + ("off", "معطل"), + ("op", "عتامة"), + ("rough", "خشونة"), + ("scatter", "تشتت"), + ("sheen", "لمعان"), + ("sheen color", "لون اللمعان"), + ("sheen rough", "خشونة اللمعان"), + ("spec", "لمعان"), + ("specular", "لمعان"), + ("transm", "نفاذية"), + ("{action} (undone)", "{action} (تم التراجع)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file}: إضافة فوق الطبقة المحددة (أو اسحبها إلى مكدس الطبقات أو إلى منفذ العرض)", + ), + ("{name} copy", "نسخة من {name}"), + ("{n} bits", "{n} بت"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "{n} نقاط تحكم. انقر على المجسم (أو العرض ثنائي الأبعاد) لإضافة نقاط واسحبها للضبط؛ وانقر على النقطة الأولى لإغلاق المسار. مفتاح Enter يرسمه بالفرشاة (المسار المغلق والمملوء يملأ داخله)، وEsc يلغي.", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} عناصر تشترك في نفس الاختصار؛ العنصر الأول المدرج له الأولوية."), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (المقياس {scale}، البذرة {seed})"), + ("Template name", "اسم القالب"), + ("Save current project as template", "حفظ المشروع الحالي كقالب"), + ("Distribution", "التوزيع"), + ("Cosine", "جيب التمام (Cosine)"), + ("Uniform", "موحد (Uniform)"), + ("Normalization", "تسوية (Normalization)"), + ("Brightness", "السطوع"), + ("Dark", "داكن"), + ("Medium dark", "متوسط الدكنة"), + ("Medium light", "متوسط السطوع"), + ("Light", "فاتح"), + ("Accent color", "لون التمييز"), + ("Copper", "نحاسي"), + ("Coral", "مرجاني"), + ("Blue", "أزرق"), + ("Violet", "بنفسجي"), + ("Green", "أخضر"), + ("Amber", "كهرماني"), + ("Pink", "وردي"), + ("Minimize", "تصغير"), + ("Maximize", "تكبير"), + ("Restore", "استعادة"), + ("Title bar", "شريط العنوان"), + ("System title bar (applies on restart)", "شريط عنوان النظام (يُطبّق عند إعادة التشغيل)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", + ), + ("Brushes", "الفرش"), + ("Brush name", "اسم الفرشاة"), + ("Save current brush", "حفظ الفرشاة الحالية"), + ("Start window", "نافذة البدء"), + ("Show at startup", "إظهار عند بدء التشغيل"), + ("Continue with the sample project", "المتابعة مع المشروع النموذجي"), + ("No recent projects yet", "لا توجد مشاريع حديثة بعد"), + ("Text", "نص"), + ("Font", "الخط"), + ("Style", "النمط"), + ("Use as brush alpha", "استخدام كألفا للفرشاة"), + ("Place as decal", "وضع كملصق"), + ("Click: turn this channel on or off. Alt+click: this channel only", "انقر: تشغيل هذه القناة أو إيقافها. Alt+نقر: هذه القناة فقط"), + ("Show all", "إظهار الكل"), + ("Hide all", "إخفاء الكل"), + ("Invert show/hide", "عكس الإظهار/الإخفاء"), + ("Show or hide texture sets", "إظهار مجموعات الخامات أو إخفاؤها"), + ("Focus: show only the active texture set", "تركيز: إظهار مجموعة الخامات النشطة فقط"), + ("Unsaved changes", "تغييرات غير محفوظة"), + ("Don't save", "عدم الحفظ"), + ("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"), + ("Radius", "نصف القطر"), + ("Remove skew correction", "إزالة تصحيح الانحراف"), + ("Twill weave", "نسيج مائل"), + ("Save the changes to {name} first?", "هل تريد حفظ التغييرات في {name} أولًا؟"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "تبقى المسارات قابلة للتعديل: اختر مسارًا لتحريك نقاطه أو تغيير فرشاته ومادته، فتُعاد رسم الطبقة الفرعية فورًا. أضف المسارات بأداة المسار.", + ), + ("Import material...", "استيراد خامة..."), + ("MaterialCraft material", "خامة MaterialCraft"), + ("Cooked at {size} px", "حُسبت بدقة {size} بكسل"), + ("Preset", "إعداد مسبق"), + ("Re-cook", "إعادة الحساب"), + ("Open in MaterialCraft", "فتح في MaterialCraft"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "فُتحت في MaterialCraft: استخدم هناك ملف > إرسال إلى TextureCraft لإعادة تغييراتك", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "تتغير المعلمات في تطبيق سطح المكتب مع تثبيت MaterialCraft"), + ("Add High-Poly Meshes", "إضافة مجسمات عالية التفاصيل"), + ("All", "الكل"), + ("Apply Diffusion", "تطبيق الانتشار"), + ("Attenuation", "التوهين"), + ("Auto Tonemapping", "تعيين درجات الألوان تلقائيًا"), + ("Average Normals", "توسيط النواظم"), + ("BBox", "صندوق الإحاطة"), + ("BSphere", "كرة الإحاطة"), + ("Mesh Map Bakers", "مُخبِزات خرائط المجسم"), + ("Common Settings", "الإعدادات المشتركة"), + ("Mesh Map Settings", "إعدادات خرائط المجسم"), + ("Check All", "تحديد الكل"), + ("No Parameters", "لا توجد معلمات"), + ("Bake Selected Textures ({n})", "خبز الخامات المحددة ({n})"), + ("By Mesh Name", "حسب اسم المجسم"), + ("Cage", "القفص"), + ("Cage Scene", "مشهد القفص"), + ("Cage Type", "نوع القفص"), + ("Color Generator", "مولد الألوان"), + ("Color Source", "مصدر اللون"), + ("Common Parameters", "المعلمات المشتركة"), + ("Custom File", "ملف مخصص"), + ("Details", "التفاصيل"), + ("Dilation Width", "عرض التمديد"), + ("Distance-Based", "حسب المسافة"), + ("Edge Contrast", "تباين الحواف"), + ("Edge Distance", "مسافة الحواف"), + ("Edge Protection", "حماية الحواف"), + ("Enable Seams", "تفعيل الوصلات"), + ("File ID", "معرّف الملف"), + ("Full Scene", "المشهد الكامل"), + ("Generate from Mesh", "إنشاء من المجسم"), + ("Generate from Normal Map", "إنشاء من خريطة المتجهات العمودية"), + ("Ground Plane", "مستوى الأرض"), + ("Ground Plane Offset", "إزاحة مستوى الأرض"), + ("High Poly Mesh Suffix", "لاحقة المجسم عالي الدقة"), + ("High Poly Scene", "مشهد عالي التفاصيل"), + ("High-Poly Parameters", "معلمات المجسم عالي التفاصيل"), + ("Hue Shift", "إزاحة تدرج اللون"), + ("Ignore Backface", "تجاهل الوجه الخلفي"), + ("Ignore Backface Suffix", "لاحقة تجاهل الوجه الخلفي"), + ("Include in Bake", "تضمين في الخبز"), + ("Load Cage", "تحميل القفص"), + ("Lock Output Size", "قفل حجم الإخراج"), + ("Low Poly Mesh Suffix", "لاحقة المجسم منخفض الدقة"), + ("Manual", "يدوي"), + ("Material Color", "لون المادة"), + ("Max Frontal Distance", "أقصى مسافة أمامية"), + ("Max Occluder Distance", "أقصى مسافة للحاجب"), + ("Max Rear Distance", "أقصى مسافة خلفية"), + ("Mesh ID", "معرّف المجسم"), + ("Method", "الطريقة"), + ("Min Occluder Distance", "أدنى مسافة للحاجب"), + ("Never", "أبدًا"), + ("No High-Poly Meshes", "لا توجد مجسمات عالية التفاصيل"), + ("Normalization Scale", "نطاق التطبيع"), + ("Normalization Type", "نوع التطبيع"), + ("Only Same Mesh Name", "نفس اسم المجسم فقط"), + ("Output Size", "حجم المخرج"), + ("Match", "المطابقة"), + ("Skew Correction Method", "طريقة تصحيح الانحراف"), + ("Mesh Normals Based", "استنادًا إلى متجهات الشبكة العمودية"), + ("Face Normals Based", "استنادًا إلى متجهات الأوجه العمودية"), + ("Reset Painted Cage", "إعادة تعيين القفص المرسوم"), + ("Paint Cage", "رسم القفص"), + ("Paint Skew Correction", "رسم تصحيح الميل"), + ("Per Material", "لكل مادة"), + ("Random", "عشوائي"), + ("Relative to Bounding Box", "بالنسبة إلى صندوق الإحاطة"), + ("Relative to Low Mesh", "بالنسبة إلى المجسم منخفض التفاصيل"), + ("Relative to Min/Max", "بالنسبة إلى الحد الأدنى والأقصى"), + ("Relative to Ray Distances", "بالنسبة إلى مسافات الأشعة"), + ("Remove Cage", "إزالة القفص"), + ("Remove Skew Correction", "إزالة تصحيح الانحراف"), + ("Restore Defaults", "استعادة الإعدادات الافتراضية"), + ("Return to Painting Mode", "العودة إلى نمط الرسم"), + ("Sampling Radius", "نصف قطر العينات"), + ("Scaling Divisor", "قاسم المقياس"), + ("Seams Intensity", "شدة الوصلات"), + ("Secondary Rays", "أشعة ثانوية"), + ("Self Intersection", "التقاطع الذاتي"), + ("Self Occlusion", "انسداد ذاتي"), + ("Skew Correction", "تصحيح الانحراف"), + ("Smooth", "ناعم"), + ("Spread Angle", "زاوية الانتشار"), + ("Submesh", "مجسم فرعي"), + ("Use Low Poly Mesh as High Poly Mesh", "استخدام المجسم منخفض الدقة كمجسم عالي الدقة"), + ("Value Bounds Max", "الحد الأقصى للقيمة"), + ("Value Bounds Min", "الحد الأدنى للقيمة"), + ("Vertex Color", "لون الرأس"), + ("Select the layer content", "تحديد محتوى الطبقة"), + ("Paint layer", "طبقة رسم"), + ("Fill layer", "طبقة تعبئة"), + ("1 effect", "تأثير واحد"), + ("{count} effects", "{count} تأثيرات"), + ("Mask effects", "تأثيرات القناع"), + ("Content effects", "تأثيرات المحتوى"), + ("Fold or unfold these effects", "طيّ هذه التأثيرات أو فردها"), + ("Remove resolution override", "إزالة تجاوز الدقة"), + ("Texture set resolution", "دقة مجموعة الخامات"), + ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Angle span", "مدى الزاوية"), + ("Axis position", "موضع المحور"), + ("Count", "العدد"), + ("Display", "العرض"), + ("Hide while painting", "إخفاء أثناء الرسم"), + ("Manipulator size", "حجم أداة التحريك"), + ("Mirror symmetry", "تناظر مرآوي"), + ("Radial settings", "إعدادات التناظر الدائري"), + ("Radial symmetry", "تناظر دائري"), + ("Show axis", "إظهار المحور"), + ("Show axis position manipulator", "إظهار أداة تحريك موضع المحور"), + ("Show cursor", "إظهار المؤشر"), + ("Show intersection", "إظهار التقاطع"), + ("Show plane", "إظهار المستوى"), + ("Symmetry", "التناظر"), + ("Symmetry color display", "لون عرض التناظر"), + ("Symmetry settings", "إعدادات التناظر"), + ("Type", "النوع"), + ("Advanced settings", "إعدادات متقدمة"), + ("Import baked maps", "استيراد خرائط مخبوزة"), + ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), + ("Add...", "إضافة..."), + ("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"), + ("Not imported: {files}", "لم يتم استيرادها: {files}"), + ("Baking Visualization", "تصور الخبز"), + ("Show for Selected Texture Set Only", "العرض لمجموعة الخامات المحددة فقط"), + ("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"), + ("UV Seams", "فواصل UV"), + ("Project Mesh (LP)", "مجسم الإسقاط (LP)"), + ("Edges", "الحواف"), + ("Cavities", "التجاويف"), + ("Edges and cavities", "الحواف والتجاويف"), + ("Raw curvature", "الانحناء الخام"), + ("Detail sizes", "أحجام التفاصيل"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "يقرأ خريطة الانحناء كما خُبزت: تغيير الوضع أو أحد الأحجام يفعّل أحجام التفاصيل.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "النقرة تملأ ما تحتها، والمستطيل المسحوب يملأ ما يحدده أثناء اتساعه", + ), + ("Contained center: fill polygons whose center is in the rectangle", "المركز المحتوى: تعبئة المضلعات التي يقع مركزها داخل المستطيل"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "تحرير القناع السريع: ترسم التعبئات حيث يُسمح بالرسم. اضغط U للإنهاء."), + ("Fill mode", "وضع التعبئة"), + ("Fill only polygons the camera sees (3D view)", "تعبئة المضلعات التي تراها الكاميرا فقط (العرض ثلاثي الأبعاد)"), + ("Hit-test", "اختبار الإصابة"), + ("How a rectangle selects polygons", "كيف يحدد المستطيل المضلعات"), + ("Intersection: fill polygons the rectangle touches", "التقاطع: تعبئة المضلعات التي يلمسها المستطيل"), + ("Rectangle fill", "تعبئة مستطيلة"), + ("Select a paint layer or a layer's mask to fill", "حدد طبقة رسم أو قناع طبقة للتعبئة"), + ("Selection mode", "وضع التحديد"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "المثلث يملأ مثلثات منفردة، والمضلع رباعيات ومضلعات كاملة، والمجسم الهندسة المتصلة، وجزيرة UV جزر UV", + ), + ("Visible polygons only", "المضلعات المرئية فقط"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), + ("The file dialog couldn't be shown: {error}", "تعذر عرض نافذة الملفات: {error}"), + ("The project changed while the dialog was open, so nothing was done", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"), + ("Cores kept for the UI", "أنوية محجوزة للواجهة"), + ("Max RAM while saving", "أقصى ذاكرة عند الحفظ"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "يستخدم الحفظ الأنوية الأخرى وحدًا أقصى بهذه النسبة من الذاكرة الحرة. يعمل نواة واحدة على الأقل دائمًا.", + ), + ("Max project size on open", "الحد الأقصى لحجم المشروع عند الفتح"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", + ), + ("Filter by type", "تصفية حسب النوع"), + ("All libraries", "كل المكتبات"), + ("Browse folders", "تصفح المجلدات"), + ("Starter assets", "الأصول المضمّنة"), + ("Your assets", "أصولك"), + ("Reset query", "إعادة تعيين الاستعلام"), + ("Refresh", "تحديث"), + ("Saved searches", "عمليات البحث المحفوظة"), + ("Save the current search", "حفظ البحث الحالي"), + ("Delete", "حذف"), + ("Filter by path", "تصفية حسب المسار"), + ("Hide non-applicable folders", "إخفاء المجلدات غير المطابقة"), + ("Thumbnail size", "حجم الصورة المصغّرة"), + ("Small", "صغير"), + ("Medium", "متوسط"), + ("Large", "كبير"), + ("List", "قائمة"), + ("Procedurals", "إجرائيات"), +]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs new file mode 100644 index 00000000..81e62b2c --- /dev/null +++ b/crates/ui-egui/src/i18n/de.rs @@ -0,0 +1,1194 @@ +//! German UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} wird gebacken ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} wird gebacken ({n}/{total}), Texturset {set} von {sets}"), + ("Follow Newest Map", "Neueste Map verfolgen"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "Das Malen ist pausiert, solange ein Bake angezeigt wird. Brich den Bake ab oder warte, bis er fertig ist.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Was die 3D-Ansicht während des Backens zeigt: die zuletzt fertige Map, eine fertige Map deiner Wahl oder das Material. Noch nicht gebackene Maps zeigen einen neutralen Wert.", + ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), + ("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"), + ("2D view only", "Nur 2D-Ansicht"), + ("32 bits (float)", "32 Bit (Float)"), + ("3D mesh", "3D-Mesh"), + ("3D meshes", "3D-Meshes"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "3D-Texturmalerei: Ebenen, Masken, Smart-Materialien, Backen von Mesh-Maps und Export.", + ), + ("3D view only", "Nur 3D-Ansicht"), + ("3D/2D views", "3D-/2D-Ansicht"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "Ein Ordner überblendet seine Unterelemente (Hindurchwirken). Die Deckkraft pro Kanal wird in den Ebenenzeilen festgelegt.", + ), + ("ACES filmic", "ACES Filmic"), + ("Ambient", "Umgebung"), + ("AO intensity", "AO-Intensität"), + ("About TextureCraft", "Über TextureCraft"), + ("About TextureCraft...", "Über TextureCraft..."), + ( + "Add an anchor point to a layer below to use its stack as a mask.", + "Einer darunterliegenden Ebene einen Ankerpunkt hinzufügen, um ihren Stapel als Maske zu verwenden.", + ), + ("Add anchor point", "Ankerpunkt hinzufügen"), + ("Add as decal (view center)", "Als Decal hinzufügen (Ansichtsmitte)"), + ("Add black mask", "Schwarze Maske hinzufügen"), + ("Add channel", "Kanal hinzufügen"), + ("Add color", "Farbe hinzufügen"), + ("Add compare mask", "Vergleichsmaske hinzufügen"), + ("Add effect", "Effekt hinzufügen"), + ("Add fill", "Füllung hinzufügen"), + ("Add fill layer", "Füllebene hinzufügen"), + ("Add filter", "Filter hinzufügen"), + ("Add folder", "Ordner hinzufügen"), + ("Add generator", "Generator hinzufügen"), + ("Add levels", "Tonwertkorrektur hinzufügen"), + ("Add mask", "Maske hinzufügen"), + ("Add mask with color selection", "Maske mit Farbauswahl hinzufügen"), + ("Add output", "Ausgabe hinzufügen"), + ("Add paint", "Malen hinzufügen"), + ("Add paint layer", "Malebene hinzufügen"), + ("Add smart material from the shelf", "Smart-Material aus der Ablage hinzufügen"), + ("Add to the layer content", "Zum Ebeneninhalt hinzufügen"), + ("Add to the mask", "Zur Maske hinzufügen"), + ("Add white mask", "Weiße Maske hinzufügen"), + ("Adjustments", "Korrekturen"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "Ausgerichtet: Der beim ersten Strich festgelegte Versatz bleibt erhalten. V + Klick legt eine neue Quelle fest.", + ), + ("Alignment", "Ausrichtung"), + ("Alignment and culling", "Ausrichtung und Culling"), + ("All layers", "Alle Ebenen"), + ("Alpha", "Alpha"), + ("Alphas", "Alphas"), + ("Also bound to {item} ({menu})", "Auch belegt für {item} ({menu})"), + ("Alt + LMB drag", "Alt + LMT ziehen"), + ("Always", "Immer"), + ("Ambient Occlusion", "Ambient Occlusion"), + ("Ambient occlusion", "Ambient occlusion"), + ("Amount", "Stärke"), + ("Anchor point", "Ankerpunkt"), + ("Anchor: {name}", "Anker: {name}"), + ("Anchor: {name} ({channel})", "Anker: {name} ({channel})"), + ("Angle", "Winkel"), + ("Angle (degrees)", "Winkel (Grad)"), + ("Angle fade from", "Winkelausblendung ab"), + ("Angle fade to", "Winkelausblendung bis"), + ("Angle jitter", "Winkelstreuung"), + ("Anisotropy angle", "Anisotropiewinkel"), + ("Anisotropy level", "Anisotropiestärke"), + ("Antialiasing", "Kantenglättung"), + ("Aperture", "Blende"), + ("Apply", "Anwenden"), + ("ArtCraft website...", "ArtCraft-Website..."), + ("Assets", "Assets"), + ("Auto", "Auto"), + ("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"), + ("Autosave every", "Automatisch speichern alle"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "Automatische Sicherungen, Smart-Materialien, Vorgaben, Vorlagen und UI-Layouts werden im Datenordner gespeichert. Ein neuer Ordner gilt nach einem Neustart; bereits gespeicherte Dateien bleiben, wo sie sind.", + ), + ("Axis", "Achse"), + ("Back to painting", "Zurück zum Malen"), + ("Backface culling", "Rückseiten-Culling"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Backe eine ID-Map (F8), um Farben vom Mesh aufzunehmen."), + ("Bake Mesh Maps", "Mesh-Maps backen"), + ("Bake mesh maps", "Mesh-Maps backen"), + ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Mesh-Maps backen (F8) für Generatoren auf Basis von Krümmung, AO und Dicke."), + ("Baked Lighting", "Gebackene Beleuchtung"), + ("Baking", "Backen"), + ("Base color", "Grundfarbe"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "Grundfarbe ist die diffuse Farbe, Specular die F0-Farbe und Glanz 1 - Rauheit (diese Kanäle in den Texturset-Einstellungen hinzufügen).", + ), + ("Base color, Metallic, Roughness and Specular level.", "Grundfarbe, Metallisch, Rauheit und Specular-Stärke."), + ("Based on each texture set's size", "Basierend auf der Größe jedes Textursets"), + ("Basic settings", "Grundeinstellungen"), + ("Bent Normals", "Gebogene Normalen"), + ("Bevel", "Abschrägung"), + ("Black", "Schwarz"), + ("Blending", "Überblendung"), + ("Blending mode of the displayed channel", "Füllmethode des angezeigten Kanals"), + ("Blur", "Weichzeichnen"), + ("Blur Directional", "Richtungsweichzeichnung"), + ("Blur and sharpen", "Weichzeichnen und Scharfzeichnen"), + ("Bounces", "Lichtsprünge"), + ("Bricks", "Ziegel"), + ("Brush", "Pinsel"), + ("Brush size", "Pinselgröße"), + ("Brush size down / up", "Pinselgröße verkleinern / vergrößern"), + ("Brushed lines", "Gebürstete Linien"), + ("Built-in (read-only): duplicate it to edit", "Integriert (schreibgeschützt): zum Bearbeiten duplizieren"), + ("Built-in templates are read-only: duplicate one to edit it", "Integrierte Vorlagen sind schreibgeschützt: zum Bearbeiten eine duplizieren"), + ("Built-in: {mesh}", "Integriert: {mesh}"), + ("Cage: {name}", "Cage: {name}"), + ("Camera", "Kamera"), + ("Colors", "Farben"), + ("Go to camera 1", "Zu Kamera 1 wechseln"), + ("Go to camera 2", "Zu Kamera 2 wechseln"), + ("Go to camera 3", "Zu Kamera 3 wechseln"), + ("Go to camera 4", "Zu Kamera 4 wechseln"), + ("Go to camera 5", "Zu Kamera 5 wechseln"), + ("Go to camera 6", "Zu Kamera 6 wechseln"), + ("Go to camera 7", "Zu Kamera 7 wechseln"), + ("Go to camera 8", "Zu Kamera 8 wechseln"), + ("Go to camera 9", "Zu Kamera 9 wechseln"), + ("Camera settings", "Kameraeinstellungen"), + ("Cancel", "Abbrechen"), + ("Cancel the stroke", "Strich abbrechen"), + ("Cell size (texels at 2K)", "Zellengröße (Texel bei 2K)"), + ("Cells", "Zellen"), + ("Channel", "Kanal"), + ("Channel source: uniform value, procedural, image or anchor", "Kanalquelle: einheitlicher Wert, prozedural, Bild oder Anker"), + ("Channels", "Kanäle"), + ("Check for Updates...", "Nach Updates suchen..."), + ("Checker", "Schachbrett"), + ("Clamp", "Begrenzen"), + ("Clear", "Leeren"), + ("Clear mask", "Maske leeren"), + ("Clear recent projects", "Letzte Projekte leeren"), + ( + "Click a mesh part to show or hide the selected layer on it.", + "Klicken Sie auf einen Teil des Meshs, um die ausgewählte Ebene dort ein- oder auszublenden.", + ), + ("Click the mesh to pick its material into the brush", "Auf das Mesh klicken, um sein Material in den Pinsel aufzunehmen"), + ("Click the mesh to place the decal", "Auf das Mesh klicken, um das Decal zu platzieren"), + ("Click, then press the new shortcut (Esc cancels)", "Klicken, dann das neue Tastenkürzel drücken (Esc bricht ab)"), + ("Clone", "Klonen"), + ("Close", "Schließen"), + ("Closed path", "Geschlossener Pfad"), + ("Cloud", "Wolke"), + ("Clouds", "Wolken"), + ("Coat normal", "Klarlack-Normale"), + ("Coat roughness", "Klarlack-Rauheit"), + ("Coat weight", "Klarlack-Gewichtung"), + ("Color", "Farbe"), + ("Color Balance", "Farbbalance"), + ("Color burn", "Farbig nachbelichten"), + ("Color dodge", "Farbig abwedeln"), + ( + "Color of the light that travels under the surface (each channel goes as far as its value)", + "Farbe des Lichts, das unter der Oberfläche wandert (jeder Kanal reicht so weit wie sein Wert)", + ), + ("Color picker", "Farbpipette"), + ("Color selection", "Farbauswahl"), + ("Color to replace", "Zu ersetzende Farbe"), + ( + "Colors near the first shift towards the second, keeping their shading.", + "Farben nahe der ersten verschieben sich zur zweiten und behalten ihre Schattierung.", + ), + ( + "Colors read as gray. Add a levels or blur effect above to shape the result.", + "Farben werden als Grau gelesen. Darüber eine Tonwertkorrektur oder einen Weichzeichnen-Effekt hinzufügen, um das Ergebnis zu formen.", + ), + ("Combine with the layer's height", "Mit der Höhe der Ebene kombinieren"), + ("Compare mask", "Vergleichsmaske"), + ("Compositing", "Compositing"), + ("Constant", "Konstante"), + ("Constants", "Konstanten"), + ("Contrast", "Kontrast"), + ("Contrast/Luminosity", "Kontrast/Luminanz"), + ("Converted maps", "Konvertierte Maps"), + ("Copy RGB values", "RGB-Werte kopieren"), + ("Copy effect", "Effekt kopieren"), + ("Copy from", "Kopieren aus"), + ("Copy layer(s)", "Ebene(n) kopieren"), + ("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"), + ("Copy to all texture sets", "In alle Textursets kopieren"), + ("Copy what the texture set shows", "Kopieren, was das Texturset anzeigt"), + ("Couldn't encode the render", "Das Rendering konnte nicht kodiert werden"), + ("Couldn't export textures: {error}", "Texturen konnten nicht exportiert werden: {error}"), + ("Couldn't export the mesh: {error}", "Das Mesh konnte nicht exportiert werden: {error}"), + ("Couldn't export the template: {error}", "Die Vorlage konnte nicht exportiert werden: {error}"), + ("Couldn't import {name}: {error}", "{name} konnte nicht importiert werden: {error}"), + ("Couldn't open {name}: {error}", "{name} konnte nicht geöffnet werden: {error}"), + ("Couldn't read the render back from the GPU", "Das Rendering konnte nicht von der GPU zurückgelesen werden"), + ("Couldn't save the render: {error}", "Das Rendering konnte nicht gespeichert werden: {error}"), + ("Couldn't save {name}: {error}", "{name} konnte nicht gespeichert werden: {error}"), + ("Count per stamp", "Anzahl pro Abdruck"), + ("Crate", "Kiste"), + ("Create", "Erstellen"), + ("Create smart material", "Smart-Material erstellen"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Strg+Ziehen mit RMT in einer Ansicht stellt Größe und Härte ein, Strg+Ziehen mit LMT Fluss und Winkel.", + ), + ("Cube", "Würfel"), + ("Current layer", "Aktuelle Ebene"), + ("Curvature", "Krümmung"), + ("Cut effect", "Effekt ausschneiden"), + ("Cut layer(s)", "Ebene(n) ausschneiden"), + ("Cyan / red", "Cyan / Rot"), + ("Cylinder", "Zylinder"), + ("Cylindrical projection", "Zylindrische Projektion"), + ( + "Dark to light: the content's luminance picks a color along these stops.", + "Dunkel nach hell: Die Luminanz des Inhalts wählt eine Farbe entlang dieser Farbunterbrechungen.", + ), + ("Darken (Min)", "Abdunkeln (Min)"), + ("Data folder", "Datenordner"), + ("Decal", "Decal"), + ("Decal projection", "Decal-Projektion"), + ("Default", "Standard"), + ("Default camera", "Standardkamera"), + ("Delete the selected template", "Ausgewählte Vorlage löschen"), + ("Delete this camera", "Diese Kamera löschen"), + ("Deleted template \"{name}\"", "Vorlage „{name}“ gelöscht"), + ("Denoise", "Entrauschen"), + ("Depth", "Tiefe"), + ("Depth of field", "Schärfentiefe"), + ("Depth of field (viewport and Rendering mode)", "Schärfentiefe (Ansichtsfenster und Rendermodus)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "Tiefe der Schärfeebene entlang der Blickrichtung (0: Orbit-Mittelpunkt)"), + ("Details saved to {file}", "Details gespeichert in {file}"), + ("Difference", "Differenz"), + ("Dilation + default background color", "Dilatation + Standard-Hintergrundfarbe"), + ("Dilation + transparent", "Dilatation + transparent"), + ("Dilation infinite", "Dilatation unendlich"), + ("DirectX normal map", "DirectX-Normal-Map"), + ("Dirt", "Schmutz"), + ("Disable", "Deaktivieren"), + ("Dismiss", "Schließen"), + ("Displacement (height channel)", "Verschiebung (Höhenkanal)"), + ("Display Settings", "Anzeigeeinstellungen"), + ("Display material", "Material anzeigen"), + ("Display next channel", "Nächsten Kanal anzeigen"), + ("Display next mesh map", "Nächste Mesh-Map anzeigen"), + ("Display previous channel", "Vorherigen Kanal anzeigen"), + ("Display previous mesh map", "Vorherige Mesh-Map anzeigen"), + ("Distance", "Distanz"), + ("Distort", "Verzerren"), + ("Divide", "Dividieren"), + ("Document resolution", "Dokumentauflösung"), + ("Documentation...", "Dokumentation..."), + ("Done on CPU: {n} / {max} samples, {s} s", "Fertig auf CPU: {n} / {max} Samples, {s} s"), + ("Done on GPU: {n} / {max} samples, {s} s", "Fertig auf GPU: {n} / {max} Samples, {s} s"), + ("Double-click to rename", "Doppelklicken zum Umbenennen"), + ("Download as", "Herunterladen als"), + ("Downloaded {name}", "{name} heruntergeladen"), + ("Drag onto an output channel", "Auf einen Ausgabekanal ziehen"), + ( + "Drags the layer stack's values along the stroke into the selected layer.", + "Zieht die Werte des Ebenenstapels entlang des Strichs in die ausgewählte Ebene.", + ), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "Zeichnet {name} aus Texturset „{set}“. Änderungen an der Quelle erscheinen in jeder Instanz.", + ), + ( + "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", + "Rahmen ziehen, um das Decal zu verschieben, eine Ecke zum Skalieren, den runden Griff zum Drehen", + ), + ( + "Drop an image from the Assets panel here to use it as this mesh map", + "Ein Bild aus dem Assets-Panel hier ablegen, um es als diese Mesh-Map zu verwenden", + ), + ("Dry streaks", "Trockene Schlieren"), + ("Duplicate effect", "Effekt duplizieren"), + ("Duplicate layer(s)", "Ebene(n) duplizieren"), + ("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"), + ("Edge Detect", "Kantenerkennung"), + ("Edit", "Bearbeiten"), + ("Edit keyboard shortcuts...", "Tastenkürzel bearbeiten..."), + ("Edit quick mask", "Schnellmaske bearbeiten"), + ( + "Editing quick mask: paint where painting is allowed (U to finish)", + "Schnellmaske bearbeiten: Bereiche malen, in denen Malen erlaubt ist (U zum Beenden)", + ), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "Schnellmaske wird bearbeitet: Striche markieren, wo Malen erlaubt ist. Zum Beenden U drücken.", + ), + ("Emissive", "Emissiv"), + ("Enable or disable the effect", "Effekt aktivieren oder deaktivieren"), + ("Enable quick mask", "Schnellmaske aktivieren"), + ("Environment blur", "Umgebungsunschärfe"), + ("Environment exposure (EV)", "Umgebungsbelichtung (EV)"), + ("Environment map", "Umgebungs-Map"), + ("Environment opacity", "Umgebungsdeckkraft"), + ("Environment rotation", "Umgebungsdrehung"), + ("Environment settings", "Umgebungseinstellungen"), + ("Environment: {name}", "Umgebung: {name}"), + ("Environments", "Umgebungen"), + ("Eraser", "Radierer"), + ("Exclusion", "Ausschluss"), + ("Expand or collapse the folder", "Ordner auf- oder zuklappen"), + ("Export", "Exportieren"), + ("Export Mesh...", "Mesh exportieren..."), + ("Export Textures...", "Texturen exportieren..."), + ("Export mesh", "Mesh exportieren"), + ("Export template", "Vorlage exportieren"), + ("Export templates", "Exportvorlagen"), + ("Export textures", "Texturen exportieren"), + ("Export the selected template (.json)", "Ausgewählte Vorlage exportieren (.json)"), + ("Exported mesh to {path}", "Mesh nach {path} exportiert"), + ("Exported template \"{name}\" to {path}", "Vorlage „{name}“ nach {path} exportiert"), + ("Exported {n} textures to {folder}", "{n} Texturen nach {folder} exportiert"), + ("F0 from specular level", "F0 aus Specular-Stärke"), + ("Fabric weave", "Stoffgewebe"), + ("Field of view (deg)", "Sichtfeld (Grad)"), + ("File", "Datei"), + ("File name without extension; variables insert names", "Dateiname ohne Erweiterung; Variablen fügen Namen ein"), + ("File type", "Dateityp"), + ("Fill", "Füllung"), + ("Fill the closed path (lasso)", "Geschlossenen Pfad füllen (Lasso)"), + ("Fill the path (close it first)", "Pfad füllen (zuerst schließen)"), + ("Filter", "Filter"), + ("Filter the remaining noise while keeping edges and texture detail", "Restrauschen filtern und dabei Kanten und Texturdetails erhalten"), + ("Filters", "Filter"), + ("Fine noise", "Feines Rauschen"), + ("Fingerprints", "Fingerabdrücke"), + ("Enter a finite number", "Eine endliche Zahl eingeben"), + ("Double-click or press Enter to edit", "Doppelklicken oder Eingabetaste zum Bearbeiten drücken"), + ("Fit the input range to the histogram", "Eingabebereich an das Histogramm anpassen"), + ("Flatten layer", "Ebene reduzieren"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Kehrt den Grünkanal des Bildes um, für Normal-Maps mit nach unten zeigendem Y", + ), + ("Flow", "Fluss"), + ("Flow and opacity", "Fluss und Deckkraft"), + ("Flow jitter", "Flussstreuung"), + ("Focus distance", "Fokusdistanz"), + ("Folder", "Ordner"), + ("Folders", "Ordner"), + ("Follow path", "Pfad folgen"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "Für das ganze Projekt: wie Normal-Map-Bilder als Mesh-Maps gelesen werden (nach einer Änderung neu zuweisen), und die Vorgabe für den Export", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Frei und quelloffen (MIT OR Apache-2.0), geschrieben in Rust."), + ("From template", "Aus Vorlage"), + ("From template / project", "Aus Vorlage / Projekt"), + ("Full", "Voll"), + ("GPU error: {error}", "GPU-Fehler: {error}"), + ("Geometry mask", "Geometriemaske"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "GGX-Specular mit höhenkorrelierter Smith-Sichtbarkeit, Lambert-Diffus, bildbasierte Split-Sum-Beleuchtung mit Irradianz aus sphärischen Harmonischen und Horizont-Ausblendung.", + ), + ("Gamma", "Gamma"), + ("General export parameters", "Allgemeine Exportparameter"), + ("General properties", "Allgemeine Eigenschaften"), + ("Generator", "Generator"), + ("Geometry and UVs only", "Nur Geometrie und UVs"), + ("Glossiness", "Glanz"), + ("Glossiness from roughness", "Glanz aus Rauheit"), + ("Glow", "Glühen"), + ("Gradient", "Verlauf"), + ("Gradient Map", "Verlaufsumsetzung"), + ("Gravity", "Schwerkraft"), + ("Gray", "Grau"), + ("Gray + A", "Grau + A"), + ("Gray 50%", "Grau 50%"), + ("Grayscale", "Graustufen"), + ("Group layer(s)", "Ebene(n) gruppieren"), + ("Grunge", "Grunge"), + ("HDR environments", "HDR-Umgebungen"), + ("High Pass", "Hochpass"), + ("HSL Perceptive", "HSL perzeptiv"), + ("Half", "Halb"), + ("Hammered", "Gehämmert"), + ("Hard light", "Hartes Licht"), + ("Hardness", "Härte"), + ("Height", "Höhe"), + ("Height offset", "Höhenversatz"), + ("Height to normal strength", "Stärke Höhe zu Normale"), + ("Help", "Hilfe"), + ("Hide UI", "UI ausblenden"), + ("High", "Hoch"), + ("High poly: {name}", "High-Poly: {name}"), + ("Highlights", "Lichter"), + ("Histogram Range", "Histogrammbereich"), + ("Histogram Scan", "Histogramm-Scan"), + ("Histogram Shift", "Histogramm-Verschiebung"), + ("History", "Verlauf"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "S gedrückt halten: Ziehen mit LMT dreht, mit RMT skaliert, mit MMT verschiebt die Schablone.", + ), + ("Hold V and click the mesh to set the clone source", "V gedrückt halten und auf das Mesh klicken, um die Klonquelle festzulegen"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "V gedrückt halten und auf das Mesh klicken, um die Quelle festzulegen, dann an anderer Stelle malen, um sie zu kopieren.", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "Wie weit Licht unter der Oberfläche wandert, als Anteil der Mesh-Größe (wo der Kanal Streuungsgewichtung bemalt ist)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "Wie stark transmissive Oberflächen Licht brechen (wo der Kanal Transmission bemalt ist): Wasser 1,33, Glas 1,5, Diamant 2,42", + ), + ("Hue shift (degrees)", "Farbtonverschiebung (Grad)"), + ("ID", "ID"), + ("Image: {name}", "Bild: {name}"), + ("Images", "Bilder"), + ("Import HDR...", "HDR importieren..."), + ("Import a template (.json)", "Vorlage importieren (.json)"), + ( + "Import an image (File > Import resources) to project it onto the mesh.", + "Ein Bild importieren (Datei > Ressourcen importieren), um es auf das Mesh zu projizieren.", + ), + ("Import resources...", "Ressourcen importieren..."), + ("Import MaterialX material...", "MaterialX-Material importieren..."), + ("MaterialX materials", "MaterialX-Materialien"), + ("Import...", "Importieren..."), + ("Imported template \"{name}\"", "Vorlage „{name}“ importiert"), + ("Imported {name}", "{name} importiert"), + ("Index of refraction", "Brechungsindex"), + ("Input high", "Eingabe hoch"), + ("Input low", "Eingabe tief"), + ("Input maps", "Eingabe-Maps"), + ("Insert a variable", "Variable einfügen"), + ("Instance", "Instanz"), + ("Instantiate across texture sets", "In allen Textursets instanziieren"), + ("Intensity (texels at 2K)", "Intensität (Texel bei 2K)"), + ("Interface", "Oberfläche"), + ("Interface scale", "Oberflächenskalierung"), + ("Inverse Subtract", "Umgekehrt subtrahieren"), + ("Inverse divide", "Umgekehrt dividieren"), + ("Invert", "Invertieren"), + ("Invert mask", "Maske invertieren"), + ("Invert mask background", "Maskenhintergrund invertieren"), + ("Invert mask value", "Maskenwert invertieren"), + ("Invert quick mask", "Schnellmaske invertieren"), + ("Jitters", "Streuung"), + ("Join the ArtCraft community on Discord", "Der ArtCraft-Community auf Discord beitreten"), + ("Join the community (Discord)...", "Der Community beitreten (Discord)..."), + ("Key light (shadow-casting light, direct only)", "Führungslicht (schattenwerfendes Licht, nur direkt)"), + ("Keyboard", "Tastatur"), + ("Keyboard shortcuts", "Tastenkürzel"), + ("Light azimuth (degrees)", "Lichtazimut (Grad)"), + ("Light elevation (degrees)", "Lichthöhe (Grad)"), + ("Light intensity", "Lichtintensität"), + ("LMB", "LMT"), + ("Language", "Sprache"), + ("Layer mask", "Ebenenmaske"), + ("Layer memory: {mb} MB", "Ebenenspeicher: {mb} MB"), + ("Layers", "Ebenen"), + ("Lazy mouse", "Lazy Mouse"), + ("Lazy mouse distance", "Lazy-Mouse-Distanz"), + ("Leather grain", "Ledernarbung"), + ("Lens size: how quickly things blur away from the focus distance", "Linsengröße: wie schnell Objekte außerhalb der Fokusdistanz unscharf werden"), + ("Level", "Stufe"), + ("Levels", "Tonwertkorrektur"), + ("Lifetime (steps)", "Lebensdauer (Schritte)"), + ("Light / direction", "Licht / Richtung"), + ("Lighten (Max)", "Aufhellen (Max)"), + ("Lightness", "Helligkeit"), + ("Linear", "Linear"), + ("Linear burn", "Linear nachbelichten"), + ("Linear dodge (Add)", "Linear abwedeln (Addieren)"), + ("Linear light", "Lineares Licht"), + ("List of exports", "Exportliste"), + ("Load UI Layout", "UI-Layout laden"), + ("Loaded UI layout {path}", "UI-Layout {path} geladen"), + ("Log", "Protokoll"), + ("Low", "Niedrig"), + ("Luminosity", "Luminanz"), + ("MMB drag / Alt + MMB", "MMT ziehen / Alt + MMT"), + ("Made by the ArtCraft team and community.", "Entwickelt vom ArtCraft-Team und der Community."), + ("Magenta / green", "Magenta / Grün"), + ("Main shader", "Haupt-Shader"), + ("Marble veins", "Marmoradern"), + ("Mask", "Maske"), + ("Mask Editor: Edge wear", "Masken-Editor: Kantenabnutzung"), + ("Mask value (gray)", "Maskenwert (Grau)"), + ("Mask with height", "Mit Höhe maskieren"), + ("MatFinish Grind", "MatFinish Schliff"), + ("MatFinish Hammered", "MatFinish Gehämmert"), + ("MatFinish Raw", "MatFinish Roh"), + ("MatFinish Sanded", "MatFinish Geschmirgelt"), + ("Material", "Material"), + ("Material ball", "Materialkugel"), + ("Material finish", "Materialoberfläche"), + ("Materials", "Materialien"), + ("Maximum", "Maximum"), + ("Mesh fill", "Mesh-Füllung"), + ("Mesh map: {map}", "Mesh-Map: {map}"), + ("Mesh maps", "Mesh-Maps"), + ("Mesh maps baked", "Mesh-Maps gebacken"), + ("Meshes", "Meshes"), + ("Metallic", "Metallisch"), + ("Midtones", "Mitteltöne"), + ("Minimum", "Minimum"), + ("Minimum size (%)", "Mindestgröße (%)"), + ("Missing (bake to create)", "Fehlt (zum Erstellen backen)"), + ("Mixed AO", "Gemischte AO"), + ("Mode", "Modus"), + ("More in Assets > Alphas: click one, or drag it here", "Mehr unter Assets > Alphas: eines anklicken oder hierher ziehen"), + ("Mosaic", "Mosaik"), + ("Move down", "Nach unten"), + ("Move up", "Nach oben"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "Verschiebt die Oberfläche anhand des Höhenkanals auf einer feineren Kopie des Meshs, mit der Stärke von Höhe zu Normale (nur im Viewport: Malen folgt der Grundoberfläche)", + ), + ("Multiply", "Multiplizieren"), + ("My smart materials", "Meine Smart-Materialien"), + ("Name", "Name"), + ("New project", "Neues Projekt"), + ("New project...", "Neues Projekt..."), + ("New template", "Neue Vorlage"), + ("No GPU renderer available", "Kein GPU-Renderer verfügbar"), + ("No font on this system can show this language", "Keine Schriftart auf diesem System kann diese Sprache darstellen"), + ( + "No outputs yet: add one above, then drag input maps onto its channels.", + "Noch keine Ausgaben: Oben eine hinzufügen, dann Eingabe-Maps auf ihre Kanäle ziehen.", + ), + ("No padding (passthrough)", "Kein Padding (unverändert)"), + ("Noise amount", "Rauschstärke"), + ("Noise scale", "Rauschskalierung"), + ("None", "Keine"), + ("Normal", "Normale"), + ("Normal DirectX", "Normale DirectX"), + ("Normal Invert", "Normale invertieren"), + ("Normal OpenGL", "Normale OpenGL"), + ("Normal from height", "Normale aus Höhe"), + ("Normal map combine", "Normal-Map kombinieren"), + ("Normal map detail", "Normal-Map-Detail"), + ("Color space", "Farbraum"), + ("Normal map format", "Normal-Map-Format"), + ("Normal map inverse detail", "Normal-Map-Detail invertiert"), + ("Normal: painting uses the flat normal", "Normale: Malen verwendet die flache Normale"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Nicht genug GPU-Speicher, um {count} Texturesets vollständig anzuzeigen ({names}): Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", + ), + ("Not exported: no source in this texture set", "Nicht exportiert: keine Quelle in diesem Texturset"), + ("Not saved: {error}", "Nicht gespeichert: {error}"), + ("Off", "Aus"), + ("Offset", "Versatz"), + ("Offset right", "Versatz rechts"), + ("Offset up", "Versatz oben"), + ("Offset {axis}", "Versatz {axis}"), + ( + "Offsets the textures by the height channel, at the height to normal strength", + "Verschiebt die Texturen anhand des Höhenkanals, mit der Stärke Höhe zu Normale", + ), + ("On", "Ein"), + ("Opacity", "Deckkraft"), + ("Open sample project...", "Beispielprojekt öffnen..."), + ("Open...", "Öffnen..."), + ("Opened {name}", "{name} geöffnet"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "Optionale Kanäle ergänzen Klarlack (Klarlack-Gewichtung, Klarlack-Rauheit, Klarlack-Normale), Schimmer (Schimmer-Gewichtung, -Farbe, -Rauheit), Anisotropie (Anisotropiestärke, -winkel), Subsurface Scattering (Streuungsgewichtung) und Transmission (Transmission).", + ), + ("Orbit", "Orbit"), + ("Orthographic", "Orthografisch"), + ("Perspective", "Perspektivisch"), + ("Output directory", "Ausgabeverzeichnis"), + ("Output high", "Ausgabe hoch"), + ("Output low", "Ausgabe tief"), + ("Output template", "Ausgabevorlage"), + ("Output templates", "Ausgabevorlagen"), + ("Overlay", "Ineinanderkopieren"), + ("Overlay opacity", "Überlagerungsdeckkraft"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallisch/Rauheit (TextureCraft)"), + ("Pick color", "Farbe aufnehmen"), + ("PNG image", "PNG-Bild"), + ("Padding", "Padding"), + ("Paint", "Malen"), + ("Paint chips", "Lackabplatzer"), + ("Paint on the mesh to edit the layer content.", "Auf das Mesh malen, um den Ebeneninhalt zu bearbeiten."), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "Auf das Mesh malen, um diese Maske zu bearbeiten. Für Grau den Maskenwert im Tab Material verwenden.", + ), + ("Paint with the current tool", "Mit dem aktuellen Werkzeug malen"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "Gemalte Ebenenpixel {pixels} MB, zusammengesetzte Kanäle {composites} MB, Compositing-Cache {cache} MB", + ), + ("Painting", "Malen"), + ("Pan", "Schwenken"), + ("Parallax occlusion (height channel)", "Parallax Occlusion (Höhenkanal)"), + ( + "Partial mask values follow the layer's height: high parts show first", + "Teilweise Maskenwerte folgen der Höhe der Ebene: Hohe Bereiche erscheinen zuerst", + ), + ("Particle brush (slides down the surface)", "Partikelpinsel (gleitet die Oberfläche hinab)"), + ("Particle brush: particles slide down the surface", "Partikelpinsel: Partikel gleiten die Oberfläche hinab"), + ("Particles", "Partikel"), + ("Passthrough", "Hindurchwirken"), + ("Paste as instance", "Als Instanz einfügen"), + ("Paste effect", "Effekt einfügen"), + ("Paste layer(s)", "Ebene(n) einfügen"), + ("Path", "Pfad"), + ("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Pfad: Klicken fügt einen Punkt hinzu, Klicken auf die Kurve fügt einen ein, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", + ), + ("Pattern scale", "Musterskalierung"), + ("Perlin noise", "Perlin-Rauschen"), + ("Pick focus in the viewport", "Fokus im Ansichtsfenster wählen"), + ("Pin light", "Lichtpunkt"), + ("Place on the surface", "Auf der Oberfläche platzieren"), + ("Place path points on the mesh", "Pfadpunkte auf dem Mesh platzieren"), + ("Planar projection", "Planare Projektion"), + ("Plane", "Fläche"), + ("Polygon fill", "Polygonfüllung"), + ("Pores", "Poren"), + ("Position", "Position"), + ("Position gradient", "Positionsverlauf"), + ("Position jitter", "Positionsstreuung"), + ("Posterize", "Tontrennung"), + ("Press a key...", "Taste drücken..."), + ("Project", "Projekt"), + ("Project Configuration...", "Projektkonfiguration..."), + ("Project opened", "Projekt geöffnet"), + ("Project template", "Projektvorlage"), + ("Projection", "Projektion"), + ("Projects and meshes", "Projekte und Meshes"), + ("Properties", "Eigenschaften"), + ("Quarter", "Viertel"), + ("Quick mask", "Schnellmaske"), + ("Quit", "Beenden"), + ("Radius (texels at 2K)", "Radius (Texel bei 2K)"), + ("RENDERING", "RENDERING"), + ("Range", "Bereich"), + ("Rebind any menu item, tool or command", "Beliebige Menüeinträge, Werkzeuge oder Befehle neu belegen"), + ("Recent projects", "Letzte Projekte"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "Erfasst den Stapel bis zu dieser Ebene. Fülleffekte in Masken (und Füllebenen) darüber können ihn als Quelle lesen.", + ), + ("Redo", "Wiederholen"), + ("Reimport mesh", "Mesh neu importieren"), + ("Remove", "Entfernen"), + ("Remove channel", "Kanal entfernen"), + ("Remove effect", "Effekt entfernen"), + ("Remove last", "Letzte entfernen"), + ("Remove layer", "Ebene entfernen"), + ("Remove layer(s)", "Ebene(n) entfernen"), + ("Remove mask", "Maske entfernen"), + ("Remove point", "Punkt entfernen"), + ("Remove resource", "Ressource entfernen"), + ("Remove the shortcut", "Tastenkürzel entfernen"), + ("Remove this output", "Diese Ausgabe entfernen"), + ("Remove unused resources...", "Unbenutzte Ressourcen entfernen..."), + ("Rename the selected template", "Ausgewählte Vorlage umbenennen"), + ("Render on the CPU", "Auf der CPU rendern"), + ("Rendering", "Rendering"), + ("Rendering (path traced)", "Rendering (Path Tracing)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "Rendern auf CPU: {n} / {max} Samples, {s} s"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "Rendern auf GPU: {n} / {max} Samples, {s} s"), + ("Rendering, path traced", "Rendering, Path Tracing"), + ("Replace", "Ersetzen"), + ("Replace Color", "Farbe ersetzen"), + ("Replacement color", "Ersatzfarbe"), + ("Report a bug...", "Fehler melden..."), + ("Rescan the library folder", "Bibliotheksordner neu einlesen"), + ("Reset", "Zurücksetzen"), + ("Reset UI", "UI zurücksetzen"), + ("Reset all", "Alle zurücksetzen"), + ("Reset to defaults", "Auf Standardwerte zurücksetzen"), + ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), + ("Resizing", "Größe wird geändert"), + ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), + ("Return to this step", "Zu diesem Schritt zurückkehren"), + ("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"), + ("Rotation", "Drehung"), + ("Rotation (degrees)", "Drehung (Grad)"), + ("Roughness", "Rauheit"), + ("Roughness from glossiness", "Rauheit aus Glanz"), + ("Round", "Rund"), + ("Rounded cube", "Abgerundeter Würfel"), + ("Samples", "Samples"), + ("Saturation", "Sättigung"), + ("Save", "Speichern"), + ("Save UI Layout", "UI-Layout speichern"), + ("Save a copy...", "Kopie speichern..."), + ("Save as...", "Speichern unter..."), + ("Save current layout...", "Aktuelles Layout speichern..."), + ("Save render...", "Rendering speichern..."), + ("Save view as camera", "Ansicht als Kamera speichern"), + ("Saved UI layout {path}", "UI-Layout {path} gespeichert"), + ("Saved {path}", "{path} gespeichert"), + ("Saving UI layouts to files is available in the desktop app", "Das Speichern von UI-Layouts in Dateien ist in der Desktop-App verfügbar"), + ("Scale", "Skalierung"), + ("Scale / tiling", "Skalierung / Kachelung"), + ("Scatter color", "Streufarbe"), + ("Scatter radius", "Streuradius"), + ("Scattering weight", "Streuungsgewichtung"), + ("Scratches", "Kratzer"), + ("Screen", "Negativ multiplizieren"), + ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), + ("Search", "Suchen"), + ("Search commands or keys", "Befehle oder Tasten suchen"), + ("Seed", "Startwert"), + ("Select a layer", "Ebene auswählen"), + ("Select an output template", "Ausgabevorlage auswählen"), + ("Select source", "Quelle auswählen"), + ("Select the mask (Alt+click: show it in the viewport)", "Maske auswählen (Alt+Klick: im Ansichtsfenster anzeigen)"), + ("Select...", "Auswählen..."), + ("Settings", "Einstellungen"), + ("Settings...", "Einstellungen..."), + ("Shader Settings", "Shader-Einstellungen"), + ("Shader instance", "Shader-Instanz"), + ("Shadows", "Tiefen"), + ("Sharpen", "Scharfzeichnen"), + ("Sheen color", "Schimmerfarbe"), + ("Sheen color × weight", "Schimmerfarbe × Gewichtung"), + ("Sheen roughness", "Schimmer-Rauheit"), + ("Sheen weight", "Schimmer-Gewichtung"), + ("Shift + wheel", "Umschalt + Mausrad"), + ("Shortcuts list...", "Liste der Tastenkürzel..."), + ("Show on all parts", "Auf allen Teilen zeigen"), + ("Show UV wireframe in the 2D view", "UV-Drahtgitter in der 2D-Ansicht anzeigen"), + ("Show entire mesh", "Gesamtes Mesh anzeigen"), + ("Show log...", "Protokoll anzeigen..."), + ("Show or hide the layer", "Ebene ein- oder ausblenden"), + ("Show or hide the texture set", "Texturset ein- oder ausblenden"), + ("Show wireframe in the 3D view", "Drahtgitter in der 3D-Ansicht anzeigen"), + ("Signed addition (AddSub)", "Vorzeichenbehaftete Addition (AddSub)"), + ("Size", "Größe"), + ("Size in screen space", "Größe im Bildschirmraum"), + ("Size jitter", "Größenstreuung"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "Größe der Texturen, die das Ansichtsfenster zeigt: niedriger braucht bei großen Texturesets weniger GPU-Speicher. Malen und Export behalten die volle Auflösung.", + ), + ("Slope Blur", "Neigungsweichzeichnung"), + ("Slope scale", "Neigungsskalierung"), + ("Smart masks", "Smart-Masken"), + ("Smart material saved to {path}", "Smart-Material in {path} gespeichert"), + ("Smart materials", "Smart-Materialien"), + ("Smudge", "Verwischen"), + ("Soft light", "Weiches Licht"), + ("Softness", "Weichheit"), + ("Source", "Quelle"), + ("Source U {u} V {v}", "Quelle U {u} V {v}"), + ("Spacing", "Abstand"), + ("Specular", "Specular"), + ("Specular level", "Specular-Stärke"), + ("Sphere", "Kugel"), + ("Spherical projection", "Sphärische Projektion"), + ("Spray", "Spray"), + ("Square", "Quadrat"), + ("Stamp depth", "Abdrucktiefe"), + ("Star", "Stern"), + ("Starting render...", "Rendering wird gestartet..."), + ("Stencil", "Schablone"), + ("Steps", "Stufen"), + ("Streaks", "Schlieren"), + ("Strength", "Stärke"), + ("Stripes", "Streifen"), + ("Stroke opacity", "Strichdeckkraft"), + ("Subsampling 2x2", "Subsampling 2x2"), + ("Subsampling 4x4", "Subsampling 4x4"), + ("Subsampling 8x8", "Subsampling 8x8"), + ("Subsurface scattering", "Subsurface Scattering"), + ("Subtract", "Subtrahieren"), + ("Tangent | Wrap", "Tangente | Umhüllen"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "Temporale Kantenglättung (verfeinert die 3D-Ansicht im Stillstand)"), + ("Texture Sets", "Textursets"), + ("Texture Set Settings", "Texturset-Einstellungen"), + ("Texture resolution", "Texturauflösung"), + ("Texture set channels", "Texturset-Kanäle"), + ("Texture sets", "Textursets"), + ("TextureCraft had to close:", "TextureCraft musste beendet werden:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metallisch/Rauheit"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - Specular/Glanz"), + ("TextureCraft project", "TextureCraft-Projekt"), + ("TextureCraft project or mesh", "TextureCraft-Projekt oder Mesh"), + ("Textures", "Texturen"), + ("Textures embedded; for game engines and most viewers", "Texturen eingebettet; für Game-Engines und die meisten Viewer"), + ("Textures packaged; for USD tools and AR Quick Look", "Texturen gepackt; für USD-Tools und AR Quick Look"), + ("The GPU couldn't render this scene: {error}", "Die GPU konnte diese Szene nicht rendern: {error}"), + ("The bake worker stopped", "Der Back-Prozess wurde beendet"), + ("The eraser removes paint from the enabled channels.", "Der Radierer entfernt Farbe aus den aktivierten Kanälen."), + ("The first stroke sets the offset from the source.", "Der erste Strich legt den Versatz zur Quelle fest."), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "Der Alphakanal des Bildes schneidet die Form des Decals aus; abgewandte Flächen und Oberflächen jenseits seiner Tiefe bleiben frei.", + ), + ("The next click in the 3D view moves the decal there", "Der nächste Klick in der 3D-Ansicht verschiebt das Decal dorthin"), + ("The resize worker stopped", "Der Skalierungsprozess wurde beendet"), + ("Thickness", "Dicke"), + ("Thin areas", "Dünne Bereiche"), + ("Threshold", "Schwellenwert"), + ("Tile", "Kacheln"), + ("Tiles", "Kacheln"), + ("Tint", "Tönung"), + ("Toggle mask", "Maske umschalten"), + ("Tolerance", "Toleranz"), + ("Tone mapping", "Tone Mapping"), + ("Tools", "Werkzeuge"), + ("Torus", "Torus"), + ("Transmission", "Transmission"), + ("Tri-planar projection", "Triplanare Projektion"), + ("Triangle fill", "Dreiecksfüllung"), + ("UDIM plane", "UDIM-Fläche"), + ("UDIM tiles painted by this texture set, each at the set's size", "Von diesem Texturset bemalte UDIM-Kacheln, jeweils in der Größe des Sets"), + ("UI layout", "UI-Layout"), + ("UI layout: {error}", "UI-Layout: {error}"), + ("UI layouts", "UI-Layouts"), + ("UI {ms} ms", "UI {ms} ms"), + ("USD binary, textures alongside", "USD binär, Texturen daneben"), + ("USD text, textures alongside", "USD-Text, Texturen daneben"), + ("USDZ with textures", "USDZ mit Texturen"), + ("UV checker", "UV-Schachbrett"), + ("UV island fill", "UV-Insel-Füllung"), + ("UV transformations", "UV-Transformationen"), + ("UV projection", "UV-Projektion"), + ("UV tiles", "UV-Kacheln"), + ("UV tiles (UDIM)", "UV-Kacheln (UDIM)"), + ("Undo", "Rückgängig"), + ("Uniform value", "Einheitlicher Wert"), + ("Use an equirectangular .hdr or .exr image as the environment", "Ein equirektangulares .hdr- oder .exr-Bild als Umgebung verwenden"), + ("Use the control channel or `texturecraft-cli render` for screenshots", "Für Screenshots den Steuerkanal oder `texturecraft-cli render` verwenden"), + ("Value", "Wert"), + ("Version {version}", "Version {version}"), + ("Version: {version} ({gpu})", "Version: {version} ({gpu})"), + ("View through this camera", "Durch diese Kamera sehen"), + ("Viewer settings", "Ansichtseinstellungen"), + ("Viewport", "Ansichtsfenster"), + ("Viewport and brush (fixed)", "Ansichtsfenster und Pinsel (fest)"), + ("Views", "Ansichten"), + ("Vivid light", "Strahlendes Licht"), + ("Voronoi", "Voronoi"), + ("Warp", "Verkrümmen"), + ("Warp Directional", "Richtungsverkrümmung"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ mit MTL, Texturen daneben"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "WebGPU ist in diesem Browser nicht verfügbar, daher läuft TextureCraft mit WebGL2: Der Rendering-Modus berechnet Path Tracing auf der CPU (langsamer), und große Texturesets werden in reduzierter Auflösung angezeigt. Aktuelle Versionen von Chrome, Edge und Safari unterstützen WebGPU.", + ), + ("Wheel / Alt + RMB drag", "Mausrad / Alt + RMT ziehen"), + ("White", "Weiß"), + ("Width", "Breite"), + ("Width (texels at 2K)", "Breite (Texel bei 2K)"), + ("Window", "Fenster"), + ("Wood grain", "Holzmaserung"), + ( + "Works in texture space, like the blur: it does not cross UV seams.", + "Arbeitet im Texturraum wie das Weichzeichnen: UV-Nähte werden nicht überschritten.", + ), + ("World Space Normal", "Normale (Weltkoordinaten)"), + ("Yellow / blue", "Gelb / Blau"), + ("Zoom", "Zoomen"), + ("a missing layer", "eine fehlende Ebene"), + ("aniso", "aniso"), + ("aniso angle", "aniso w"), + ("ao", "ao"), + ("coat", "lack"), + ("coat nrm", "lack nrm"), + ("coat rough", "lack rau"), + ("color", "farbe"), + ("emiss", "emiss"), + ("glTF binary with textures", "glTF binär mit Texturen"), + ("gloss", "glanz"), + ("height", "höhe"), + ("metal", "metall"), + ("min", "Min."), + ("missing", "fehlt"), + ("missing source", "Quelle fehlt"), + ("no GPU", "keine GPU"), + ("none", "keins"), + ("nrm", "nrm"), + ("off", "aus"), + ("op", "deck"), + ("rough", "rau"), + ("scatter", "streu"), + ("sheen", "schim"), + ("sheen color", "schim fb"), + ("sheen rough", "schim rau"), + ("spec", "spec"), + ("specular", "specular"), + ("transm", "transm"), + ("{action} (undone)", "{action} (rückgängig gemacht)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file}: über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel bzw. in das Ansichtsfenster ziehen)", + ), + ("{name} copy", "{name} Kopie"), + ("{n} bits", "{n} Bit"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "{n} Kontrollpunkte. Klicken Sie auf das Mesh (oder die 2D-Ansicht), um Punkte hinzuzufügen, und ziehen Sie sie zum Anpassen; ein Klick auf den ersten Punkt schließt den Pfad. Eingabe malt ihn mit dem Pinsel (ein geschlossener, gefüllter Pfad füllt sein Inneres), Esc bricht ab.", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} Einträge teilen sich ein Tastenkürzel; der erste in der Liste hat Vorrang."), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (Skalierung {scale}, Startwert {seed})"), + ("Template name", "Vorlagenname"), + ("Save current project as template", "Aktuelles Projekt als Vorlage speichern"), + ("Distribution", "Verteilung"), + ("Cosine", "Kosinus"), + ("Uniform", "Gleichmäßig"), + ("Normalization", "Normalisierung"), + // Settings › Interface: brightness and accent color. + ("Brightness", "Helligkeit"), + ("Dark", "Dunkel"), + ("Medium dark", "Mitteldunkel"), + ("Medium light", "Mittelhell"), + ("Light", "Hell"), + ("Accent color", "Akzentfarbe"), + ("Copper", "Kupfer"), + ("Coral", "Koralle"), + ("Blue", "Blau"), + ("Violet", "Violett"), + ("Green", "Grün"), + ("Amber", "Bernstein"), + ("Pink", "Pink"), + ("Minimize", "Minimieren"), + ("Maximize", "Maximieren"), + ("Restore", "Wiederherstellen"), + ("Title bar", "Titelleiste"), + ("System title bar (applies on restart)", "Titelleiste des Systems (ab dem nächsten Start)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", + ), + ("Brushes", "Pinsel"), + ("Brush name", "Pinselname"), + ("Save current brush", "Aktuellen Pinsel speichern"), + ("Start window", "Startfenster"), + ("Show at startup", "Beim Start anzeigen"), + ("Continue with the sample project", "Mit dem Beispielprojekt fortfahren"), + ("No recent projects yet", "Noch keine zuletzt geöffneten Projekte"), + ("Text", "Text"), + ("Font", "Schrift"), + ("Style", "Schnitt"), + ("Use as brush alpha", "Als Pinsel-Alpha verwenden"), + ("Place as decal", "Als Decal platzieren"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Klick: diesen Kanal ein- oder ausschalten. Alt+Klick: nur diesen Kanal"), + ("Show all", "Alle einblenden"), + ("Hide all", "Alle ausblenden"), + ("Invert show/hide", "Ein-/Ausblenden umkehren"), + ("Show or hide texture sets", "Texturesets ein- oder ausblenden"), + ("Focus: show only the active texture set", "Fokus: nur das aktive Textureset zeigen"), + ("Unsaved changes", "Ungespeicherte Änderungen"), + ("Don't save", "Nicht speichern"), + ("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"), + ("Radius", "Radius"), + ("Remove skew correction", "Skew-Korrektur entfernen"), + ("Twill weave", "Köperbindung"), + ("Save the changes to {name} first?", "Änderungen an {name} zuerst speichern?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Pfade bleiben bearbeitbar: Wähle einen, um seine Punkte zu verschieben oder Pinsel und Material zu ändern, und die Unterebene wird sofort neu gemalt. Füge Pfade mit dem Pfad-Werkzeug hinzu.", + ), + ("Import material...", "Material importieren..."), + ("MaterialCraft material", "MaterialCraft-Material"), + ("Cooked at {size} px", "Berechnet mit {size} px"), + ("Preset", "Vorgabe"), + ("Re-cook", "Neu berechnen"), + ("Open in MaterialCraft", "In MaterialCraft öffnen"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "In MaterialCraft geöffnet: Dort mit Datei > An TextureCraft senden die Änderungen zurückholen", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "Parameter lassen sich in der Desktop-App mit installiertem MaterialCraft ändern"), + ("Add High-Poly Meshes", "High-Poly-Meshes hinzufügen"), + ("All", "Alle"), + ("Apply Diffusion", "Diffusion anwenden"), + ("Attenuation", "Abschwächung"), + ("Auto Tonemapping", "Automatisches Tonemapping"), + ("Average Normals", "Normalen mitteln"), + ("BBox", "Begrenzungsrahmen"), + ("BSphere", "Begrenzungskugel"), + ("Mesh Map Bakers", "Mesh-Map-Baker"), + ("Common Settings", "Allgemeine Einstellungen"), + ("Mesh Map Settings", "Mesh-Map-Einstellungen"), + ("Check All", "Alle auswählen"), + ("No Parameters", "Keine Parameter"), + ("Bake Selected Textures ({n})", "Ausgewählte Texturen backen ({n})"), + ("By Mesh Name", "Nach Mesh-Name"), + ("Cage", "Käfig"), + ("Cage Scene", "Käfigszene"), + ("Cage Type", "Käfigtyp"), + ("Color Generator", "Farbgenerator"), + ("Color Source", "Farbquelle"), + ("Common Parameters", "Gemeinsame Parameter"), + ("Custom File", "Benutzerdefinierte Datei"), + ("Details", "Details"), + ("Dilation Width", "Dilatationsbreite"), + ("Distance-Based", "Distanzbasiert"), + ("Edge Contrast", "Kantenkontrast"), + ("Edge Distance", "Kantenabstand"), + ("Edge Protection", "Kantenschutz"), + ("Enable Seams", "Nähte aktivieren"), + ("File ID", "Datei-ID"), + ("Full Scene", "Gesamte Szene"), + ("Generate from Mesh", "Aus Mesh erzeugen"), + ("Generate from Normal Map", "Aus Normal-Map erzeugen"), + ("Ground Plane", "Bodenebene"), + ("Ground Plane Offset", "Bodenversatz"), + ("High Poly Mesh Suffix", "Suffix für High-Poly-Mesh"), + ("High Poly Scene", "High-Poly-Szene"), + ("High-Poly Parameters", "High-Poly-Parameter"), + ("Hue Shift", "Farbtonverschiebung"), + ("Ignore Backface", "Rückseiten ignorieren"), + ("Ignore Backface Suffix", "Suffix für ignorierte Rückseiten"), + ("Include in Bake", "Beim Backen einschließen"), + ("Load Cage", "Käfig laden"), + ("Lock Output Size", "Ausgabegröße sperren"), + ("Low Poly Mesh Suffix", "Suffix für Low-Poly-Mesh"), + ("Manual", "Manuell"), + ("Material Color", "Materialfarbe"), + ("Max Frontal Distance", "Max. vordere Distanz"), + ("Max Occluder Distance", "Max. Verdeckerdistanz"), + ("Max Rear Distance", "Max. hintere Distanz"), + ("Mesh ID", "Mesh-ID"), + ("Method", "Methode"), + ("Min Occluder Distance", "Minimaler Verdeckungsabstand"), + ("Never", "Nie"), + ("No High-Poly Meshes", "Keine High-Poly-Meshes"), + ("Normalization Scale", "Normalisierungsskala"), + ("Normalization Type", "Normalisierungstyp"), + ("Only Same Mesh Name", "Nur gleicher Mesh-Name"), + ("Output Size", "Ausgabegröße"), + ("Match", "Zuordnung"), + ("Skew Correction Method", "Methode der Verzerrungskorrektur"), + ("Mesh Normals Based", "Basierend auf Mesh-Normalen"), + ("Face Normals Based", "Basierend auf Flächennormalen"), + ("Reset Painted Cage", "Gemalten Käfig Zurücksetzen"), + ("Paint Cage", "Käfig malen"), + ("Paint Skew Correction", "Verzerrungskorrektur malen"), + ("Per Material", "Pro Material"), + ("Random", "Zufällig"), + ("Relative to Bounding Box", "Relativ zum Begrenzungsrahmen"), + ("Relative to Low Mesh", "Relativ zum Low-Poly-Mesh"), + ("Relative to Min/Max", "Relativ zu Min/Max"), + ("Relative to Ray Distances", "Relativ zu Strahlabständen"), + ("Remove Cage", "Käfig entfernen"), + ("Remove Skew Correction", "Skew-Korrektur entfernen"), + ("Restore Defaults", "Standardwerte wiederherstellen"), + ("Return to Painting Mode", "Zurück zum Malmodus"), + ("Sampling Radius", "Abtastradius"), + ("Scaling Divisor", "Skalierungsdivisor"), + ("Seams Intensity", "Nahtintensität"), + ("Secondary Rays", "Sekundärstrahlen"), + ("Self Intersection", "Selbstüberschneidung"), + ("Self Occlusion", "Eigenverdeckung"), + ("Skew Correction", "Skew-Korrektur"), + ("Smooth", "Glatt"), + ("Spread Angle", "Streuwinkel"), + ("Submesh", "Teilmesh"), + ("Use Low Poly Mesh as High Poly Mesh", "Low-Poly-Mesh als High-Poly-Mesh verwenden"), + ("Value Bounds Max", "Maximaler Grenzwert"), + ("Value Bounds Min", "Minimaler Grenzwert"), + ("Vertex Color", "Scheitelpunktfarbe"), + ("Select the layer content", "Ebeneninhalt auswählen"), + ("Paint layer", "Malebene"), + ("Fill layer", "Füllebene"), + ("1 effect", "1 Effekt"), + ("{count} effects", "{count} Effekte"), + ("Mask effects", "Maskeneffekte"), + ("Content effects", "Inhaltseffekte"), + ("Fold or unfold these effects", "Diese Effekte ein- oder ausklappen"), + ("Remove resolution override", "Auflösungsüberschreibung entfernen"), + ("Texture set resolution", "Auflösung des Textursets"), + ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Angle span", "Winkelbereich"), + ("Axis position", "Achsenposition"), + ("Count", "Anzahl"), + ("Display", "Anzeige"), + ("Hide while painting", "Beim Malen ausblenden"), + ("Manipulator size", "Manipulatorgröße"), + ("Mirror symmetry", "Spiegelsymmetrie"), + ("Radial settings", "Radial-Einstellungen"), + ("Radial symmetry", "Radialsymmetrie"), + ("Show axis", "Achse anzeigen"), + ("Show axis position manipulator", "Manipulator für die Achsenposition anzeigen"), + ("Show cursor", "Cursor anzeigen"), + ("Show intersection", "Schnittlinie anzeigen"), + ("Show plane", "Ebene anzeigen"), + ("Symmetry", "Symmetrie"), + ("Symmetry color display", "Anzeigefarbe der Symmetrie"), + ("Symmetry settings", "Symmetrie-Einstellungen"), + ("Type", "Typ"), + ("Advanced settings", "Erweiterte Einstellungen"), + ("Import baked maps", "Gebackene Maps importieren"), + ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), + ("Add...", "Hinzufügen..."), + ("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"), + ("Not imported: {files}", "Nicht importiert: {files}"), + ("Baking Visualization", "Bake-Visualisierung"), + ("Show for Selected Texture Set Only", "Nur für das ausgewählte Texturset anzeigen"), + ("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"), + ("UV Seams", "UV-Nähte"), + ("Project Mesh (LP)", "Projektions-Mesh (LP)"), + ("Edges", "Kanten"), + ("Cavities", "Vertiefungen"), + ("Edges and cavities", "Kanten und Vertiefungen"), + ("Raw curvature", "Rohe Krümmung"), + ("Detail sizes", "Detailgrößen"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Liest die Krümmungskarte wie gebacken: Eine Änderung des Modus oder einer Größe schaltet die Detailgrößen ein.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Ein Klick füllt, was darunter liegt; ein aufgezogenes Rechteck füllt, was es beim Aufziehen erfasst", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Enthaltener Mittelpunkt: Polygone füllen, deren Mittelpunkt im Rechteck liegt"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Schnellmaske wird bearbeitet: Füllungen markieren, wo Malen erlaubt ist. Zum Beenden U drücken.", + ), + ("Fill mode", "Füllmodus"), + ("Fill only polygons the camera sees (3D view)", "Nur Polygone füllen, die die Kamera sieht (3D-Ansicht)"), + ("Hit-test", "Treffertest"), + ("How a rectangle selects polygons", "Wie ein Rechteck Polygone auswählt"), + ("Intersection: fill polygons the rectangle touches", "Schnittmenge: Polygone füllen, die das Rechteck berührt"), + ("Rectangle fill", "Rechteckfüllung"), + ("Select a paint layer or a layer's mask to fill", "Wähle zum Füllen eine Malebene oder eine Ebenenmaske"), + ("Selection mode", "Auswahlmodus"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Dreieck füllt einzelne Dreiecke, Polygon ganze Vierecke und N-Ecke, Mesh die zusammenhängende Geometrie, UV-Insel die UV-Inseln", + ), + ("Visible polygons only", "Nur sichtbare Polygone"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"), + ("The file dialog couldn't be shown: {error}", "Der Dateidialog konnte nicht angezeigt werden: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Das Projekt hat sich geändert, während der Dialog geöffnet war, daher wurde nichts ausgeführt", + ), + ("Cores kept for the UI", "Für die Oberfläche reservierte Kerne"), + ("Max RAM while saving", "Max. RAM beim Speichern"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Das Speichern nutzt die übrigen Kerne und höchstens diesen Anteil des freien RAMs. Mindestens ein Kern arbeitet immer.", + ), + ("Max project size on open", "Max. Projektgröße beim Öffnen"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", + ), + ("Filter by type", "Nach Typ filtern"), + ("All libraries", "Alle Bibliotheken"), + ("Browse folders", "Ordner durchsuchen"), + ("Starter assets", "Mitgelieferte Assets"), + ("Your assets", "Eigene Assets"), + ("Reset query", "Abfrage zurücksetzen"), + ("Refresh", "Aktualisieren"), + ("Saved searches", "Gespeicherte Suchen"), + ("Save the current search", "Aktuelle Suche speichern"), + ("Delete", "Löschen"), + ("Filter by path", "Nach Pfad filtern"), + ("Hide non-applicable folders", "Nicht zutreffende Ordner ausblenden"), + ("Thumbnail size", "Vorschaugröße"), + ("Small", "Klein"), + ("Medium", "Mittel"), + ("Large", "Groß"), + ("List", "Liste"), + ("Procedurals", "Prozedurale"), +]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs new file mode 100644 index 00000000..ed759054 --- /dev/null +++ b/crates/ui-egui/src/i18n/es.rs @@ -0,0 +1,1185 @@ +//! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Horneando {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Horneando {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir el mapa más reciente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pintura está en pausa mientras se muestra un horneado. Cancela el horneado o espera a que termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Lo que muestra la vista 3D mientras se hornea: el último mapa terminado, un mapa terminado a elección o el material. Los mapas aún sin hornear muestran un valor neutro.", + ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), + ("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"), + ("2D view only", "Solo vista 2D"), + ("32 bits (float)", "32 bits (float)"), + ("3D mesh", "Malla 3D"), + ("3D meshes", "Mallas 3D"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "Pintura de texturas 3D: capas, máscaras, materiales inteligentes, horneado de mapas de malla y exportación.", + ), + ("3D view only", "Solo vista 3D"), + ("3D/2D views", "Vistas 3D/2D"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "Una carpeta fusiona sus elementos (paso directo). Define la opacidad por canal en las filas de capa.", + ), + ("ACES filmic", "ACES fílmico"), + ("Ambient", "Ambiente"), + ("AO intensity", "Intensidad de AO"), + ("About TextureCraft", "Acerca de TextureCraft"), + ("About TextureCraft...", "Acerca de TextureCraft..."), + ("Add an anchor point to a layer below to use its stack as a mask.", "Añade un punto de anclaje a una capa inferior para usar su pila como máscara."), + ("Add anchor point", "Añadir punto de anclaje"), + ("Add as decal (view center)", "Añadir como calcomanía (centro de la vista)"), + ("Add black mask", "Añadir máscara negra"), + ("Add channel", "Añadir canal"), + ("Add color", "Añadir color"), + ("Add compare mask", "Añadir máscara de comparación"), + ("Add effect", "Añadir efecto"), + ("Add fill", "Añadir relleno"), + ("Add fill layer", "Añadir capa de relleno"), + ("Add filter", "Añadir filtro"), + ("Add folder", "Añadir carpeta"), + ("Add generator", "Añadir generador"), + ("Add levels", "Añadir niveles"), + ("Add mask", "Añadir máscara"), + ("Add mask with color selection", "Añadir máscara con selección de color"), + ("Add output", "Añadir salida"), + ("Add paint", "Añadir pintura"), + ("Add paint layer", "Añadir capa de pintura"), + ("Add smart material from the shelf", "Añadir material inteligente desde la biblioteca"), + ("Add to the layer content", "Añadir al contenido de la capa"), + ("Add to the mask", "Añadir a la máscara"), + ("Add white mask", "Añadir máscara blanca"), + ("Adjustments", "Ajustes de imagen"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "Alineado: se mantiene el desplazamiento definido por el primer trazo. V + clic define un nuevo origen.", + ), + ("Alignment", "Alineación"), + ("Alignment and culling", "Alineación y descarte"), + ("All layers", "Todas las capas"), + ("Alpha", "Alfa"), + ("Alphas", "Alfas"), + ("Also bound to {item} ({menu})", "También asignado a {item} ({menu})"), + ("Alt + LMB drag", "Alt + arrastrar con botón izq."), + ("Always", "Siempre"), + ("Ambient Occlusion", "Oclusión ambiental"), + ("Ambient occlusion", "Oclusión ambiental"), + ("Amount", "Cantidad"), + ("Anchor point", "Punto de anclaje"), + ("Anchor: {name}", "Anclaje: {name}"), + ("Anchor: {name} ({channel})", "Anclaje: {name} ({channel})"), + ("Angle", "Ángulo"), + ("Angle (degrees)", "Ángulo (grados)"), + ("Angle fade from", "Atenuación por ángulo desde"), + ("Angle fade to", "Atenuación por ángulo hasta"), + ("Angle jitter", "Variación de ángulo"), + ("Anisotropy angle", "Ángulo de anisotropía"), + ("Anisotropy level", "Nivel de anisotropía"), + ("Antialiasing", "Antialiasing"), + ("Aperture", "Apertura"), + ("Apply", "Aplicar"), + ("ArtCraft website...", "Sitio web de ArtCraft..."), + ("Assets", "Recursos"), + ("Auto", "Auto"), + ("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"), + ("Autosave every", "Autoguardar cada"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "Las copias automáticas, los materiales inteligentes, los ajustes preestablecidos, las plantillas y los diseños de la interfaz se guardan en la carpeta de datos. Una carpeta nueva se aplica al reiniciar; los archivos ya guardados se quedan donde están.", + ), + ("Axis", "Eje"), + ("Back to painting", "Volver a pintar"), + ("Backface culling", "Descarte de caras traseras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Hornea un mapa de ID (F8) para tomar colores de la malla."), + ("Bake Mesh Maps", "Hornear mapas de malla"), + ("Bake mesh maps", "Hornear mapas de malla"), + ( + "Bake mesh maps (F8) for curvature, AO and thickness based generators.", + "Hornea los mapas de malla (F8) para los generadores basados en curvatura, AO y grosor.", + ), + ("Baked Lighting", "Iluminación horneada"), + ("Baking", "Horneado"), + ("Base color", "Color base"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "Color base es el color difuso, Especular el color F0 y Brillo 1 - rugosidad (añade estos canales en los ajustes del conjunto de texturas).", + ), + ("Base color, Metallic, Roughness and Specular level.", "Color base, Metálico, Rugosidad y Nivel especular."), + ("Based on each texture set's size", "Según el tamaño de cada conjunto de texturas"), + ("Basic settings", "Ajustes básicos"), + ("Bent Normals", "Normales curvadas"), + ("Bevel", "Bisel"), + ("Black", "Negro"), + ("Blending", "Fusión"), + ("Blending mode of the displayed channel", "Modo de fusión del canal mostrado"), + ("Blur", "Desenfoque"), + ("Blur Directional", "Desenfoque direccional"), + ("Blur and sharpen", "Desenfocar y enfocar"), + ("Bounces", "Rebotes"), + ("Bricks", "Ladrillos"), + ("Brush", "Pincel"), + ("Brush size", "Tamaño del pincel"), + ("Brush size down / up", "Reducir / aumentar tamaño del pincel"), + ("Brushed lines", "Líneas cepilladas"), + ("Built-in (read-only): duplicate it to edit", "Integrada (solo lectura): duplícala para editarla"), + ("Built-in templates are read-only: duplicate one to edit it", "Las plantillas integradas son de solo lectura: duplica una para editarla"), + ("Built-in: {mesh}", "Integrada: {mesh}"), + ("Cage: {name}", "Jaula: {name}"), + ("Camera", "Cámara"), + ("Colors", "Colores"), + ("Go to camera 1", "Ir a la cámara 1"), + ("Go to camera 2", "Ir a la cámara 2"), + ("Go to camera 3", "Ir a la cámara 3"), + ("Go to camera 4", "Ir a la cámara 4"), + ("Go to camera 5", "Ir a la cámara 5"), + ("Go to camera 6", "Ir a la cámara 6"), + ("Go to camera 7", "Ir a la cámara 7"), + ("Go to camera 8", "Ir a la cámara 8"), + ("Go to camera 9", "Ir a la cámara 9"), + ("Camera settings", "Ajustes de cámara"), + ("Cancel", "Cancelar"), + ("Cancel the stroke", "Cancelar el trazo"), + ("Cell size (texels at 2K)", "Tamaño de celda (téxeles a 2K)"), + ("Cells", "Celdas"), + ("Channel", "Canal"), + ("Channel source: uniform value, procedural, image or anchor", "Origen del canal: valor uniforme, procedural, imagen o anclaje"), + ("Channels", "Canales"), + ("Check for Updates...", "Buscar actualizaciones..."), + ("Checker", "Damero"), + ("Clamp", "Limitar"), + ("Clear", "Borrar"), + ("Clear mask", "Borrar máscara"), + ("Clear recent projects", "Borrar proyectos recientes"), + ("Click a mesh part to show or hide the selected layer on it.", "Haz clic en una parte de la malla para mostrar u ocultar en ella la capa seleccionada."), + ("Click the mesh to pick its material into the brush", "Haz clic en la malla para tomar su material en el pincel"), + ("Click the mesh to place the decal", "Haz clic en la malla para colocar la calcomanía"), + ("Click, then press the new shortcut (Esc cancels)", "Haz clic y pulsa el nuevo atajo (Esc cancela)"), + ("Clone", "Clonar"), + ("Close", "Cerrar"), + ("Closed path", "Trazado cerrado"), + ("Cloud", "Nube"), + ("Clouds", "Nubes"), + ("Coat normal", "Normal del barniz"), + ("Coat roughness", "Rugosidad del barniz"), + ("Coat weight", "Peso del barniz"), + ("Color", "Color"), + ("Color Balance", "Equilibrio de color"), + ("Color burn", "Subexponer color"), + ("Color dodge", "Sobreexponer color"), + ( + "Color of the light that travels under the surface (each channel goes as far as its value)", + "Color de la luz que viaja bajo la superficie (cada canal llega tan lejos como su valor)", + ), + ("Color picker", "Cuentagotas"), + ("Color selection", "Selección de color"), + ("Color to replace", "Color a reemplazar"), + ( + "Colors near the first shift towards the second, keeping their shading.", + "Los colores cercanos al primero se desplazan hacia el segundo y conservan su sombreado.", + ), + ( + "Colors read as gray. Add a levels or blur effect above to shape the result.", + "Los colores se leen como gris. Añade encima un efecto de niveles o desenfoque para ajustar el resultado.", + ), + ("Combine with the layer's height", "Combinar con la altura de la capa"), + ("Compare mask", "Máscara de comparación"), + ("Compositing", "Composición"), + ("Constant", "Constante"), + ("Constants", "Constantes"), + ("Contrast", "Contraste"), + ("Contrast/Luminosity", "Contraste/Luminosidad"), + ("Converted maps", "Mapas convertidos"), + ("Copy RGB values", "Copiar los valores RGB"), + ("Copy effect", "Copiar efecto"), + ("Copy from", "Copiar de"), + ("Copy layer(s)", "Copiar capa(s)"), + ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"), + ("Copy to all texture sets", "Copiar a todos los conjuntos de texturas"), + ("Copy what the texture set shows", "Copiar lo que muestra el conjunto de texturas"), + ("Couldn't encode the render", "No se pudo codificar el render"), + ("Couldn't export textures: {error}", "No se pudieron exportar las texturas: {error}"), + ("Couldn't export the mesh: {error}", "No se pudo exportar la malla: {error}"), + ("Couldn't export the template: {error}", "No se pudo exportar la plantilla: {error}"), + ("Couldn't import {name}: {error}", "No se pudo importar {name}: {error}"), + ("Couldn't open {name}: {error}", "No se pudo abrir {name}: {error}"), + ("Couldn't read the render back from the GPU", "No se pudo recuperar el render de la GPU"), + ("Couldn't save the render: {error}", "No se pudo guardar el render: {error}"), + ("Couldn't save {name}: {error}", "No se pudo guardar {name}: {error}"), + ("Count per stamp", "Cantidad por estampado"), + ("Crate", "Caja"), + ("Create", "Crear"), + ("Create smart material", "Crear material inteligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+arrastrar con botón der. en una vista ajusta el tamaño y la dureza; Ctrl+arrastrar con botón izq., el flujo y el ángulo.", + ), + ("Cube", "Cubo"), + ("Current layer", "Capa actual"), + ("Curvature", "Curvatura"), + ("Cut effect", "Cortar efecto"), + ("Cut layer(s)", "Cortar capa(s)"), + ("Cyan / red", "Cian / rojo"), + ("Cylinder", "Cilindro"), + ("Cylindrical projection", "Proyección cilíndrica"), + ( + "Dark to light: the content's luminance picks a color along these stops.", + "De oscuro a claro: la luminancia del contenido elige un color a lo largo de estos puntos.", + ), + ("Darken (Min)", "Oscurecer (mín.)"), + ("Data folder", "Carpeta de datos"), + ("Decal", "Calcomanía"), + ("Decal projection", "Proyección de calcomanía"), + ("Default", "Predeterminado"), + ("Default camera", "Cámara predeterminada"), + ("Delete the selected template", "Eliminar la plantilla seleccionada"), + ("Delete this camera", "Eliminar esta cámara"), + ("Deleted template \"{name}\"", "Plantilla \"{name}\" eliminada"), + ("Denoise", "Eliminar ruido"), + ("Depth", "Profundidad"), + ("Depth of field", "Profundidad de campo"), + ("Depth of field (viewport and Rendering mode)", "Profundidad de campo (ventana gráfica y modo Renderizado)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "Profundidad del plano nítido a lo largo de la vista (0: el centro de órbita)"), + ("Details saved to {file}", "Detalles guardados en {file}"), + ("Difference", "Diferencia"), + ("Dilation + default background color", "Dilatación + color de fondo predeterminado"), + ("Dilation + transparent", "Dilatación + transparente"), + ("Dilation infinite", "Dilatación infinita"), + ("DirectX normal map", "Mapa de normales DirectX"), + ("Dirt", "Suciedad"), + ("Disable", "Desactivado"), + ("Dismiss", "Cerrar"), + ("Displacement (height channel)", "Desplazamiento (canal de altura)"), + ("Display Settings", "Ajustes de visualización"), + ("Display material", "Mostrar material"), + ("Display next channel", "Mostrar canal siguiente"), + ("Display next mesh map", "Mostrar mapa de malla siguiente"), + ("Display previous channel", "Mostrar canal anterior"), + ("Display previous mesh map", "Mostrar mapa de malla anterior"), + ("Distance", "Distancia"), + ("Distort", "Distorsionar"), + ("Divide", "Dividir"), + ("Document resolution", "Resolución del documento"), + ("Documentation...", "Documentación..."), + ("Done on CPU: {n} / {max} samples, {s} s", "Terminado en CPU: {n} / {max} muestras, {s} s"), + ("Done on GPU: {n} / {max} samples, {s} s", "Terminado en GPU: {n} / {max} muestras, {s} s"), + ("Double-click to rename", "Doble clic para cambiar el nombre"), + ("Download as", "Descargar como"), + ("Downloaded {name}", "{name} descargado"), + ("Drag onto an output channel", "Arrastrar a un canal de salida"), + ( + "Drags the layer stack's values along the stroke into the selected layer.", + "Arrastra los valores de la pila de capas a lo largo del trazo hacia la capa seleccionada.", + ), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "Dibuja {name} del conjunto de texturas \"{set}\". Los cambios en el original se ven en todas las instancias.", + ), + ( + "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", + "Arrastra el marco para mover la calcomanía, una esquina para escalarla y el tirador redondo para girarla", + ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Suelta aquí una imagen del panel Recursos para usarla como este mapa de malla"), + ("Dry streaks", "Trazos secos"), + ("Duplicate effect", "Duplicar efecto"), + ("Duplicate layer(s)", "Duplicar capa(s)"), + ("Duplicate the selected template", "Duplicar la plantilla seleccionada"), + ("Edge Detect", "Detección de bordes"), + ("Edit", "Editar"), + ("Edit keyboard shortcuts...", "Editar atajos de teclado..."), + ("Edit quick mask", "Editar máscara rápida"), + ("Editing quick mask: paint where painting is allowed (U to finish)", "Editando máscara rápida: pinta donde se permite pintar (U para terminar)"), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "Editando la máscara rápida: los trazos pintan donde se permite pintar. Pulsa U para terminar.", + ), + ("Emissive", "Emisivo"), + ("Enable or disable the effect", "Activar o desactivar el efecto"), + ("Enable quick mask", "Activar máscara rápida"), + ("Environment blur", "Desenfoque del entorno"), + ("Environment exposure (EV)", "Exposición del entorno (EV)"), + ("Environment map", "Mapa de entorno"), + ("Environment opacity", "Opacidad del entorno"), + ("Environment rotation", "Rotación del entorno"), + ("Environment settings", "Ajustes de entorno"), + ("Environment: {name}", "Entorno: {name}"), + ("Environments", "Entornos"), + ("Eraser", "Borrador"), + ("Exclusion", "Exclusión"), + ("Expand or collapse the folder", "Expandir o contraer la carpeta"), + ("Export", "Exportar"), + ("Export Mesh...", "Exportar malla..."), + ("Export Textures...", "Exportar texturas..."), + ("Export mesh", "Exportar malla"), + ("Export template", "Plantilla de exportación"), + ("Export templates", "Plantillas de exportación"), + ("Export textures", "Exportar texturas"), + ("Export the selected template (.json)", "Exportar la plantilla seleccionada (.json)"), + ("Exported mesh to {path}", "Malla exportada a {path}"), + ("Exported template \"{name}\" to {path}", "Plantilla \"{name}\" exportada a {path}"), + ("Exported {n} textures to {folder}", "{n} texturas exportadas a {folder}"), + ("F0 from specular level", "F0 desde nivel especular"), + ("Fabric weave", "Tejido"), + ("Field of view (deg)", "Campo de visión (grados)"), + ("File", "Archivo"), + ("File name without extension; variables insert names", "Nombre de archivo sin extensión; las variables insertan nombres"), + ("File type", "Tipo de archivo"), + ("Fill", "Relleno"), + ("Fill the closed path (lasso)", "Rellenar el trazado cerrado (lazo)"), + ("Fill the path (close it first)", "Rellenar el trazado (ciérralo antes)"), + ("Filter", "Filtro"), + ("Filter the remaining noise while keeping edges and texture detail", "Filtrar el ruido restante conservando los bordes y el detalle de la textura"), + ("Filters", "Filtros"), + ("Fine noise", "Ruido fino"), + ("Fingerprints", "Huellas dactilares"), + ("Enter a finite number", "Introduce un número finito"), + ("Double-click or press Enter to edit", "Haz doble clic o pulsa Intro para editar"), + ("Fit the input range to the histogram", "Ajustar el rango de entrada al histograma"), + ("Flatten layer", "Acoplar capa"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Invierte el canal verde de la imagen, para mapas de normales hechos con Y hacia abajo", + ), + ("Flow", "Flujo"), + ("Flow and opacity", "Flujo y opacidad"), + ("Flow jitter", "Variación de flujo"), + ("Focus distance", "Distancia de enfoque"), + ("Folder", "Carpeta"), + ("Folders", "Carpetas"), + ("Follow path", "Seguir trayectoria"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "Para todo el proyecto: cómo se leen las imágenes de mapas de normales usadas como mapas de malla (vuelve a asignarlas tras un cambio) y el valor predeterminado al exportar", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libre y de código abierto (MIT OR Apache-2.0), escrito en Rust."), + ("From template", "Desde la plantilla"), + ("From template / project", "Desde la plantilla / el proyecto"), + ("Full", "Completa"), + ("GPU error: {error}", "Error de GPU: {error}"), + ("Geometry mask", "Máscara de geometría"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "Especular GGX con visibilidad Smith correlacionada con la altura, difuso Lambert, iluminación basada en imagen de suma dividida con irradiancia por armónicos esféricos y atenuación en el horizonte.", + ), + ("Gamma", "Gamma"), + ("General export parameters", "Parámetros generales de exportación"), + ("General properties", "Propiedades generales"), + ("Generator", "Generador"), + ("Geometry and UVs only", "Solo geometría y UV"), + ("Glossiness", "Brillo"), + ("Glossiness from roughness", "Brillo desde rugosidad"), + ("Glow", "Resplandor"), + ("Gradient", "Degradado"), + ("Gradient Map", "Mapa de degradado"), + ("Gravity", "Gravedad"), + ("Gray", "Gris"), + ("Gray + A", "Gris + A"), + ("Gray 50%", "Gris 50%"), + ("Grayscale", "Escala de grises"), + ("Group layer(s)", "Agrupar capa(s)"), + ("Grunge", "Grunge"), + ("HDR environments", "Entornos HDR"), + ("High Pass", "Paso alto"), + ("HSL Perceptive", "HSL perceptivo"), + ("Half", "Mitad"), + ("Hammered", "Martillado"), + ("Hard light", "Luz fuerte"), + ("Hardness", "Dureza"), + ("Height", "Altura"), + ("Height offset", "Desplazamiento de altura"), + ("Height to normal strength", "Intensidad de altura a normal"), + ("Help", "Ayuda"), + ("Hide UI", "Ocultar interfaz"), + ("High", "Alto"), + ("High poly: {name}", "High poly: {name}"), + ("Highlights", "Iluminaciones"), + ("Histogram Range", "Rango de histograma"), + ("Histogram Scan", "Barrido de histograma"), + ("Histogram Shift", "Desplazamiento de histograma"), + ("History", "Historial"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "Mantén S: arrastrar con botón izq. rota, con botón der. escala y con botón central mueve la plantilla.", + ), + ("Hold V and click the mesh to set the clone source", "Mantén V y haz clic en la malla para definir el origen de clonado"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "Mantén V y haz clic en la malla para definir el origen; luego pinta en otro lugar para copiarlo.", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "Distancia que recorre la luz bajo la superficie, como fracción del tamaño de la malla (donde se pinta el canal Peso de dispersión)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "Cuánto desvían la luz las superficies transmisivas (donde se pinta el canal Transmisión): agua 1.33, vidrio 1.5, diamante 2.42", + ), + ("Hue shift (degrees)", "Cambio de tono (grados)"), + ("ID", "ID"), + ("Image: {name}", "Imagen: {name}"), + ("Images", "Imágenes"), + ("Import HDR...", "Importar HDR..."), + ("Import a template (.json)", "Importar una plantilla (.json)"), + ( + "Import an image (File > Import resources) to project it onto the mesh.", + "Importa una imagen (Archivo > Importar recursos) para proyectarla sobre la malla.", + ), + ("Import resources...", "Importar recursos..."), + ("Import MaterialX material...", "Importar material MaterialX..."), + ("MaterialX materials", "Materiales MaterialX"), + ("Import...", "Importar..."), + ("Imported template \"{name}\"", "Plantilla \"{name}\" importada"), + ("Imported {name}", "{name} importado"), + ("Index of refraction", "Índice de refracción"), + ("Input high", "Entrada alta"), + ("Input low", "Entrada baja"), + ("Input maps", "Mapas de entrada"), + ("Insert a variable", "Insertar una variable"), + ("Instance", "Instancia"), + ("Instantiate across texture sets", "Instanciar en los conjuntos de texturas"), + ("Intensity (texels at 2K)", "Intensidad (téxeles a 2K)"), + ("Interface", "Interfaz"), + ("Interface scale", "Escala de la interfaz"), + ("Inverse Subtract", "Resta inversa"), + ("Inverse divide", "División inversa"), + ("Invert", "Invertir"), + ("Invert mask", "Invertir máscara"), + ("Invert mask background", "Invertir fondo de la máscara"), + ("Invert mask value", "Invertir valor de máscara"), + ("Invert quick mask", "Invertir máscara rápida"), + ("Jitters", "Variaciones"), + ("Join the ArtCraft community on Discord", "Únete a la comunidad de ArtCraft en Discord"), + ("Join the community (Discord)...", "Unirse a la comunidad (Discord)..."), + ("Key light (shadow-casting light, direct only)", "Luz principal (proyecta sombras, solo directa)"), + ("Keyboard", "Teclado"), + ("Keyboard shortcuts", "Atajos de teclado"), + ("Light azimuth (degrees)", "Acimut de la luz (grados)"), + ("Light elevation (degrees)", "Elevación de la luz (grados)"), + ("Light intensity", "Intensidad de la luz"), + ("LMB", "Botón izq."), + ("Language", "Idioma"), + ("Layer mask", "Máscara de capa"), + ("Layer memory: {mb} MB", "Memoria de capas: {mb} MB"), + ("Layers", "Capas"), + ("Lazy mouse", "Ratón perezoso"), + ("Lazy mouse distance", "Distancia del ratón perezoso"), + ("Leather grain", "Grano de cuero"), + ("Lens size: how quickly things blur away from the focus distance", "Tamaño de la lente: lo rápido que se desenfoca todo fuera de la distancia de enfoque"), + ("Level", "Nivel"), + ("Levels", "Niveles"), + ("Lifetime (steps)", "Duración (pasos)"), + ("Light / direction", "Luz / dirección"), + ("Lighten (Max)", "Aclarar (máx.)"), + ("Lightness", "Claridad"), + ("Linear", "Lineal"), + ("Linear burn", "Subexposición lineal"), + ("Linear dodge (Add)", "Sobreexposición lineal (añadir)"), + ("Linear light", "Luz lineal"), + ("List of exports", "Lista de exportaciones"), + ("Load UI Layout", "Cargar diseño de interfaz"), + ("Loaded UI layout {path}", "Diseño de interfaz cargado: {path}"), + ("Log", "Registro"), + ("Low", "Bajo"), + ("Luminosity", "Luminosidad"), + ("MMB drag / Alt + MMB", "Arrastrar con botón central / Alt + botón central"), + ("Made by the ArtCraft team and community.", "Creado por el equipo y la comunidad de ArtCraft."), + ("Magenta / green", "Magenta / verde"), + ("Main shader", "Sombreador principal"), + ("Marble veins", "Vetas de mármol"), + ("Mask", "Máscara"), + ("Mask Editor: Edge wear", "Editor de máscaras: desgaste de bordes"), + ("Mask value (gray)", "Valor de máscara (gris)"), + ("Mask with height", "Enmascarar con la altura"), + ("MatFinish Grind", "Acabado amolado"), + ("MatFinish Hammered", "Acabado martillado"), + ("MatFinish Raw", "Acabado en bruto"), + ("MatFinish Sanded", "Acabado lijado"), + ("Material", "Material"), + ("Material ball", "Bola de material"), + ("Material finish", "Acabado de material"), + ("Materials", "Materiales"), + ("Maximum", "Máximo"), + ("Mesh fill", "Relleno de malla"), + ("Mesh map: {map}", "Mapa de malla: {map}"), + ("Mesh maps", "Mapas de malla"), + ("Mesh maps baked", "Mapas de malla horneados"), + ("Meshes", "Mallas"), + ("Metallic", "Metálico"), + ("Midtones", "Medios tonos"), + ("Minimum", "Mínimo"), + ("Minimum size (%)", "Tamaño mínimo (%)"), + ("Missing (bake to create)", "Falta (hornear para crear)"), + ("Mixed AO", "AO mixta"), + ("Mode", "Modo"), + ("More in Assets > Alphas: click one, or drag it here", "Más en Recursos > Alfas: haz clic en uno o arrástralo aquí"), + ("Mosaic", "Mosaico"), + ("Move down", "Bajar"), + ("Move up", "Subir"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "Desplaza la superficie según el canal de altura sobre una copia más fina de la malla, con la intensidad de altura a normal (solo en el visor: la pintura sigue la superficie base)", + ), + ("Multiply", "Multiplicar"), + ("My smart materials", "Mis materiales inteligentes"), + ("Name", "Nombre"), + ("New project", "Nuevo proyecto"), + ("New project...", "Nuevo proyecto..."), + ("New template", "Nueva plantilla"), + ("No GPU renderer available", "No hay ningún renderizador de GPU disponible"), + ("No font on this system can show this language", "Ninguna fuente del sistema puede mostrar este idioma"), + ( + "No outputs yet: add one above, then drag input maps onto its channels.", + "Aún no hay salidas: añade una arriba y arrastra mapas de entrada a sus canales.", + ), + ("No padding (passthrough)", "Sin margen (paso directo)"), + ("Noise amount", "Cantidad de ruido"), + ("Noise scale", "Escala del ruido"), + ("None", "Ninguno"), + ("Normal", "Normal"), + ("Normal DirectX", "Normal DirectX"), + ("Normal Invert", "Invertir normal"), + ("Normal OpenGL", "Normal OpenGL"), + ("Normal from height", "Normal desde altura"), + ("Normal map combine", "Combinar mapa de normales"), + ("Normal map detail", "Detalle de mapa de normales"), + ("Color space", "Espacio de color"), + ("Normal map format", "Formato del mapa de normales"), + ("Normal map inverse detail", "Detalle inverso de mapa de normales"), + ("Normal: painting uses the flat normal", "Normal: la pintura usa la normal plana"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "No hay suficiente memoria de GPU para mostrar por completo {count} conjuntos de texturas ({names}): reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", + ), + ("Not exported: no source in this texture set", "No exportado: no hay origen en este conjunto de texturas"), + ("Not saved: {error}", "No guardado: {error}"), + ("Off", "Desactivado"), + ("Offset", "Desplazamiento"), + ("Offset right", "Desplazamiento a la derecha"), + ("Offset up", "Desplazamiento hacia arriba"), + ("Offset {axis}", "Desplazamiento {axis}"), + ( + "Offsets the textures by the height channel, at the height to normal strength", + "Desplaza las texturas según el canal de altura, con la intensidad de altura a normal", + ), + ("On", "Activado"), + ("Opacity", "Opacidad"), + ("Open sample project...", "Abrir proyecto de ejemplo..."), + ("Open...", "Abrir..."), + ("Opened {name}", "{name} abierto"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "Los canales opcionales añaden barniz (Peso del barniz, Rugosidad del barniz, Normal del barniz), lustre (Peso del lustre, color, rugosidad), anisotropía (Nivel de anisotropía, ángulo), dispersión subsuperficial (Peso de dispersión) y transmisión (Transmisión).", + ), + ("Orbit", "Orbitar"), + ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), + ("Output directory", "Directorio de salida"), + ("Output high", "Salida alta"), + ("Output low", "Salida baja"), + ("Output template", "Plantilla de salida"), + ("Output templates", "Plantillas de salida"), + ("Overlay", "Superponer"), + ("Overlay opacity", "Opacidad de superposición"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidad (TextureCraft)"), + ("Pick color", "Tomar color"), + ("PNG image", "Imagen PNG"), + ("Padding", "Margen"), + ("Paint", "Pintar"), + ("Paint chips", "Pintura desconchada"), + ("Paint on the mesh to edit the layer content.", "Pinta sobre la malla para editar el contenido de la capa."), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "Pinta sobre la malla para editar esta máscara. Usa el valor de máscara de la pestaña Material para el gris.", + ), + ("Paint with the current tool", "Pintar con la herramienta actual"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "Píxeles de capas pintadas {pixels} MB, canales compuestos {composites} MB, caché de composición {cache} MB", + ), + ("Painting", "Pintura"), + ("Pan", "Desplazar"), + ("Parallax occlusion (height channel)", "Oclusión de paralaje (canal de altura)"), + ( + "Partial mask values follow the layer's height: high parts show first", + "Los valores parciales de la máscara siguen la altura de la capa: las partes altas aparecen primero", + ), + ("Particle brush (slides down the surface)", "Pincel de partículas (se deslizan por la superficie)"), + ("Particle brush: particles slide down the surface", "Pincel de partículas: las partículas se deslizan por la superficie"), + ("Particles", "Partículas"), + ("Passthrough", "Paso directo"), + ("Paste as instance", "Pegar como instancia"), + ("Paste effect", "Pegar efecto"), + ("Paste layer(s)", "Pegar capa(s)"), + ("Path", "Trazado"), + ("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Trazado: clic añade un punto, clic en la curva inserta uno, arrastrar lo mueve, Intro aplica, Esc cancela", + ), + ("Pattern scale", "Escala del patrón"), + ("Perlin noise", "Ruido Perlin"), + ("Pick focus in the viewport", "Elegir el enfoque en la ventana gráfica"), + ("Pin light", "Luz focal"), + ("Place on the surface", "Colocar en la superficie"), + ("Place path points on the mesh", "Coloca puntos del trazado sobre la malla"), + ("Planar projection", "Proyección planar"), + ("Plane", "Plano"), + ("Polygon fill", "Relleno de polígonos"), + ("Pores", "Poros"), + ("Position", "Posición"), + ("Position gradient", "Degradado de posición"), + ("Position jitter", "Variación de posición"), + ("Posterize", "Posterizar"), + ("Press a key...", "Pulsa una tecla..."), + ("Project", "Proyecto"), + ("Project Configuration...", "Configuración del proyecto..."), + ("Project opened", "Proyecto abierto"), + ("Project template", "Plantilla de proyecto"), + ("Projection", "Proyección"), + ("Projects and meshes", "Proyectos y mallas"), + ("Properties", "Propiedades"), + ("Quarter", "Cuarto"), + ("Quick mask", "Máscara rápida"), + ("Quit", "Salir"), + ("Radius (texels at 2K)", "Radio (téxeles a 2K)"), + ("RENDERING", "RENDERIZADO"), + ("Range", "Rango"), + ("Rebind any menu item, tool or command", "Reasignar cualquier elemento de menú, herramienta o comando"), + ("Recent projects", "Proyectos recientes"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "Registra la pila hasta esta capa. Los efectos de relleno de las máscaras (y las capas de relleno) superiores pueden leerla como origen.", + ), + ("Redo", "Rehacer"), + ("Reimport mesh", "Reimportar malla"), + ("Remove", "Quitar"), + ("Remove channel", "Quitar canal"), + ("Remove effect", "Quitar efecto"), + ("Remove last", "Quitar el último"), + ("Remove layer", "Eliminar capa"), + ("Remove layer(s)", "Eliminar capa(s)"), + ("Remove mask", "Quitar máscara"), + ("Remove point", "Quitar punto"), + ("Remove resource", "Quitar recurso"), + ("Remove the shortcut", "Quitar el atajo"), + ("Remove this output", "Quitar esta salida"), + ("Remove unused resources...", "Quitar recursos no usados..."), + ("Rename the selected template", "Cambiar el nombre de la plantilla seleccionada"), + ("Render on the CPU", "Renderizar en la CPU"), + ("Rendering", "Renderizado"), + ("Rendering (path traced)", "Renderizado (trazado de trayectorias)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "Renderizando en CPU: {n} / {max} muestras, {s} s"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "Renderizando en GPU: {n} / {max} muestras, {s} s"), + ("Rendering, path traced", "Renderizado con trazado de trayectorias"), + ("Replace", "Reemplazar"), + ("Replace Color", "Reemplazar color"), + ("Replacement color", "Color de reemplazo"), + ("Report a bug...", "Informar de un error..."), + ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), + ("Reset", "Restablecer"), + ("Reset UI", "Restablecer interfaz"), + ("Reset all", "Restablecer todo"), + ("Reset to defaults", "Restablecer valores predeterminados"), + ("Reset to {shortcut}", "Restablecer a {shortcut}"), + ("Resizing", "Redimensionando"), + ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), + ("Return to this step", "Volver a este paso"), + ("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"), + ("Rotation", "Rotación"), + ("Rotation (degrees)", "Rotación (grados)"), + ("Roughness", "Rugosidad"), + ("Roughness from glossiness", "Rugosidad desde brillo"), + ("Round", "Redondo"), + ("Rounded cube", "Cubo redondeado"), + ("Samples", "Muestras"), + ("Saturation", "Saturación"), + ("Save", "Guardar"), + ("Save UI Layout", "Guardar diseño de interfaz"), + ("Save a copy...", "Guardar una copia..."), + ("Save as...", "Guardar como..."), + ("Save current layout...", "Guardar diseño actual..."), + ("Save render...", "Guardar render..."), + ("Save view as camera", "Guardar vista como cámara"), + ("Saved UI layout {path}", "Diseño de interfaz guardado: {path}"), + ("Saved {path}", "Guardado: {path}"), + ("Saving UI layouts to files is available in the desktop app", "Guardar diseños de interfaz en archivos está disponible en la aplicación de escritorio"), + ("Scale", "Escala"), + ("Scale / tiling", "Escala / repetición"), + ("Scatter color", "Color de dispersión"), + ("Scatter radius", "Radio de dispersión"), + ("Scattering weight", "Peso de dispersión"), + ("Scratches", "Arañazos"), + ("Screen", "Trama"), + ("Screenshot of the viewport", "Captura de la ventana gráfica"), + ("Search", "Buscar"), + ("Search commands or keys", "Buscar comandos o teclas"), + ("Seed", "Semilla"), + ("Select a layer", "Selecciona una capa"), + ("Select an output template", "Selecciona una plantilla de salida"), + ("Select source", "Seleccionar origen"), + ("Select the mask (Alt+click: show it in the viewport)", "Seleccionar la máscara (Alt+clic: mostrarla en la ventana gráfica)"), + ("Select...", "Seleccionar..."), + ("Settings", "Ajustes"), + ("Settings...", "Ajustes..."), + ("Shader Settings", "Ajustes del sombreador"), + ("Shader instance", "Instancia de sombreador"), + ("Shadows", "Sombras"), + ("Sharpen", "Enfocar"), + ("Sheen color", "Color del lustre"), + ("Sheen color × weight", "Color del lustre × peso"), + ("Sheen roughness", "Rugosidad del lustre"), + ("Sheen weight", "Peso del lustre"), + ("Shift + wheel", "Mayús + rueda"), + ("Shortcuts list...", "Lista de atajos..."), + ("Show on all parts", "Mostrar en todas las partes"), + ("Show UV wireframe in the 2D view", "Mostrar la malla de alambre UV en la vista 2D"), + ("Show entire mesh", "Mostrar toda la malla"), + ("Show log...", "Mostrar registro..."), + ("Show or hide the layer", "Mostrar u ocultar la capa"), + ("Show or hide the texture set", "Mostrar u ocultar el conjunto de texturas"), + ("Show wireframe in the 3D view", "Mostrar la malla de alambre en la vista 3D"), + ("Signed addition (AddSub)", "Suma con signo (AddSub)"), + ("Size", "Tamaño"), + ("Size in screen space", "Tamaño en espacio de pantalla"), + ("Size jitter", "Variación de tamaño"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "Tamaño de las texturas que muestra la ventana gráfica: un valor menor usa menos memoria de GPU con conjuntos de texturas grandes. La pintura y la exportación mantienen la resolución completa.", + ), + ("Slope Blur", "Desenfoque de pendiente"), + ("Slope scale", "Escala de pendiente"), + ("Smart masks", "Máscaras inteligentes"), + ("Smart material saved to {path}", "Material inteligente guardado en {path}"), + ("Smart materials", "Materiales inteligentes"), + ("Smudge", "Difuminar"), + ("Soft light", "Luz suave"), + ("Softness", "Suavidad"), + ("Source", "Origen"), + ("Source U {u} V {v}", "Origen U {u} V {v}"), + ("Spacing", "Espaciado"), + ("Specular", "Especular"), + ("Specular level", "Nivel especular"), + ("Sphere", "Esfera"), + ("Spherical projection", "Proyección esférica"), + ("Spray", "Aerosol"), + ("Square", "Cuadrado"), + ("Stamp depth", "Profundidad del estampado"), + ("Star", "Estrella"), + ("Starting render...", "Iniciando render..."), + ("Stencil", "Plantilla"), + ("Steps", "Pasos"), + ("Streaks", "Chorreones"), + ("Strength", "Intensidad"), + ("Stripes", "Rayas"), + ("Stroke opacity", "Opacidad del trazo"), + ("Subsampling 2x2", "Submuestreo 2x2"), + ("Subsampling 4x4", "Submuestreo 4x4"), + ("Subsampling 8x8", "Submuestreo 8x8"), + ("Subsurface scattering", "Dispersión subsuperficial"), + ("Subtract", "Restar"), + ("Tangent | Wrap", "Tangente | Envolver"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antialiasing temporal (refina la vista 3D mientras está quieta)"), + ("Texture Sets", "Conjuntos de texturas"), + ("Texture Set Settings", "Ajustes del conjunto de texturas"), + ("Texture resolution", "Resolución de texturas"), + ("Texture set channels", "Canales del conjunto de texturas"), + ("Texture sets", "Conjuntos de texturas"), + ("TextureCraft had to close:", "TextureCraft tuvo que cerrarse:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metálico Rugosidad"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - Especular Brillo"), + ("TextureCraft project", "Proyecto de TextureCraft"), + ("TextureCraft project or mesh", "Proyecto o malla de TextureCraft"), + ("Textures", "Texturas"), + ("Textures embedded; for game engines and most viewers", "Texturas incrustadas; para motores de juego y la mayoría de visores"), + ("Textures packaged; for USD tools and AR Quick Look", "Texturas empaquetadas; para herramientas USD y AR Quick Look"), + ("The GPU couldn't render this scene: {error}", "La GPU no pudo renderizar esta escena: {error}"), + ("The bake worker stopped", "El proceso de horneado se detuvo"), + ("The eraser removes paint from the enabled channels.", "El borrador elimina la pintura de los canales activados."), + ("The first stroke sets the offset from the source.", "El primer trazo define el desplazamiento respecto al origen."), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "El alfa de la imagen recorta la forma de la calcomanía; las caras orientadas hacia atrás y las superficies más allá de su profundidad quedan libres.", + ), + ("The next click in the 3D view moves the decal there", "El próximo clic en la vista 3D mueve la calcomanía allí"), + ("The resize worker stopped", "El proceso de redimensionado se detuvo"), + ("Thickness", "Grosor"), + ("Thin areas", "Zonas finas"), + ("Threshold", "Umbral"), + ("Tile", "Mosaico"), + ("Tiles", "Baldosas"), + ("Tint", "Tinte"), + ("Toggle mask", "Activar/desactivar máscara"), + ("Tolerance", "Tolerancia"), + ("Tone mapping", "Mapeo de tonos"), + ("Tools", "Herramientas"), + ("Torus", "Toro"), + ("Transmission", "Transmisión"), + ("Tri-planar projection", "Proyección triplanar"), + ("Triangle fill", "Relleno de triángulos"), + ("UDIM plane", "Plano UDIM"), + ("UDIM tiles painted by this texture set, each at the set's size", "Mosaicos UDIM pintados por este conjunto de texturas, cada uno al tamaño del conjunto"), + ("UI layout", "Diseño de interfaz"), + ("UI layout: {error}", "Diseño de interfaz: {error}"), + ("UI layouts", "Diseños de interfaz"), + ("UI {ms} ms", "Interfaz {ms} ms"), + ("USD binary, textures alongside", "USD binario, texturas aparte"), + ("USD text, textures alongside", "USD texto, texturas aparte"), + ("USDZ with textures", "USDZ con texturas"), + ("UV checker", "Damero UV"), + ("UV island fill", "Relleno de islas UV"), + ("UV transformations", "Transformaciones UV"), + ("UV projection", "Proyección UV"), + ("UV tiles", "Mosaicos UV"), + ("UV tiles (UDIM)", "Mosaicos UV (UDIM)"), + ("Undo", "Deshacer"), + ("Uniform value", "Valor uniforme"), + ("Use an equirectangular .hdr or .exr image as the environment", "Usar una imagen equirrectangular .hdr o .exr como entorno"), + ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa el canal de control o `texturecraft-cli render` para las capturas"), + ("Value", "Valor"), + ("Version {version}", "Versión {version}"), + ("Version: {version} ({gpu})", "Versión: {version} ({gpu})"), + ("View through this camera", "Ver a través de esta cámara"), + ("Viewer settings", "Ajustes del visor"), + ("Viewport", "Ventana gráfica"), + ("Viewport and brush (fixed)", "Ventana gráfica y pincel (fijos)"), + ("Views", "Vistas"), + ("Vivid light", "Luz intensa"), + ("Voronoi", "Voronoi"), + ("Warp", "Deformar"), + ("Warp Directional", "Deformación direccional"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ con MTL, texturas al lado"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "WebGPU no está disponible en este navegador, así que TextureCraft usa WebGL2: el modo Renderizado calcula el trazado de trayectorias en la CPU (más lento) y los conjuntos de texturas grandes se muestran a resolución reducida. Las versiones actuales de Chrome, Edge y Safari admiten WebGPU.", + ), + ("Wheel / Alt + RMB drag", "Rueda / Alt + arrastrar con botón der."), + ("White", "Blanco"), + ("Width", "Ancho"), + ("Width (texels at 2K)", "Anchura (téxeles a 2K)"), + ("Window", "Ventana"), + ("Wood grain", "Veta de madera"), + ("Works in texture space, like the blur: it does not cross UV seams.", "Funciona en espacio de textura, como el desenfoque: no cruza las costuras UV."), + ("World Space Normal", "Normal en espacio de mundo"), + ("Yellow / blue", "Amarillo / azul"), + ("Zoom", "Zoom"), + ("a missing layer", "una capa inexistente"), + ("aniso", "aniso"), + ("aniso angle", "áng anis"), + ("ao", "ao"), + ("coat", "barniz"), + ("coat nrm", "nrm barn"), + ("coat rough", "rug barn"), + ("color", "color"), + ("emiss", "emis"), + ("glTF binary with textures", "glTF binario con texturas"), + ("gloss", "brillo"), + ("height", "altura"), + ("metal", "metal"), + ("min", "min"), + ("missing", "no encontrado"), + ("missing source", "origen no encontrado"), + ("no GPU", "sin GPU"), + ("none", "ninguno"), + ("nrm", "nrm"), + ("off", "desact."), + ("op", "opac"), + ("rough", "rugos"), + ("scatter", "dispers"), + ("sheen", "lustre"), + ("sheen color", "col lust"), + ("sheen rough", "rug lust"), + ("spec", "niv esp"), + ("specular", "especul"), + ("transm", "transm"), + ("{action} (undone)", "{action} (deshecho)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file}: añadir sobre la capa seleccionada (o arrastrarlo a la pila de capas o a la ventana gráfica)", + ), + ("{name} copy", "Copia de {name}"), + ("{n} bits", "{n} bits"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "{n} puntos de control. Haz clic en la malla (o en la vista 2D) para añadir puntos y arrástralos para ajustarlos; haz clic en el primer punto para cerrar el trazado. Intro lo pinta con el pincel (un trazado cerrado y relleno rellena su interior), Esc cancela.", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} elementos comparten un atajo; prevalece el primero de la lista."), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (escala {scale}, semilla {seed})"), + ("Template name", "Nombre de la plantilla"), + ("Save current project as template", "Guardar el proyecto actual como plantilla"), + ("Distribution", "Distribución"), + ("Cosine", "Coseno"), + ("Uniform", "Uniforme"), + ("Normalization", "Normalización"), + // Settings › Interface: brightness and accent color. + ("Brightness", "Brillo"), + ("Dark", "Oscuro"), + ("Medium dark", "Medio oscuro"), + ("Medium light", "Medio claro"), + ("Light", "Claro"), + ("Accent color", "Color de acento"), + ("Copper", "Cobre"), + ("Coral", "Coral"), + ("Blue", "Azul"), + ("Violet", "Violeta"), + ("Green", "Verde"), + ("Amber", "Ámbar"), + ("Pink", "Rosa"), + ("Minimize", "Minimizar"), + ("Maximize", "Maximizar"), + ("Restore", "Restaurar"), + ("Title bar", "Barra de título"), + ("System title bar (applies on restart)", "Barra de título del sistema (se aplica al reiniciar)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", + ), + ("Brushes", "Pinceles"), + ("Brush name", "Nombre del pincel"), + ("Save current brush", "Guardar el pincel actual"), + ("Start window", "Ventana de inicio"), + ("Show at startup", "Mostrar al iniciar"), + ("Continue with the sample project", "Continuar con el proyecto de ejemplo"), + ("No recent projects yet", "Aún no hay proyectos recientes"), + ("Text", "Texto"), + ("Font", "Fuente"), + ("Style", "Estilo"), + ("Use as brush alpha", "Usar como alfa del pincel"), + ("Place as decal", "Colocar como calcomanía"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clic: activa o desactiva este canal. Alt+clic: solo este canal"), + ("Show all", "Mostrar todo"), + ("Hide all", "Ocultar todo"), + ("Invert show/hide", "Invertir mostrar/ocultar"), + ("Show or hide texture sets", "Mostrar u ocultar conjuntos de texturas"), + ("Focus: show only the active texture set", "Enfoque: mostrar solo el conjunto de texturas activo"), + ("Unsaved changes", "Cambios sin guardar"), + ("Don't save", "No guardar"), + ("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"), + ("Radius", "Radio"), + ("Remove skew correction", "Quitar la corrección de sesgo"), + ("Twill weave", "Tejido de sarga"), + ("Save the changes to {name} first?", "¿Guardar primero los cambios de {name}?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Los trazados siguen siendo editables: elige uno para mover sus puntos o cambiar su pincel y material, y la subcapa se vuelve a pintar al instante. Añade trazados con la herramienta Trazado.", + ), + ("Import material...", "Importar material..."), + ("MaterialCraft material", "Material de MaterialCraft"), + ("Cooked at {size} px", "Calculado a {size} px"), + ("Preset", "Preajuste"), + ("Re-cook", "Recalcular"), + ("Open in MaterialCraft", "Abrir en MaterialCraft"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "Abierto en MaterialCraft: usa allí Archivo > Enviar a TextureCraft para traer tus cambios", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "Los parámetros se cambian en la app de escritorio, con MaterialCraft instalado"), + ("Add High-Poly Meshes", "Añadir mallas de alta resolución"), + ("All", "Todos"), + ("Apply Diffusion", "Aplicar difusión"), + ("Attenuation", "Atenuación"), + ("Auto Tonemapping", "Mapeo tonal automático"), + ("Average Normals", "Promediar normales"), + ("BBox", "Caja delimitadora"), + ("BSphere", "Esfera delimitadora"), + ("Mesh Map Bakers", "Horneadores de mapas de malla"), + ("Common Settings", "Ajustes comunes"), + ("Mesh Map Settings", "Ajustes de mapas de malla"), + ("Check All", "Marcar todo"), + ("No Parameters", "Sin parámetros"), + ("Bake Selected Textures ({n})", "Hornear texturas seleccionadas ({n})"), + ("By Mesh Name", "Por nombre de malla"), + ("Cage", "Jaula"), + ("Cage Scene", "Escena de jaula"), + ("Cage Type", "Tipo de jaula"), + ("Color Generator", "Generador de color"), + ("Color Source", "Origen del color"), + ("Common Parameters", "Parámetros comunes"), + ("Custom File", "Archivo personalizado"), + ("Details", "Detalles"), + ("Dilation Width", "Ancho de dilatación"), + ("Distance-Based", "Basada en distancia"), + ("Edge Contrast", "Contraste de bordes"), + ("Edge Distance", "Distancia de bordes"), + ("Edge Protection", "Protección de bordes"), + ("Enable Seams", "Activar costuras"), + ("File ID", "ID de archivo"), + ("Full Scene", "Escena completa"), + ("Generate from Mesh", "Generar desde la malla"), + ("Generate from Normal Map", "Generar desde el mapa de normales"), + ("Ground Plane", "Plano del suelo"), + ("Ground Plane Offset", "Desplazamiento del suelo"), + ("High Poly Mesh Suffix", "Sufijo de malla high poly"), + ("High Poly Scene", "Escena de alta resolución"), + ("High-Poly Parameters", "Parámetros de alta resolución"), + ("Hue Shift", "Cambio de tono"), + ("Ignore Backface", "Ignorar caras traseras"), + ("Ignore Backface Suffix", "Sufijo para ignorar caras traseras"), + ("Include in Bake", "Incluir en el horneado"), + ("Load Cage", "Cargar jaula"), + ("Lock Output Size", "Bloquear tamaño de salida"), + ("Low Poly Mesh Suffix", "Sufijo de malla low poly"), + ("Manual", "Manual"), + ("Material Color", "Color del material"), + ("Max Frontal Distance", "Distancia frontal máx."), + ("Max Occluder Distance", "Distancia máx. de oclusor"), + ("Max Rear Distance", "Distancia trasera máx."), + ("Mesh ID", "ID de malla"), + ("Method", "Método"), + ("Min Occluder Distance", "Distancia mínima del oclusor"), + ("Never", "Nunca"), + ("No High-Poly Meshes", "Sin mallas de alta resolución"), + ("Normalization Scale", "Escala de normalización"), + ("Normalization Type", "Tipo de normalización"), + ("Only Same Mesh Name", "Solo el mismo nombre de malla"), + ("Output Size", "Tamaño de salida"), + ("Match", "Coincidencia"), + ("Skew Correction Method", "Método de Corrección de Sesgo"), + ("Mesh Normals Based", "Basado en Normales de Malla"), + ("Face Normals Based", "Basado en Normales de Cara"), + ("Reset Painted Cage", "Restablecer Jaula Pintada"), + ("Paint Cage", "Pintar jaula"), + ("Paint Skew Correction", "Pintar corrección de inclinación"), + ("Per Material", "Por material"), + ("Random", "Aleatorio"), + ("Relative to Bounding Box", "Relativo a la caja delimitadora"), + ("Relative to Low Mesh", "Relativo a la malla de baja resolución"), + ("Relative to Min/Max", "Relativo al mínimo/máximo"), + ("Relative to Ray Distances", "Relativo a distancias de rayos"), + ("Remove Cage", "Eliminar jaula"), + ("Remove Skew Correction", "Quitar la corrección de sesgo"), + ("Restore Defaults", "Restaurar valores predeterminados"), + ("Return to Painting Mode", "Volver al modo de pintura"), + ("Sampling Radius", "Radio de muestreo"), + ("Scaling Divisor", "Divisor de escala"), + ("Seams Intensity", "Intensidad de costuras"), + ("Secondary Rays", "Rayos secundarios"), + ("Self Intersection", "Autointersección"), + ("Self Occlusion", "Autooclusión"), + ("Skew Correction", "Corrección de sesgo"), + ("Smooth", "Suave"), + ("Spread Angle", "Ángulo de dispersión"), + ("Submesh", "Submalla"), + ("Use Low Poly Mesh as High Poly Mesh", "Usar la malla low poly como malla high poly"), + ("Value Bounds Max", "Límite máximo"), + ("Value Bounds Min", "Límite mínimo"), + ("Vertex Color", "Color de vértice"), + ("Select the layer content", "Seleccionar el contenido de la capa"), + ("Paint layer", "Capa de pintura"), + ("Fill layer", "Capa de relleno"), + ("1 effect", "1 efecto"), + ("{count} effects", "{count} efectos"), + ("Mask effects", "Efectos de la máscara"), + ("Content effects", "Efectos del contenido"), + ("Fold or unfold these effects", "Plegar o desplegar estos efectos"), + ("Remove resolution override", "Quitar resolución personalizada"), + ("Texture set resolution", "Resolución del conjunto de texturas"), + ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Angle span", "Amplitud del ángulo"), + ("Axis position", "Posición del eje"), + ("Count", "Cantidad"), + ("Display", "Visualización"), + ("Hide while painting", "Ocultar al pintar"), + ("Manipulator size", "Tamaño del manipulador"), + ("Mirror symmetry", "Simetría de espejo"), + ("Radial settings", "Ajustes radiales"), + ("Radial symmetry", "Simetría radial"), + ("Show axis", "Mostrar eje"), + ("Show axis position manipulator", "Mostrar manipulador de posición del eje"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar intersección"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetría"), + ("Symmetry color display", "Color de visualización de simetría"), + ("Symmetry settings", "Ajustes de simetría"), + ("Type", "Tipo"), + ("Advanced settings", "Ajustes avanzados"), + ("Import baked maps", "Importar mapas horneados"), + ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), + ("Add...", "Añadir..."), + ("Baked maps imported: {count}", "Mapas horneados importados: {count}"), + ("Not imported: {files}", "Sin importar: {files}"), + ("Baking Visualization", "Visualización del horneado"), + ("Show for Selected Texture Set Only", "Mostrar solo para el conjunto de texturas seleccionado"), + ("High Definition Mesh (HP)", "Malla de alta resolución (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malla de proyección (LP)"), + ("Edges", "Bordes"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordes y cavidades"), + ("Raw curvature", "Curvatura sin procesar"), + ("Detail sizes", "Tamaños de detalle"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lee el mapa de curvatura tal como se horneó: cambiar el modo o un tamaño activa los tamaños de detalle.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic rellena lo que hay debajo; un rectángulo arrastrado rellena lo que selecciona mientras crece", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenido: rellenar los polígonos cuyo centro está en el rectángulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando la máscara rápida: los rellenos pintan donde se permite pintar. Pulsa U para terminar.", + ), + ("Fill mode", "Modo de relleno"), + ("Fill only polygons the camera sees (3D view)", "Rellenar solo los polígonos que ve la cámara (vista 3D)"), + ("Hit-test", "Prueba de selección"), + ("How a rectangle selects polygons", "Cómo selecciona polígonos un rectángulo"), + ("Intersection: fill polygons the rectangle touches", "Intersección: rellenar los polígonos que toca el rectángulo"), + ("Rectangle fill", "Relleno rectangular"), + ("Select a paint layer or a layer's mask to fill", "Selecciona una capa de pintura o una máscara de capa para rellenar"), + ("Selection mode", "Modo de selección"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triángulo rellena triángulos sueltos, Polígono cuadriláteros y n-gonos enteros, Malla la geometría conectada, Isla UV las islas UV", + ), + ("Visible polygons only", "Solo polígonos visibles"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa", + ), + ("The file dialog couldn't be shown: {error}", "No se pudo mostrar el cuadro de diálogo de archivos: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "El proyecto cambió mientras el cuadro de diálogo estaba abierto, así que no se hizo nada", + ), + ("Cores kept for the UI", "Núcleos reservados para la interfaz"), + ("Max RAM while saving", "RAM máx. al guardar"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Guardar usa los demás núcleos y como máximo esta parte de la RAM libre. Siempre trabaja al menos un núcleo.", + ), + ("Max project size on open", "Tamaño máximo al abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", + ), + ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas las bibliotecas"), + ("Browse folders", "Explorar carpetas"), + ("Starter assets", "Recursos incluidos"), + ("Your assets", "Tus recursos"), + ("Reset query", "Restablecer consulta"), + ("Refresh", "Actualizar"), + ("Saved searches", "Búsquedas guardadas"), + ("Save the current search", "Guardar la búsqueda actual"), + ("Delete", "Eliminar"), + ("Filter by path", "Filtrar por ruta"), + ("Hide non-applicable folders", "Ocultar carpetas no aplicables"), + ("Thumbnail size", "Tamaño de miniatura"), + ("Small", "Pequeño"), + ("Medium", "Mediano"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurales"), +]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs new file mode 100644 index 00000000..ebcb248a --- /dev/null +++ b/crates/ui-egui/src/i18n/fr.rs @@ -0,0 +1,1209 @@ +//! French UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Cuisson de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Cuisson de {map} ({n}/{total}), jeu de textures {set} sur {sets}"), + ("Follow Newest Map", "Suivre la dernière carte"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La peinture est suspendue tant qu'une cuisson est affichée. Annulez la cuisson ou attendez qu'elle se termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Ce que la vue 3D affiche pendant la cuisson : la dernière carte terminée, une carte terminée au choix ou le matériau. Les cartes pas encore cuites affichent une valeur neutre.", + ), + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", + ), + ("0 turns autosave off. Copies go to {folder}", "0 désactive la sauvegarde automatique. Les copies vont dans {folder}"), + ("2D view only", "Vue 2D seule"), + ("32 bits (float)", "32 bits (flottant)"), + ("3D mesh", "Maillage 3D"), + ("3D meshes", "Maillages 3D"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "Peinture de textures 3D : calques, masques, matériaux intelligents, précalcul des cartes de maillage et export.", + ), + ("3D view only", "Vue 3D seule"), + ("3D/2D views", "Vues 3D/2D"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "Un dossier fusionne ses enfants (transfert). Réglez l'opacité par canal dans les lignes des calques.", + ), + ("ACES filmic", "ACES filmique"), + ("Ambient", "Ambiante"), + ("AO intensity", "Intensité de l'AO"), + ("About TextureCraft", "À propos de TextureCraft"), + ("About TextureCraft...", "À propos de TextureCraft..."), + ( + "Add an anchor point to a layer below to use its stack as a mask.", + "Ajoutez un point d'ancrage à un calque inférieur pour utiliser sa pile comme masque.", + ), + ("Add anchor point", "Ajouter un point d'ancrage"), + ("Add as decal (view center)", "Ajouter comme décalque (centre de la vue)"), + ("Add black mask", "Ajouter un masque noir"), + ("Add channel", "Ajouter un canal"), + ("Add color", "Ajouter une couleur"), + ("Add compare mask", "Ajouter un masque de comparaison"), + ("Add effect", "Ajouter un effet"), + ("Add fill", "Ajouter un remplissage"), + ("Add fill layer", "Ajouter un calque de remplissage"), + ("Add filter", "Ajouter un filtre"), + ("Add folder", "Ajouter un dossier"), + ("Add generator", "Ajouter un générateur"), + ("Add levels", "Ajouter des niveaux"), + ("Add mask", "Ajouter un masque"), + ("Add mask with color selection", "Ajouter un masque par sélection de couleur"), + ("Add output", "Ajouter une sortie"), + ("Add paint", "Ajouter de la peinture"), + ("Add paint layer", "Ajouter un calque de peinture"), + ("Add smart material from the shelf", "Ajouter un matériau intelligent depuis la bibliothèque"), + ("Add to the layer content", "Ajouter au contenu du calque"), + ("Add to the mask", "Ajouter au masque"), + ("Add white mask", "Ajouter un masque blanc"), + ("Adjustments", "Réglages"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "Aligné : le décalage défini par le premier trait est conservé. V + clic définit une nouvelle source.", + ), + ("Alignment", "Alignement"), + ("Alignment and culling", "Alignement et élimination"), + ("All layers", "Tous les calques"), + ("Alpha", "Alpha"), + ("Alphas", "Alphas"), + ("Also bound to {item} ({menu})", "Également attribué à {item} ({menu})"), + ("Alt + LMB drag", "Alt + glisser (clic gauche)"), + ("Always", "Toujours"), + ("Ambient Occlusion", "Occlusion ambiante"), + ("Ambient occlusion", "Occlusion ambiante"), + ("Amount", "Quantité"), + ("Anchor point", "Point d'ancrage"), + ("Anchor: {name}", "Ancrage : {name}"), + ("Anchor: {name} ({channel})", "Ancrage : {name} ({channel})"), + ("Angle", "Angle"), + ("Angle (degrees)", "Angle (degrés)"), + ("Angle fade from", "Atténuation angulaire (début)"), + ("Angle fade to", "Atténuation angulaire (fin)"), + ("Angle jitter", "Variation d'angle"), + ("Anisotropy angle", "Angle d'anisotropie"), + ("Anisotropy level", "Niveau d'anisotropie"), + ("Antialiasing", "Anticrénelage"), + ("Aperture", "Ouverture"), + ("Apply", "Appliquer"), + ("ArtCraft website...", "Site web d'ArtCraft..."), + ("Assets", "Ressources"), + ("Auto", "Auto"), + ("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"), + ("Autosave every", "Sauvegarde automatique toutes les"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "Les sauvegardes automatiques, matériaux intelligents, préréglages, modèles et dispositions de l'interface vont dans le dossier de données. Un nouveau dossier s'applique au redémarrage ; les fichiers déjà enregistrés restent où ils sont.", + ), + ("Axis", "Axe"), + ("Back to painting", "Retour à la peinture"), + ("Backface culling", "Élimination des faces arrière"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Précalculez une carte d'ID (F8) pour prélever des couleurs sur le maillage."), + ("Bake Mesh Maps", "Précalculer les cartes de maillage"), + ("Bake mesh maps", "Précalculer les cartes de maillage"), + ( + "Bake mesh maps (F8) for curvature, AO and thickness based generators.", + "Précalculez les cartes de maillage (F8) pour les générateurs basés sur la courbure, l'AO et l'épaisseur.", + ), + ("Baked Lighting", "Éclairage précalculé"), + ("Baking", "Précalcul"), + ("Base color", "Couleur de base"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "Couleur de base est la couleur diffuse, Spéculaire la couleur F0 et Brillance 1 - rugosité (ajoutez ces canaux dans les paramètres de l'ensemble de textures).", + ), + ("Base color, Metallic, Roughness and Specular level.", "Couleur de base, Métallique, Rugosité et Niveau spéculaire."), + ("Based on each texture set's size", "Selon la taille de chaque ensemble de textures"), + ("Basic settings", "Paramètres de base"), + ("Bent Normals", "Normales déviées"), + ("Bevel", "Biseau"), + ("Black", "Noir"), + ("Blending", "Fusion"), + ("Blending mode of the displayed channel", "Mode de fusion du canal affiché"), + ("Blur", "Flou"), + ("Blur Directional", "Flou directionnel"), + ("Blur and sharpen", "Flou et netteté"), + ("Bounces", "Rebonds"), + ("Bricks", "Briques"), + ("Brush", "Pinceau"), + ("Brush size", "Taille du pinceau"), + ("Brush size down / up", "Réduire / augmenter la taille du pinceau"), + ("Brushed lines", "Lignes brossées"), + ("Built-in (read-only): duplicate it to edit", "Intégré (lecture seule) : dupliquez-le pour le modifier"), + ("Built-in templates are read-only: duplicate one to edit it", "Les modèles intégrés sont en lecture seule : dupliquez-en un pour le modifier"), + ("Built-in: {mesh}", "Intégré : {mesh}"), + ("Cage: {name}", "Cage : {name}"), + ("Camera", "Caméra"), + ("Colors", "Couleurs"), + ("Go to camera 1", "Aller à la caméra 1"), + ("Go to camera 2", "Aller à la caméra 2"), + ("Go to camera 3", "Aller à la caméra 3"), + ("Go to camera 4", "Aller à la caméra 4"), + ("Go to camera 5", "Aller à la caméra 5"), + ("Go to camera 6", "Aller à la caméra 6"), + ("Go to camera 7", "Aller à la caméra 7"), + ("Go to camera 8", "Aller à la caméra 8"), + ("Go to camera 9", "Aller à la caméra 9"), + ("Camera settings", "Paramètres de la caméra"), + ("Cancel", "Annuler"), + ("Cancel the stroke", "Annuler le trait"), + ("Cell size (texels at 2K)", "Taille des cellules (texels en 2K)"), + ("Cells", "Cellules"), + ("Channel", "Canal"), + ("Channel source: uniform value, procedural, image or anchor", "Source du canal : valeur uniforme, procédural, image ou ancrage"), + ("Channels", "Canaux"), + ("Check for Updates...", "Rechercher des mises à jour..."), + ("Checker", "Damier"), + ("Clamp", "Limiter"), + ("Clear", "Effacer"), + ("Clear mask", "Effacer le masque"), + ("Clear recent projects", "Effacer les projets récents"), + ("Click a mesh part to show or hide the selected layer on it.", "Cliquez sur une partie du maillage pour y afficher ou masquer le calque sélectionné."), + ("Click the mesh to pick its material into the brush", "Cliquez sur le maillage pour prélever son matériau dans le pinceau"), + ("Click the mesh to place the decal", "Cliquez sur le maillage pour placer le décalque"), + ("Click, then press the new shortcut (Esc cancels)", "Cliquez, puis appuyez sur le nouveau raccourci (Esc pour annuler)"), + ("Clone", "Clonage"), + ("Close", "Fermer"), + ("Closed path", "Tracé fermé"), + ("Cloud", "Nuage"), + ("Clouds", "Nuages"), + ("Coat normal", "Normale du vernis"), + ("Coat roughness", "Rugosité du vernis"), + ("Coat weight", "Poids du vernis"), + ("Color", "Couleur"), + ("Color Balance", "Balance des couleurs"), + ("Color burn", "Densité couleur +"), + ("Color dodge", "Densité couleur -"), + ( + "Color of the light that travels under the surface (each channel goes as far as its value)", + "Couleur de la lumière qui se propage sous la surface (chaque canal va aussi loin que sa valeur)", + ), + ("Color picker", "Pipette"), + ("Color selection", "Sélection de couleur"), + ("Color to replace", "Couleur à remplacer"), + ( + "Colors near the first shift towards the second, keeping their shading.", + "Les couleurs proches de la première glissent vers la seconde en gardant leur ombrage.", + ), + ( + "Colors read as gray. Add a levels or blur effect above to shape the result.", + "Les couleurs sont lues en niveaux de gris. Ajoutez un effet de niveaux ou de flou au-dessus pour ajuster le résultat.", + ), + ("Combine with the layer's height", "Combiner avec la hauteur du calque"), + ("Compare mask", "Masque de comparaison"), + ("Compositing", "Composition"), + ("Constant", "Constante"), + ("Constants", "Constantes"), + ("Contrast", "Contraste"), + ("Contrast/Luminosity", "Contraste/Luminosité"), + ("Converted maps", "Cartes converties"), + ("Copy RGB values", "Copier les valeurs RVB"), + ("Copy effect", "Copier l'effet"), + ("Copy from", "Copier depuis"), + ("Copy layer(s)", "Copier le(s) calque(s)"), + ("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"), + ("Copy to all texture sets", "Copier dans tous les ensembles de textures"), + ("Copy what the texture set shows", "Copier ce qu'affiche l'ensemble de textures"), + ("Couldn't encode the render", "Impossible d'encoder le rendu"), + ("Couldn't export textures: {error}", "Impossible d'exporter les textures : {error}"), + ("Couldn't export the mesh: {error}", "Impossible d'exporter le maillage : {error}"), + ("Couldn't export the template: {error}", "Impossible d'exporter le modèle : {error}"), + ("Couldn't import {name}: {error}", "Impossible d'importer {name} : {error}"), + ("Couldn't open {name}: {error}", "Impossible d'ouvrir {name} : {error}"), + ("Couldn't read the render back from the GPU", "Impossible de relire le rendu depuis le GPU"), + ("Couldn't save the render: {error}", "Impossible d'enregistrer le rendu : {error}"), + ("Couldn't save {name}: {error}", "Impossible d'enregistrer {name} : {error}"), + ("Count per stamp", "Nombre par empreinte"), + ("Crate", "Caisse"), + ("Create", "Créer"), + ("Create smart material", "Créer un matériau intelligent"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+glisser (clic droit) dans une vue règle la taille et la dureté, Ctrl+glisser (clic gauche) le flux et l'angle.", + ), + ("Cube", "Cube"), + ("Current layer", "Calque actuel"), + ("Curvature", "Courbure"), + ("Cut effect", "Couper l'effet"), + ("Cut layer(s)", "Couper le(s) calque(s)"), + ("Cyan / red", "Cyan / rouge"), + ("Cylinder", "Cylindre"), + ("Cylindrical projection", "Projection cylindrique"), + ( + "Dark to light: the content's luminance picks a color along these stops.", + "Du sombre au clair : la luminance du contenu choisit une couleur le long de ces repères.", + ), + ("Darken (Min)", "Obscurcir (Min)"), + ("Data folder", "Dossier de données"), + ("Decal", "Décalque"), + ("Decal projection", "Projection de décalque"), + ("Default", "Par défaut"), + ("Default camera", "Caméra par défaut"), + ("Delete the selected template", "Supprimer le modèle sélectionné"), + ("Delete this camera", "Supprimer cette caméra"), + ("Deleted template \"{name}\"", "Modèle « {name} » supprimé"), + ("Denoise", "Débruitage"), + ("Depth", "Profondeur"), + ("Depth of field", "Profondeur de champ"), + ("Depth of field (viewport and Rendering mode)", "Profondeur de champ (fenêtre d'affichage et mode Rendu)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "Profondeur du plan net le long de la vue (0 : le centre d'orbite)"), + ("Details saved to {file}", "Détails enregistrés dans {file}"), + ("Difference", "Différence"), + ("Dilation + default background color", "Dilatation + couleur de fond par défaut"), + ("Dilation + transparent", "Dilatation + transparent"), + ("Dilation infinite", "Dilatation infinie"), + ("DirectX normal map", "Carte de normales DirectX"), + ("Dirt", "Saleté"), + ("Disable", "Désactivé"), + ("Dismiss", "Fermer"), + ("Displacement (height channel)", "Déplacement (canal de hauteur)"), + ("Display Settings", "Paramètres d'affichage"), + ("Display material", "Afficher le matériau"), + ("Display next channel", "Afficher le canal suivant"), + ("Display next mesh map", "Afficher la carte de maillage suivante"), + ("Display previous channel", "Afficher le canal précédent"), + ("Display previous mesh map", "Afficher la carte de maillage précédente"), + ("Distance", "Distance"), + ("Distort", "Déformation"), + ("Divide", "Division"), + ("Document resolution", "Résolution du document"), + ("Documentation...", "Documentation..."), + ("Done on CPU: {n} / {max} samples, {s} s", "Terminé sur CPU : {n} / {max} échantillons, {s} s"), + ("Done on GPU: {n} / {max} samples, {s} s", "Terminé sur GPU : {n} / {max} échantillons, {s} s"), + ("Double-click to rename", "Double-cliquer pour renommer"), + ("Download as", "Télécharger en"), + ("Downloaded {name}", "{name} téléchargé"), + ("Drag onto an output channel", "Glisser sur un canal de sortie"), + ( + "Drags the layer stack's values along the stroke into the selected layer.", + "Entraîne les valeurs de la pile de calques le long du trait dans le calque sélectionné.", + ), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "Affiche {name} de l'ensemble de textures « {set} ». Les modifications de la source apparaissent dans chaque instance.", + ), + ( + "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", + "Faites glisser le cadre pour déplacer le décalque, un coin pour le mettre à l'échelle, la poignée ronde pour le faire pivoter", + ), + ( + "Drop an image from the Assets panel here to use it as this mesh map", + "Déposez ici une image du panneau Ressources pour l'utiliser comme cette carte de maillage", + ), + ("Dry streaks", "Traînées sèches"), + ("Duplicate effect", "Dupliquer l'effet"), + ("Duplicate layer(s)", "Dupliquer le(s) calque(s)"), + ("Duplicate the selected template", "Dupliquer le modèle sélectionné"), + ("Edge Detect", "Détection des contours"), + ("Edit", "Édition"), + ("Edit keyboard shortcuts...", "Modifier les raccourcis clavier..."), + ("Edit quick mask", "Modifier le masque rapide"), + ( + "Editing quick mask: paint where painting is allowed (U to finish)", + "Modification du masque rapide : peignez là où la peinture est autorisée (U pour terminer)", + ), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "Modification du masque rapide : les traits peignent là où la peinture est autorisée. Appuyez sur U pour terminer.", + ), + ("Emissive", "Émissif"), + ("Enable or disable the effect", "Activer ou désactiver l'effet"), + ("Enable quick mask", "Activer le masque rapide"), + ("Environment blur", "Flou de l'environnement"), + ("Environment exposure (EV)", "Exposition de l'environnement (EV)"), + ("Environment map", "Carte d'environnement"), + ("Environment opacity", "Opacité de l'environnement"), + ("Environment rotation", "Rotation de l'environnement"), + ("Environment settings", "Paramètres d'environnement"), + ("Environment: {name}", "Environnement : {name}"), + ("Environments", "Environnements"), + ("Eraser", "Gomme"), + ("Exclusion", "Exclusion"), + ("Expand or collapse the folder", "Déplier ou replier le dossier"), + ("Export", "Exporter"), + ("Export Mesh...", "Exporter le maillage..."), + ("Export Textures...", "Exporter les textures..."), + ("Export mesh", "Exporter le maillage"), + ("Export template", "Modèle d'export"), + ("Export templates", "Modèles d'export"), + ("Export textures", "Exporter les textures"), + ("Export the selected template (.json)", "Exporter le modèle sélectionné (.json)"), + ("Exported mesh to {path}", "Maillage exporté vers {path}"), + ("Exported template \"{name}\" to {path}", "Modèle « {name} » exporté vers {path}"), + ("Exported {n} textures to {folder}", "{n} textures exportées vers {folder}"), + ("F0 from specular level", "F0 depuis le niveau spéculaire"), + ("Fabric weave", "Tissage"), + ("Field of view (deg)", "Champ de vision (degrés)"), + ("File", "Fichier"), + ("File name without extension; variables insert names", "Nom de fichier sans extension ; les variables insèrent des noms"), + ("File type", "Type de fichier"), + ("Fill", "Remplissage"), + ("Fill the closed path (lasso)", "Remplir le tracé fermé (lasso)"), + ("Fill the path (close it first)", "Remplir le tracé (le fermer d'abord)"), + ("Filter", "Filtre"), + ("Filter the remaining noise while keeping edges and texture detail", "Filtrer le bruit restant en préservant les contours et les détails de texture"), + ("Filters", "Filtres"), + ("Fine noise", "Bruit fin"), + ("Fingerprints", "Empreintes digitales"), + ("Enter a finite number", "Saisissez un nombre fini"), + ("Double-click or press Enter to edit", "Double-cliquez ou appuyez sur Entrée pour modifier"), + ("Fit the input range to the histogram", "Ajuster la plage d'entrée à l'histogramme"), + ("Flatten layer", "Aplatir le calque"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Inverse le canal vert de l'image, pour les cartes de normales faites avec Y vers le bas", + ), + ("Flow", "Flux"), + ("Flow and opacity", "Flux et opacité"), + ("Flow jitter", "Variation du flux"), + ("Focus distance", "Distance de mise au point"), + ("Folder", "Dossier"), + ("Folders", "Dossiers"), + ("Follow path", "Suivre le tracé"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "Pour tout le projet : comment les images de carte de normales utilisées comme cartes de maillage sont lues (réaffectez-les après un changement), et la valeur par défaut à l'export", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libre et open source (MIT OR Apache-2.0), écrit en Rust."), + ("From template", "Selon le modèle"), + ("From template / project", "Selon le modèle / projet"), + ("Full", "Pleine"), + ("GPU error: {error}", "Erreur GPU : {error}"), + ("Geometry mask", "Masque de géométrie"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "Spéculaire GGX avec visibilité de Smith corrélée à la hauteur, diffus Lambert, éclairage basé sur l'image en split-sum avec irradiance en harmoniques sphériques et atténuation à l'horizon.", + ), + ("Gamma", "Gamma"), + ("General export parameters", "Paramètres d'export généraux"), + ("General properties", "Propriétés générales"), + ("Generator", "Générateur"), + ("Geometry and UVs only", "Géométrie et UV uniquement"), + ("Glossiness", "Brillance"), + ("Glossiness from roughness", "Brillance depuis la rugosité"), + ("Glow", "Lueur"), + ("Gradient", "Dégradé"), + ("Gradient Map", "Carte de dégradé"), + ("Gravity", "Gravité"), + ("Gray", "Gris"), + ("Gray + A", "Gris + A"), + ("Gray 50%", "Gris 50 %"), + ("Grayscale", "Niveaux de gris"), + ("Group layer(s)", "Grouper le(s) calque(s)"), + ("Grunge", "Grunge"), + ("HDR environments", "Environnements HDR"), + ("High Pass", "Passe-haut"), + ("HSL Perceptive", "TSL perceptuel"), + ("Half", "Moitié"), + ("Hammered", "Martelé"), + ("Hard light", "Lumière crue"), + ("Hardness", "Dureté"), + ("Height", "Hauteur"), + ("Height offset", "Décalage de hauteur"), + ("Height to normal strength", "Intensité hauteur vers normale"), + ("Help", "Aide"), + ("Hide UI", "Masquer l'interface"), + ("High", "Haut"), + ("High poly: {name}", "High poly : {name}"), + ("Highlights", "Tons clairs"), + ("Histogram Range", "Plage d'histogramme"), + ("Histogram Scan", "Balayage d'histogramme"), + ("Histogram Shift", "Décalage d'histogramme"), + ("History", "Historique"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "Maintenez S : glisser (clic gauche) fait pivoter, glisser (clic droit) redimensionne, glisser (clic milieu) déplace le pochoir.", + ), + ("Hold V and click the mesh to set the clone source", "Maintenez V et cliquez sur le maillage pour définir la source du clonage"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "Maintenez V et cliquez sur le maillage pour définir la source, puis peignez ailleurs pour la copier.", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "Distance parcourue par la lumière sous la surface, en fraction de la taille du maillage (là où le canal Poids de diffusion est peint)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "Degré de déviation de la lumière par les surfaces transmissives (là où le canal Transmission est peint) : eau 1,33, verre 1,5, diamant 2,42", + ), + ("Hue shift (degrees)", "Décalage de teinte (degrés)"), + ("ID", "ID"), + ("Image: {name}", "Image : {name}"), + ("Images", "Images"), + ("Import HDR...", "Importer un HDR..."), + ("Import a template (.json)", "Importer un modèle (.json)"), + ( + "Import an image (File > Import resources) to project it onto the mesh.", + "Importez une image (Fichier > Importer des ressources) pour la projeter sur le maillage.", + ), + ("Import resources...", "Importer des ressources..."), + ("Import MaterialX material...", "Importer un matériau MaterialX..."), + ("MaterialX materials", "Matériaux MaterialX"), + ("Import...", "Importer..."), + ("Imported template \"{name}\"", "Modèle « {name} » importé"), + ("Imported {name}", "{name} importé"), + ("Index of refraction", "Indice de réfraction"), + ("Input high", "Entrée haute"), + ("Input low", "Entrée basse"), + ("Input maps", "Cartes d'entrée"), + ("Insert a variable", "Insérer une variable"), + ("Instance", "Instance"), + ("Instantiate across texture sets", "Instancier dans les ensembles de textures"), + ("Intensity (texels at 2K)", "Intensité (texels en 2K)"), + ("Interface", "Interface"), + ("Interface scale", "Échelle de l'interface"), + ("Inverse Subtract", "Soustraction inverse"), + ("Inverse divide", "Division inverse"), + ("Invert", "Inverser"), + ("Invert mask", "Inverser le masque"), + ("Invert mask background", "Inverser le fond du masque"), + ("Invert mask value", "Inverser la valeur du masque"), + ("Invert quick mask", "Inverser le masque rapide"), + ("Jitters", "Variations"), + ("Join the ArtCraft community on Discord", "Rejoindre la communauté ArtCraft sur Discord"), + ("Join the community (Discord)...", "Rejoindre la communauté (Discord)..."), + ("Key light (shadow-casting light, direct only)", "Lumière principale (projette des ombres, directe uniquement)"), + ("Keyboard", "Clavier"), + ("Keyboard shortcuts", "Raccourcis clavier"), + ("Light azimuth (degrees)", "Azimut de la lumière (degrés)"), + ("Light elevation (degrees)", "Élévation de la lumière (degrés)"), + ("Light intensity", "Intensité de la lumière"), + ("LMB", "Clic gauche"), + ("Language", "Langue"), + ("Layer mask", "Masque de calque"), + ("Layer memory: {mb} MB", "Mémoire des calques : {mb} Mo"), + ("Layers", "Calques"), + ("Lazy mouse", "Stabilisateur"), + ("Lazy mouse distance", "Distance du stabilisateur"), + ("Leather grain", "Grain de cuir"), + ( + "Lens size: how quickly things blur away from the focus distance", + "Taille de l'objectif : vitesse à laquelle les objets deviennent flous en s'éloignant de la distance de mise au point", + ), + ("Level", "Niveau"), + ("Levels", "Niveaux"), + ("Lifetime (steps)", "Durée de vie (pas)"), + ("Light / direction", "Lumière / direction"), + ("Lighten (Max)", "Éclaircir (Max)"), + ("Lightness", "Clarté"), + ("Linear", "Linéaire"), + ("Linear burn", "Densité linéaire +"), + ("Linear dodge (Add)", "Densité linéaire - (Ajout)"), + ("Linear light", "Lumière linéaire"), + ("List of exports", "Liste des exports"), + ("Load UI Layout", "Charger une disposition"), + ("Loaded UI layout {path}", "Disposition de l'interface chargée : {path}"), + ("Log", "Journal"), + ("Low", "Bas"), + ("Luminosity", "Luminosité"), + ("MMB drag / Alt + MMB", "Glisser (clic milieu) / Alt + clic milieu"), + ("Made by the ArtCraft team and community.", "Créé par l'équipe et la communauté ArtCraft."), + ("Magenta / green", "Magenta / vert"), + ("Main shader", "Shader principal"), + ("Marble veins", "Veines de marbre"), + ("Mask", "Masque"), + ("Mask Editor: Edge wear", "Éditeur de masque : usure des arêtes"), + ("Mask value (gray)", "Valeur du masque (gris)"), + ("Mask with height", "Masquer avec la hauteur"), + ("MatFinish Grind", "MatFinish Meulé"), + ("MatFinish Hammered", "MatFinish Martelé"), + ("MatFinish Raw", "MatFinish Brut"), + ("MatFinish Sanded", "MatFinish Poncé"), + ("Material", "Matériau"), + ("Material ball", "Boule de matériau"), + ("Material finish", "Finition du matériau"), + ("Materials", "Matériaux"), + ("Maximum", "Maximum"), + ("Mesh fill", "Remplissage par maillage"), + ("Mesh map: {map}", "Carte de maillage : {map}"), + ("Mesh maps", "Cartes de maillage"), + ("Mesh maps baked", "Cartes de maillage précalculées"), + ("Meshes", "Maillages"), + ("Metallic", "Métallique"), + ("Midtones", "Tons moyens"), + ("Minimum", "Minimum"), + ("Minimum size (%)", "Taille minimale (%)"), + ("Missing (bake to create)", "Manquante (précalculer pour la créer)"), + ("Mixed AO", "AO mixte"), + ("Mode", "Mode"), + ("More in Assets > Alphas: click one, or drag it here", "Plus dans Ressources > Alphas : cliquez sur l'un d'eux ou faites-le glisser ici"), + ("Mosaic", "Mosaïque"), + ("Move down", "Descendre"), + ("Move up", "Monter"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "Déplace la surface selon le canal de hauteur sur une copie plus fine du maillage, à la force de hauteur vers normale (fenêtre d'affichage uniquement : la peinture suit la surface de base)", + ), + ("Multiply", "Produit"), + ("My smart materials", "Mes matériaux intelligents"), + ("Name", "Nom"), + ("New project", "Nouveau projet"), + ("New project...", "Nouveau projet..."), + ("New template", "Nouveau modèle"), + ("No GPU renderer available", "Aucun moteur de rendu GPU disponible"), + ("No font on this system can show this language", "Aucune police de ce système ne peut afficher cette langue"), + ( + "No outputs yet: add one above, then drag input maps onto its channels.", + "Aucune sortie pour l'instant : ajoutez-en une ci-dessus, puis glissez des cartes d'entrée sur ses canaux.", + ), + ("No padding (passthrough)", "Sans marge (transfert direct)"), + ("Noise amount", "Quantité de bruit"), + ("Noise scale", "Échelle du bruit"), + ("None", "Aucun"), + ("Normal", "Normal"), + ("Normal DirectX", "Normale DirectX"), + ("Normal Invert", "Inversion de normale"), + ("Normal OpenGL", "Normale OpenGL"), + ("Normal from height", "Normale depuis la hauteur"), + ("Normal map combine", "Normales : combinaison"), + ("Normal map detail", "Normales : détail"), + ("Color space", "Espace colorimétrique"), + ("Normal map format", "Format de carte de normales"), + ("Normal map inverse detail", "Normales : détail inverse"), + ("Normal: painting uses the flat normal", "Normal : la peinture utilise la normale plate"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Mémoire GPU insuffisante pour afficher entièrement {count} ensembles de textures ({names}) : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", + ), + ("Not exported: no source in this texture set", "Non exporté : aucune source dans cet ensemble de textures"), + ("Not saved: {error}", "Non enregistré : {error}"), + ("Off", "Désactivé"), + ("Offset", "Décalage"), + ("Offset right", "Décalage vers la droite"), + ("Offset up", "Décalage vers le haut"), + ("Offset {axis}", "Décalage {axis}"), + ( + "Offsets the textures by the height channel, at the height to normal strength", + "Décale les textures selon le canal de hauteur, avec l'intensité hauteur vers normale", + ), + ("On", "Activé"), + ("Opacity", "Opacité"), + ("Open sample project...", "Ouvrir un projet d'exemple..."), + ("Open...", "Ouvrir..."), + ("Opened {name}", "{name} ouvert"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "Les canaux optionnels ajoutent un vernis (Poids du vernis, Rugosité du vernis, Normale du vernis), un lustre (Poids du lustre, couleur, rugosité), une anisotropie (Niveau d'anisotropie, angle), une diffusion sous-surfacique (Poids de diffusion) et une transmission (Transmission).", + ), + ("Orbit", "Orbite"), + ("Orthographic", "Orthographique"), + ("Perspective", "Perspective"), + ("Output directory", "Dossier de sortie"), + ("Output high", "Sortie haute"), + ("Output low", "Sortie basse"), + ("Output template", "Modèle de sortie"), + ("Output templates", "Modèles de sortie"), + ("Overlay", "Incrustation"), + ("Overlay opacity", "Opacité de superposition"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - Métallique Rugosité (TextureCraft)"), + ("Pick color", "Prélever une couleur"), + ("PNG image", "Image PNG"), + ("Padding", "Marge"), + ("Paint", "Peinture"), + ("Paint chips", "Éclats de peinture"), + ("Paint on the mesh to edit the layer content.", "Peignez sur le maillage pour modifier le contenu du calque."), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "Peignez sur le maillage pour modifier ce masque. Utilisez la valeur de masque de l'onglet Matériau pour le gris.", + ), + ("Paint with the current tool", "Peindre avec l'outil actuel"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "Pixels des calques peints {pixels} Mo, canaux composités {composites} Mo, cache de composition {cache} Mo", + ), + ("Painting", "Peinture"), + ("Pan", "Panoramique"), + ("Parallax occlusion (height channel)", "Occlusion parallaxe (canal de hauteur)"), + ( + "Partial mask values follow the layer's height: high parts show first", + "Les valeurs de masque partielles suivent la hauteur du calque : les parties hautes apparaissent en premier", + ), + ("Particle brush (slides down the surface)", "Pinceau à particules (glisse le long de la surface)"), + ("Particle brush: particles slide down the surface", "Pinceau à particules : les particules glissent le long de la surface"), + ("Particles", "Particules"), + ("Passthrough", "Transfert"), + ("Paste as instance", "Coller comme instance"), + ("Paste effect", "Coller l'effet"), + ("Paste layer(s)", "Coller le(s) calque(s)"), + ("Path", "Tracé"), + ("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracé : cliquer ajoute un point, cliquer sur la courbe en insère un, glisser le déplace, Enter applique, Esc annule", + ), + ("Pattern scale", "Échelle du motif"), + ("Perlin noise", "Bruit de Perlin"), + ("Pick focus in the viewport", "Choisir la mise au point dans la fenêtre d'affichage"), + ("Pin light", "Lumière ponctuelle"), + ("Place on the surface", "Placer sur la surface"), + ("Place path points on the mesh", "Placez les points du tracé sur le maillage"), + ("Planar projection", "Projection planaire"), + ("Plane", "Plan"), + ("Polygon fill", "Remplissage de polygones"), + ("Pores", "Pores"), + ("Position", "Position"), + ("Position gradient", "Dégradé de position"), + ("Position jitter", "Variation de position"), + ("Posterize", "Postérisation"), + ("Press a key...", "Appuyez sur une touche..."), + ("Project", "Projet"), + ("Project Configuration...", "Configuration du projet..."), + ("Project opened", "Projet ouvert"), + ("Project template", "Modèle de projet"), + ("Projection", "Projection"), + ("Projects and meshes", "Projets et maillages"), + ("Properties", "Propriétés"), + ("Quarter", "Quart"), + ("Quick mask", "Masque rapide"), + ("Quit", "Quitter"), + ("Radius (texels at 2K)", "Rayon (texels en 2K)"), + ("RENDERING", "RENDU"), + ("Range", "Plage"), + ("Rebind any menu item, tool or command", "Réattribuer n'importe quel élément de menu, outil ou commande"), + ("Recent projects", "Projets récents"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "Enregistre la pile jusqu'à ce calque. Les effets de remplissage des masques (et les calques de remplissage) situés au-dessus peuvent l'utiliser comme source.", + ), + ("Redo", "Rétablir"), + ("Reimport mesh", "Réimporter le maillage"), + ("Remove", "Supprimer"), + ("Remove channel", "Supprimer le canal"), + ("Remove effect", "Supprimer l'effet"), + ("Remove last", "Supprimer le dernier"), + ("Remove layer", "Supprimer le calque"), + ("Remove layer(s)", "Supprimer le(s) calque(s)"), + ("Remove mask", "Supprimer le masque"), + ("Remove point", "Retirer le point"), + ("Remove resource", "Supprimer la ressource"), + ("Remove the shortcut", "Supprimer le raccourci"), + ("Remove this output", "Supprimer cette sortie"), + ("Remove unused resources...", "Supprimer les ressources inutilisées..."), + ("Rename the selected template", "Renommer le modèle sélectionné"), + ("Render on the CPU", "Rendu sur le CPU"), + ("Rendering", "Rendu"), + ("Rendering (path traced)", "Rendu (tracé de chemins)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "Rendu sur CPU : {n} / {max} échantillons, {s} s"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "Rendu sur GPU : {n} / {max} échantillons, {s} s"), + ("Rendering, path traced", "Rendu, tracé de chemins"), + ("Replace", "Remplacer"), + ("Replace Color", "Remplacer la couleur"), + ("Replacement color", "Couleur de remplacement"), + ("Report a bug...", "Signaler un bug..."), + ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), + ("Reset", "Réinitialiser"), + ("Reset UI", "Réinitialiser l'interface"), + ("Reset all", "Tout réinitialiser"), + ("Reset to defaults", "Rétablir les valeurs par défaut"), + ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), + ("Resizing", "Redimensionnement"), + ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), + ("Return to this step", "Revenir à cette étape"), + ("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"), + ("Rotation", "Rotation"), + ("Rotation (degrees)", "Rotation (degrés)"), + ("Roughness", "Rugosité"), + ("Roughness from glossiness", "Rugosité depuis la brillance"), + ("Round", "Rond"), + ("Rounded cube", "Cube arrondi"), + ("Samples", "Échantillons"), + ("Saturation", "Saturation"), + ("Save", "Enregistrer"), + ("Save UI Layout", "Enregistrer la disposition"), + ("Save a copy...", "Enregistrer une copie..."), + ("Save as...", "Enregistrer sous..."), + ("Save current layout...", "Enregistrer la disposition actuelle..."), + ("Save render...", "Enregistrer le rendu..."), + ("Save view as camera", "Enregistrer la vue comme caméra"), + ("Saved UI layout {path}", "Disposition de l'interface enregistrée : {path}"), + ("Saved {path}", "Enregistré : {path}"), + ( + "Saving UI layouts to files is available in the desktop app", + "L'enregistrement des dispositions dans des fichiers est disponible dans l'application de bureau", + ), + ("Scale", "Échelle"), + ("Scale / tiling", "Échelle / répétition"), + ("Scatter color", "Couleur de diffusion"), + ("Scatter radius", "Rayon de diffusion"), + ("Scattering weight", "Poids de diffusion"), + ("Scratches", "Rayures"), + ("Screen", "Superposition"), + ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), + ("Search", "Rechercher"), + ("Search commands or keys", "Rechercher des commandes ou des touches"), + ("Seed", "Graine"), + ("Select a layer", "Sélectionnez un calque"), + ("Select an output template", "Sélectionnez un modèle de sortie"), + ("Select source", "Sélectionner la source"), + ("Select the mask (Alt+click: show it in the viewport)", "Sélectionner le masque (Alt+clic : l'afficher dans la fenêtre d'affichage)"), + ("Select...", "Sélectionner..."), + ("Settings", "Paramètres"), + ("Settings...", "Paramètres..."), + ("Shader Settings", "Paramètres du shader"), + ("Shader instance", "Instance de shader"), + ("Shadows", "Tons foncés"), + ("Sharpen", "Netteté"), + ("Sheen color", "Couleur du lustre"), + ("Sheen color × weight", "Couleur du lustre × poids"), + ("Sheen roughness", "Rugosité du lustre"), + ("Sheen weight", "Poids du lustre"), + ("Shift + wheel", "Shift + molette"), + ("Shortcuts list...", "Liste des raccourcis..."), + ("Show on all parts", "Afficher sur toutes les parties"), + ("Show UV wireframe in the 2D view", "Afficher le filaire UV dans la vue 2D"), + ("Show entire mesh", "Afficher tout le maillage"), + ("Show log...", "Afficher le journal..."), + ("Show or hide the layer", "Afficher ou masquer le calque"), + ("Show or hide the texture set", "Afficher ou masquer l'ensemble de textures"), + ("Show wireframe in the 3D view", "Afficher le filaire dans la vue 3D"), + ("Signed addition (AddSub)", "Addition signée (AddSub)"), + ("Size", "Taille"), + ("Size in screen space", "Taille en espace écran"), + ("Size jitter", "Variation de taille"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "Taille des textures affichées dans la fenêtre d'affichage : plus basse, elle consomme moins de mémoire GPU avec de grands ensembles de textures. La peinture et l'export gardent la pleine résolution.", + ), + ("Slope Blur", "Flou de pente"), + ("Slope scale", "Échelle de pente"), + ("Smart masks", "Masques intelligents"), + ("Smart material saved to {path}", "Matériau intelligent enregistré dans {path}"), + ("Smart materials", "Matériaux intelligents"), + ("Smudge", "Barbouillage"), + ("Soft light", "Lumière tamisée"), + ("Softness", "Douceur"), + ("Source", "Source"), + ("Source U {u} V {v}", "Source U {u} V {v}"), + ("Spacing", "Espacement"), + ("Specular", "Spéculaire"), + ("Specular level", "Niveau spéculaire"), + ("Sphere", "Sphère"), + ("Spherical projection", "Projection sphérique"), + ("Spray", "Aérosol"), + ("Square", "Carré"), + ("Stamp depth", "Profondeur d'empreinte"), + ("Star", "Étoile"), + ("Starting render...", "Démarrage du rendu..."), + ("Stencil", "Pochoir"), + ("Steps", "Paliers"), + ("Streaks", "Traînées"), + ("Strength", "Force"), + ("Stripes", "Bandes"), + ("Stroke opacity", "Opacité du trait"), + ("Subsampling 2x2", "Sous-échantillonnage 2x2"), + ("Subsampling 4x4", "Sous-échantillonnage 4x4"), + ("Subsampling 8x8", "Sous-échantillonnage 8x8"), + ("Subsurface scattering", "Diffusion sous-surfacique"), + ("Subtract", "Soustraction"), + ("Tangent | Wrap", "Tangente | Enveloppe"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anticrénelage temporel (affine la vue 3D tant qu'elle est immobile)"), + ("Texture Sets", "Ensembles de textures"), + ("Texture Set Settings", "Paramètres de l'ensemble de textures"), + ("Texture resolution", "Résolution des textures"), + ("Texture set channels", "Canaux de l'ensemble de textures"), + ("Texture sets", "Ensembles de textures"), + ("TextureCraft had to close:", "TextureCraft a dû se fermer :"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Métallique Rugosité"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - Spéculaire Brillance"), + ("TextureCraft project", "Projet TextureCraft"), + ("TextureCraft project or mesh", "Projet TextureCraft ou maillage"), + ("Textures", "Textures"), + ("Textures embedded; for game engines and most viewers", "Textures intégrées ; pour les moteurs de jeu et la plupart des visionneuses"), + ("Textures packaged; for USD tools and AR Quick Look", "Textures empaquetées ; pour les outils USD et AR Quick Look"), + ("The GPU couldn't render this scene: {error}", "Le GPU n'a pas pu rendre cette scène : {error}"), + ("The bake worker stopped", "Le processus de précalcul s'est arrêté"), + ("The eraser removes paint from the enabled channels.", "La gomme efface la peinture des canaux activés."), + ("The first stroke sets the offset from the source.", "Le premier trait définit le décalage par rapport à la source."), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "L'alpha de l'image découpe la forme du décalque ; les faces orientées à l'opposé et les surfaces au-delà de sa profondeur restent intactes.", + ), + ("The next click in the 3D view moves the decal there", "Le prochain clic dans la vue 3D y déplace le décalque"), + ("The resize worker stopped", "Le processus de redimensionnement s'est arrêté"), + ("Thickness", "Épaisseur"), + ("Thin areas", "Zones fines"), + ("Threshold", "Seuil"), + ("Tile", "Répéter"), + ("Tiles", "Carreaux"), + ("Tint", "Teinte"), + ("Toggle mask", "Activer/désactiver le masque"), + ("Tolerance", "Tolérance"), + ("Tone mapping", "Mappage des tons"), + ("Tools", "Outils"), + ("Torus", "Tore"), + ("Transmission", "Transmission"), + ("Tri-planar projection", "Projection triplanaire"), + ("Triangle fill", "Remplissage de triangles"), + ("UDIM plane", "Plan UDIM"), + ("UDIM tiles painted by this texture set, each at the set's size", "Tuiles UDIM peintes par cet ensemble de textures, chacune à la taille de l'ensemble"), + ("UI layout", "Disposition de l'interface"), + ("UI layout: {error}", "Disposition de l'interface : {error}"), + ("UI layouts", "Dispositions de l'interface"), + ("UI {ms} ms", "Interface {ms} ms"), + ("USD binary, textures alongside", "USD binaire, textures à côté"), + ("USD text, textures alongside", "USD texte, textures à côté"), + ("USDZ with textures", "USDZ avec textures"), + ("UV checker", "Damier UV"), + ("UV island fill", "Remplissage d'îlots UV"), + ("UV transformations", "Transformations UV"), + ("UV projection", "Projection UV"), + ("UV tiles", "Tuiles UV"), + ("UV tiles (UDIM)", "Tuiles UV (UDIM)"), + ("Undo", "Annuler"), + ("Uniform value", "Valeur uniforme"), + ("Use an equirectangular .hdr or .exr image as the environment", "Utiliser une image équirectangulaire .hdr ou .exr comme environnement"), + ( + "Use the control channel or `texturecraft-cli render` for screenshots", + "Utilisez le canal de contrôle ou `texturecraft-cli render` pour les captures d'écran", + ), + ("Value", "Valeur"), + ("Version {version}", "Version {version}"), + ("Version: {version} ({gpu})", "Version : {version} ({gpu})"), + ("View through this camera", "Voir à travers cette caméra"), + ("Viewer settings", "Paramètres de visualisation"), + ("Viewport", "Affichage"), + ("Viewport and brush (fixed)", "Fenêtre d'affichage et pinceau (fixes)"), + ("Views", "Vues"), + ("Vivid light", "Lumière vive"), + ("Voronoi", "Voronoï"), + ("Warp", "Distorsion"), + ("Warp Directional", "Distorsion directionnelle"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ avec MTL, textures à côté"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "WebGPU n'est pas disponible dans ce navigateur : TextureCraft utilise WebGL2. Le mode Rendu calcule le tracé de chemins sur le CPU (plus lent) et les grands ensembles de textures s'affichent en résolution réduite. Une version récente de Chrome, Edge ou Safari prend en charge WebGPU.", + ), + ("Wheel / Alt + RMB drag", "Molette / Alt + glisser (clic droit)"), + ("White", "Blanc"), + ("Width", "Largeur"), + ("Width (texels at 2K)", "Largeur (texels en 2K)"), + ("Window", "Fenêtre"), + ("Wood grain", "Veinage du bois"), + ("Works in texture space, like the blur: it does not cross UV seams.", "Fonctionne en espace texture, comme le flou : ne traverse pas les coutures UV."), + ("World Space Normal", "Normale en espace monde"), + ("Yellow / blue", "Jaune / bleu"), + ("Zoom", "Zoom"), + ("a missing layer", "un calque manquant"), + ("aniso", "aniso"), + ("aniso angle", "ang aniso"), + ("ao", "ao"), + ("coat", "vernis"), + ("coat nrm", "nrm vern"), + ("coat rough", "rug vern"), + ("color", "couleur"), + ("emiss", "émis"), + ("glTF binary with textures", "glTF binaire avec textures"), + ("gloss", "brill"), + ("height", "hauteur"), + ("metal", "métal"), + ("min", "min"), + ("missing", "manquant"), + ("missing source", "source manquante"), + ("no GPU", "pas de GPU"), + ("none", "aucun"), + ("nrm", "nrm"), + ("off", "désact."), + ("op", "op"), + ("rough", "rug"), + ("scatter", "diffus"), + ("sheen", "lustre"), + ("sheen color", "coul lus"), + ("sheen rough", "rug lus"), + ("spec", "spéc"), + ("specular", "spécul"), + ("transm", "transm"), + ("{action} (undone)", "{action} (annulé)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file} : ajouter au-dessus du calque sélectionné (ou le glisser dans la pile de calques ou sur la fenêtre d'affichage)", + ), + ("{name} copy", "Copie de {name}"), + ("{n} bits", "{n} bits"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "{n} points de contrôle. Cliquez sur le maillage (ou la vue 2D) pour ajouter des points et faites-les glisser pour les ajuster ; cliquez sur le premier point pour fermer le tracé. Entrée le peint avec le pinceau (un tracé fermé et rempli remplit son intérieur), Échap annule.", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} éléments partagent un raccourci ; le premier de la liste l'emporte."), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (échelle {scale}, graine {seed})"), + ("Template name", "Nom du modèle"), + ("Save current project as template", "Enregistrer le projet actuel comme modèle"), + ("Distribution", "Distribution"), + ("Cosine", "Cosinus"), + ("Uniform", "Uniforme"), + ("Normalization", "Normalisation"), + // Settings › Interface: brightness and accent color. + ("Brightness", "Luminosité"), + ("Dark", "Sombre"), + ("Medium dark", "Moyennement sombre"), + ("Medium light", "Moyennement clair"), + ("Light", "Clair"), + ("Accent color", "Couleur d'accentuation"), + ("Copper", "Cuivre"), + ("Coral", "Corail"), + ("Blue", "Bleu"), + ("Violet", "Violet"), + ("Green", "Vert"), + ("Amber", "Ambre"), + ("Pink", "Rose"), + ("Minimize", "Réduire"), + ("Maximize", "Agrandir"), + ("Restore", "Restaurer"), + ("Title bar", "Barre de titre"), + ("System title bar (applies on restart)", "Barre de titre du système (au prochain démarrage)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", + ), + ("Brushes", "Pinceaux"), + ("Brush name", "Nom du pinceau"), + ("Save current brush", "Enregistrer le pinceau actuel"), + ("Start window", "Fenêtre de démarrage"), + ("Show at startup", "Afficher au démarrage"), + ("Continue with the sample project", "Continuer avec le projet d'exemple"), + ("No recent projects yet", "Aucun projet récent pour l'instant"), + ("Text", "Texte"), + ("Font", "Police"), + ("Style", "Style"), + ("Use as brush alpha", "Utiliser comme alpha du pinceau"), + ("Place as decal", "Placer en décalque"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clic : active ou désactive ce canal. Alt+clic : ce canal uniquement"), + ("Show all", "Tout afficher"), + ("Hide all", "Tout masquer"), + ("Invert show/hide", "Inverser afficher/masquer"), + ("Show or hide texture sets", "Afficher ou masquer les ensembles de textures"), + ("Focus: show only the active texture set", "Focus : n'afficher que l'ensemble de textures actif"), + ("Unsaved changes", "Modifications non enregistrées"), + ("Don't save", "Ne pas enregistrer"), + ("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"), + ("Radius", "Rayon"), + ("Remove skew correction", "Supprimer la correction d'inclinaison"), + ("Twill weave", "Armure sergé"), + ("Save the changes to {name} first?", "Enregistrer d'abord les modifications de {name} ?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Les tracés restent modifiables : choisissez-en un pour déplacer ses points ou changer sa brosse et sa matière, et la sous-couche se repeint aussitôt. Ajoutez des tracés avec l'outil Tracé.", + ), + ("Import material...", "Importer un matériau..."), + ("MaterialCraft material", "Matériau MaterialCraft"), + ("Cooked at {size} px", "Calculé en {size} px"), + ("Preset", "Préréglage"), + ("Re-cook", "Recalculer"), + ("Open in MaterialCraft", "Ouvrir dans MaterialCraft"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "Ouvert dans MaterialCraft : utilisez-y Fichier > Envoyer vers TextureCraft pour récupérer vos modifications", + ), + ( + "Parameters change in the desktop app, with MaterialCraft installed", + "Les paramètres se modifient dans l'application de bureau, avec MaterialCraft installé", + ), + ("Add High-Poly Meshes", "Ajouter des maillages haute définition"), + ("All", "Tous"), + ("Apply Diffusion", "Appliquer la diffusion"), + ("Attenuation", "Atténuation"), + ("Auto Tonemapping", "Mappage tonal automatique"), + ("Average Normals", "Moyenne des normales"), + ("BBox", "Boîte englobante"), + ("BSphere", "Sphère englobante"), + ("Mesh Map Bakers", "Précalculateurs de cartes de maillage"), + ("Common Settings", "Paramètres communs"), + ("Mesh Map Settings", "Paramètres des cartes de maillage"), + ("Check All", "Tout cocher"), + ("No Parameters", "Aucun paramètre"), + ("Bake Selected Textures ({n})", "Précalculer les textures sélectionnées ({n})"), + ("By Mesh Name", "Par nom de maillage"), + ("Cage", "Cage"), + ("Cage Scene", "Scène de cage"), + ("Cage Type", "Type de cage"), + ("Color Generator", "Générateur de couleurs"), + ("Color Source", "Source de couleur"), + ("Common Parameters", "Paramètres communs"), + ("Custom File", "Fichier personnalisé"), + ("Details", "Détails"), + ("Dilation Width", "Largeur de dilatation"), + ("Distance-Based", "Selon la distance"), + ("Edge Contrast", "Contraste des arêtes"), + ("Edge Distance", "Distance des arêtes"), + ("Edge Protection", "Protection des arêtes"), + ("Enable Seams", "Activer les coutures"), + ("File ID", "ID du fichier"), + ("Full Scene", "Scène entière"), + ("Generate from Mesh", "Générer depuis le maillage"), + ("Generate from Normal Map", "Générer depuis la carte de normales"), + ("Ground Plane", "Plan du sol"), + ("Ground Plane Offset", "Décalage du sol"), + ("High Poly Mesh Suffix", "Suffixe du maillage high poly"), + ("High Poly Scene", "Scène haute définition"), + ("High-Poly Parameters", "Paramètres haute définition"), + ("Hue Shift", "Décalage de teinte"), + ("Ignore Backface", "Ignorer les faces arrière"), + ("Ignore Backface Suffix", "Suffixe des faces arrière ignorées"), + ("Include in Bake", "Inclure dans le précalcul"), + ("Load Cage", "Charger une cage"), + ("Lock Output Size", "Verrouiller les dimensions de sortie"), + ("Low Poly Mesh Suffix", "Suffixe du maillage low poly"), + ("Manual", "Manuel"), + ("Material Color", "Couleur du matériau"), + ("Max Frontal Distance", "Distance frontale max"), + ("Max Occluder Distance", "Distance max des occulteurs"), + ("Max Rear Distance", "Distance arrière max"), + ("Mesh ID", "ID du maillage"), + ("Method", "Méthode"), + ("Min Occluder Distance", "Distance minimale des occluseurs"), + ("Never", "Jamais"), + ("No High-Poly Meshes", "Aucun maillage haute définition"), + ("Normalization Scale", "Échelle de normalisation"), + ("Normalization Type", "Type de normalisation"), + ("Only Same Mesh Name", "Seulement le même nom de maillage"), + ("Output Size", "Taille de sortie"), + ("Match", "Correspondance"), + ("Skew Correction Method", "Méthode de Correction de Déformation"), + ("Mesh Normals Based", "Basée sur les Normales du Maillage"), + ("Face Normals Based", "Basée sur les Normales des Faces"), + ("Reset Painted Cage", "Réinitialiser la Cage Peinte"), + ("Paint Cage", "Peindre la cage"), + ("Paint Skew Correction", "Peindre la correction d'inclinaison"), + ("Per Material", "Par matériau"), + ("Random", "Aléatoire"), + ("Relative to Bounding Box", "Relatif à la boîte englobante"), + ("Relative to Low Mesh", "Relatif au maillage basse définition"), + ("Relative to Min/Max", "Relatif au minimum/maximum"), + ("Relative to Ray Distances", "Relatif aux distances des rayons"), + ("Remove Cage", "Supprimer la cage"), + ("Remove Skew Correction", "Supprimer la correction d'inclinaison"), + ("Restore Defaults", "Rétablir les valeurs par défaut"), + ("Return to Painting Mode", "Revenir au mode peinture"), + ("Sampling Radius", "Rayon d'échantillonnage"), + ("Scaling Divisor", "Diviseur d'échelle"), + ("Seams Intensity", "Intensité des coutures"), + ("Secondary Rays", "Rayons secondaires"), + ("Self Intersection", "Auto-intersection"), + ("Self Occlusion", "Auto-occlusion"), + ("Skew Correction", "Correction d'inclinaison"), + ("Smooth", "Lisse"), + ("Spread Angle", "Angle de dispersion"), + ("Submesh", "Sous-maillage"), + ("Use Low Poly Mesh as High Poly Mesh", "Utiliser le maillage low poly comme maillage high poly"), + ("Value Bounds Max", "Borne maximale"), + ("Value Bounds Min", "Borne minimale"), + ("Vertex Color", "Couleur des sommets"), + ("Select the layer content", "Sélectionner le contenu du calque"), + ("Paint layer", "Calque de peinture"), + ("Fill layer", "Calque de remplissage"), + ("1 effect", "1 effet"), + ("{count} effects", "{count} effets"), + ("Mask effects", "Effets du masque"), + ("Content effects", "Effets du contenu"), + ("Fold or unfold these effects", "Replier ou déplier ces effets"), + ("Remove resolution override", "Supprimer la résolution personnalisée"), + ("Texture set resolution", "Résolution de l'ensemble de textures"), + ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Angle span", "Amplitude d'angle"), + ("Axis position", "Position de l'axe"), + ("Count", "Nombre"), + ("Display", "Affichage"), + ("Hide while painting", "Masquer pendant la peinture"), + ("Manipulator size", "Taille du manipulateur"), + ("Mirror symmetry", "Symétrie miroir"), + ("Radial settings", "Paramètres radiaux"), + ("Radial symmetry", "Symétrie radiale"), + ("Show axis", "Afficher l'axe"), + ("Show axis position manipulator", "Afficher le manipulateur de position de l'axe"), + ("Show cursor", "Afficher le curseur"), + ("Show intersection", "Afficher l'intersection"), + ("Show plane", "Afficher le plan"), + ("Symmetry", "Symétrie"), + ("Symmetry color display", "Couleur d'affichage de la symétrie"), + ("Symmetry settings", "Paramètres de symétrie"), + ("Type", "Type"), + ("Advanced settings", "Paramètres avancés"), + ("Import baked maps", "Importer des cartes précalculées"), + ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), + ("Add...", "Ajouter..."), + ("Baked maps imported: {count}", "Cartes précalculées importées : {count}"), + ("Not imported: {files}", "Non importés : {files}"), + ("Baking Visualization", "Visualisation du baking"), + ("Show for Selected Texture Set Only", "Afficher uniquement pour l'ensemble de textures sélectionné"), + ("High Definition Mesh (HP)", "Maillage haute définition (HP)"), + ("UV Seams", "Coutures UV"), + ("Project Mesh (LP)", "Maillage de projection (LP)"), + ("Edges", "Arêtes"), + ("Cavities", "Cavités"), + ("Edges and cavities", "Arêtes et cavités"), + ("Raw curvature", "Courbure brute"), + ("Detail sizes", "Tailles de détail"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lit la carte de courbure telle que calculée : changer le mode ou une taille active les tailles de détail.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic remplit ce qui est dessous ; un rectangle tracé remplit ce qu'il sélectionne à mesure qu'il grandit", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centre contenu : remplir les polygones dont le centre est dans le rectangle"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modification du masque rapide : les remplissages peignent là où la peinture est autorisée. Appuyez sur U pour terminer.", + ), + ("Fill mode", "Mode de remplissage"), + ("Fill only polygons the camera sees (3D view)", "Remplir uniquement les polygones que voit la caméra (vue 3D)"), + ("Hit-test", "Test de sélection"), + ("How a rectangle selects polygons", "Comment un rectangle sélectionne les polygones"), + ("Intersection: fill polygons the rectangle touches", "Intersection : remplir les polygones que touche le rectangle"), + ("Rectangle fill", "Remplissage rectangulaire"), + ("Select a paint layer or a layer's mask to fill", "Sélectionnez un calque de peinture ou un masque de calque à remplir"), + ("Selection mode", "Mode de sélection"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangle remplit des triangles seuls, Polygone des quads et n-gones entiers, Maillage la géométrie connectée, Îlot UV les îlots UV", + ), + ("Visible polygons only", "Polygones visibles uniquement"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque", + ), + ("The file dialog couldn't be shown: {error}", "Impossible d'afficher la boîte de dialogue de fichiers : {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Le projet a changé pendant que la boîte de dialogue était ouverte ; rien n'a été fait", + ), + ("Cores kept for the UI", "Cœurs réservés à l'interface"), + ("Max RAM while saving", "RAM max. à l'enregistrement"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "L'enregistrement utilise les autres cœurs et au plus cette part de la RAM libre. Au moins un cœur travaille toujours.", + ), + ("Max project size on open", "Taille max. à l’ouverture"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", + ), + ("Filter by type", "Filtrer par type"), + ("All libraries", "Toutes les bibliothèques"), + ("Browse folders", "Parcourir les dossiers"), + ("Starter assets", "Ressources fournies"), + ("Your assets", "Vos ressources"), + ("Reset query", "Réinitialiser la requête"), + ("Refresh", "Actualiser"), + ("Saved searches", "Recherches enregistrées"), + ("Save the current search", "Enregistrer la recherche actuelle"), + ("Delete", "Supprimer"), + ("Filter by path", "Filtrer par chemin"), + ("Hide non-applicable folders", "Masquer les dossiers non applicables"), + ("Thumbnail size", "Taille des miniatures"), + ("Small", "Petit"), + ("Medium", "Moyen"), + ("Large", "Grand"), + ("List", "Liste"), + ("Procedurals", "Procéduraux"), +]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs new file mode 100644 index 00000000..55fe9abd --- /dev/null +++ b/crates/ui-egui/src/i18n/it.rs @@ -0,0 +1,1191 @@ +//! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Bake di {map} in corso ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Bake di {map} in corso ({n}/{total}), set di texture {set} di {sets}"), + ("Follow Newest Map", "Segui la mappa più recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pittura è in pausa finché viene mostrato un bake. Annulla il bake o attendi che finisca.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Cosa mostra la vista 3D durante il bake: l'ultima mappa completata, una mappa completata a scelta o il materiale. Le mappe non ancora create mostrano un valore neutro.", + ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), + ("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"), + ("2D view only", "Solo vista 2D"), + ("32 bits (float)", "32 bit (float)"), + ("3D mesh", "Mesh 3D"), + ("3D meshes", "Mesh 3D"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "Pittura di texture 3D: livelli, maschere, materiali intelligenti, bake delle mappe mesh ed esportazione.", + ), + ("3D view only", "Solo vista 3D"), + ("3D/2D views", "Viste 3D/2D"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "Una cartella fonde i livelli che contiene (pass-through). Imposta l'opacità per canale nelle righe dei livelli.", + ), + ("ACES filmic", "ACES filmico"), + ("Ambient", "Ambiente"), + ("AO intensity", "Intensità AO"), + ("About TextureCraft", "Informazioni su TextureCraft"), + ("About TextureCraft...", "Informazioni su TextureCraft..."), + ( + "Add an anchor point to a layer below to use its stack as a mask.", + "Aggiungi un punto di ancoraggio a un livello sottostante per usarne la pila come maschera.", + ), + ("Add anchor point", "Aggiungi punto di ancoraggio"), + ("Add as decal (view center)", "Aggiungi come decal (centro della vista)"), + ("Add black mask", "Aggiungi maschera nera"), + ("Add channel", "Aggiungi canale"), + ("Add color", "Aggiungi colore"), + ("Add compare mask", "Aggiungi maschera di confronto"), + ("Add effect", "Aggiungi effetto"), + ("Add fill", "Aggiungi riempimento"), + ("Add fill layer", "Aggiungi livello di riempimento"), + ("Add filter", "Aggiungi filtro"), + ("Add folder", "Aggiungi cartella"), + ("Add generator", "Aggiungi generatore"), + ("Add levels", "Aggiungi Livelli"), + ("Add mask", "Aggiungi maschera"), + ("Add mask with color selection", "Aggiungi maschera con selezione colore"), + ("Add output", "Aggiungi output"), + ("Add paint", "Aggiungi pittura"), + ("Add paint layer", "Aggiungi livello di pittura"), + ("Add smart material from the shelf", "Aggiungi un materiale intelligente dalla libreria"), + ("Add to the layer content", "Aggiungi al contenuto del livello"), + ("Add to the mask", "Aggiungi alla maschera"), + ("Add white mask", "Aggiungi maschera bianca"), + ("Adjustments", "Regolazioni"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "Allineato: viene mantenuto l'offset impostato dal primo tratto. V + clic imposta una nuova sorgente.", + ), + ("Alignment", "Allineamento"), + ("Alignment and culling", "Allineamento e culling"), + ("All layers", "Tutti i livelli"), + ("Alpha", "Alpha"), + ("Alphas", "Alpha"), + ("Also bound to {item} ({menu})", "Assegnata anche a {item} ({menu})"), + ("Alt + LMB drag", "Alt + trascina (tasto sinistro)"), + ("Always", "Sempre"), + ("Ambient Occlusion", "Occlusione ambientale"), + ("Ambient occlusion", "Occlusione ambientale"), + ("Amount", "Quantità"), + ("Anchor point", "Punto di ancoraggio"), + ("Anchor: {name}", "Ancoraggio: {name}"), + ("Anchor: {name} ({channel})", "Ancoraggio: {name} ({channel})"), + ("Angle", "Angolo"), + ("Angle (degrees)", "Angolo (gradi)"), + ("Angle fade from", "Dissolvenza angolo da"), + ("Angle fade to", "Dissolvenza angolo a"), + ("Angle jitter", "Variazione angolo"), + ("Anisotropy angle", "Angolo anisotropia"), + ("Anisotropy level", "Livello anisotropia"), + ("Antialiasing", "Antialiasing"), + ("Aperture", "Apertura"), + ("Apply", "Applica"), + ("ArtCraft website...", "Sito web di ArtCraft..."), + ("Assets", "Risorse"), + ("Auto", "Auto"), + ("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"), + ("Autosave every", "Salvataggio automatico ogni"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "Salvataggi automatici, materiali smart, preset, modelli e layout dell'interfaccia vanno nella cartella dei dati. Una nuova cartella si applica al riavvio; i file già salvati restano dove sono.", + ), + ("Axis", "Asse"), + ("Back to painting", "Torna alla pittura"), + ("Backface culling", "Culling facce posteriori"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Esegui il bake di una mappa ID (F8) per prelevare i colori dalla mesh."), + ("Bake Mesh Maps", "Bake mappe mesh"), + ("Bake mesh maps", "Bake mappe mesh"), + ( + "Bake mesh maps (F8) for curvature, AO and thickness based generators.", + "Esegui il bake delle mappe mesh (F8) per i generatori basati su curvatura, AO e spessore.", + ), + ("Baked Lighting", "Illuminazione precalcolata"), + ("Baking", "Baking"), + ("Base color", "Colore base"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "Colore base è il colore diffuso, Speculare il colore F0 e Lucentezza 1 - rugosità (aggiungi questi canali nelle impostazioni del set di texture).", + ), + ("Base color, Metallic, Roughness and Specular level.", "Colore base, Metallico, Rugosità e Livello speculare."), + ("Based on each texture set's size", "In base alla dimensione di ciascun set di texture"), + ("Basic settings", "Impostazioni di base"), + ("Bent Normals", "Bent normal"), + ("Bevel", "Smusso"), + ("Black", "Nero"), + ("Blending", "Fusione"), + ("Blending mode of the displayed channel", "Metodo di fusione del canale visualizzato"), + ("Blur", "Sfocatura"), + ("Blur Directional", "Sfocatura direzionale"), + ("Blur and sharpen", "Sfocatura e nitidezza"), + ("Bounces", "Rimbalzi"), + ("Bricks", "Mattoni"), + ("Brush", "Pennello"), + ("Brush size", "Dimensione pennello"), + ("Brush size down / up", "Riduci / aumenta dimensione pennello"), + ("Brushed lines", "Linee spazzolate"), + ("Built-in (read-only): duplicate it to edit", "Integrato (sola lettura): duplicalo per modificarlo"), + ("Built-in templates are read-only: duplicate one to edit it", "I modelli integrati sono di sola lettura: duplicane uno per modificarlo"), + ("Built-in: {mesh}", "Integrata: {mesh}"), + ("Cage: {name}", "Gabbia: {name}"), + ("Camera", "Camera"), + ("Colors", "Colori"), + ("Go to camera 1", "Vai alla camera 1"), + ("Go to camera 2", "Vai alla camera 2"), + ("Go to camera 3", "Vai alla camera 3"), + ("Go to camera 4", "Vai alla camera 4"), + ("Go to camera 5", "Vai alla camera 5"), + ("Go to camera 6", "Vai alla camera 6"), + ("Go to camera 7", "Vai alla camera 7"), + ("Go to camera 8", "Vai alla camera 8"), + ("Go to camera 9", "Vai alla camera 9"), + ("Camera settings", "Impostazioni camera"), + ("Cancel", "Annulla"), + ("Cancel the stroke", "Annulla il tratto"), + ("Cell size (texels at 2K)", "Dimensione celle (texel a 2K)"), + ("Cells", "Celle"), + ("Channel", "Canale"), + ("Channel source: uniform value, procedural, image or anchor", "Sorgente del canale: valore uniforme, procedurale, immagine o ancoraggio"), + ("Channels", "Canali"), + ("Check for Updates...", "Controlla aggiornamenti..."), + ("Checker", "Scacchiera"), + ("Clamp", "Limita"), + ("Clear", "Cancella"), + ("Clear mask", "Cancella maschera"), + ("Clear recent projects", "Cancella progetti recenti"), + ( + "Click a mesh part to show or hide the selected layer on it.", + "Fai clic su una parte della mesh per mostrare o nascondere il livello selezionato su di essa.", + ), + ("Click the mesh to pick its material into the brush", "Fai clic sulla mesh per prelevarne il materiale nel pennello"), + ("Click the mesh to place the decal", "Fai clic sulla mesh per posizionare la decal"), + ("Click, then press the new shortcut (Esc cancels)", "Fai clic, poi premi la nuova scorciatoia (Esc per annullare)"), + ("Clone", "Clona"), + ("Close", "Chiudi"), + ("Closed path", "Tracciato chiuso"), + ("Cloud", "Nuvola"), + ("Clouds", "Nuvole"), + ("Coat normal", "Normale rivestimento"), + ("Coat roughness", "Rugosità rivestimento"), + ("Coat weight", "Peso rivestimento"), + ("Color", "Colore"), + ("Color Balance", "Bilanciamento colore"), + ("Color burn", "Brucia colore"), + ("Color dodge", "Scherma colore"), + ( + "Color of the light that travels under the surface (each channel goes as far as its value)", + "Colore della luce che viaggia sotto la superficie (ogni canale arriva fino al proprio valore)", + ), + ("Color picker", "Contagocce"), + ("Color selection", "Selezione colore"), + ("Color to replace", "Colore da sostituire"), + ( + "Colors near the first shift towards the second, keeping their shading.", + "I colori vicini al primo si spostano verso il secondo, mantenendo l'ombreggiatura.", + ), + ( + "Colors read as gray. Add a levels or blur effect above to shape the result.", + "I colori vengono letti come grigio. Aggiungi sopra un effetto Livelli o Sfocatura per modellare il risultato.", + ), + ("Combine with the layer's height", "Combina con l'altezza del livello"), + ("Compare mask", "Maschera di confronto"), + ("Compositing", "Compositing"), + ("Constant", "Costante"), + ("Constants", "Costanti"), + ("Contrast", "Contrasto"), + ("Contrast/Luminosity", "Contrasto/Luminosità"), + ("Converted maps", "Mappe convertite"), + ("Copy RGB values", "Copia i valori RGB"), + ("Copy effect", "Copia effetto"), + ("Copy from", "Copia da"), + ("Copy layer(s)", "Copia livello/i"), + ("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"), + ("Copy to all texture sets", "Copia in tutti i set di texture"), + ("Copy what the texture set shows", "Copia ciò che mostra il set di texture"), + ("Couldn't encode the render", "Impossibile codificare il render"), + ("Couldn't export textures: {error}", "Impossibile esportare le texture: {error}"), + ("Couldn't export the mesh: {error}", "Impossibile esportare la mesh: {error}"), + ("Couldn't export the template: {error}", "Impossibile esportare il modello: {error}"), + ("Couldn't import {name}: {error}", "Impossibile importare {name}: {error}"), + ("Couldn't open {name}: {error}", "Impossibile aprire {name}: {error}"), + ("Couldn't read the render back from the GPU", "Impossibile rileggere il render dalla GPU"), + ("Couldn't save the render: {error}", "Impossibile salvare il render: {error}"), + ("Couldn't save {name}: {error}", "Impossibile salvare {name}: {error}"), + ("Count per stamp", "Quantità per impronta"), + ("Crate", "Cassa"), + ("Create", "Crea"), + ("Create smart material", "Crea materiale intelligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+trascina con il tasto destro in una vista per regolare dimensione e durezza, con il sinistro flusso e angolo.", + ), + ("Cube", "Cubo"), + ("Current layer", "Livello corrente"), + ("Curvature", "Curvatura"), + ("Cut effect", "Taglia effetto"), + ("Cut layer(s)", "Taglia livello/i"), + ("Cyan / red", "Ciano / rosso"), + ("Cylinder", "Cilindro"), + ("Cylindrical projection", "Proiezione cilindrica"), + ( + "Dark to light: the content's luminance picks a color along these stops.", + "Da scuro a chiaro: la luminanza del contenuto sceglie un colore lungo questi punti di colore.", + ), + ("Darken (Min)", "Scurisci (Min)"), + ("Data folder", "Cartella dei dati"), + ("Decal", "Decal"), + ("Decal projection", "Proiezione decal"), + ("Default", "Predefinito"), + ("Default camera", "Camera predefinita"), + ("Delete the selected template", "Elimina il modello selezionato"), + ("Delete this camera", "Elimina questa camera"), + ("Deleted template \"{name}\"", "Modello \"{name}\" eliminato"), + ("Denoise", "Riduzione rumore"), + ("Depth", "Profondità"), + ("Depth of field", "Profondità di campo"), + ("Depth of field (viewport and Rendering mode)", "Profondità di campo (viewport e modalità Rendering)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "Profondità del piano a fuoco lungo la vista (0: il centro di orbita)"), + ("Details saved to {file}", "Dettagli salvati in {file}"), + ("Difference", "Differenza"), + ("Dilation + default background color", "Dilatazione + colore di sfondo predefinito"), + ("Dilation + transparent", "Dilatazione + trasparente"), + ("Dilation infinite", "Dilatazione infinita"), + ("DirectX normal map", "Mappa normali DirectX"), + ("Dirt", "Sporco"), + ("Disable", "Disattiva"), + ("Dismiss", "Chiudi"), + ("Displacement (height channel)", "Displacement (canale altezza)"), + ("Display Settings", "Impostazioni di visualizzazione"), + ("Display material", "Mostra materiale"), + ("Display next channel", "Mostra canale successivo"), + ("Display next mesh map", "Mostra mappa mesh successiva"), + ("Display previous channel", "Mostra canale precedente"), + ("Display previous mesh map", "Mostra mappa mesh precedente"), + ("Distance", "Distanza"), + ("Distort", "Distorsione"), + ("Divide", "Dividi"), + ("Document resolution", "Risoluzione documento"), + ("Documentation...", "Documentazione..."), + ("Done on CPU: {n} / {max} samples, {s} s", "Completato su CPU: {n} / {max} campioni, {s} s"), + ("Done on GPU: {n} / {max} samples, {s} s", "Completato su GPU: {n} / {max} campioni, {s} s"), + ("Double-click to rename", "Doppio clic per rinominare"), + ("Download as", "Scarica come"), + ("Downloaded {name}", "{name} scaricato"), + ("Drag onto an output channel", "Trascina su un canale di output"), + ( + "Drags the layer stack's values along the stroke into the selected layer.", + "Trascina i valori della pila dei livelli lungo il tratto nel livello selezionato.", + ), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "Disegna {name} del set di texture \"{set}\". Le modifiche alla sorgente appaiono in ogni istanza.", + ), + ( + "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", + "Trascina il riquadro per spostare la decal, un angolo per scalarla, la maniglia rotonda per ruotarla", + ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Rilascia qui un'immagine dal pannello Risorse per usarla come questa mappa mesh"), + ("Dry streaks", "Striature secche"), + ("Duplicate effect", "Duplica effetto"), + ("Duplicate layer(s)", "Duplica livello/i"), + ("Duplicate the selected template", "Duplica il modello selezionato"), + ("Edge Detect", "Rilevamento bordi"), + ("Edit", "Modifica"), + ("Edit keyboard shortcuts...", "Modifica scorciatoie da tastiera..."), + ("Edit quick mask", "Modifica maschera rapida"), + ("Editing quick mask: paint where painting is allowed (U to finish)", "Modifica maschera rapida: dipingi dove è consentito dipingere (U per terminare)"), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "Modifica della maschera rapida: i tratti dipingono le aree in cui è consentito dipingere. Premi U per terminare.", + ), + ("Emissive", "Emissivo"), + ("Enable or disable the effect", "Attiva o disattiva l'effetto"), + ("Enable quick mask", "Attiva maschera rapida"), + ("Environment blur", "Sfocatura ambiente"), + ("Environment exposure (EV)", "Esposizione ambiente (EV)"), + ("Environment map", "Mappa ambiente"), + ("Environment opacity", "Opacità ambiente"), + ("Environment rotation", "Rotazione ambiente"), + ("Environment settings", "Impostazioni ambiente"), + ("Environment: {name}", "Ambiente: {name}"), + ("Environments", "Ambienti"), + ("Eraser", "Gomma"), + ("Exclusion", "Esclusione"), + ("Expand or collapse the folder", "Espandi o comprimi la cartella"), + ("Export", "Esporta"), + ("Export Mesh...", "Esporta mesh..."), + ("Export Textures...", "Esporta texture..."), + ("Export mesh", "Esporta mesh"), + ("Export template", "Modello di esportazione"), + ("Export templates", "Modelli di esportazione"), + ("Export textures", "Esporta texture"), + ("Export the selected template (.json)", "Esporta il modello selezionato (.json)"), + ("Exported mesh to {path}", "Mesh esportata in {path}"), + ("Exported template \"{name}\" to {path}", "Modello \"{name}\" esportato in {path}"), + ("Exported {n} textures to {folder}", "{n} texture esportate in {folder}"), + ("F0 from specular level", "F0 da livello speculare"), + ("Fabric weave", "Trama tessuto"), + ("Field of view (deg)", "Campo visivo (gradi)"), + ("File", "File"), + ("File name without extension; variables insert names", "Nome file senza estensione; le variabili inseriscono i nomi"), + ("File type", "Tipo di file"), + ("Fill", "Riempimento"), + ("Fill the closed path (lasso)", "Riempi il tracciato chiuso (lazo)"), + ("Fill the path (close it first)", "Riempi il tracciato (prima chiudilo)"), + ("Filter", "Filtro"), + ("Filter the remaining noise while keeping edges and texture detail", "Filtra il rumore residuo preservando i bordi e i dettagli della texture"), + ("Filters", "Filtri"), + ("Fine noise", "Rumore fine"), + ("Fingerprints", "Impronte digitali"), + ("Enter a finite number", "Inserisci un numero finito"), + ("Double-click or press Enter to edit", "Fai doppio clic o premi Invio per modificare"), + ("Fit the input range to the histogram", "Adatta l'intervallo di input all'istogramma"), + ("Flatten layer", "Appiattisci livello"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Inverte il canale verde dell'immagine, per mappe normali create con Y rivolto verso il basso", + ), + ("Flow", "Flusso"), + ("Flow and opacity", "Flusso e opacità"), + ("Flow jitter", "Variazione flusso"), + ("Focus distance", "Distanza di messa a fuoco"), + ("Folder", "Cartella"), + ("Folders", "Cartelle"), + ("Follow path", "Segui tracciato"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "Per l'intero progetto: come vengono lette le immagini di mappe normali usate come mappe mesh (riassegnale dopo una modifica) e il valore predefinito per l'esportazione", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libero e open source (MIT OR Apache-2.0), scritto in Rust."), + ("From template", "Da modello"), + ("From template / project", "Da modello / progetto"), + ("Full", "Piena"), + ("GPU error: {error}", "Errore GPU: {error}"), + ("Geometry mask", "Maschera geometria"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "Speculare GGX con visibilità Smith correlata all'altezza, diffusa Lambert, illuminazione basata su immagine split-sum con irradianza in armoniche sferiche e attenuazione all'orizzonte.", + ), + ("Gamma", "Gamma"), + ("General export parameters", "Parametri generali di esportazione"), + ("General properties", "Proprietà generali"), + ("Generator", "Generatore"), + ("Geometry and UVs only", "Solo geometria e UV"), + ("Glossiness", "Lucentezza"), + ("Glossiness from roughness", "Lucentezza da rugosità"), + ("Glow", "Bagliore"), + ("Gradient", "Sfumatura"), + ("Gradient Map", "Mappa sfumatura"), + ("Gravity", "Gravità"), + ("Gray", "Grigio"), + ("Gray + A", "Grigio + A"), + ("Gray 50%", "Grigio 50%"), + ("Grayscale", "Scala di grigi"), + ("Group layer(s)", "Raggruppa livello/i"), + ("Grunge", "Grunge"), + ("HDR environments", "Ambienti HDR"), + ("High Pass", "Passa-alto"), + ("HSL Perceptive", "HSL percettivo"), + ("Half", "Metà"), + ("Hammered", "Martellato"), + ("Hard light", "Luce intensa"), + ("Hardness", "Durezza"), + ("Height", "Altezza"), + ("Height offset", "Offset altezza"), + ("Height to normal strength", "Intensità altezza in normale"), + ("Help", "Aiuto"), + ("Hide UI", "Nascondi interfaccia"), + ("High", "Alto"), + ("High poly: {name}", "High poly: {name}"), + ("Highlights", "Luci"), + ("Histogram Range", "Intervallo istogramma"), + ("Histogram Scan", "Scansione istogramma"), + ("Histogram Shift", "Spostamento istogramma"), + ("History", "Cronologia"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "Tieni premuto S: trascina con il tasto sinistro per ruotare, con il destro per scalare e con il centrale per spostare lo stencil.", + ), + ("Hold V and click the mesh to set the clone source", "Tieni premuto V e fai clic sulla mesh per impostare la sorgente di clonazione"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "Tieni premuto V e fai clic sulla mesh per impostare la sorgente, poi dipingi altrove per copiarla.", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "Distanza percorsa dalla luce sotto la superficie, come frazione della dimensione della mesh (dove è dipinto il canale Peso scattering)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "Quanto le superfici trasmissive deviano la luce (dove è dipinto il canale Trasmissione): acqua 1,33, vetro 1,5, diamante 2,42", + ), + ("Hue shift (degrees)", "Spostamento tonalità (gradi)"), + ("ID", "ID"), + ("Image: {name}", "Immagine: {name}"), + ("Images", "Immagini"), + ("Import HDR...", "Importa HDR..."), + ("Import a template (.json)", "Importa un modello (.json)"), + ("Import an image (File > Import resources) to project it onto the mesh.", "Importa un'immagine (File > Importa risorse) per proiettarla sulla mesh."), + ("Import resources...", "Importa risorse..."), + ("Import MaterialX material...", "Importa materiale MaterialX..."), + ("MaterialX materials", "Materiali MaterialX"), + ("Import...", "Importa..."), + ("Imported template \"{name}\"", "Modello \"{name}\" importato"), + ("Imported {name}", "{name} importato"), + ("Index of refraction", "Indice di rifrazione"), + ("Input high", "Input alto"), + ("Input low", "Input basso"), + ("Input maps", "Mappe di input"), + ("Insert a variable", "Inserisci una variabile"), + ("Instance", "Istanza"), + ("Instantiate across texture sets", "Crea istanze nei set di texture"), + ("Intensity (texels at 2K)", "Intensità (texel a 2K)"), + ("Interface", "Interfaccia"), + ("Interface scale", "Scala interfaccia"), + ("Inverse Subtract", "Sottrai inverso"), + ("Inverse divide", "Dividi inverso"), + ("Invert", "Inverti"), + ("Invert mask", "Inverti maschera"), + ("Invert mask background", "Inverti sfondo maschera"), + ("Invert mask value", "Inverti valore maschera"), + ("Invert quick mask", "Inverti maschera rapida"), + ("Jitters", "Variazioni"), + ("Join the ArtCraft community on Discord", "Unisciti alla community di ArtCraft su Discord"), + ("Join the community (Discord)...", "Unisciti alla community (Discord)..."), + ("Key light (shadow-casting light, direct only)", "Luce principale (proietta ombre, solo diretta)"), + ("Keyboard", "Tastiera"), + ("Keyboard shortcuts", "Scorciatoie da tastiera"), + ("Light azimuth (degrees)", "Azimut della luce (gradi)"), + ("Light elevation (degrees)", "Elevazione della luce (gradi)"), + ("Light intensity", "Intensità della luce"), + ("LMB", "Tasto sinistro"), + ("Language", "Lingua"), + ("Layer mask", "Maschera di livello"), + ("Layer memory: {mb} MB", "Memoria livelli: {mb} MB"), + ("Layers", "Livelli"), + ("Lazy mouse", "Lazy mouse"), + ("Lazy mouse distance", "Distanza lazy mouse"), + ("Leather grain", "Grana pelle"), + ( + "Lens size: how quickly things blur away from the focus distance", + "Dimensione dell'obiettivo: rapidità con cui gli oggetti si sfocano allontanandosi dalla distanza di messa a fuoco", + ), + ("Level", "Livello"), + ("Levels", "Livelli"), + ("Lifetime (steps)", "Durata (passi)"), + ("Light / direction", "Luce / direzione"), + ("Lighten (Max)", "Schiarisci (Max)"), + ("Lightness", "Luminosità"), + ("Linear", "Lineare"), + ("Linear burn", "Brucia lineare"), + ("Linear dodge (Add)", "Scherma lineare (Aggiungi)"), + ("Linear light", "Luce lineare"), + ("List of exports", "Elenco esportazioni"), + ("Load UI Layout", "Carica layout interfaccia"), + ("Loaded UI layout {path}", "Layout interfaccia caricato: {path}"), + ("Log", "Log"), + ("Low", "Basso"), + ("Luminosity", "Luminosità"), + ("MMB drag / Alt + MMB", "Trascina (tasto centrale) / Alt + tasto centrale"), + ("Made by the ArtCraft team and community.", "Realizzato dal team e dalla community di ArtCraft."), + ("Magenta / green", "Magenta / verde"), + ("Main shader", "Shader principale"), + ("Marble veins", "Venature marmo"), + ("Mask", "Maschera"), + ("Mask Editor: Edge wear", "Editor maschera: Usura bordi"), + ("Mask value (gray)", "Valore maschera (grigio)"), + ("Mask with height", "Maschera con altezza"), + ("MatFinish Grind", "MatFinish Molato"), + ("MatFinish Hammered", "MatFinish Martellato"), + ("MatFinish Raw", "MatFinish Grezzo"), + ("MatFinish Sanded", "MatFinish Carteggiato"), + ("Material", "Materiale"), + ("Material ball", "Sfera materiale"), + ("Material finish", "Finitura materiale"), + ("Materials", "Materiali"), + ("Maximum", "Massimo"), + ("Mesh fill", "Riempimento mesh"), + ("Mesh map: {map}", "Mappa mesh: {map}"), + ("Mesh maps", "Mappe mesh"), + ("Mesh maps baked", "Bake delle mappe mesh completato"), + ("Meshes", "Mesh"), + ("Metallic", "Metallico"), + ("Midtones", "Mezzitoni"), + ("Minimum", "Minimo"), + ("Minimum size (%)", "Dimensione minima (%)"), + ("Missing (bake to create)", "Mancante (esegui il bake per crearla)"), + ("Mixed AO", "AO miscelata"), + ("Mode", "Modalità"), + ("More in Assets > Alphas: click one, or drag it here", "Altri in Risorse > Alpha: fai clic su uno o trascinalo qui"), + ("Mosaic", "Mosaico"), + ("Move down", "Sposta giù"), + ("Move up", "Sposta su"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "Sposta la superficie in base al canale altezza su una copia più fine della mesh, con l'intensità da altezza a normale (solo nel viewport: la pittura segue la superficie di base)", + ), + ("Multiply", "Moltiplica"), + ("My smart materials", "I miei materiali intelligenti"), + ("Name", "Nome"), + ("New project", "Nuovo progetto"), + ("New project...", "Nuovo progetto..."), + ("New template", "Nuovo modello"), + ("No GPU renderer available", "Nessun renderer GPU disponibile"), + ("No font on this system can show this language", "Nessun font di questo sistema può visualizzare questa lingua"), + ( + "No outputs yet: add one above, then drag input maps onto its channels.", + "Ancora nessun output: aggiungine uno sopra, poi trascina le mappe di input sui suoi canali.", + ), + ("No padding (passthrough)", "Nessun padding (passthrough)"), + ("Noise amount", "Quantità rumore"), + ("Noise scale", "Scala rumore"), + ("None", "Nessuno"), + ("Normal", "Normale"), + ("Normal DirectX", "Normale DirectX"), + ("Normal Invert", "Inverti normale"), + ("Normal OpenGL", "Normale OpenGL"), + ("Normal from height", "Normale da altezza"), + ("Normal map combine", "Combina mappa normali"), + ("Normal map detail", "Dettaglio mappa normali"), + ("Color space", "Spazio colore"), + ("Normal map format", "Formato mappa normali"), + ("Normal map inverse detail", "Dettaglio inverso mappa normali"), + ("Normal: painting uses the flat normal", "Normale: la pittura usa la normale piatta"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memoria GPU insufficiente per mostrare per intero {count} set di texture ({names}): riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", + ), + ("Not exported: no source in this texture set", "Non esportato: nessuna sorgente in questo set di texture"), + ("Not saved: {error}", "Non salvato: {error}"), + ("Off", "Disattivato"), + ("Offset", "Scostamento"), + ("Offset right", "Offset a destra"), + ("Offset up", "Offset in alto"), + ("Offset {axis}", "Scostamento {axis}"), + ( + "Offsets the textures by the height channel, at the height to normal strength", + "Sposta le texture in base al canale altezza, con l'intensità altezza in normale", + ), + ("On", "Attivato"), + ("Opacity", "Opacità"), + ("Open sample project...", "Apri progetto di esempio..."), + ("Open...", "Apri..."), + ("Opened {name}", "{name} aperto"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "I canali opzionali aggiungono un rivestimento trasparente (Peso rivestimento, Rugosità rivestimento, Normale rivestimento), sheen (Peso sheen, colore, rugosità), anisotropia (Livello anisotropia, angolo), subsurface scattering (Peso scattering) e trasmissione (Trasmissione).", + ), + ("Orbit", "Orbita"), + ("Orthographic", "Ortografica"), + ("Perspective", "Prospettica"), + ("Output directory", "Cartella di output"), + ("Output high", "Output alto"), + ("Output low", "Output basso"), + ("Output template", "Modello di output"), + ("Output templates", "Modelli di output"), + ("Overlay", "Sovrapponi"), + ("Overlay opacity", "Opacità sovrapposizione"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallico Rugosità (TextureCraft)"), + ("Pick color", "Preleva colore"), + ("PNG image", "Immagine PNG"), + ("Padding", "Padding"), + ("Paint", "Pittura"), + ("Paint chips", "Scaglie di vernice"), + ("Paint on the mesh to edit the layer content.", "Dipingi sulla mesh per modificare il contenuto del livello."), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "Dipingi sulla mesh per modificare questa maschera. Usa il valore maschera della scheda Materiale per il grigio.", + ), + ("Paint with the current tool", "Dipingi con lo strumento corrente"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "Pixel dei livelli dipinti {pixels} MB, canali composti {composites} MB, cache di composizione {cache} MB", + ), + ("Painting", "Pittura"), + ("Pan", "Panoramica"), + ("Parallax occlusion (height channel)", "Occlusione parallasse (canale altezza)"), + ( + "Partial mask values follow the layer's height: high parts show first", + "I valori parziali della maschera seguono l'altezza del livello: le parti alte appaiono per prime", + ), + ("Particle brush (slides down the surface)", "Pennello particellare (scivola giù lungo la superficie)"), + ("Particle brush: particles slide down the surface", "Pennello particellare: le particelle scivolano giù lungo la superficie"), + ("Particles", "Particelle"), + ("Passthrough", "Pass-through"), + ("Paste as instance", "Incolla come istanza"), + ("Paste effect", "Incolla effetto"), + ("Paste layer(s)", "Incolla livello/i"), + ("Path", "Tracciato"), + ("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracciato: clic aggiunge un punto, clic sulla curva ne inserisce uno, trascina lo sposta, Invio applica, Esc annulla", + ), + ("Pattern scale", "Scala motivo"), + ("Perlin noise", "Rumore Perlin"), + ("Pick focus in the viewport", "Seleziona il fuoco nella viewport"), + ("Pin light", "Luce puntiforme"), + ("Place on the surface", "Posiziona sulla superficie"), + ("Place path points on the mesh", "Posiziona i punti del tracciato sulla mesh"), + ("Planar projection", "Proiezione planare"), + ("Plane", "Piano"), + ("Polygon fill", "Riempimento poligono"), + ("Pores", "Pori"), + ("Position", "Posizione"), + ("Position gradient", "Sfumatura posizione"), + ("Position jitter", "Variazione posizione"), + ("Posterize", "Posterizza"), + ("Press a key...", "Premi un tasto..."), + ("Project", "Progetto"), + ("Project Configuration...", "Configurazione progetto..."), + ("Project opened", "Progetto aperto"), + ("Project template", "Modello di progetto"), + ("Projection", "Proiezione"), + ("Projects and meshes", "Progetti e mesh"), + ("Properties", "Proprietà"), + ("Quarter", "Un quarto"), + ("Quick mask", "Maschera rapida"), + ("Quit", "Esci"), + ("Radius (texels at 2K)", "Raggio (texel a 2K)"), + ("RENDERING", "RENDERING"), + ("Range", "Intervallo"), + ("Rebind any menu item, tool or command", "Riassegna qualsiasi voce di menu, strumento o comando"), + ("Recent projects", "Progetti recenti"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "Registra la pila fino a questo livello. Gli effetti di riempimento nelle maschere (e i livelli di riempimento) soprastanti possono leggerla come sorgente.", + ), + ("Redo", "Ripeti"), + ("Reimport mesh", "Reimporta mesh"), + ("Remove", "Rimuovi"), + ("Remove channel", "Rimuovi canale"), + ("Remove effect", "Rimuovi effetto"), + ("Remove last", "Rimuovi ultimo"), + ("Remove layer", "Rimuovi livello"), + ("Remove layer(s)", "Rimuovi livello/i"), + ("Remove mask", "Rimuovi maschera"), + ("Remove point", "Rimuovi punto"), + ("Remove resource", "Rimuovi risorsa"), + ("Remove the shortcut", "Rimuovi la scorciatoia"), + ("Remove this output", "Rimuovi questo output"), + ("Remove unused resources...", "Rimuovi risorse inutilizzate..."), + ("Rename the selected template", "Rinomina il modello selezionato"), + ("Render on the CPU", "Renderizza sulla CPU"), + ("Rendering", "Rendering"), + ("Rendering (path traced)", "Rendering (path tracing)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "Rendering su CPU: {n} / {max} campioni, {s} s"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "Rendering su GPU: {n} / {max} campioni, {s} s"), + ("Rendering, path traced", "Rendering, path tracing"), + ("Replace", "Sostituisci"), + ("Replace Color", "Sostituisci colore"), + ("Replacement color", "Colore sostitutivo"), + ("Report a bug...", "Segnala un bug..."), + ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), + ("Reset", "Reimposta"), + ("Reset UI", "Ripristina interfaccia"), + ("Reset all", "Ripristina tutto"), + ("Reset to defaults", "Ripristina i valori predefiniti"), + ("Reset to {shortcut}", "Ripristina {shortcut}"), + ("Resizing", "Ridimensionamento"), + ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), + ("Return to this step", "Torna a questo passaggio"), + ("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"), + ("Rotation", "Rotazione"), + ("Rotation (degrees)", "Rotazione (gradi)"), + ("Roughness", "Rugosità"), + ("Roughness from glossiness", "Rugosità da lucentezza"), + ("Round", "Rotondo"), + ("Rounded cube", "Cubo arrotondato"), + ("Samples", "Campioni"), + ("Saturation", "Saturazione"), + ("Save", "Salva"), + ("Save UI Layout", "Salva layout interfaccia"), + ("Save a copy...", "Salva una copia..."), + ("Save as...", "Salva con nome..."), + ("Save current layout...", "Salva layout corrente..."), + ("Save render...", "Salva render..."), + ("Save view as camera", "Salva vista come camera"), + ("Saved UI layout {path}", "Layout interfaccia salvato: {path}"), + ("Saved {path}", "Salvato: {path}"), + ("Saving UI layouts to files is available in the desktop app", "Il salvataggio dei layout dell'interfaccia su file è disponibile nell'app desktop"), + ("Scale", "Scala"), + ("Scale / tiling", "Scala / ripetizione"), + ("Scatter color", "Colore scattering"), + ("Scatter radius", "Raggio scattering"), + ("Scattering weight", "Peso scattering"), + ("Scratches", "Graffi"), + ("Screen", "Scolora"), + ("Screenshot of the viewport", "Screenshot della viewport"), + ("Search", "Cerca"), + ("Search commands or keys", "Cerca comandi o tasti"), + ("Seed", "Seme"), + ("Select a layer", "Seleziona un livello"), + ("Select an output template", "Seleziona un modello di output"), + ("Select source", "Seleziona sorgente"), + ("Select the mask (Alt+click: show it in the viewport)", "Seleziona la maschera (Alt+clic: mostrala nella viewport)"), + ("Select...", "Seleziona..."), + ("Settings", "Impostazioni"), + ("Settings...", "Impostazioni..."), + ("Shader Settings", "Impostazioni shader"), + ("Shader instance", "Istanza shader"), + ("Shadows", "Ombre"), + ("Sharpen", "Nitidezza"), + ("Sheen color", "Colore sheen"), + ("Sheen color × weight", "Colore sheen × peso"), + ("Sheen roughness", "Rugosità sheen"), + ("Sheen weight", "Peso sheen"), + ("Shift + wheel", "Maiusc + rotella"), + ("Shortcuts list...", "Elenco scorciatoie..."), + ("Show on all parts", "Mostra su tutte le parti"), + ("Show UV wireframe in the 2D view", "Mostra il wireframe UV nella vista 2D"), + ("Show entire mesh", "Mostra intera mesh"), + ("Show log...", "Mostra log..."), + ("Show or hide the layer", "Mostra o nascondi il livello"), + ("Show or hide the texture set", "Mostra o nascondi il set di texture"), + ("Show wireframe in the 3D view", "Mostra il wireframe nella vista 3D"), + ("Signed addition (AddSub)", "Addizione con segno (AddSub)"), + ("Size", "Dimensione"), + ("Size in screen space", "Dimensione nello spazio schermo"), + ("Size jitter", "Variazione dimensione"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "Dimensione delle texture mostrate nella viewport: valori più bassi usano meno memoria GPU con set di texture grandi. Pittura ed esportazione mantengono la risoluzione piena.", + ), + ("Slope Blur", "Sfocatura pendenza"), + ("Slope scale", "Scala pendenza"), + ("Smart masks", "Maschere intelligenti"), + ("Smart material saved to {path}", "Materiale intelligente salvato in {path}"), + ("Smart materials", "Materiali intelligenti"), + ("Smudge", "Sfumino"), + ("Soft light", "Luce soffusa"), + ("Softness", "Morbidezza"), + ("Source", "Sorgente"), + ("Source U {u} V {v}", "Sorgente U {u} V {v}"), + ("Spacing", "Spaziatura"), + ("Specular", "Speculare"), + ("Specular level", "Livello speculare"), + ("Sphere", "Sfera"), + ("Spherical projection", "Proiezione sferica"), + ("Spray", "Spray"), + ("Square", "Quadrato"), + ("Stamp depth", "Profondità impronta"), + ("Star", "Stella"), + ("Starting render...", "Avvio del render..."), + ("Stencil", "Stencil"), + ("Steps", "Passi"), + ("Streaks", "Striature"), + ("Strength", "Intensità"), + ("Stripes", "Strisce"), + ("Stroke opacity", "Opacità tratto"), + ("Subsampling 2x2", "Sottocampionamento 2x2"), + ("Subsampling 4x4", "Sottocampionamento 4x4"), + ("Subsampling 8x8", "Sottocampionamento 8x8"), + ("Subsurface scattering", "Subsurface scattering"), + ("Subtract", "Sottrai"), + ("Tangent | Wrap", "Tangente | Avvolgi"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anti-aliasing temporale (affina la vista 3D quando è ferma)"), + ("Texture Sets", "Set di texture"), + ("Texture Set Settings", "Impostazioni set di texture"), + ("Texture resolution", "Risoluzione texture"), + ("Texture set channels", "Canali del set di texture"), + ("Texture sets", "Set di texture"), + ("TextureCraft had to close:", "TextureCraft ha dovuto chiudersi:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metallico Rugosità"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - Speculare Lucentezza"), + ("TextureCraft project", "Progetto TextureCraft"), + ("TextureCraft project or mesh", "Progetto o mesh TextureCraft"), + ("Textures", "Texture"), + ("Textures embedded; for game engines and most viewers", "Texture incorporate; per motori di gioco e la maggior parte dei visualizzatori"), + ("Textures packaged; for USD tools and AR Quick Look", "Texture incluse nel pacchetto; per strumenti USD e AR Quick Look"), + ("The GPU couldn't render this scene: {error}", "La GPU non è riuscita a eseguire il rendering di questa scena: {error}"), + ("The bake worker stopped", "Il processo di bake si è interrotto"), + ("The eraser removes paint from the enabled channels.", "La gomma rimuove la pittura dai canali attivi."), + ("The first stroke sets the offset from the source.", "Il primo tratto imposta l'offset dalla sorgente."), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "L'alpha dell'immagine ritaglia la forma della decal; le facce rivolte altrove e le superfici oltre la sua profondità restano libere.", + ), + ("The next click in the 3D view moves the decal there", "Il prossimo clic nella vista 3D sposta lì la decal"), + ("The resize worker stopped", "Il processo di ridimensionamento si è interrotto"), + ("Thickness", "Spessore"), + ("Thin areas", "Aree sottili"), + ("Threshold", "Soglia"), + ("Tile", "Ripeti"), + ("Tiles", "Piastrelle"), + ("Tint", "Tinta"), + ("Toggle mask", "Attiva/disattiva maschera"), + ("Tolerance", "Tolleranza"), + ("Tone mapping", "Mappatura dei toni"), + ("Tools", "Strumenti"), + ("Torus", "Toro"), + ("Transmission", "Trasmissione"), + ("Tri-planar projection", "Proiezione triplanare"), + ("Triangle fill", "Riempimento triangolo"), + ("UDIM plane", "Piano UDIM"), + ("UDIM tiles painted by this texture set, each at the set's size", "Tile UDIM dipinti da questo set di texture, ciascuno alla dimensione del set"), + ("UI layout", "Layout interfaccia"), + ("UI layout: {error}", "Layout interfaccia: {error}"), + ("UI layouts", "Layout interfaccia"), + ("UI {ms} ms", "Interfaccia {ms} ms"), + ("USD binary, textures alongside", "USD binario, texture a parte"), + ("USD text, textures alongside", "USD testuale, texture a parte"), + ("USDZ with textures", "USDZ con texture"), + ("UV checker", "Scacchiera UV"), + ("UV island fill", "Riempimento isola UV"), + ("UV transformations", "Trasformazioni UV"), + ("UV projection", "Proiezione UV"), + ("UV tiles", "Tile UV"), + ("UV tiles (UDIM)", "Tile UV (UDIM)"), + ("Undo", "Annulla"), + ("Uniform value", "Valore uniforme"), + ("Use an equirectangular .hdr or .exr image as the environment", "Usa un'immagine equirettangolare .hdr o .exr come ambiente"), + ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa il canale di controllo o `texturecraft-cli render` per gli screenshot"), + ("Value", "Valore"), + ("Version {version}", "Versione {version}"), + ("Version: {version} ({gpu})", "Versione: {version} ({gpu})"), + ("View through this camera", "Guarda attraverso questa camera"), + ("Viewer settings", "Impostazioni visualizzatore"), + ("Viewport", "Viewport"), + ("Viewport and brush (fixed)", "Viewport e pennello (fissi)"), + ("Views", "Viste"), + ("Vivid light", "Luce vivida"), + ("Voronoi", "Voronoi"), + ("Warp", "Deformazione"), + ("Warp Directional", "Deformazione direzionale"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ con MTL, texture accanto"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "WebGPU non è disponibile in questo browser, quindi TextureCraft usa WebGL2: la modalità Rendering esegue il path tracing sulla CPU (più lento) e i set di texture grandi vengono mostrati a risoluzione ridotta. Le versioni recenti di Chrome, Edge e Safari supportano WebGPU.", + ), + ("Wheel / Alt + RMB drag", "Rotella / Alt + trascina (tasto destro)"), + ("White", "Bianco"), + ("Width", "Larghezza"), + ("Width (texels at 2K)", "Larghezza (texel a 2K)"), + ("Window", "Finestra"), + ("Wood grain", "Venatura legno"), + ("Works in texture space, like the blur: it does not cross UV seams.", "Opera nello spazio texture, come la sfocatura: non attraversa le cuciture UV."), + ("World Space Normal", "Normale spazio mondo"), + ("Yellow / blue", "Giallo / blu"), + ("Zoom", "Zoom"), + ("a missing layer", "un livello mancante"), + ("aniso", "aniso"), + ("aniso angle", "ang aniso"), + ("ao", "ao"), + ("coat", "riv"), + ("coat nrm", "riv nrm"), + ("coat rough", "riv rug"), + ("color", "colore"), + ("emiss", "emiss"), + ("glTF binary with textures", "glTF binario con texture"), + ("gloss", "lucent"), + ("height", "altezza"), + ("metal", "metal"), + ("min", "min"), + ("missing", "mancante"), + ("missing source", "sorgente mancante"), + ("no GPU", "nessuna GPU"), + ("none", "nessuna"), + ("nrm", "nrm"), + ("off", "disattivo"), + ("op", "op"), + ("rough", "rug"), + ("scatter", "scatter"), + ("sheen", "sheen"), + ("sheen color", "col sheen"), + ("sheen rough", "rug sheen"), + ("spec", "spec"), + ("specular", "speculare"), + ("transm", "trasm"), + ("{action} (undone)", "{action} (annullato)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file}: aggiungi sopra il livello selezionato (o trascinalo nella pila dei livelli o nella viewport)", + ), + ("{name} copy", "{name} copia"), + ("{n} bits", "{n} bit"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "{n} punti di controllo. Fai clic sulla mesh (o sulla vista 2D) per aggiungere punti e trascinali per regolarli; fai clic sul primo punto per chiudere il tracciato. Invio lo dipinge con il pennello (un tracciato chiuso e riempito riempie il suo interno), Esc annulla.", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} elementi condividono una scorciatoia; ha la precedenza il primo dell'elenco."), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (scala {scale}, seme {seed})"), + ("Template name", "Nome del modello"), + ("Save current project as template", "Salva il progetto corrente come modello"), + ("Distribution", "Distribuzione"), + ("Cosine", "Coseno"), + ("Uniform", "Uniforme"), + ("Normalization", "Normalizzazione"), + // Settings › Interface: brightness and accent color. + ("Brightness", "Luminosità"), + ("Dark", "Scuro"), + ("Medium dark", "Medio scuro"), + ("Medium light", "Medio chiaro"), + ("Light", "Chiaro"), + ("Accent color", "Colore di accento"), + ("Copper", "Rame"), + ("Coral", "Corallo"), + ("Blue", "Blu"), + ("Violet", "Viola"), + ("Green", "Verde"), + ("Amber", "Ambra"), + ("Pink", "Rosa"), + ("Minimize", "Riduci a icona"), + ("Maximize", "Ingrandisci"), + ("Restore", "Ripristina"), + ("Title bar", "Barra del titolo"), + ("System title bar (applies on restart)", "Barra del titolo di sistema (si applica al riavvio)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", + ), + ("Brushes", "Pennelli"), + ("Brush name", "Nome del pennello"), + ("Save current brush", "Salva il pennello attuale"), + ("Start window", "Finestra iniziale"), + ("Show at startup", "Mostra all'avvio"), + ("Continue with the sample project", "Continua con il progetto di esempio"), + ("No recent projects yet", "Ancora nessun progetto recente"), + ("Text", "Testo"), + ("Font", "Carattere"), + ("Style", "Stile"), + ("Use as brush alpha", "Usa come alpha del pennello"), + ("Place as decal", "Posiziona come decal"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clic: attiva o disattiva questo canale. Alt+clic: solo questo canale"), + ("Show all", "Mostra tutto"), + ("Hide all", "Nascondi tutto"), + ("Invert show/hide", "Inverti mostra/nascondi"), + ("Show or hide texture sets", "Mostra o nascondi i set di texture"), + ("Focus: show only the active texture set", "Focus: mostra solo il set di texture attivo"), + ("Unsaved changes", "Modifiche non salvate"), + ("Don't save", "Non salvare"), + ("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"), + ("Radius", "Raggio"), + ("Remove skew correction", "Rimuovi la correzione dell'inclinazione"), + ("Twill weave", "Tessuto a saia"), + ("Save the changes to {name} first?", "Salvare prima le modifiche a {name}?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "I tracciati restano modificabili: scegline uno per spostarne i punti o cambiarne pennello e materiale, e il sottolivello si ridipinge subito. Aggiungi tracciati con lo strumento Tracciato.", + ), + ("Import material...", "Importa materiale..."), + ("MaterialCraft material", "Materiale MaterialCraft"), + ("Cooked at {size} px", "Calcolato a {size} px"), + ("Preset", "Preset"), + ("Re-cook", "Ricalcola"), + ("Open in MaterialCraft", "Apri in MaterialCraft"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "Aperto in MaterialCraft: usa lì File > Invia a TextureCraft per riportare le modifiche", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "I parametri si modificano nell'app desktop, con MaterialCraft installato"), + ("Add High-Poly Meshes", "Aggiungi mesh ad alta risoluzione"), + ("All", "Tutti"), + ("Apply Diffusion", "Applica diffusione"), + ("Attenuation", "Attenuazione"), + ("Auto Tonemapping", "Mappatura tonale automatica"), + ("Average Normals", "Normali medie"), + ("BBox", "Riquadro di delimitazione"), + ("BSphere", "Sfera di delimitazione"), + ("Mesh Map Bakers", "Baker delle mappe mesh"), + ("Common Settings", "Impostazioni comuni"), + ("Mesh Map Settings", "Impostazioni mappe mesh"), + ("Check All", "Seleziona tutto"), + ("No Parameters", "Nessun parametro"), + ("Bake Selected Textures ({n})", "Bake texture selezionate ({n})"), + ("By Mesh Name", "Per nome della mesh"), + ("Cage", "Gabbia"), + ("Cage Scene", "Scena della gabbia"), + ("Cage Type", "Tipo di gabbia"), + ("Color Generator", "Generatore di colori"), + ("Color Source", "Origine del colore"), + ("Common Parameters", "Parametri comuni"), + ("Custom File", "File personalizzato"), + ("Details", "Dettagli"), + ("Dilation Width", "Ampiezza dilatazione"), + ("Distance-Based", "Basata sulla distanza"), + ("Edge Contrast", "Contrasto dei bordi"), + ("Edge Distance", "Distanza dei bordi"), + ("Edge Protection", "Protezione dei bordi"), + ("Enable Seams", "Abilita cuciture"), + ("File ID", "ID del file"), + ("Full Scene", "Intera scena"), + ("Generate from Mesh", "Genera dalla mesh"), + ("Generate from Normal Map", "Genera dalla mappa delle normali"), + ("Ground Plane", "Piano del terreno"), + ("Ground Plane Offset", "Scostamento del terreno"), + ("High Poly Mesh Suffix", "Suffisso mesh high poly"), + ("High Poly Scene", "Scena ad alta risoluzione"), + ("High-Poly Parameters", "Parametri ad alta risoluzione"), + ("Hue Shift", "Variazione di tonalità"), + ("Ignore Backface", "Ignora facce posteriori"), + ("Ignore Backface Suffix", "Suffisso per ignorare le facce posteriori"), + ("Include in Bake", "Includi nel bake"), + ("Load Cage", "Carica gabbia"), + ("Lock Output Size", "Blocca dimensioni di output"), + ("Low Poly Mesh Suffix", "Suffisso mesh low poly"), + ("Manual", "Manuale"), + ("Material Color", "Colore del materiale"), + ("Max Frontal Distance", "Distanza frontale max"), + ("Max Occluder Distance", "Distanza max occlusori"), + ("Max Rear Distance", "Distanza posteriore max"), + ("Mesh ID", "ID della mesh"), + ("Method", "Metodo"), + ("Min Occluder Distance", "Distanza minima dell'occlusore"), + ("Never", "Mai"), + ("No High-Poly Meshes", "Nessuna mesh ad alta risoluzione"), + ("Normalization Scale", "Scala di normalizzazione"), + ("Normalization Type", "Tipo di normalizzazione"), + ("Only Same Mesh Name", "Solo stesso nome mesh"), + ("Output Size", "Dimensione output"), + ("Match", "Corrispondenza"), + ("Skew Correction Method", "Metodo di Correzione della Distorsione"), + ("Mesh Normals Based", "Basato sulle Normali della Mesh"), + ("Face Normals Based", "Basato sulle Normali delle Facce"), + ("Reset Painted Cage", "Ripristina Gabbia Dipinta"), + ("Paint Cage", "Dipingi gabbia"), + ("Paint Skew Correction", "Dipingi correzione dell'inclinazione"), + ("Per Material", "Per materiale"), + ("Random", "Casuale"), + ("Relative to Bounding Box", "Relativo al riquadro di delimitazione"), + ("Relative to Low Mesh", "Relativo alla mesh a bassa risoluzione"), + ("Relative to Min/Max", "Relativo a minimo/massimo"), + ("Relative to Ray Distances", "Relativo alle distanze dei raggi"), + ("Remove Cage", "Rimuovi gabbia"), + ("Remove Skew Correction", "Rimuovi la correzione dell'inclinazione"), + ("Restore Defaults", "Ripristina valori predefiniti"), + ("Return to Painting Mode", "Torna alla modalità pittura"), + ("Sampling Radius", "Raggio di campionamento"), + ("Scaling Divisor", "Divisore di scala"), + ("Seams Intensity", "Intensità delle cuciture"), + ("Secondary Rays", "Raggi secondari"), + ("Self Intersection", "Autointersezione"), + ("Self Occlusion", "Auto-occlusione"), + ("Skew Correction", "Correzione dell'inclinazione"), + ("Smooth", "Uniforme"), + ("Spread Angle", "Angolo di diffusione"), + ("Submesh", "Sottomesh"), + ("Use Low Poly Mesh as High Poly Mesh", "Usa la mesh low poly come mesh high poly"), + ("Value Bounds Max", "Limite massimo"), + ("Value Bounds Min", "Limite minimo"), + ("Vertex Color", "Colore dei vertici"), + ("Select the layer content", "Seleziona il contenuto del livello"), + ("Paint layer", "Livello di pittura"), + ("Fill layer", "Livello di riempimento"), + ("1 effect", "1 effetto"), + ("{count} effects", "{count} effetti"), + ("Mask effects", "Effetti della maschera"), + ("Content effects", "Effetti del contenuto"), + ("Fold or unfold these effects", "Comprimi o espandi questi effetti"), + ("Remove resolution override", "Rimuovi risoluzione personalizzata"), + ("Texture set resolution", "Risoluzione del set di texture"), + ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Angle span", "Ampiezza angolo"), + ("Axis position", "Posizione asse"), + ("Count", "Numero"), + ("Display", "Visualizzazione"), + ("Hide while painting", "Nascondi durante la pittura"), + ("Manipulator size", "Dimensione manipolatore"), + ("Mirror symmetry", "Simmetria speculare"), + ("Radial settings", "Impostazioni radiali"), + ("Radial symmetry", "Simmetria radiale"), + ("Show axis", "Mostra asse"), + ("Show axis position manipulator", "Mostra manipolatore posizione asse"), + ("Show cursor", "Mostra cursore"), + ("Show intersection", "Mostra intersezione"), + ("Show plane", "Mostra piano"), + ("Symmetry", "Simmetria"), + ("Symmetry color display", "Colore di visualizzazione simmetria"), + ("Symmetry settings", "Impostazioni simmetria"), + ("Type", "Tipo"), + ("Advanced settings", "Impostazioni avanzate"), + ("Import baked maps", "Importa mappe bake"), + ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), + ("Add...", "Aggiungi..."), + ("Baked maps imported: {count}", "Mappe bake importate: {count}"), + ("Not imported: {files}", "Non importati: {files}"), + ("Baking Visualization", "Visualizzazione del baking"), + ("Show for Selected Texture Set Only", "Mostra solo per il set di texture selezionato"), + ("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"), + ("UV Seams", "Cuciture UV"), + ("Project Mesh (LP)", "Mesh di proiezione (LP)"), + ("Edges", "Bordi"), + ("Cavities", "Cavità"), + ("Edges and cavities", "Bordi e cavità"), + ("Raw curvature", "Curvatura grezza"), + ("Detail sizes", "Dimensioni del dettaglio"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Legge la mappa di curvatura così come è stata calcolata: cambiare la modalità o una dimensione attiva le dimensioni del dettaglio.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic riempie ciò che c'è sotto; un rettangolo trascinato riempie ciò che seleziona mentre si allarga", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenuto: riempi i poligoni il cui centro è nel rettangolo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modifica della maschera rapida: i riempimenti dipingono le aree in cui è consentito dipingere. Premi U per terminare.", + ), + ("Fill mode", "Modalità di riempimento"), + ("Fill only polygons the camera sees (3D view)", "Riempi solo i poligoni visti dalla camera (vista 3D)"), + ("Hit-test", "Test di selezione"), + ("How a rectangle selects polygons", "Come un rettangolo seleziona i poligoni"), + ("Intersection: fill polygons the rectangle touches", "Intersezione: riempi i poligoni toccati dal rettangolo"), + ("Rectangle fill", "Riempimento rettangolare"), + ("Select a paint layer or a layer's mask to fill", "Seleziona un livello di pittura o una maschera di livello da riempire"), + ("Selection mode", "Modalità di selezione"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangolo riempie singoli triangoli, Poligono quad e n-goni interi, Mesh la geometria connessa, Isola UV le isole UV", + ), + ("Visible polygons only", "Solo poligoni visibili"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello", + ), + ("The file dialog couldn't be shown: {error}", "Impossibile mostrare la finestra di dialogo dei file: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Il progetto è cambiato mentre la finestra di dialogo era aperta, quindi non è stato fatto nulla", + ), + ("Cores kept for the UI", "Core riservati all'interfaccia"), + ("Max RAM while saving", "RAM max durante il salvataggio"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Il salvataggio usa gli altri core e al massimo questa quota della RAM libera. Almeno un core lavora sempre.", + ), + ("Max project size on open", "Dimensione massima all’apertura"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", + ), + ("Filter by type", "Filtra per tipo"), + ("All libraries", "Tutte le librerie"), + ("Browse folders", "Sfoglia cartelle"), + ("Starter assets", "Risorse incluse"), + ("Your assets", "Le tue risorse"), + ("Reset query", "Reimposta query"), + ("Refresh", "Aggiorna"), + ("Saved searches", "Ricerche salvate"), + ("Save the current search", "Salva la ricerca attuale"), + ("Delete", "Elimina"), + ("Filter by path", "Filtra per percorso"), + ("Hide non-applicable folders", "Nascondi le cartelle non pertinenti"), + ("Thumbnail size", "Dimensione miniature"), + ("Small", "Piccolo"), + ("Medium", "Medio"), + ("Large", "Grande"), + ("List", "Elenco"), + ("Procedurals", "Procedurali"), +]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs new file mode 100644 index 00000000..bb4f5152 --- /dev/null +++ b/crates/ui-egui/src/i18n/ja.rs @@ -0,0 +1,1176 @@ +//! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} をベイク中 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} をベイク中 ({n}/{total})、テクスチャセット {set}/{sets}"), + ("Follow Newest Map", "最新のマップを追う"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "ベイクの表示中はペイントを一時停止しています。ベイクをキャンセルするか、終わるまでお待ちください。", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ベイク中に3Dビューが表示するもの:最後に完成したマップ、完成済みの好きなマップ、またはマテリアル。まだベイクされていないマップは中立値で表示されます。", + ), + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", + ), + ("0 turns autosave off. Copies go to {folder}", "0で自動保存をオフにします。コピーの保存先: {folder}"), + ("2D view only", "2Dビューのみ"), + ("32 bits (float)", "32ビット (浮動小数点)"), + ("3D mesh", "3Dメッシュ"), + ("3D meshes", "3Dメッシュ"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "3Dテクスチャペイント: レイヤー、マスク、スマートマテリアル、メッシュマップのベイク、エクスポート。", + ), + ("3D view only", "3Dビューのみ"), + ("3D/2D views", "3D/2Dビュー"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "フォルダーは子レイヤーをそのまま合成します (通過)。チャンネルごとの不透明度はレイヤー行で設定します。", + ), + ("ACES filmic", "ACES フィルミック"), + ("Ambient", "アンビエント"), + ("AO intensity", "AO強度"), + ("About TextureCraft", "TextureCraftについて"), + ("About TextureCraft...", "TextureCraftについて..."), + ( + "Add an anchor point to a layer below to use its stack as a mask.", + "下のレイヤーにアンカーポイントを追加すると、そのスタックをマスクとして使用できます。", + ), + ("Add anchor point", "アンカーポイントを追加"), + ("Add as decal (view center)", "デカールとして追加 (ビュー中央)"), + ("Add black mask", "黒マスクを追加"), + ("Add channel", "チャンネルを追加"), + ("Add color", "カラーを追加"), + ("Add compare mask", "比較マスクを追加"), + ("Add effect", "エフェクトを追加"), + ("Add fill", "塗りつぶしを追加"), + ("Add fill layer", "塗りつぶしレイヤーを追加"), + ("Add filter", "フィルターを追加"), + ("Add folder", "フォルダーを追加"), + ("Add generator", "ジェネレーターを追加"), + ("Add levels", "レベル補正を追加"), + ("Add mask", "マスクを追加"), + ("Add mask with color selection", "カラー選択でマスクを追加"), + ("Add output", "出力を追加"), + ("Add paint", "ペイントを追加"), + ("Add paint layer", "ペイントレイヤーを追加"), + ("Add smart material from the shelf", "シェルフからスマートマテリアルを追加"), + ("Add to the layer content", "レイヤーのコンテンツに追加"), + ("Add to the mask", "マスクに追加"), + ("Add white mask", "白マスクを追加"), + ("Adjustments", "色調補正"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "整列: 最初のストロークで決まったオフセットを維持します。V + クリックで新しいソースを設定します。", + ), + ("Alignment", "アライメント"), + ("Alignment and culling", "アライメントとカリング"), + ("All layers", "すべてのレイヤー"), + ("Alpha", "アルファ"), + ("Alphas", "アルファ"), + ("Also bound to {item} ({menu})", "{item} ({menu}) にも割り当て済み"), + ("Alt + LMB drag", "Alt + 左ドラッグ"), + ("Always", "常に"), + ("Ambient Occlusion", "アンビエントオクルージョン"), + ("Ambient occlusion", "アンビエントオクルージョン"), + ("Amount", "量"), + ("Anchor point", "アンカーポイント"), + ("Anchor: {name}", "アンカー: {name}"), + ("Anchor: {name} ({channel})", "アンカー: {name} ({channel})"), + ("Angle", "角度"), + ("Angle (degrees)", "角度 (度)"), + ("Angle fade from", "角度フェード開始"), + ("Angle fade to", "角度フェード終了"), + ("Angle jitter", "角度ジッター"), + ("Anisotropy angle", "異方性角度"), + ("Anisotropy level", "異方性レベル"), + ("Antialiasing", "アンチエイリアス"), + ("Aperture", "絞り"), + ("Apply", "適用"), + ("ArtCraft website...", "ArtCraft ウェブサイト..."), + ("Assets", "アセット"), + ("Auto", "自動"), + ("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"), + ("Autosave every", "自動保存の間隔"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "自動保存、スマートマテリアル、プリセット、テンプレート、UI レイアウトはデータフォルダーに保存されます。新しいフォルダーは再起動後に適用され、保存済みのファイルはそのまま残ります。", + ), + ("Axis", "軸"), + ("Back to painting", "ペイントに戻る"), + ("Backface culling", "背面カリング"), + ("Bake an ID map (F8) to pick colors from the mesh.", "メッシュから色を拾うには ID マップをベイクしてください (F8)。"), + ("Bake Mesh Maps", "メッシュマップのベイク"), + ("Bake mesh maps", "メッシュマップをベイク"), + ( + "Bake mesh maps (F8) for curvature, AO and thickness based generators.", + "曲率、AO、厚みに基づくジェネレーターには、メッシュマップのベイク (F8) が必要です。", + ), + ("Baked Lighting", "ライティングのベイク"), + ("Baking", "ベイク"), + ("Base color", "ベースカラー"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "ベースカラーはディフューズカラー、スペキュラーはF0カラー、グロッシネスは 1 - ラフネスです (これらのチャンネルはテクスチャセット設定で追加します)。", + ), + ("Base color, Metallic, Roughness and Specular level.", "ベースカラー、メタリック、ラフネス、スペキュラーレベル。"), + ("Based on each texture set's size", "各テクスチャセットのサイズに基づく"), + ("Basic settings", "基本設定"), + ("Bent Normals", "ベントノーマル"), + ("Bevel", "ベベル"), + ("Black", "黒"), + ("Blending", "ブレンド"), + ("Blending mode of the displayed channel", "表示中のチャンネルのブレンドモード"), + ("Blur", "ぼかし"), + ("Blur Directional", "方向ぼかし"), + ("Blur and sharpen", "ぼかしとシャープ"), + ("Bounces", "バウンス数"), + ("Bricks", "レンガ"), + ("Brush", "ブラシ"), + ("Brush size", "ブラシサイズ"), + ("Brush size down / up", "ブラシサイズ 縮小 / 拡大"), + ("Brushed lines", "ヘアライン"), + ("Built-in (read-only): duplicate it to edit", "組み込み (読み取り専用): 複製して編集"), + ("Built-in templates are read-only: duplicate one to edit it", "組み込みテンプレートは読み取り専用です: 複製して編集"), + ("Built-in: {mesh}", "組み込み: {mesh}"), + ("Cage: {name}", "ケージ: {name}"), + ("Camera", "カメラ"), + ("Colors", "カラー"), + ("Go to camera 1", "カメラ 1 に移動"), + ("Go to camera 2", "カメラ 2 に移動"), + ("Go to camera 3", "カメラ 3 に移動"), + ("Go to camera 4", "カメラ 4 に移動"), + ("Go to camera 5", "カメラ 5 に移動"), + ("Go to camera 6", "カメラ 6 に移動"), + ("Go to camera 7", "カメラ 7 に移動"), + ("Go to camera 8", "カメラ 8 に移動"), + ("Go to camera 9", "カメラ 9 に移動"), + ("Camera settings", "カメラ設定"), + ("Cancel", "キャンセル"), + ("Cancel the stroke", "ストロークをキャンセル"), + ("Cell size (texels at 2K)", "セルサイズ (2K時のテクセル)"), + ("Cells", "セル"), + ("Channel", "チャンネル"), + ("Channel source: uniform value, procedural, image or anchor", "チャンネルのソース: 均一値、プロシージャル、画像、アンカー"), + ("Channels", "チャンネル"), + ("Check for Updates...", "アップデートを確認..."), + ("Checker", "チェッカー"), + ("Clamp", "クランプ"), + ("Clear", "クリア"), + ("Clear mask", "マスクをクリア"), + ("Clear recent projects", "最近使ったプロジェクトをクリア"), + ( + "Click a mesh part to show or hide the selected layer on it.", + "メッシュのパーツをクリックすると、選択したレイヤーをそのパーツで表示または非表示にします。", + ), + ("Click the mesh to pick its material into the brush", "メッシュをクリックしてマテリアルをブラシに取得"), + ("Click the mesh to place the decal", "メッシュをクリックしてデカールを配置"), + ("Click, then press the new shortcut (Esc cancels)", "クリックして新しいショートカットを押す (Escでキャンセル)"), + ("Clone", "クローン"), + ("Close", "閉じる"), + ("Closed path", "閉じたパス"), + ("Cloud", "雲"), + ("Clouds", "雲"), + ("Coat normal", "コートノーマル"), + ("Coat roughness", "コートラフネス"), + ("Coat weight", "コートウェイト"), + ("Color", "カラー"), + ("Color Balance", "カラーバランス"), + ("Color burn", "焼き込みカラー"), + ("Color dodge", "覆い焼きカラー"), + ( + "Color of the light that travels under the surface (each channel goes as far as its value)", + "表面下を伝わる光の色 (各チャンネルは値に応じた距離まで届く)", + ), + ("Color picker", "カラーピッカー"), + ("Color selection", "カラー選択"), + ("Color to replace", "置き換える色"), + ("Colors near the first shift towards the second, keeping their shading.", "最初の色に近い色が、陰影を保ったまま2番目の色へ移ります。"), + ( + "Colors read as gray. Add a levels or blur effect above to shape the result.", + "カラーはグレーとして読み取られます。結果を調整するには、上にレベル補正またはぼかしエフェクトを追加します。", + ), + ("Combine with the layer's height", "レイヤーのハイトと合成"), + ("Compare mask", "比較マスク"), + ("Compositing", "合成中"), + ("Constant", "定数"), + ("Constants", "定数"), + ("Contrast", "コントラスト"), + ("Contrast/Luminosity", "コントラスト/輝度"), + ("Converted maps", "変換マップ"), + ("Copy RGB values", "RGB 値をコピー"), + ("Copy effect", "エフェクトをコピー"), + ("Copy from", "コピー元"), + ("Copy layer(s)", "レイヤーをコピー"), + ("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"), + ("Copy to all texture sets", "すべてのテクスチャセットにコピー"), + ("Copy what the texture set shows", "テクスチャセットの表示内容をコピー"), + ("Couldn't encode the render", "レンダリング結果をエンコードできませんでした"), + ("Couldn't export textures: {error}", "テクスチャをエクスポートできませんでした: {error}"), + ("Couldn't export the mesh: {error}", "メッシュをエクスポートできませんでした: {error}"), + ("Couldn't export the template: {error}", "テンプレートをエクスポートできませんでした: {error}"), + ("Couldn't import {name}: {error}", "{name} をインポートできませんでした: {error}"), + ("Couldn't open {name}: {error}", "{name} を開けませんでした: {error}"), + ("Couldn't read the render back from the GPU", "GPUからレンダリング結果を読み戻せませんでした"), + ("Couldn't save the render: {error}", "レンダリング結果を保存できませんでした: {error}"), + ("Couldn't save {name}: {error}", "{name} を保存できませんでした: {error}"), + ("Count per stamp", "スタンプあたりの数"), + ("Crate", "木箱"), + ("Create", "作成"), + ("Create smart material", "スマートマテリアルを作成"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "ビューでCtrl+右ドラッグでサイズと硬さ、Ctrl+左ドラッグでフローと角度を設定します。", + ), + ("Cube", "立方体"), + ("Current layer", "現在のレイヤー"), + ("Curvature", "曲率"), + ("Cut effect", "エフェクトを切り取り"), + ("Cut layer(s)", "レイヤーを切り取り"), + ("Cyan / red", "シアン / レッド"), + ("Cylinder", "円柱"), + ("Cylindrical projection", "円柱投影"), + ("Dark to light: the content's luminance picks a color along these stops.", "暗→明: コンテンツの輝度に応じて、これらのストップに沿った色が選ばれます。"), + ("Darken (Min)", "比較(暗) (Min)"), + ("Data folder", "データフォルダー"), + ("Decal", "デカール"), + ("Decal projection", "デカール投影"), + ("Default", "デフォルト"), + ("Default camera", "デフォルトカメラ"), + ("Delete the selected template", "選択中のテンプレートを削除"), + ("Delete this camera", "このカメラを削除"), + ("Deleted template \"{name}\"", "テンプレート「{name}」を削除しました"), + ("Denoise", "ノイズ除去"), + ("Depth", "奥行き"), + ("Depth of field", "被写界深度"), + ("Depth of field (viewport and Rendering mode)", "被写界深度 (ビューポートとレンダリングモード)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "ピントが合う面の視線方向の深度 (0: オービット中心)"), + ("Details saved to {file}", "詳細の保存先: {file}"), + ("Difference", "差の絶対値"), + ("Dilation + default background color", "ダイレーション + デフォルト背景色"), + ("Dilation + transparent", "ダイレーション + 透明"), + ("Dilation infinite", "ダイレーション (無限)"), + ("DirectX normal map", "DirectX ノーマルマップ"), + ("Dirt", "汚れ"), + ("Disable", "無効"), + ("Dismiss", "閉じる"), + ("Displacement (height channel)", "ディスプレイスメント(ハイトチャンネル)"), + ("Display Settings", "表示設定"), + ("Display material", "マテリアルを表示"), + ("Display next channel", "次のチャンネルを表示"), + ("Display next mesh map", "次のメッシュマップを表示"), + ("Display previous channel", "前のチャンネルを表示"), + ("Display previous mesh map", "前のメッシュマップを表示"), + ("Distance", "距離"), + ("Distort", "変形"), + ("Divide", "除算"), + ("Document resolution", "ドキュメント解像度"), + ("Documentation...", "ドキュメント..."), + ("Done on CPU: {n} / {max} samples, {s} s", "CPUで完了: {n} / {max} サンプル、{s} 秒"), + ("Done on GPU: {n} / {max} samples, {s} s", "GPUで完了: {n} / {max} サンプル、{s} 秒"), + ("Double-click to rename", "ダブルクリックで名前を変更"), + ("Download as", "ダウンロード形式"), + ("Downloaded {name}", "{name} をダウンロードしました"), + ("Drag onto an output channel", "出力チャンネルにドラッグ"), + ("Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "枠をドラッグでデカールを移動、角で拡大縮小、丸いハンドルで回転"), + ("Drags the layer stack's values along the stroke into the selected layer.", "レイヤースタックの値をストロークに沿って選択中のレイヤーへ引き伸ばします。"), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "テクスチャセット「{set}」の {name} を描画します。ソースへの編集はすべてのインスタンスに反映されます。", + ), + ("Drop an image from the Assets panel here to use it as this mesh map", "アセットパネルから画像をここにドロップすると、このメッシュマップとして使用します"), + ("Dry streaks", "かすれ"), + ("Duplicate effect", "エフェクトを複製"), + ("Duplicate layer(s)", "レイヤーを複製"), + ("Duplicate the selected template", "選択中のテンプレートを複製"), + ("Edge Detect", "エッジ検出"), + ("Edit", "編集"), + ("Edit keyboard shortcuts...", "キーボードショートカットを編集..."), + ("Edit quick mask", "クイックマスクを編集"), + ("Editing quick mask: paint where painting is allowed (U to finish)", "クイックマスク編集中: ペイントを許可する範囲を塗る (Uで終了)"), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "クイックマスク編集中: ストロークでペイントを許可する範囲を塗ります。Uキーで終了します。", + ), + ("Emissive", "エミッシブ"), + ("Enable or disable the effect", "エフェクトの有効/無効を切り替え"), + ("Enable quick mask", "クイックマスクを有効化"), + ("Environment blur", "環境のぼかし"), + ("Environment exposure (EV)", "環境の露出 (EV)"), + ("Environment map", "環境マップ"), + ("Environment opacity", "環境の不透明度"), + ("Environment rotation", "環境の回転"), + ("Environment settings", "環境の設定"), + ("Environment: {name}", "環境: {name}"), + ("Environments", "環境"), + ("Eraser", "消しゴム"), + ("Exclusion", "除外"), + ("Expand or collapse the folder", "フォルダーを展開/折りたたみ"), + ("Export", "エクスポート"), + ("Export Mesh...", "メッシュをエクスポート..."), + ("Export Textures...", "テクスチャをエクスポート..."), + ("Export mesh", "メッシュのエクスポート"), + ("Export template", "出力テンプレート"), + ("Export templates", "出力テンプレート"), + ("Export textures", "テクスチャのエクスポート"), + ("Export the selected template (.json)", "選択中のテンプレートをエクスポート (.json)"), + ("Exported mesh to {path}", "メッシュを {path} にエクスポートしました"), + ("Exported template \"{name}\" to {path}", "テンプレート「{name}」を {path} にエクスポートしました"), + ("Exported {n} textures to {folder}", "{n} 個のテクスチャを {folder} にエクスポートしました"), + ("F0 from specular level", "スペキュラーレベルからF0"), + ("Fabric weave", "布の織り目"), + ("Field of view (deg)", "視野角 (度)"), + ("File", "ファイル"), + ("File name without extension; variables insert names", "拡張子なしのファイル名。変数で名前を挿入"), + ("File type", "ファイル形式"), + ("Fill", "塗りつぶし"), + ("Fill the closed path (lasso)", "閉じたパスを塗りつぶし (なげなわ)"), + ("Fill the path (close it first)", "パスを塗りつぶし (先にパスを閉じる)"), + ("Filter", "フィルター"), + ("Filter the remaining noise while keeping edges and texture detail", "エッジとテクスチャのディテールを保ちながら残りのノイズを除去"), + ("Filters", "フィルター"), + ("Fine noise", "細かいノイズ"), + ("Fingerprints", "指紋"), + ("Enter a finite number", "有限の数値を入力してください"), + ("Double-click or press Enter to edit", "ダブルクリックまたは Enter キーで編集"), + ("Fit the input range to the histogram", "入力範囲をヒストグラムに合わせる"), + ("Flatten layer", "レイヤーを統合"), + ("Flips the image's green channel, for normal maps made with Y pointing down", "画像の緑チャンネルを反転します (Y が下向きで作られたノーマルマップ用)"), + ("Flow", "フロー"), + ("Flow and opacity", "フローと不透明度"), + ("Flow jitter", "フロージッター"), + ("Focus distance", "フォーカス距離"), + ("Folder", "フォルダー"), + ("Folders", "フォルダー"), + ("Follow path", "パスに沿う"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "プロジェクト全体: メッシュマップとして設定したノーマルマップ画像の読み取り方 (変更後は設定し直してください) と、書き出しの既定値", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "無料のオープンソース (MIT OR Apache-2.0)、Rustで開発。"), + ("From template", "テンプレートから"), + ("From template / project", "テンプレート / プロジェクトから"), + ("Full", "フル"), + ("GPU error: {error}", "GPU エラー: {error}"), + ("Geometry mask", "ジオメトリマスク"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "GGXスペキュラー (高さ相関Smithビジビリティ)、Lambertディフューズ、球面調和関数による放射照度とホライズンフェードを用いたスプリットサムのイメージベースドライティング。", + ), + ("Gamma", "ガンマ"), + ("General export parameters", "一般エクスポートパラメーター"), + ("General properties", "一般プロパティ"), + ("Generator", "ジェネレーター"), + ("Geometry and UVs only", "ジオメトリとUVのみ"), + ("Glossiness", "グロッシネス"), + ("Glossiness from roughness", "ラフネスからグロッシネス"), + ("Glow", "グロー"), + ("Gradient", "グラデーション"), + ("Gradient Map", "グラデーションマップ"), + ("Gravity", "重力"), + ("Gray", "グレー"), + ("Gray + A", "グレー + A"), + ("Gray 50%", "グレー 50%"), + ("Grayscale", "グレースケール"), + ("Group layer(s)", "レイヤーをグループ化"), + ("Grunge", "グランジ"), + ("HDR environments", "HDR環境"), + ("High Pass", "ハイパス"), + ("HSL Perceptive", "HSL (知覚)"), + ("Half", "1/2"), + ("Hammered", "槌目"), + ("Hard light", "ハードライト"), + ("Hardness", "硬さ"), + ("Height", "ハイト"), + ("Height offset", "ハイトオフセット"), + ("Height to normal strength", "ハイト→ノーマル強度"), + ("Help", "ヘルプ"), + ("Hide UI", "UIを非表示"), + ("High", "高"), + ("High poly: {name}", "ハイポリ: {name}"), + ("Highlights", "ハイライト"), + ("Histogram Range", "ヒストグラム範囲"), + ("Histogram Scan", "ヒストグラムスキャン"), + ("Histogram Shift", "ヒストグラムシフト"), + ("History", "履歴"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "Sを押したまま: 左ドラッグで回転、右ドラッグで拡大縮小、中ドラッグでステンシルを移動。", + ), + ("Hold V and click the mesh to set the clone source", "Vを押しながらメッシュをクリックしてクローンソースを設定"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "Vを押しながらメッシュをクリックしてソースを設定し、別の場所をペイントしてコピーします。", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "表面下を光が伝わる距離。メッシュサイズに対する割合 (スキャタリングウェイトチャンネルをペイントした箇所)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "透過する表面が光を屈折させる強さ (トランスミッションチャンネルをペイントした箇所): 水 1.33、ガラス 1.5、ダイヤモンド 2.42", + ), + ("Hue shift (degrees)", "色相シフト (度)"), + ("ID", "ID"), + ("Image: {name}", "画像: {name}"), + ("Images", "画像"), + ("Import HDR...", "HDRをインポート..."), + ("Import a template (.json)", "テンプレートをインポート (.json)"), + ( + "Import an image (File > Import resources) to project it onto the mesh.", + "画像をインポートすると (ファイル > リソースをインポート)、メッシュに投影できます。", + ), + ("Import resources...", "リソースをインポート..."), + ("Import MaterialX material...", "MaterialX マテリアルをインポート..."), + ("MaterialX materials", "MaterialX マテリアル"), + ("Import...", "インポート..."), + ("Imported template \"{name}\"", "テンプレート「{name}」をインポートしました"), + ("Imported {name}", "{name} をインポートしました"), + ("Index of refraction", "屈折率"), + ("Input high", "入力の上限"), + ("Input low", "入力の下限"), + ("Input maps", "入力マップ"), + ("Insert a variable", "変数を挿入"), + ("Instance", "インスタンス"), + ("Instantiate across texture sets", "テクスチャセット間でインスタンス化"), + ("Intensity (texels at 2K)", "強度 (2K時のテクセル)"), + ("Interface", "インターフェイス"), + ("Interface scale", "インターフェイスのスケール"), + ("Inverse Subtract", "逆減算"), + ("Inverse divide", "逆除算"), + ("Invert", "反転"), + ("Invert mask", "マスクを反転"), + ("Invert mask background", "マスクの背景を反転"), + ("Invert mask value", "マスク値を反転"), + ("Invert quick mask", "クイックマスクを反転"), + ("Jitters", "ジッター"), + ("Join the ArtCraft community on Discord", "DiscordでArtCraftコミュニティに参加"), + ("Join the community (Discord)...", "コミュニティに参加 (Discord)..."), + ("Key light (shadow-casting light, direct only)", "キーライト (影を落とすライト、直接光のみ)"), + ("Keyboard", "キーボード"), + ("Keyboard shortcuts", "キーボードショートカット"), + ("Light azimuth (degrees)", "ライトの方位角 (度)"), + ("Light elevation (degrees)", "ライトの仰角 (度)"), + ("Light intensity", "ライトの強度"), + ("LMB", "左ドラッグ"), + ("Language", "言語"), + ("Layer mask", "レイヤーマスク"), + ("Layer memory: {mb} MB", "レイヤーメモリ: {mb} MB"), + ("Layers", "レイヤー"), + ("Lazy mouse", "レイジーマウス"), + ("Lazy mouse distance", "レイジーマウスの距離"), + ("Leather grain", "革のシボ"), + ("Lens size: how quickly things blur away from the focus distance", "レンズサイズ: フォーカス距離から離れるにつれてぼける速さ"), + ("Level", "レベル"), + ("Levels", "レベル補正"), + ("Lifetime (steps)", "寿命 (ステップ)"), + ("Light / direction", "ライト / 方向"), + ("Lighten (Max)", "比較(明) (Max)"), + ("Lightness", "明度"), + ("Linear", "リニア"), + ("Linear burn", "焼き込み(リニア)"), + ("Linear dodge (Add)", "覆い焼き(リニア) - 加算"), + ("Linear light", "リニアライト"), + ("List of exports", "エクスポート一覧"), + ("Load UI Layout", "UIレイアウトを読み込み"), + ("Loaded UI layout {path}", "UIレイアウト {path} を読み込みました"), + ("Log", "ログ"), + ("Low", "低"), + ("Luminosity", "輝度"), + ("MMB drag / Alt + MMB", "中ドラッグ / Alt + 中ドラッグ"), + ("Made by the ArtCraft team and community.", "ArtCraftチームとコミュニティによって制作。"), + ("Magenta / green", "マゼンタ / グリーン"), + ("Main shader", "メインシェーダー"), + ("Marble veins", "大理石の筋"), + ("Mask", "マスク"), + ("Mask Editor: Edge wear", "マスクエディター: エッジの摩耗"), + ("Mask value (gray)", "マスク値 (グレー)"), + ("Mask with height", "ハイトでマスク"), + ("MatFinish Grind", "MatFinish 研削"), + ("MatFinish Hammered", "MatFinish 槌目"), + ("MatFinish Raw", "MatFinish 未加工"), + ("MatFinish Sanded", "MatFinish サンディング"), + ("Material", "マテリアル"), + ("Material ball", "マテリアルボール"), + ("Material finish", "マテリアル仕上げ"), + ("Materials", "マテリアル"), + ("Maximum", "最大"), + ("Mesh fill", "メッシュ塗りつぶし"), + ("Mesh map: {map}", "メッシュマップ: {map}"), + ("Mesh maps", "メッシュマップ"), + ("Mesh maps baked", "メッシュマップをベイクしました"), + ("Meshes", "メッシュ"), + ("Metallic", "メタリック"), + ("Midtones", "中間調"), + ("Minimum", "最小"), + ("Minimum size (%)", "最小サイズ (%)"), + ("Missing (bake to create)", "なし (ベイクで作成)"), + ("Mixed AO", "ミックスAO"), + ("Mode", "モード"), + ("More in Assets > Alphas: click one, or drag it here", "アセット > アルファ にさらにあります: クリックするか、ここにドラッグ"), + ("Mosaic", "モザイク"), + ("Move down", "下へ移動"), + ("Move up", "上へ移動"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "メッシュの細分化コピー上で、ハイトからノーマルへの強度でハイトチャンネルに沿って表面を動かします(ビューポートのみ:ペイントは元の表面に従います)", + ), + ("Multiply", "乗算"), + ("My smart materials", "マイ スマートマテリアル"), + ("Name", "名前"), + ("New project", "新規プロジェクト"), + ("New project...", "新規プロジェクト..."), + ("New template", "新規テンプレート"), + ("No GPU renderer available", "使用可能なGPUレンダラーがありません"), + ("No font on this system can show this language", "このシステムにはこの言語を表示できるフォントがありません"), + ( + "No outputs yet: add one above, then drag input maps onto its channels.", + "出力がまだありません: 上で追加し、入力マップをそのチャンネルにドラッグします。", + ), + ("No padding (passthrough)", "パディングなし (パススルー)"), + ("Noise amount", "ノイズ量"), + ("Noise scale", "ノイズスケール"), + ("None", "なし"), + ("Normal", "ノーマル"), + ("Normal DirectX", "ノーマル DirectX"), + ("Normal Invert", "ノーマル反転"), + ("Normal OpenGL", "ノーマル OpenGL"), + ("Normal from height", "ハイトからノーマル"), + ("Normal map combine", "ノーマルマップ合成"), + ("Normal map detail", "ノーマルマップ ディテール"), + ("Color space", "カラースペース"), + ("Normal map format", "ノーマルマップ形式"), + ("Normal map inverse detail", "ノーマルマップ 逆ディテール"), + ("Normal: painting uses the flat normal", "ノーマル: ペイントにはフラットな法線を使用"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU メモリが不足しているため、{count} 個のテクスチャセット({names})を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", + ), + ("Not exported: no source in this texture set", "エクスポートされません: このテクスチャセットにソースがありません"), + ("Not saved: {error}", "保存されていません: {error}"), + ("Off", "オフ"), + ("Offset", "オフセット"), + ("Offset right", "右オフセット"), + ("Offset up", "上オフセット"), + ("Offset {axis}", "オフセット {axis}"), + ( + "Offsets the textures by the height channel, at the height to normal strength", + "ハイトチャンネルに応じてテクスチャをオフセットします (強度はハイト→ノーマル強度)", + ), + ("On", "オン"), + ("Opacity", "不透明度"), + ("Open sample project...", "サンプルプロジェクトを開く..."), + ("Open...", "開く..."), + ("Opened {name}", "{name} を開きました"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "オプションのチャンネルで、クリアコート (コートウェイト、コートラフネス、コートノーマル)、シーン (シーンウェイト、カラー、ラフネス)、異方性 (異方性レベル、角度)、サブサーフェススキャタリング (スキャタリングウェイト)、トランスミッション (トランスミッション) を追加できます。", + ), + ("Orbit", "オービット"), + ("Orthographic", "平行投影"), + ("Perspective", "透視投影"), + ("Output directory", "出力先フォルダー"), + ("Output high", "出力の上限"), + ("Output low", "出力の下限"), + ("Output template", "出力テンプレート"), + ("Output templates", "出力テンプレート"), + ("Overlay", "オーバーレイ"), + ("Overlay opacity", "オーバーレイの不透明度"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - メタリック/ラフネス (TextureCraft)"), + ("Pick color", "色を拾う"), + ("PNG image", "PNG画像"), + ("Padding", "パディング"), + ("Paint", "ペイント"), + ("Paint chips", "塗装の剥がれ"), + ("Paint on the mesh to edit the layer content.", "メッシュにペイントしてレイヤーのコンテンツを編集します。"), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "メッシュにペイントしてこのマスクを編集します。グレーには「マテリアル」タブのマスク値を使用します。", + ), + ("Paint with the current tool", "現在のツールでペイント"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "ペイントしたレイヤーのピクセル {pixels} MB、合成済みチャンネル {composites} MB、合成キャッシュ {cache} MB", + ), + ("Painting", "ペイント"), + ("Pan", "パン"), + ("Parallax occlusion (height channel)", "視差オクルージョン (ハイトチャンネル)"), + ("Partial mask values follow the layer's height: high parts show first", "中間のマスク値はレイヤーのハイトに従い、高い部分から表示されます"), + ("Particle brush (slides down the surface)", "パーティクルブラシ (表面を滑り落ちる)"), + ("Particle brush: particles slide down the surface", "パーティクルブラシ: パーティクルが表面を滑り落ちます"), + ("Particles", "パーティクル"), + ("Passthrough", "通過"), + ("Paste as instance", "インスタンスとして貼り付け"), + ("Paste effect", "エフェクトを貼り付け"), + ("Paste layer(s)", "レイヤーを貼り付け"), + ("Path", "パス"), + ("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "パス: クリックでポイントを追加、カーブをクリックで挿入、ドラッグで移動、Enterで適用、Escでキャンセル", + ), + ("Pattern scale", "パターンのスケール"), + ("Perlin noise", "パーリンノイズ"), + ("Pick focus in the viewport", "ビューポートでフォーカスを指定"), + ("Pin light", "ピンライト"), + ("Place on the surface", "表面に配置"), + ("Place path points on the mesh", "メッシュ上にパスのポイントを配置"), + ("Planar projection", "平面投影"), + ("Plane", "平面"), + ("Polygon fill", "ポリゴン塗りつぶし"), + ("Pores", "毛穴"), + ("Position", "位置"), + ("Position gradient", "位置グラデーション"), + ("Position jitter", "位置ジッター"), + ("Posterize", "ポスタリゼーション"), + ("Press a key...", "キーを押してください..."), + ("Project", "プロジェクト"), + ("Project Configuration...", "プロジェクト構成..."), + ("Project opened", "プロジェクトを開きました"), + ("Project template", "プロジェクトテンプレート"), + ("Projection", "投影"), + ("Projects and meshes", "プロジェクトとメッシュ"), + ("Properties", "プロパティ"), + ("Quarter", "1/4"), + ("Quick mask", "クイックマスク"), + ("Quit", "終了"), + ("Radius (texels at 2K)", "半径 (2K時のテクセル)"), + ("RENDERING", "レンダリング"), + ("Range", "範囲"), + ("Rebind any menu item, tool or command", "メニュー項目、ツール、コマンドのショートカットを再割り当て"), + ("Recent projects", "最近使ったプロジェクト"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "このレイヤーまでのスタックを記録します。上にあるマスク内の塗りつぶしエフェクト (および塗りつぶしレイヤー) は、これをソースとして読み取れます。", + ), + ("Redo", "やり直し"), + ("Reimport mesh", "メッシュを再インポート"), + ("Remove", "削除"), + ("Remove channel", "チャンネルを削除"), + ("Remove effect", "エフェクトを削除"), + ("Remove last", "最後を削除"), + ("Remove layer", "レイヤーを削除"), + ("Remove layer(s)", "レイヤーを削除"), + ("Remove mask", "マスクを削除"), + ("Remove point", "ポイントを削除"), + ("Remove resource", "リソースを削除"), + ("Remove the shortcut", "ショートカットを削除"), + ("Remove this output", "この出力を削除"), + ("Remove unused resources...", "未使用のリソースを削除..."), + ("Rename the selected template", "選択中のテンプレートの名前を変更"), + ("Render on the CPU", "CPUでレンダリング"), + ("Rendering", "レンダリング"), + ("Rendering (path traced)", "レンダリング (パストレース)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "CPUでレンダリング中: {n} / {max} サンプル、{s} 秒"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "GPUでレンダリング中: {n} / {max} サンプル、{s} 秒"), + ("Rendering, path traced", "パストレースによるレンダリング"), + ("Replace", "置換"), + ("Replace Color", "色の置き換え"), + ("Replacement color", "置き換え後の色"), + ("Report a bug...", "バグを報告..."), + ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), + ("Reset", "リセット"), + ("Reset UI", "UIをリセット"), + ("Reset all", "すべてリセット"), + ("Reset to defaults", "デフォルトに戻す"), + ("Reset to {shortcut}", "{shortcut} にリセット"), + ("Resizing", "サイズ変更中"), + ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), + ("Return to this step", "このステップに戻る"), + ("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"), + ("Rotation", "回転"), + ("Rotation (degrees)", "回転 (度)"), + ("Roughness", "ラフネス"), + ("Roughness from glossiness", "グロッシネスからラフネス"), + ("Round", "円形"), + ("Rounded cube", "角丸立方体"), + ("Samples", "サンプル数"), + ("Saturation", "彩度"), + ("Save", "保存"), + ("Save UI Layout", "UIレイアウトを保存"), + ("Save a copy...", "コピーを保存..."), + ("Save as...", "名前を付けて保存..."), + ("Save current layout...", "現在のレイアウトを保存..."), + ("Save render...", "レンダリング結果を保存..."), + ("Save view as camera", "ビューをカメラとして保存"), + ("Saved UI layout {path}", "UIレイアウト {path} を保存しました"), + ("Saved {path}", "{path} を保存しました"), + ("Saving UI layouts to files is available in the desktop app", "UIレイアウトのファイル保存はデスクトップアプリで利用できます"), + ("Scale", "スケール"), + ("Scale / tiling", "スケール / タイリング"), + ("Scatter color", "スキャタリングカラー"), + ("Scatter radius", "スキャタリング半径"), + ("Scattering weight", "スキャタリングウェイト"), + ("Scratches", "引っかき傷"), + ("Screen", "スクリーン"), + ("Screenshot of the viewport", "ビューポートのスクリーンショット"), + ("Search", "検索"), + ("Search commands or keys", "コマンドまたはキーを検索"), + ("Seed", "シード"), + ("Select a layer", "レイヤーを選択"), + ("Select an output template", "出力テンプレートを選択"), + ("Select source", "ソースを選択"), + ("Select the mask (Alt+click: show it in the viewport)", "マスクを選択 (Alt+クリック: ビューポートに表示)"), + ("Select...", "選択..."), + ("Settings", "設定"), + ("Settings...", "設定..."), + ("Shader Settings", "シェーダー設定"), + ("Shader instance", "シェーダーインスタンス"), + ("Shadows", "シャドウ"), + ("Sharpen", "シャープ"), + ("Sheen color", "シーンカラー"), + ("Sheen color × weight", "シーンカラー × ウェイト"), + ("Sheen roughness", "シーンラフネス"), + ("Sheen weight", "シーンウェイト"), + ("Shift + wheel", "Shift + ホイール"), + ("Shortcuts list...", "ショートカット一覧..."), + ("Show on all parts", "すべてのパーツに表示"), + ("Show UV wireframe in the 2D view", "2DビューにUVワイヤーフレームを表示"), + ("Show entire mesh", "メッシュ全体を表示"), + ("Show log...", "ログを表示..."), + ("Show or hide the layer", "レイヤーの表示/非表示"), + ("Show or hide the texture set", "テクスチャセットの表示/非表示"), + ("Show wireframe in the 3D view", "3Dビューにワイヤーフレームを表示"), + ("Signed addition (AddSub)", "符号付き加算 (AddSub)"), + ("Size", "サイズ"), + ("Size in screen space", "スクリーン空間でのサイズ"), + ("Size jitter", "サイズジッター"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "ビューポートに表示するテクスチャのサイズ。低くすると大きなテクスチャセットでも GPU メモリの使用量が減ります。ペイントと書き出しはフル解像度のままです。", + ), + ("Slope Blur", "スロープぼかし"), + ("Slope scale", "スロープスケール"), + ("Smart masks", "スマートマスク"), + ("Smart material saved to {path}", "スマートマテリアルを {path} に保存しました"), + ("Smart materials", "スマートマテリアル"), + ("Smudge", "スマッジ"), + ("Soft light", "ソフトライト"), + ("Softness", "柔らかさ"), + ("Source", "ソース"), + ("Source U {u} V {v}", "ソース U {u} V {v}"), + ("Spacing", "間隔"), + ("Specular", "スペキュラー"), + ("Specular level", "スペキュラーレベル"), + ("Sphere", "球"), + ("Spherical projection", "球面投影"), + ("Spray", "スプレー"), + ("Square", "正方形"), + ("Stamp depth", "スタンプの深度"), + ("Star", "星"), + ("Starting render...", "レンダリングを開始しています..."), + ("Stencil", "ステンシル"), + ("Steps", "ステップ数"), + ("Streaks", "筋"), + ("Strength", "強度"), + ("Stripes", "ストライプ"), + ("Stroke opacity", "ストロークの不透明度"), + ("Subsampling 2x2", "サブサンプリング 2x2"), + ("Subsampling 4x4", "サブサンプリング 4x4"), + ("Subsampling 8x8", "サブサンプリング 8x8"), + ("Subsurface scattering", "サブサーフェススキャタリング"), + ("Subtract", "減算"), + ("Tangent | Wrap", "タンジェント | ラップ"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "テンポラルアンチエイリアス (静止中に3Dビューを精細化)"), + ("Texture Sets", "テクスチャセット"), + ("Texture Set Settings", "テクスチャセット設定"), + ("Texture resolution", "テクスチャ解像度"), + ("Texture set channels", "テクスチャセットのチャンネル"), + ("Texture sets", "テクスチャセット"), + ("TextureCraft had to close:", "TextureCraft を終了する必要がありました:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - メタリック/ラフネス"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - スペキュラー/グロッシネス"), + ("TextureCraft project", "TextureCraftプロジェクト"), + ("TextureCraft project or mesh", "TextureCraftプロジェクトまたはメッシュ"), + ("Textures", "テクスチャ"), + ("Textures embedded; for game engines and most viewers", "テクスチャ埋め込み。ゲームエンジンや多くのビューアー向け"), + ("Textures packaged; for USD tools and AR Quick Look", "テクスチャをパッケージ化。USDツールやAR Quick Look向け"), + ("The GPU couldn't render this scene: {error}", "GPUでこのシーンをレンダリングできませんでした: {error}"), + ("The bake worker stopped", "ベイク処理が停止しました"), + ("The eraser removes paint from the enabled channels.", "消しゴムは有効なチャンネルからペイントを消去します。"), + ("The first stroke sets the offset from the source.", "最初のストロークでソースからのオフセットが決まります。"), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "画像のアルファでデカールの形状を切り抜きます。裏向きの面と奥行きを超えた面には投影されません。", + ), + ("The next click in the 3D view moves the decal there", "3Dビューで次にクリックした位置にデカールを移動"), + ("The resize worker stopped", "サイズ変更の処理が停止しました"), + ("Thickness", "厚み"), + ("Thin areas", "薄い領域"), + ("Threshold", "しきい値"), + ("Tile", "タイル"), + ("Tiles", "タイル"), + ("Tint", "色合い"), + ("Toggle mask", "マスクの切り替え"), + ("Tolerance", "許容値"), + ("Tone mapping", "トーンマッピング"), + ("Tools", "ツール"), + ("Torus", "トーラス"), + ("Transmission", "トランスミッション"), + ("Tri-planar projection", "トライプラナー投影"), + ("Triangle fill", "三角形塗りつぶし"), + ("UDIM plane", "UDIM平面"), + ("UDIM tiles painted by this texture set, each at the set's size", "このテクスチャセットがペイントするUDIMタイル (各タイルはセットのサイズ)"), + ("UI layout", "UIレイアウト"), + ("UI layout: {error}", "UIレイアウト: {error}"), + ("UI layouts", "UIレイアウト"), + ("UI {ms} ms", "UI {ms} ms"), + ("USD binary, textures alongside", "USDバイナリ、テクスチャは別ファイル"), + ("USD text, textures alongside", "USDテキスト、テクスチャは別ファイル"), + ("USDZ with textures", "USDZ (テクスチャ付き)"), + ("UV checker", "UVチェッカー"), + ("UV island fill", "UVアイランド塗りつぶし"), + ("UV transformations", "UV変換"), + ("UV projection", "UV投影"), + ("UV tiles", "UVタイル"), + ("UV tiles (UDIM)", "UVタイル (UDIM)"), + ("Undo", "元に戻す"), + ("Uniform value", "均一値"), + ("Use an equirectangular .hdr or .exr image as the environment", "正距円筒図法の .hdr または .exr 画像を環境として使用"), + ( + "Use the control channel or `texturecraft-cli render` for screenshots", + "スクリーンショットにはコントロールチャンネルまたは `texturecraft-cli render` を使用", + ), + ("Value", "値"), + ("Version {version}", "バージョン {version}"), + ("Version: {version} ({gpu})", "バージョン: {version} ({gpu})"), + ("View through this camera", "このカメラから見る"), + ("Viewer settings", "ビューアー設定"), + ("Viewport", "ビューポート"), + ("Viewport and brush (fixed)", "ビューポートとブラシ (固定)"), + ("Views", "ビュー"), + ("Vivid light", "ビビッドライト"), + ("Voronoi", "ボロノイ"), + ("Warp", "ワープ"), + ("Warp Directional", "方向ワープ"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ(MTL付き)、テクスチャは別ファイル"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "このブラウザーでは WebGPU を利用できないため、TextureCraft は WebGL2 で動作しています。レンダリングモードのパストレーシングは CPU で行われ (低速)、大きなテクスチャセットは解像度を下げて表示されます。最新の Chrome、Edge、Safari は WebGPU に対応しています。", + ), + ("Wheel / Alt + RMB drag", "ホイール / Alt + 右ドラッグ"), + ("White", "白"), + ("Width", "幅"), + ("Width (texels at 2K)", "幅 (2K時のテクセル)"), + ("Window", "ウィンドウ"), + ("Wood grain", "木目"), + ("Works in texture space, like the blur: it does not cross UV seams.", "ぼかしと同様にテクスチャ空間で処理するため、UVシームをまたぎません。"), + ("World Space Normal", "ワールド空間ノーマル"), + ("Yellow / blue", "イエロー / ブルー"), + ("Zoom", "ズーム"), + ("a missing layer", "見つからないレイヤー"), + ("aniso", "異方性"), + ("aniso angle", "異方角"), + ("ao", "AO"), + ("coat", "コート"), + ("coat nrm", "コート法線"), + ("coat rough", "コートラフ"), + ("color", "カラー"), + ("emiss", "エミッシブ"), + ("glTF binary with textures", "glTFバイナリ (テクスチャ付き)"), + ("gloss", "グロス"), + ("height", "ハイト"), + ("metal", "メタル"), + ("min", "分"), + ("missing", "不明"), + ("missing source", "ソース不明"), + ("no GPU", "GPUなし"), + ("none", "なし"), + ("nrm", "法線"), + ("off", "オフ"), + ("op", "不透明"), + ("rough", "ラフ"), + ("scatter", "散乱"), + ("sheen", "シーン"), + ("sheen color", "シーン色"), + ("sheen rough", "シーンラフ"), + ("spec", "スペLv"), + ("specular", "スペキュラ"), + ("transm", "透過"), + ("{action} (undone)", "{action} (取り消し済み)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file}: 選択中のレイヤーの上に追加 (レイヤースタックやビューポートへのドラッグも可)", + ), + ("{name} copy", "{name} のコピー"), + ("{n} bits", "{n} ビット"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "コントロールポイント {n} 個。メッシュ (または 2D ビュー) をクリックしてポイントを追加し、ドラッグして調整します。最初のポイントをクリックするとパスが閉じます。Enter でブラシを使ってペイントし (閉じて塗りつぶすパスは内側を塗りつぶします)、Esc でキャンセルします。", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} 個の項目が同じショートカットを共有しています。一覧の最初の項目が優先されます。"), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (スケール {scale}、シード {seed})"), + ("Template name", "テンプレート名"), + ("Save current project as template", "現在のプロジェクトをテンプレートとして保存"), + ("Distribution", "分布"), + ("Cosine", "コサイン"), + ("Uniform", "均一"), + ("Normalization", "正規化"), + // Settings › Interface: brightness and accent color. + ("Brightness", "明るさ"), + ("Dark", "ダーク"), + ("Medium dark", "ミディアムダーク"), + ("Medium light", "ミディアムライト"), + ("Light", "ライト"), + ("Accent color", "アクセントカラー"), + ("Copper", "カッパー"), + ("Coral", "コーラル"), + ("Blue", "ブルー"), + ("Violet", "バイオレット"), + ("Green", "グリーン"), + ("Amber", "アンバー"), + ("Pink", "ピンク"), + ("Minimize", "最小化"), + ("Maximize", "最大化"), + ("Restore", "元のサイズに戻す"), + ("Title bar", "タイトルバー"), + ("System title bar (applies on restart)", "システムのタイトルバー (再起動後に適用)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", + ), + ("Brushes", "ブラシ一覧"), + ("Brush name", "ブラシ名"), + ("Save current brush", "現在のブラシを保存"), + ("Start window", "スタートウィンドウ"), + ("Show at startup", "起動時に表示"), + ("Continue with the sample project", "サンプルプロジェクトで続ける"), + ("No recent projects yet", "最近のプロジェクトはまだありません"), + ("Text", "テキスト"), + ("Font", "フォント"), + ("Style", "スタイル"), + ("Use as brush alpha", "ブラシのアルファとして使用"), + ("Place as decal", "デカールとして配置"), + ("Click: turn this channel on or off. Alt+click: this channel only", "クリック: このチャンネルのオン/オフ。Alt+クリック: このチャンネルのみ"), + ("Show all", "すべて表示"), + ("Hide all", "すべて非表示"), + ("Invert show/hide", "表示/非表示を反転"), + ("Show or hide texture sets", "テクスチャセットの表示/非表示"), + ("Focus: show only the active texture set", "フォーカス: アクティブなテクスチャセットのみ表示"), + ("Unsaved changes", "未保存の変更"), + ("Don't save", "保存しない"), + ("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"), + ("Radius", "半径"), + ("Remove skew correction", "スキュー補正を削除"), + ("Twill weave", "綾織り"), + ("Save the changes to {name} first?", "先に {name} の変更を保存しますか?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "パスは編集可能なままです。パスを選んで点を移動したりブラシやマテリアルを変えたりすると、サブレイヤーがすぐに描き直されます。パスはパスツールで追加します。", + ), + ("Import material...", "マテリアルを読み込む..."), + ("MaterialCraft material", "MaterialCraft マテリアル"), + ("Cooked at {size} px", "{size} px で計算済み"), + ("Preset", "プリセット"), + ("Re-cook", "再計算"), + ("Open in MaterialCraft", "MaterialCraft で開く"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "MaterialCraft で開きました。変更を戻すには、そちらで「ファイル > TextureCraft に送る」を使います", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "パラメーターは MaterialCraft をインストールしたデスクトップ版で変更できます"), + ("Add High-Poly Meshes", "ハイポリメッシュを追加"), + ("All", "すべて"), + ("Apply Diffusion", "拡散を適用"), + ("Attenuation", "減衰"), + ("Auto Tonemapping", "自動トーンマッピング"), + ("Average Normals", "法線を平均化"), + ("BBox", "バウンディングボックス"), + ("BSphere", "バウンディングスフィア"), + ("Mesh Map Bakers", "メッシュマップベイカー"), + ("Common Settings", "共通設定"), + ("Mesh Map Settings", "メッシュマップ設定"), + ("Check All", "すべてチェック"), + ("No Parameters", "パラメーターなし"), + ("Bake Selected Textures ({n})", "選択したテクスチャをベイク ({n})"), + ("By Mesh Name", "メッシュ名で"), + ("Cage", "ケージ"), + ("Cage Scene", "ケージシーン"), + ("Cage Type", "ケージの種類"), + ("Color Generator", "カラー生成"), + ("Color Source", "カラーソース"), + ("Common Parameters", "共通パラメーター"), + ("Custom File", "カスタムファイル"), + ("Details", "ディテール"), + ("Dilation Width", "ダイレーション幅"), + ("Distance-Based", "距離ベース"), + ("Edge Contrast", "エッジコントラスト"), + ("Edge Distance", "エッジ距離"), + ("Edge Protection", "エッジ保護"), + ("Enable Seams", "シームを有効化"), + ("File ID", "ファイルID"), + ("Full Scene", "シーン全体"), + ("Generate from Mesh", "メッシュから生成"), + ("Generate from Normal Map", "法線マップから生成"), + ("Ground Plane", "グラウンドプレーン"), + ("Ground Plane Offset", "グラウンドプレーンのオフセット"), + ("High Poly Mesh Suffix", "ハイポリメッシュの接尾辞"), + ("High Poly Scene", "ハイポリシーン"), + ("High-Poly Parameters", "ハイポリパラメーター"), + ("Hue Shift", "色相シフト"), + ("Ignore Backface", "裏面を無視"), + ("Ignore Backface Suffix", "裏面を無視するサフィックス"), + ("Include in Bake", "ベイク対象に含める"), + ("Load Cage", "ケージを読み込む"), + ("Lock Output Size", "出力サイズをロック"), + ("Low Poly Mesh Suffix", "ローポリメッシュの接尾辞"), + ("Manual", "手動"), + ("Material Color", "マテリアルカラー"), + ("Max Frontal Distance", "前方最大距離"), + ("Max Occluder Distance", "遮蔽物の最大距離"), + ("Max Rear Distance", "後方最大距離"), + ("Mesh ID", "メッシュID"), + ("Method", "方式"), + ("Min Occluder Distance", "最小遮蔽距離"), + ("Never", "しない"), + ("No High-Poly Meshes", "ハイポリメッシュなし"), + ("Normalization Scale", "正規化スケール"), + ("Normalization Type", "正規化の種類"), + ("Only Same Mesh Name", "同じメッシュ名のみ"), + ("Output Size", "出力サイズ"), + ("Match", "マッチング"), + ("Skew Correction Method", "スキュー補正方法"), + ("Mesh Normals Based", "メッシュ法線ベース"), + ("Face Normals Based", "面法線ベース"), + ("Reset Painted Cage", "ペイントしたケージをリセット"), + ("Paint Cage", "ケージをペイント"), + ("Paint Skew Correction", "スキュー補正をペイント"), + ("Per Material", "マテリアルごと"), + ("Random", "ランダム"), + ("Relative to Bounding Box", "バウンディングボックスに相対"), + ("Relative to Low Mesh", "ローポリメッシュに相対"), + ("Relative to Min/Max", "最小値・最大値に相対"), + ("Relative to Ray Distances", "レイ距離に相対"), + ("Remove Cage", "ケージを削除"), + ("Remove Skew Correction", "スキュー補正を削除"), + ("Restore Defaults", "既定値に戻す"), + ("Return to Painting Mode", "ペイントモードに戻る"), + ("Sampling Radius", "サンプリング半径"), + ("Scaling Divisor", "スケーリング除数"), + ("Seams Intensity", "シームの強度"), + ("Secondary Rays", "二次レイ"), + ("Self Intersection", "自己交差"), + ("Self Occlusion", "自己遮蔽"), + ("Skew Correction", "スキュー補正"), + ("Smooth", "スムーズ"), + ("Spread Angle", "拡散角度"), + ("Submesh", "サブメッシュ"), + ("Use Low Poly Mesh as High Poly Mesh", "ローポリメッシュをハイポリメッシュとして使用"), + ("Value Bounds Max", "値の上限"), + ("Value Bounds Min", "値の下限"), + ("Vertex Color", "頂点カラー"), + ("Select the layer content", "レイヤーの内容を選択"), + ("Paint layer", "ペイントレイヤー"), + ("Fill layer", "塗りつぶしレイヤー"), + ("1 effect", "エフェクト 1 件"), + ("{count} effects", "エフェクト {count} 件"), + ("Mask effects", "マスクのエフェクト"), + ("Content effects", "コンテンツのエフェクト"), + ("Fold or unfold these effects", "これらのエフェクトを折りたたむ/展開する"), + ("Remove resolution override", "解像度の上書きを解除"), + ("Texture set resolution", "テクスチャセットの解像度"), + ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Angle span", "角度範囲"), + ("Axis position", "軸の位置"), + ("Count", "数"), + ("Display", "表示"), + ("Hide while painting", "ペイント中は隠す"), + ("Manipulator size", "マニピュレーターのサイズ"), + ("Mirror symmetry", "ミラー対称"), + ("Radial settings", "放射の設定"), + ("Radial symmetry", "放射対称"), + ("Show axis", "軸を表示"), + ("Show axis position manipulator", "軸位置マニピュレーターを表示"), + ("Show cursor", "カーソルを表示"), + ("Show intersection", "交差部を表示"), + ("Show plane", "平面を表示"), + ("Symmetry", "対称"), + ("Symmetry color display", "対称の表示色"), + ("Symmetry settings", "対称の設定"), + ("Type", "種類"), + ("Advanced settings", "詳細設定"), + ("Import baked maps", "ベイク済みマップを読み込む"), + ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), + ("Add...", "追加..."), + ("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"), + ("Not imported: {files}", "読み込まれなかったファイル: {files}"), + ("Baking Visualization", "ベイクの可視化"), + ("Show for Selected Texture Set Only", "選択したテクスチャセットのみ表示"), + ("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"), + ("UV Seams", "UVシーム"), + ("Project Mesh (LP)", "投影メッシュ (LP)"), + ("Edges", "エッジ"), + ("Cavities", "くぼみ"), + ("Edges and cavities", "エッジとくぼみ"), + ("Raw curvature", "生の曲率"), + ("Detail sizes", "ディテールサイズ"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "曲率マップをベイクされたまま読み取ります。モードやサイズを変更するとディテールサイズが有効になります。", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "クリックでその下を塗りつぶし、ドラッグした矩形は広げるにつれて選択した範囲を塗りつぶします", + ), + ("Contained center: fill polygons whose center is in the rectangle", "中心を含む: 中心が矩形内にあるポリゴンを塗りつぶします"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "クイックマスク編集中: 塗りつぶしでペイントを許可する範囲を塗ります。Uキーで終了します。", + ), + ("Fill mode", "塗りつぶしモード"), + ("Fill only polygons the camera sees (3D view)", "カメラから見えるポリゴンだけを塗りつぶします (3Dビュー)"), + ("Hit-test", "ヒットテスト"), + ("How a rectangle selects polygons", "矩形がポリゴンを選択する方法"), + ("Intersection: fill polygons the rectangle touches", "交差: 矩形が触れるポリゴンを塗りつぶします"), + ("Rectangle fill", "矩形塗りつぶし"), + ("Select a paint layer or a layer's mask to fill", "塗りつぶすペイントレイヤーまたはレイヤーマスクを選択してください"), + ("Selection mode", "選択モード"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形は個々の三角形、ポリゴンは四角形やNゴン全体、メッシュはつながったジオメトリ、UVアイランドはUVアイランドを塗りつぶします", + ), + ("Visible polygons only", "表示されているポリゴンのみ"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください", + ), + ("The file dialog couldn't be shown: {error}", "ファイルダイアログを表示できませんでした: {error}"), + ("The project changed while the dialog was open, so nothing was done", "ダイアログを開いている間にプロジェクトが変更されたため、何も実行されませんでした"), + ("Cores kept for the UI", "UI用に確保するコア数"), + ("Max RAM while saving", "保存時のRAM上限"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存は残りのコアと、空きRAMのこの割合までを使います。少なくとも1コアは常に動作します。", + ), + ("Max project size on open", "開くプロジェクトの最大サイズ"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", + ), + ("Filter by type", "種類で絞り込む"), + ("All libraries", "すべてのライブラリ"), + ("Browse folders", "フォルダーを参照"), + ("Starter assets", "付属アセット"), + ("Your assets", "マイアセット"), + ("Reset query", "クエリをリセット"), + ("Refresh", "更新"), + ("Saved searches", "保存した検索"), + ("Save the current search", "現在の検索を保存"), + ("Delete", "削除"), + ("Filter by path", "パスで絞り込む"), + ("Hide non-applicable folders", "該当しないフォルダーを隠す"), + ("Thumbnail size", "サムネイルのサイズ"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "リスト"), + ("Procedurals", "プロシージャル"), +]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs new file mode 100644 index 00000000..4273f92c --- /dev/null +++ b/crates/ui-egui/src/i18n/ko.rs @@ -0,0 +1,1161 @@ +//! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} 베이크 중 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} 베이크 중 ({n}/{total}), 텍스처 세트 {set}/{sets}"), + ("Follow Newest Map", "최신 맵 따라가기"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "베이크를 표시하는 동안에는 페인팅이 일시 중지됩니다. 베이크를 취소하거나 끝날 때까지 기다리세요.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "베이크하는 동안 3D 뷰가 보여 주는 것: 가장 최근에 완료된 맵, 완료된 맵 중 선택한 하나, 또는 머티리얼. 아직 베이크되지 않은 맵은 중립 값으로 표시됩니다.", + ), + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", + ), + ("0 turns autosave off. Copies go to {folder}", "0으로 설정하면 자동 저장이 꺼집니다. 사본 저장 위치: {folder}"), + ("2D view only", "2D 뷰만"), + ("32 bits (float)", "32비트 (float)"), + ("3D mesh", "3D 메시"), + ("3D meshes", "3D 메시"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "3D 텍스처 페인팅: 레이어, 마스크, 스마트 머티리얼, 메시 맵 베이크 및 내보내기.", + ), + ("3D view only", "3D 뷰만"), + ("3D/2D views", "3D/2D 뷰"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "폴더는 하위 항목을 블렌딩합니다(통과). 채널별 불투명도는 레이어 행에서 설정합니다.", + ), + ("ACES filmic", "ACES 필믹"), + ("Ambient", "앰비언트"), + ("AO intensity", "AO 강도"), + ("About TextureCraft", "TextureCraft 정보"), + ("About TextureCraft...", "TextureCraft 정보..."), + ("Add an anchor point to a layer below to use its stack as a mask.", "아래 레이어에 앵커 포인트를 추가하면 해당 스택을 마스크로 사용할 수 있습니다."), + ("Add anchor point", "앵커 포인트 추가"), + ("Add as decal (view center)", "데칼로 추가 (뷰 중앙)"), + ("Add black mask", "검은색 마스크 추가"), + ("Add channel", "채널 추가"), + ("Add color", "색상 추가"), + ("Add compare mask", "비교 마스크 추가"), + ("Add effect", "이펙트 추가"), + ("Add fill", "채우기 추가"), + ("Add fill layer", "채우기 레이어 추가"), + ("Add filter", "필터 추가"), + ("Add folder", "폴더 추가"), + ("Add generator", "제너레이터 추가"), + ("Add levels", "레벨 추가"), + ("Add mask", "마스크 추가"), + ("Add mask with color selection", "색상 선택으로 마스크 추가"), + ("Add output", "출력 추가"), + ("Add paint", "페인트 추가"), + ("Add paint layer", "페인트 레이어 추가"), + ("Add smart material from the shelf", "셸프에서 스마트 머티리얼 추가"), + ("Add to the layer content", "레이어 콘텐츠에 추가"), + ("Add to the mask", "마스크에 추가"), + ("Add white mask", "흰색 마스크 추가"), + ("Adjustments", "조정"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "정렬됨: 첫 번째 스트로크로 설정된 오프셋이 유지됩니다. V + 클릭으로 새 소스를 설정합니다.", + ), + ("Alignment", "정렬"), + ("Alignment and culling", "정렬 및 컬링"), + ("All layers", "모든 레이어"), + ("Alpha", "알파"), + ("Alphas", "알파"), + ("Also bound to {item} ({menu})", "{item}({menu})에도 지정됨"), + ("Alt + LMB drag", "Alt + 왼쪽 드래그"), + ("Always", "항상"), + ("Ambient Occlusion", "앰비언트 오클루전"), + ("Ambient occlusion", "앰비언트 오클루전"), + ("Amount", "양"), + ("Anchor point", "앵커 포인트"), + ("Anchor: {name}", "앵커: {name}"), + ("Anchor: {name} ({channel})", "앵커: {name} ({channel})"), + ("Angle", "각도"), + ("Angle (degrees)", "각도 (도)"), + ("Angle fade from", "각도 페이드 시작"), + ("Angle fade to", "각도 페이드 끝"), + ("Angle jitter", "각도 지터"), + ("Anisotropy angle", "이방성 각도"), + ("Anisotropy level", "이방성 레벨"), + ("Antialiasing", "안티앨리어싱"), + ("Aperture", "조리개"), + ("Apply", "적용"), + ("ArtCraft website...", "ArtCraft 웹사이트..."), + ("Assets", "에셋"), + ("Auto", "자동"), + ("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"), + ("Autosave every", "자동 저장 간격"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "자동 저장, 스마트 머티리얼, 프리셋, 템플릿과 UI 레이아웃은 데이터 폴더에 저장됩니다. 새 폴더는 다시 시작하면 적용되며, 이미 저장된 파일은 그대로 남습니다.", + ), + ("Axis", "축"), + ("Back to painting", "페인팅으로 돌아가기"), + ("Backface culling", "후면 컬링"), + ("Bake an ID map (F8) to pick colors from the mesh.", "메시에서 색을 고르려면 ID 맵을 베이크하세요 (F8)."), + ("Bake Mesh Maps", "메시 맵 베이크"), + ("Bake mesh maps", "메시 맵 베이크"), + ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "곡률, AO, 두께 기반 제너레이터를 사용하려면 메시 맵을 베이크하세요 (F8)."), + ("Baked Lighting", "베이크된 조명"), + ("Baking", "베이킹"), + ("Base color", "베이스 컬러"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "베이스 컬러는 디퓨즈 색상, 스페큘러는 F0 색상, 글로시니스는 1 - 러프니스입니다 (이 채널들은 텍스처 세트 설정에서 추가).", + ), + ("Base color, Metallic, Roughness and Specular level.", "베이스 컬러, 메탈릭, 러프니스, 스페큘러 레벨."), + ("Based on each texture set's size", "각 텍스처 세트 크기 기준"), + ("Basic settings", "기본 설정"), + ("Bent Normals", "벤트 노멀"), + ("Bevel", "베벨"), + ("Black", "검은색"), + ("Blending", "블렌딩"), + ("Blending mode of the displayed channel", "표시된 채널의 블렌딩 모드"), + ("Blur", "블러"), + ("Blur Directional", "방향성 블러"), + ("Blur and sharpen", "블러 및 선명하게"), + ("Bounces", "바운스"), + ("Bricks", "벽돌"), + ("Brush", "브러시"), + ("Brush size", "브러시 크기"), + ("Brush size down / up", "브러시 크기 축소 / 확대"), + ("Brushed lines", "브러시드 라인"), + ("Built-in (read-only): duplicate it to edit", "기본 제공 (읽기 전용): 편집하려면 복제하세요"), + ("Built-in templates are read-only: duplicate one to edit it", "기본 제공 템플릿은 읽기 전용입니다. 편집하려면 복제하세요"), + ("Built-in: {mesh}", "기본 제공: {mesh}"), + ("Cage: {name}", "케이지: {name}"), + ("Camera", "카메라"), + ("Colors", "색상"), + ("Go to camera 1", "카메라 1 보기"), + ("Go to camera 2", "카메라 2 보기"), + ("Go to camera 3", "카메라 3 보기"), + ("Go to camera 4", "카메라 4 보기"), + ("Go to camera 5", "카메라 5 보기"), + ("Go to camera 6", "카메라 6 보기"), + ("Go to camera 7", "카메라 7 보기"), + ("Go to camera 8", "카메라 8 보기"), + ("Go to camera 9", "카메라 9 보기"), + ("Camera settings", "카메라 설정"), + ("Cancel", "취소"), + ("Cancel the stroke", "스트로크 취소"), + ("Cell size (texels at 2K)", "셀 크기 (2K 기준 텍셀)"), + ("Cells", "셀"), + ("Channel", "채널"), + ("Channel source: uniform value, procedural, image or anchor", "채널 소스: 균일 값, 프로시저럴, 이미지 또는 앵커"), + ("Channels", "채널"), + ("Check for Updates...", "업데이트 확인..."), + ("Checker", "체커"), + ("Clamp", "클램프"), + ("Clear", "지우기"), + ("Clear mask", "마스크 지우기"), + ("Clear recent projects", "최근 프로젝트 지우기"), + ("Click a mesh part to show or hide the selected layer on it.", "메시 파트를 클릭하면 선택한 레이어를 해당 파트에서 표시하거나 숨깁니다."), + ("Click the mesh to pick its material into the brush", "메시를 클릭하여 해당 머티리얼을 브러시로 가져옵니다"), + ("Click the mesh to place the decal", "메시를 클릭하여 데칼 배치"), + ("Click, then press the new shortcut (Esc cancels)", "클릭한 후 새 단축키를 누르세요 (Esc로 취소)"), + ("Clone", "복제"), + ("Close", "닫기"), + ("Closed path", "닫힌 패스"), + ("Cloud", "구름"), + ("Clouds", "구름"), + ("Coat normal", "코트 노멀"), + ("Coat roughness", "코트 러프니스"), + ("Coat weight", "코트 가중치"), + ("Color", "색상"), + ("Color Balance", "색상 균형"), + ("Color burn", "색상 번"), + ("Color dodge", "색상 닷지"), + ( + "Color of the light that travels under the surface (each channel goes as far as its value)", + "표면 아래로 이동하는 빛의 색상입니다 (각 채널은 값만큼 멀리 이동)", + ), + ("Color picker", "색상 피커"), + ("Color selection", "색상 선택"), + ("Color to replace", "바꿀 색상"), + ("Colors near the first shift towards the second, keeping their shading.", "첫 번째 색상에 가까운 색상이 음영을 유지한 채 두 번째 색상으로 바뀝니다."), + ( + "Colors read as gray. Add a levels or blur effect above to shape the result.", + "색상은 회색으로 읽힙니다. 결과를 조정하려면 위에 레벨 또는 블러 이펙트를 추가하세요.", + ), + ("Combine with the layer's height", "레이어 높이와 결합"), + ("Compare mask", "비교 마스크"), + ("Compositing", "합성 중"), + ("Constant", "상수"), + ("Constants", "상수"), + ("Contrast", "대비"), + ("Contrast/Luminosity", "대비/광도"), + ("Converted maps", "변환된 맵"), + ("Copy RGB values", "RGB 값 복사"), + ("Copy effect", "이펙트 복사"), + ("Copy from", "복사 원본"), + ("Copy layer(s)", "레이어 복사"), + ("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"), + ("Copy to all texture sets", "모든 텍스처 세트에 복사"), + ("Copy what the texture set shows", "텍스처 세트에 표시되는 내용을 복사합니다"), + ("Couldn't encode the render", "렌더를 인코딩할 수 없습니다"), + ("Couldn't export textures: {error}", "텍스처를 내보낼 수 없습니다: {error}"), + ("Couldn't export the mesh: {error}", "메시를 내보낼 수 없습니다: {error}"), + ("Couldn't export the template: {error}", "템플릿을 내보낼 수 없습니다: {error}"), + ("Couldn't import {name}: {error}", "가져올 수 없습니다 ({name}): {error}"), + ("Couldn't open {name}: {error}", "열 수 없습니다 ({name}): {error}"), + ("Couldn't read the render back from the GPU", "GPU에서 렌더를 읽어올 수 없습니다"), + ("Couldn't save the render: {error}", "렌더를 저장할 수 없습니다: {error}"), + ("Couldn't save {name}: {error}", "저장할 수 없습니다 ({name}): {error}"), + ("Count per stamp", "스탬프당 개수"), + ("Crate", "상자"), + ("Create", "만들기"), + ("Create smart material", "스마트 머티리얼 만들기"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "뷰에서 Ctrl+오른쪽 드래그로 크기와 경도를, Ctrl+왼쪽 드래그로 흐름과 각도를 설정합니다.", + ), + ("Cube", "큐브"), + ("Current layer", "현재 레이어"), + ("Curvature", "곡률"), + ("Cut effect", "이펙트 잘라내기"), + ("Cut layer(s)", "레이어 잘라내기"), + ("Cyan / red", "녹청 / 빨강"), + ("Cylinder", "실린더"), + ("Cylindrical projection", "원통형 투영"), + ( + "Dark to light: the content's luminance picks a color along these stops.", + "어두운 색에서 밝은 색 순: 콘텐츠의 휘도에 따라 이 정지점을 따라 색상이 선택됩니다.", + ), + ("Darken (Min)", "어둡게 하기 (최소)"), + ("Data folder", "데이터 폴더"), + ("Decal", "데칼"), + ("Decal projection", "데칼 투영"), + ("Default", "기본값"), + ("Default camera", "기본 카메라"), + ("Delete the selected template", "선택한 템플릿을 삭제합니다"), + ("Delete this camera", "이 카메라를 삭제합니다"), + ("Deleted template \"{name}\"", "템플릿 \"{name}\" 삭제됨"), + ("Denoise", "노이즈 제거"), + ("Depth", "깊이"), + ("Depth of field", "피사계 심도"), + ("Depth of field (viewport and Rendering mode)", "피사계 심도 (뷰포트 및 렌더링 모드)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "뷰 방향으로 초점 평면의 깊이 (0: 궤도 중심)"), + ("Details saved to {file}", "자세한 내용 저장 위치: {file}"), + ("Difference", "차이"), + ("Dilation + default background color", "확장 + 기본 배경색"), + ("Dilation + transparent", "확장 + 투명"), + ("Dilation infinite", "무한 확장"), + ("DirectX normal map", "DirectX 노멀 맵"), + ("Dirt", "먼지"), + ("Disable", "비활성화"), + ("Dismiss", "닫기"), + ("Displacement (height channel)", "디스플레이스먼트 (높이 채널)"), + ("Display Settings", "디스플레이 설정"), + ("Display material", "머티리얼 표시"), + ("Display next channel", "다음 채널 표시"), + ("Display next mesh map", "다음 메시 맵 표시"), + ("Display previous channel", "이전 채널 표시"), + ("Display previous mesh map", "이전 메시 맵 표시"), + ("Distance", "거리"), + ("Distort", "왜곡"), + ("Divide", "나누기"), + ("Document resolution", "문서 해상도"), + ("Documentation...", "문서..."), + ("Done on CPU: {n} / {max} samples, {s} s", "CPU에서 완료: 샘플 {n} / {max}, {s}초"), + ("Done on GPU: {n} / {max} samples, {s} s", "GPU에서 완료: 샘플 {n} / {max}, {s}초"), + ("Double-click to rename", "더블클릭하여 이름 변경"), + ("Download as", "다운로드 형식"), + ("Downloaded {name}", "다운로드됨: {name}"), + ("Drag onto an output channel", "출력 채널로 드래그하세요"), + ( + "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", + "프레임을 드래그하여 데칼 이동, 모서리로 크기 조절, 둥근 핸들로 회전", + ), + ("Drags the layer stack's values along the stroke into the selected layer.", "스트로크를 따라 레이어 스택의 값을 선택한 레이어로 끌어옵니다."), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "텍스처 세트 \"{set}\"의 {name}을(를) 그립니다. 원본을 편집하면 모든 인스턴스에 반영됩니다.", + ), + ("Drop an image from the Assets panel here to use it as this mesh map", "에셋 패널의 이미지를 여기에 놓으면 이 메시 맵으로 사용합니다"), + ("Dry streaks", "마른 붓자국"), + ("Duplicate effect", "이펙트 복제"), + ("Duplicate layer(s)", "레이어 복제"), + ("Duplicate the selected template", "선택한 템플릿을 복제합니다"), + ("Edge Detect", "가장자리 검출"), + ("Edit", "편집"), + ("Edit keyboard shortcuts...", "키보드 단축키 편집..."), + ("Edit quick mask", "퀵 마스크 편집"), + ("Editing quick mask: paint where painting is allowed (U to finish)", "퀵 마스크 편집 중: 페인팅을 허용할 영역을 칠하세요 (U로 완료)"), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "퀵 마스크 편집 중: 스트로크로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.", + ), + ("Emissive", "이미시브"), + ("Enable or disable the effect", "이펙트를 켜거나 끕니다"), + ("Enable quick mask", "퀵 마스크 사용"), + ("Environment blur", "환경 블러"), + ("Environment exposure (EV)", "환경 노출 (EV)"), + ("Environment map", "환경 맵"), + ("Environment opacity", "환경 불투명도"), + ("Environment rotation", "환경 회전"), + ("Environment settings", "환경 설정"), + ("Environment: {name}", "환경: {name}"), + ("Environments", "환경"), + ("Eraser", "지우개"), + ("Exclusion", "제외"), + ("Expand or collapse the folder", "폴더를 펼치거나 접습니다"), + ("Export", "내보내기"), + ("Export Mesh...", "메시 내보내기..."), + ("Export Textures...", "텍스처 내보내기..."), + ("Export mesh", "메시 내보내기"), + ("Export template", "출력 템플릿"), + ("Export templates", "출력 템플릿"), + ("Export textures", "텍스처 내보내기"), + ("Export the selected template (.json)", "선택한 템플릿을 내보냅니다 (.json)"), + ("Exported mesh to {path}", "메시를 내보냈습니다: {path}"), + ("Exported template \"{name}\" to {path}", "템플릿 \"{name}\"을(를) 내보냈습니다: {path}"), + ("Exported {n} textures to {folder}", "텍스처 {n}개를 내보냈습니다: {folder}"), + ("F0 from specular level", "스페큘러 레벨에서 F0"), + ("Fabric weave", "직물 짜임"), + ("Field of view (deg)", "시야각 (도)"), + ("File", "파일"), + ("File name without extension; variables insert names", "확장자 없는 파일 이름입니다. 변수를 사용하면 이름이 삽입됩니다"), + ("File type", "파일 형식"), + ("Fill", "채우기"), + ("Fill the closed path (lasso)", "닫힌 패스를 채웁니다 (올가미)"), + ("Fill the path (close it first)", "패스를 채웁니다 (먼저 패스를 닫으세요)"), + ("Filter", "필터"), + ("Filter the remaining noise while keeping edges and texture detail", "가장자리와 텍스처 디테일을 유지하면서 남은 노이즈를 걸러냅니다"), + ("Filters", "필터"), + ("Fine noise", "미세 노이즈"), + ("Fingerprints", "지문"), + ("Enter a finite number", "유한한 숫자를 입력하세요"), + ("Double-click or press Enter to edit", "두 번 클릭하거나 Enter 키를 눌러 편집"), + ("Fit the input range to the histogram", "입력 범위를 히스토그램에 맞추기"), + ("Flatten layer", "레이어 병합"), + ("Flips the image's green channel, for normal maps made with Y pointing down", "이미지의 녹색 채널을 뒤집습니다 (Y가 아래를 향하도록 만든 노멀 맵용)"), + ("Flow", "흐름"), + ("Flow and opacity", "흐름 및 불투명도"), + ("Flow jitter", "흐름 지터"), + ("Focus distance", "초점 거리"), + ("Folder", "폴더"), + ("Folders", "폴더"), + ("Follow path", "패스 따라가기"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "프로젝트 전체: 메시 맵으로 지정한 노멀 맵 이미지를 읽는 방식(변경 후 다시 지정하세요)과 내보내기 기본값", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Rust로 작성된 무료 오픈 소스 소프트웨어입니다 (MIT OR Apache-2.0)."), + ("From template", "템플릿 기준"), + ("From template / project", "템플릿 / 프로젝트 기준"), + ("Full", "전체"), + ("GPU error: {error}", "GPU 오류: {error}"), + ("Geometry mask", "지오메트리 마스크"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "높이 상관 Smith 가시성을 사용하는 GGX 스페큘러, Lambert 디퓨즈, 구면 조화 함수 조도와 수평선 페이딩을 적용한 분할 합 이미지 기반 라이팅.", + ), + ("Gamma", "감마"), + ("General export parameters", "일반 내보내기 매개변수"), + ("General properties", "일반 속성"), + ("Generator", "제너레이터"), + ("Geometry and UVs only", "지오메트리와 UV만"), + ("Glossiness", "글로시니스"), + ("Glossiness from roughness", "러프니스에서 글로시니스"), + ("Glow", "글로우"), + ("Gradient", "그레이디언트"), + ("Gradient Map", "그레이디언트 맵"), + ("Gravity", "중력"), + ("Gray", "회색"), + ("Gray + A", "회색 + A"), + ("Gray 50%", "회색 50%"), + ("Grayscale", "회색조"), + ("Group layer(s)", "레이어 그룹화"), + ("Grunge", "그런지"), + ("HDR environments", "HDR 환경"), + ("High Pass", "하이 패스"), + ("HSL Perceptive", "HSL 지각"), + ("Half", "1/2"), + ("Hammered", "망치 자국"), + ("Hard light", "하드 라이트"), + ("Hardness", "경도"), + ("Height", "높이"), + ("Height offset", "높이 오프셋"), + ("Height to normal strength", "높이-노멀 변환 강도"), + ("Help", "도움말"), + ("Hide UI", "UI 숨기기"), + ("High", "높음"), + ("High poly: {name}", "하이 폴리: {name}"), + ("Highlights", "밝은 영역"), + ("Histogram Range", "히스토그램 범위"), + ("Histogram Scan", "히스토그램 스캔"), + ("Histogram Shift", "히스토그램 이동"), + ("History", "히스토리"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "S 누른 채: 왼쪽 드래그로 회전, 오른쪽 드래그로 크기 조절, 가운데 드래그로 스텐실을 이동합니다.", + ), + ("Hold V and click the mesh to set the clone source", "V를 누른 채 메시를 클릭하여 복제 소스를 설정합니다"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "V를 누른 채 메시를 클릭하여 소스를 설정한 다음, 다른 곳을 칠하면 복사됩니다.", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "빛이 표면 아래로 이동하는 거리로, 메시 크기에 대한 비율입니다 (산란 가중치 채널이 칠해진 곳)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "투과 표면이 빛을 굴절시키는 정도입니다 (투과 채널이 칠해진 곳): 물 1.33, 유리 1.5, 다이아몬드 2.42", + ), + ("Hue shift (degrees)", "색조 이동 (도)"), + ("ID", "ID"), + ("Image: {name}", "이미지: {name}"), + ("Images", "이미지"), + ("Import HDR...", "HDR 가져오기..."), + ("Import a template (.json)", "템플릿을 가져옵니다 (.json)"), + ("Import an image (File > Import resources) to project it onto the mesh.", "메시에 투영할 이미지를 가져오세요 (파일 > 리소스 가져오기)."), + ("Import resources...", "리소스 가져오기..."), + ("Import MaterialX material...", "MaterialX 머티리얼 가져오기..."), + ("MaterialX materials", "MaterialX 머티리얼"), + ("Import...", "가져오기..."), + ("Imported template \"{name}\"", "템플릿 \"{name}\" 가져옴"), + ("Imported {name}", "가져옴: {name}"), + ("Index of refraction", "굴절률"), + ("Input high", "입력 상한"), + ("Input low", "입력 하한"), + ("Input maps", "입력 맵"), + ("Insert a variable", "변수 삽입"), + ("Instance", "인스턴스"), + ("Instantiate across texture sets", "모든 텍스처 세트에 인스턴스화"), + ("Intensity (texels at 2K)", "강도 (2K 기준 텍셀)"), + ("Interface", "인터페이스"), + ("Interface scale", "인터페이스 배율"), + ("Inverse Subtract", "역 빼기"), + ("Inverse divide", "역 나누기"), + ("Invert", "반전"), + ("Invert mask", "마스크 반전"), + ("Invert mask background", "마스크 배경 반전"), + ("Invert mask value", "마스크 값 반전"), + ("Invert quick mask", "퀵 마스크 반전"), + ("Jitters", "지터"), + ("Join the ArtCraft community on Discord", "Discord에서 ArtCraft 커뮤니티에 참여하세요"), + ("Join the community (Discord)...", "커뮤니티 참여 (Discord)..."), + ("Key light (shadow-casting light, direct only)", "키 라이트 (그림자를 드리우는 조명, 직접광만)"), + ("Keyboard", "키보드"), + ("Keyboard shortcuts", "키보드 단축키"), + ("Light azimuth (degrees)", "조명 방위각 (도)"), + ("Light elevation (degrees)", "조명 고도 (도)"), + ("Light intensity", "조명 강도"), + ("LMB", "왼쪽 버튼"), + ("Language", "언어"), + ("Layer mask", "레이어 마스크"), + ("Layer memory: {mb} MB", "레이어 메모리: {mb} MB"), + ("Layers", "레이어"), + ("Lazy mouse", "레이지 마우스"), + ("Lazy mouse distance", "레이지 마우스 거리"), + ("Leather grain", "가죽 결"), + ("Lens size: how quickly things blur away from the focus distance", "렌즈 크기: 초점 거리에서 멀어질수록 얼마나 빠르게 흐려지는지 결정합니다"), + ("Level", "레벨"), + ("Levels", "레벨"), + ("Lifetime (steps)", "수명 (단계)"), + ("Light / direction", "조명 / 방향"), + ("Lighten (Max)", "밝게 하기 (최대)"), + ("Lightness", "명도"), + ("Linear", "선형"), + ("Linear burn", "선형 번"), + ("Linear dodge (Add)", "선형 닷지 (추가)"), + ("Linear light", "선형 라이트"), + ("List of exports", "내보내기 목록"), + ("Load UI Layout", "UI 레이아웃 불러오기"), + ("Loaded UI layout {path}", "UI 레이아웃 불러옴: {path}"), + ("Log", "로그"), + ("Low", "낮음"), + ("Luminosity", "광도"), + ("MMB drag / Alt + MMB", "가운데 드래그 / Alt + 가운데 버튼"), + ("Made by the ArtCraft team and community.", "ArtCraft 팀과 커뮤니티가 만들었습니다."), + ("Magenta / green", "마젠타 / 녹색"), + ("Main shader", "메인 셰이더"), + ("Marble veins", "대리석 무늬"), + ("Mask", "마스크"), + ("Mask Editor: Edge wear", "마스크 에디터: 모서리 마모"), + ("Mask value (gray)", "마스크 값 (회색)"), + ("Mask with height", "높이로 마스크"), + ("MatFinish Grind", "마감 - 연마"), + ("MatFinish Hammered", "마감 - 망치 자국"), + ("MatFinish Raw", "마감 - 원재료"), + ("MatFinish Sanded", "마감 - 샌딩"), + ("Material", "머티리얼"), + ("Material ball", "머티리얼 볼"), + ("Material finish", "머티리얼 마감"), + ("Materials", "머티리얼"), + ("Maximum", "최대"), + ("Mesh fill", "메시 채우기"), + ("Mesh map: {map}", "메시 맵: {map}"), + ("Mesh maps", "메시 맵"), + ("Mesh maps baked", "메시 맵 베이크 완료"), + ("Meshes", "메시"), + ("Metallic", "메탈릭"), + ("Midtones", "중간 영역"), + ("Minimum", "최소"), + ("Minimum size (%)", "최소 크기 (%)"), + ("Missing (bake to create)", "없음 (베이크하여 생성)"), + ("Mixed AO", "혼합 AO"), + ("Mode", "모드"), + ("More in Assets > Alphas: click one, or drag it here", "에셋 > 알파에서 더 보기: 클릭하거나 여기로 드래그하세요"), + ("Mosaic", "모자이크"), + ("Move down", "아래로 이동"), + ("Move up", "위로 이동"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "더 세밀한 메시 사본에서 높이를 노멀로 변환하는 강도로 높이 채널에 따라 표면을 이동합니다 (뷰포트 전용: 페인팅은 기본 표면을 따릅니다)", + ), + ("Multiply", "곱하기"), + ("My smart materials", "내 스마트 머티리얼"), + ("Name", "이름"), + ("New project", "새 프로젝트"), + ("New project...", "새 프로젝트..."), + ("New template", "새 템플릿"), + ("No GPU renderer available", "사용 가능한 GPU 렌더러가 없습니다"), + ("No font on this system can show this language", "이 시스템에는 이 언어를 표시할 수 있는 글꼴이 없습니다"), + ( + "No outputs yet: add one above, then drag input maps onto its channels.", + "아직 출력이 없습니다. 위에서 출력을 추가한 다음 입력 맵을 해당 채널로 드래그하세요.", + ), + ("No padding (passthrough)", "패딩 없음 (통과)"), + ("Noise amount", "노이즈 양"), + ("Noise scale", "노이즈 스케일"), + ("None", "없음"), + ("Normal", "노멀"), + ("Normal DirectX", "노멀 DirectX"), + ("Normal Invert", "노멀 반전"), + ("Normal OpenGL", "노멀 OpenGL"), + ("Normal from height", "높이에서 노멀"), + ("Normal map combine", "노멀 맵 결합"), + ("Normal map detail", "노멀 맵 디테일"), + ("Color space", "색 공간"), + ("Normal map format", "노멀 맵 형식"), + ("Normal map inverse detail", "노멀 맵 역 디테일"), + ("Normal: painting uses the flat normal", "노멀: 평면 노멀로 페인팅합니다"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 메모리가 부족하여 텍스처 세트 {count}개({names})를 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", + ), + ("Not exported: no source in this texture set", "내보내지 않음: 이 텍스처 세트에 소스가 없습니다"), + ("Not saved: {error}", "저장되지 않음: {error}"), + ("Off", "끄기"), + ("Offset", "오프셋"), + ("Offset right", "오른쪽 오프셋"), + ("Offset up", "위쪽 오프셋"), + ("Offset {axis}", "오프셋 {axis}"), + ("Offsets the textures by the height channel, at the height to normal strength", "높이-노멀 변환 강도로 높이 채널에 따라 텍스처를 오프셋합니다"), + ("On", "켜기"), + ("Opacity", "불투명도"), + ("Open sample project...", "샘플 프로젝트 열기..."), + ("Open...", "열기..."), + ("Opened {name}", "열림: {name}"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "선택 채널로 클리어 코트(코트 가중치, 코트 러프니스, 코트 노멀), 쉰(쉰 가중치, 색상, 러프니스), 이방성(이방성 레벨, 각도), 서브서피스 스캐터링(산란 가중치), 투과(투과)를 추가할 수 있습니다.", + ), + ("Orbit", "궤도 회전"), + ("Orthographic", "직교"), + ("Perspective", "원근"), + ("Output directory", "출력 디렉터리"), + ("Output high", "출력 상한"), + ("Output low", "출력 하한"), + ("Output template", "출력 템플릿"), + ("Output templates", "출력 템플릿"), + ("Overlay", "오버레이"), + ("Overlay opacity", "오버레이 불투명도"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - 메탈릭 러프니스 (TextureCraft)"), + ("Pick color", "색 고르기"), + ("PNG image", "PNG 이미지"), + ("Padding", "패딩"), + ("Paint", "페인트"), + ("Paint chips", "페인트 벗겨짐"), + ("Paint on the mesh to edit the layer content.", "메시에 칠하여 레이어 콘텐츠를 편집합니다."), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "메시에 칠하여 이 마스크를 편집합니다. 회색은 머티리얼 탭의 마스크 값을 사용하세요.", + ), + ("Paint with the current tool", "현재 도구로 페인팅"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "페인트한 레이어 픽셀 {pixels} MB, 합성된 채널 {composites} MB, 합성 캐시 {cache} MB", + ), + ("Painting", "페인팅"), + ("Pan", "이동"), + ("Parallax occlusion (height channel)", "시차 오클루전 (높이 채널)"), + ("Partial mask values follow the layer's height: high parts show first", "부분 마스크 값이 레이어 높이를 따릅니다. 높은 부분이 먼저 나타납니다"), + ("Particle brush (slides down the surface)", "파티클 브러시 (표면을 따라 흘러내림)"), + ("Particle brush: particles slide down the surface", "파티클 브러시: 파티클이 표면을 따라 흘러내립니다"), + ("Particles", "파티클"), + ("Passthrough", "통과"), + ("Paste as instance", "인스턴스로 붙여넣기"), + ("Paste effect", "이펙트 붙여넣기"), + ("Paste layer(s)", "레이어 붙여넣기"), + ("Path", "패스"), + ("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "패스: 클릭으로 점 추가, 곡선 클릭으로 점 삽입, 드래그로 이동, Enter로 적용, Esc로 취소", + ), + ("Pattern scale", "패턴 스케일"), + ("Perlin noise", "펄린 노이즈"), + ("Pick focus in the viewport", "뷰포트에서 초점 선택"), + ("Pin light", "핀 라이트"), + ("Place on the surface", "표면에 배치"), + ("Place path points on the mesh", "메시에 패스 점을 배치하세요"), + ("Planar projection", "평면 투영"), + ("Plane", "평면"), + ("Polygon fill", "폴리곤 채우기"), + ("Pores", "모공"), + ("Position", "위치"), + ("Position gradient", "위치 그레이디언트"), + ("Position jitter", "위치 지터"), + ("Posterize", "포스터화"), + ("Press a key...", "키를 누르세요..."), + ("Project", "프로젝트"), + ("Project Configuration...", "프로젝트 구성..."), + ("Project opened", "프로젝트를 열었습니다"), + ("Project template", "프로젝트 템플릿"), + ("Projection", "투영"), + ("Projects and meshes", "프로젝트 및 메시"), + ("Properties", "속성"), + ("Quarter", "1/4"), + ("Quick mask", "퀵 마스크"), + ("Quit", "종료"), + ("Radius (texels at 2K)", "반경 (2K 기준 텍셀)"), + ("RENDERING", "렌더링"), + ("Range", "범위"), + ("Rebind any menu item, tool or command", "메뉴 항목, 도구 또는 명령의 단축키를 다시 지정합니다"), + ("Recent projects", "최근 프로젝트"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "이 레이어까지의 스택을 기록합니다. 위쪽 마스크의 채우기 이펙트(및 채우기 레이어)에서 이를 소스로 읽을 수 있습니다.", + ), + ("Redo", "다시 실행"), + ("Reimport mesh", "메시 다시 가져오기"), + ("Remove", "제거"), + ("Remove channel", "채널 제거"), + ("Remove effect", "이펙트 제거"), + ("Remove last", "마지막 항목 제거"), + ("Remove layer", "레이어 제거"), + ("Remove layer(s)", "레이어 제거"), + ("Remove mask", "마스크 제거"), + ("Remove point", "점 제거"), + ("Remove resource", "리소스 제거"), + ("Remove the shortcut", "단축키를 제거합니다"), + ("Remove this output", "이 출력을 제거합니다"), + ("Remove unused resources...", "사용하지 않는 리소스 제거..."), + ("Rename the selected template", "선택한 템플릿의 이름을 변경합니다"), + ("Render on the CPU", "CPU에서 렌더링"), + ("Rendering", "렌더링"), + ("Rendering (path traced)", "렌더링 (패스 트레이싱)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "CPU에서 렌더링 중: 샘플 {n} / {max}, {s}초"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "GPU에서 렌더링 중: 샘플 {n} / {max}, {s}초"), + ("Rendering, path traced", "렌더링, 패스 트레이싱"), + ("Replace", "대체"), + ("Replace Color", "색상 바꾸기"), + ("Replacement color", "대체 색상"), + ("Report a bug...", "버그 신고..."), + ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), + ("Reset", "초기화"), + ("Reset UI", "UI 초기화"), + ("Reset all", "모두 초기화"), + ("Reset to defaults", "기본값으로 초기화"), + ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), + ("Resizing", "크기 조정 중"), + ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), + ("Return to this step", "이 단계로 돌아가기"), + ("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"), + ("Rotation", "회전"), + ("Rotation (degrees)", "회전 (도)"), + ("Roughness", "러프니스"), + ("Roughness from glossiness", "글로시니스에서 러프니스"), + ("Round", "원형"), + ("Rounded cube", "둥근 큐브"), + ("Samples", "샘플"), + ("Saturation", "채도"), + ("Save", "저장"), + ("Save UI Layout", "UI 레이아웃 저장"), + ("Save a copy...", "사본 저장..."), + ("Save as...", "다른 이름으로 저장..."), + ("Save current layout...", "현재 레이아웃 저장..."), + ("Save render...", "렌더 저장..."), + ("Save view as camera", "뷰를 카메라로 저장"), + ("Saved UI layout {path}", "UI 레이아웃 저장됨: {path}"), + ("Saved {path}", "저장됨: {path}"), + ("Saving UI layouts to files is available in the desktop app", "UI 레이아웃을 파일로 저장하는 기능은 데스크톱 앱에서 사용할 수 있습니다"), + ("Scale", "스케일"), + ("Scale / tiling", "스케일 / 타일링"), + ("Scatter color", "산란 색상"), + ("Scatter radius", "산란 반경"), + ("Scattering weight", "산란 가중치"), + ("Scratches", "스크래치"), + ("Screen", "스크린"), + ("Screenshot of the viewport", "뷰포트 스크린샷"), + ("Search", "검색"), + ("Search commands or keys", "명령 또는 키 검색"), + ("Seed", "시드"), + ("Select a layer", "레이어를 선택하세요"), + ("Select an output template", "출력 템플릿을 선택하세요"), + ("Select source", "소스 선택"), + ("Select the mask (Alt+click: show it in the viewport)", "마스크를 선택합니다 (Alt+클릭: 뷰포트에 표시)"), + ("Select...", "선택..."), + ("Settings", "설정"), + ("Settings...", "설정..."), + ("Shader Settings", "셰이더 설정"), + ("Shader instance", "셰이더 인스턴스"), + ("Shadows", "어두운 영역"), + ("Sharpen", "선명하게"), + ("Sheen color", "쉰 색상"), + ("Sheen color × weight", "쉰 색상 × 가중치"), + ("Sheen roughness", "쉰 러프니스"), + ("Sheen weight", "쉰 가중치"), + ("Shift + wheel", "Shift + 휠"), + ("Shortcuts list...", "단축키 목록..."), + ("Show on all parts", "모든 파트에 표시"), + ("Show UV wireframe in the 2D view", "2D 뷰에 UV 와이어프레임 표시"), + ("Show entire mesh", "전체 메시 표시"), + ("Show log...", "로그 표시..."), + ("Show or hide the layer", "레이어를 표시하거나 숨깁니다"), + ("Show or hide the texture set", "텍스처 세트를 표시하거나 숨깁니다"), + ("Show wireframe in the 3D view", "3D 뷰에 와이어프레임 표시"), + ("Signed addition (AddSub)", "부호 있는 더하기 (AddSub)"), + ("Size", "크기"), + ("Size in screen space", "화면 공간 기준 크기"), + ("Size jitter", "크기 지터"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "뷰포트에 표시할 텍스처 크기입니다. 낮을수록 큰 텍스처 세트에서 GPU 메모리를 덜 사용합니다. 페인팅과 내보내기는 전체 해상도를 유지합니다.", + ), + ("Slope Blur", "슬로프 블러"), + ("Slope scale", "슬로프 스케일"), + ("Smart masks", "스마트 마스크"), + ("Smart material saved to {path}", "스마트 머티리얼 저장됨: {path}"), + ("Smart materials", "스마트 머티리얼"), + ("Smudge", "스머지"), + ("Soft light", "소프트 라이트"), + ("Softness", "부드러움"), + ("Source", "소스"), + ("Source U {u} V {v}", "소스 U {u} V {v}"), + ("Spacing", "간격"), + ("Specular", "스페큘러"), + ("Specular level", "스페큘러 레벨"), + ("Sphere", "구"), + ("Spherical projection", "구형 투영"), + ("Spray", "스프레이"), + ("Square", "사각형"), + ("Stamp depth", "스탬프 깊이"), + ("Star", "별"), + ("Starting render...", "렌더 시작 중..."), + ("Stencil", "스텐실"), + ("Steps", "단계"), + ("Streaks", "줄 얼룩"), + ("Strength", "강도"), + ("Stripes", "줄무늬"), + ("Stroke opacity", "스트로크 불투명도"), + ("Subsampling 2x2", "서브샘플링 2x2"), + ("Subsampling 4x4", "서브샘플링 4x4"), + ("Subsampling 8x8", "서브샘플링 8x8"), + ("Subsurface scattering", "서브서피스 스캐터링"), + ("Subtract", "빼기"), + ("Tangent | Wrap", "탄젠트 | 랩"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "시간적 안티앨리어싱 (3D 뷰가 정지해 있을 때 품질을 높임)"), + ("Texture Sets", "텍스처 세트"), + ("Texture Set Settings", "텍스처 세트 설정"), + ("Texture resolution", "텍스처 해상도"), + ("Texture set channels", "텍스처 세트 채널"), + ("Texture sets", "텍스처 세트"), + ("TextureCraft had to close:", "TextureCraft를 종료해야 했습니다:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - 메탈릭 러프니스"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - 스페큘러 글로시니스"), + ("TextureCraft project", "TextureCraft 프로젝트"), + ("TextureCraft project or mesh", "TextureCraft 프로젝트 또는 메시"), + ("Textures", "텍스처"), + ("Textures embedded; for game engines and most viewers", "텍스처 포함, 게임 엔진 및 대부분의 뷰어용"), + ("Textures packaged; for USD tools and AR Quick Look", "텍스처 패키징, USD 도구 및 AR Quick Look용"), + ("The GPU couldn't render this scene: {error}", "GPU가 이 장면을 렌더링할 수 없습니다: {error}"), + ("The bake worker stopped", "베이크 작업자가 중지되었습니다"), + ("The eraser removes paint from the enabled channels.", "지우개는 활성화된 채널에서 페인트를 지웁니다."), + ("The first stroke sets the offset from the source.", "첫 번째 스트로크가 소스로부터의 오프셋을 설정합니다."), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "이미지의 알파가 데칼의 모양을 잘라냅니다. 반대쪽을 향한 면과 깊이를 벗어난 표면에는 적용되지 않습니다.", + ), + ("The next click in the 3D view moves the decal there", "3D 뷰에서 다음에 클릭한 위치로 데칼이 이동합니다"), + ("The resize worker stopped", "크기 조정 작업이 중지되었습니다"), + ("Thickness", "두께"), + ("Thin areas", "얇은 영역"), + ("Threshold", "한계값"), + ("Tile", "타일"), + ("Tiles", "타일"), + ("Tint", "틴트"), + ("Toggle mask", "마스크 켜기/끄기"), + ("Tolerance", "허용 범위"), + ("Tone mapping", "톤 매핑"), + ("Tools", "도구"), + ("Torus", "토러스"), + ("Transmission", "투과"), + ("Tri-planar projection", "트라이플래너 투영"), + ("Triangle fill", "삼각형 채우기"), + ("UDIM plane", "UDIM 평면"), + ("UDIM tiles painted by this texture set, each at the set's size", "이 텍스처 세트가 칠하는 UDIM 타일이며, 각 타일은 세트 크기를 따릅니다"), + ("UI layout", "UI 레이아웃"), + ("UI layout: {error}", "UI 레이아웃: {error}"), + ("UI layouts", "UI 레이아웃"), + ("UI {ms} ms", "UI {ms} ms"), + ("USD binary, textures alongside", "USD 바이너리, 텍스처 별도"), + ("USD text, textures alongside", "USD 텍스트, 텍스처 별도"), + ("USDZ with textures", "텍스처 포함 USDZ"), + ("UV checker", "UV 체커"), + ("UV island fill", "UV 아일랜드 채우기"), + ("UV transformations", "UV 변환"), + ("UV projection", "UV 투영"), + ("UV tiles", "UV 타일"), + ("UV tiles (UDIM)", "UV 타일 (UDIM)"), + ("Undo", "실행 취소"), + ("Uniform value", "균일 값"), + ("Use an equirectangular .hdr or .exr image as the environment", "등장방형 .hdr 또는 .exr 이미지를 환경으로 사용합니다"), + ("Use the control channel or `texturecraft-cli render` for screenshots", "스크린샷은 제어 채널 또는 `texturecraft-cli render`를 사용하세요"), + ("Value", "값"), + ("Version {version}", "버전 {version}"), + ("Version: {version} ({gpu})", "버전: {version} ({gpu})"), + ("View through this camera", "이 카메라로 보기"), + ("Viewer settings", "뷰어 설정"), + ("Viewport", "뷰포트"), + ("Viewport and brush (fixed)", "뷰포트 및 브러시 (고정)"), + ("Views", "뷰"), + ("Vivid light", "선명한 라이트"), + ("Voronoi", "보로노이"), + ("Warp", "워프"), + ("Warp Directional", "방향성 워프"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ(MTL 포함), 텍스처는 옆에"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "이 브라우저에서는 WebGPU를 사용할 수 없어 TextureCraft가 WebGL2로 실행됩니다. 렌더링 모드의 패스 트레이싱은 CPU에서 수행되며(더 느림), 큰 텍스처 세트는 낮은 해상도로 표시됩니다. 최신 Chrome, Edge, Safari는 WebGPU를 지원합니다.", + ), + ("Wheel / Alt + RMB drag", "휠 / Alt + 오른쪽 드래그"), + ("White", "흰색"), + ("Width", "너비"), + ("Width (texels at 2K)", "폭 (2K 기준 텍셀)"), + ("Window", "창"), + ("Wood grain", "나뭇결"), + ("Works in texture space, like the blur: it does not cross UV seams.", "블러와 마찬가지로 텍스처 공간에서 작동하므로 UV 경계를 넘지 않습니다."), + ("World Space Normal", "월드 공간 노멀"), + ("Yellow / blue", "노랑 / 파랑"), + ("Zoom", "확대/축소"), + ("a missing layer", "누락된 레이어"), + ("aniso", "이방성"), + ("aniso angle", "이방 각도"), + ("ao", "AO"), + ("coat", "코트"), + ("coat nrm", "코트 노멀"), + ("coat rough", "코트 러프"), + ("color", "컬러"), + ("emiss", "이미시브"), + ("glTF binary with textures", "텍스처 포함 glTF 바이너리"), + ("gloss", "글로시"), + ("height", "높이"), + ("metal", "메탈"), + ("min", "분"), + ("missing", "누락됨"), + ("missing source", "소스 누락"), + ("no GPU", "GPU 없음"), + ("none", "없음"), + ("nrm", "노멀"), + ("off", "끔"), + ("op", "불투명"), + ("rough", "러프"), + ("scatter", "산란"), + ("sheen", "쉰"), + ("sheen color", "쉰 컬러"), + ("sheen rough", "쉰 러프"), + ("spec", "스펙"), + ("specular", "스페큘러"), + ("transm", "투과"), + ("{action} (undone)", "{action} (실행 취소됨)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file}: 선택한 레이어 위에 추가합니다 (또는 레이어 스택이나 뷰포트로 드래그)", + ), + ("{name} copy", "{name} 사본"), + ("{n} bits", "{n}비트"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "컨트롤 포인트 {n}개. 메시(또는 2D 뷰)를 클릭해 포인트를 추가하고 드래그해 조정합니다. 첫 포인트를 클릭하면 패스가 닫힙니다. Enter는 브러시로 패스를 페인트하고(닫히고 채워진 패스는 내부를 채움), Esc는 취소합니다.", + ), + ("{n} items share a shortcut; the first one listed wins.", "항목 {n}개가 같은 단축키를 사용합니다. 목록의 첫 번째 항목이 우선합니다."), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (스케일 {scale}, 시드 {seed})"), + ("Template name", "템플릿 이름"), + ("Save current project as template", "현재 프로젝트를 템플릿으로 저장"), + ("Distribution", "분포"), + ("Cosine", "코사인"), + ("Uniform", "균일"), + ("Normalization", "정규화"), + // Settings › Interface: brightness and accent color. + ("Brightness", "밝기"), + ("Dark", "어둡게"), + ("Medium dark", "약간 어둡게"), + ("Medium light", "약간 밝게"), + ("Light", "밝게"), + ("Accent color", "강조 색상"), + ("Copper", "구리"), + ("Coral", "코랄"), + ("Blue", "파랑"), + ("Violet", "보라"), + ("Green", "초록"), + ("Amber", "호박색"), + ("Pink", "분홍"), + ("Minimize", "최소화"), + ("Maximize", "최대화"), + ("Restore", "이전 크기로 복원"), + ("Title bar", "제목 표시줄"), + ("System title bar (applies on restart)", "시스템 제목 표시줄 (다시 시작하면 적용)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", + ), + ("Brushes", "브러시 목록"), + ("Brush name", "브러시 이름"), + ("Save current brush", "현재 브러시 저장"), + ("Start window", "시작 창"), + ("Show at startup", "시작 시 표시"), + ("Continue with the sample project", "샘플 프로젝트로 계속"), + ("No recent projects yet", "아직 최근 프로젝트가 없습니다"), + ("Text", "텍스트"), + ("Font", "글꼴"), + ("Style", "스타일"), + ("Use as brush alpha", "브러시 알파로 사용"), + ("Place as decal", "데칼로 배치"), + ("Click: turn this channel on or off. Alt+click: this channel only", "클릭: 이 채널 켜기/끄기. Alt+클릭: 이 채널만"), + ("Show all", "모두 표시"), + ("Hide all", "모두 숨기기"), + ("Invert show/hide", "표시/숨기기 반전"), + ("Show or hide texture sets", "텍스처 세트 표시 또는 숨기기"), + ("Focus: show only the active texture set", "포커스: 활성 텍스처 세트만 표시"), + ("Unsaved changes", "저장되지 않은 변경 사항"), + ("Don't save", "저장 안 함"), + ("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"), + ("Radius", "반경"), + ("Remove skew correction", "스큐 보정 제거"), + ("Twill weave", "능직"), + ("Save the changes to {name} first?", "먼저 {name}의 변경 사항을 저장할까요?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "패스는 계속 편집할 수 있습니다. 패스를 골라 점을 옮기거나 브러시와 재질을 바꾸면 하위 레이어가 바로 다시 칠해집니다. 패스는 패스 도구로 추가합니다.", + ), + ("Import material...", "머티리얼 가져오기..."), + ("MaterialCraft material", "MaterialCraft 머티리얼"), + ("Cooked at {size} px", "{size} px로 계산됨"), + ("Preset", "프리셋"), + ("Re-cook", "다시 계산"), + ("Open in MaterialCraft", "MaterialCraft에서 열기"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "MaterialCraft에서 열었습니다. 변경 내용을 가져오려면 그곳에서 파일 > TextureCraft로 보내기를 사용하세요", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "매개변수는 MaterialCraft가 설치된 데스크톱 앱에서 바꿀 수 있습니다"), + ("Add High-Poly Meshes", "하이 폴리 메시 추가"), + ("All", "전체"), + ("Apply Diffusion", "확산 적용"), + ("Attenuation", "감쇠"), + ("Auto Tonemapping", "자동 톤 매핑"), + ("Average Normals", "노멀 평균화"), + ("BBox", "경계 상자"), + ("BSphere", "경계 구"), + ("Mesh Map Bakers", "메시 맵 베이커"), + ("Common Settings", "공통 설정"), + ("Mesh Map Settings", "메시 맵 설정"), + ("Check All", "모두 선택"), + ("No Parameters", "매개변수 없음"), + ("Bake Selected Textures ({n})", "선택한 텍스처 베이크 ({n})"), + ("By Mesh Name", "메시 이름으로"), + ("Cage", "케이지"), + ("Cage Scene", "케이지 장면"), + ("Cage Type", "케이지 유형"), + ("Color Generator", "색상 생성기"), + ("Color Source", "색상 소스"), + ("Common Parameters", "공통 매개변수"), + ("Custom File", "사용자 지정 파일"), + ("Details", "세부 사항"), + ("Dilation Width", "확장 폭"), + ("Distance-Based", "거리 기반"), + ("Edge Contrast", "가장자리 대비"), + ("Edge Distance", "가장자리 거리"), + ("Edge Protection", "가장자리 보호"), + ("Enable Seams", "이음새 활성화"), + ("File ID", "파일 ID"), + ("Full Scene", "전체 장면"), + ("Generate from Mesh", "메시에서 생성"), + ("Generate from Normal Map", "노멀 맵에서 생성"), + ("Ground Plane", "바닥 평면"), + ("Ground Plane Offset", "바닥 평면 오프셋"), + ("High Poly Mesh Suffix", "하이 폴리 메시 접미사"), + ("High Poly Scene", "하이 폴리 장면"), + ("High-Poly Parameters", "하이 폴리 매개변수"), + ("Hue Shift", "색조 이동"), + ("Ignore Backface", "뒷면 무시"), + ("Ignore Backface Suffix", "뒷면 무시 접미사"), + ("Include in Bake", "베이크에 포함"), + ("Load Cage", "케이지 불러오기"), + ("Lock Output Size", "출력 크기 잠금"), + ("Low Poly Mesh Suffix", "로우 폴리 메시 접미사"), + ("Manual", "수동"), + ("Material Color", "재질 색상"), + ("Max Frontal Distance", "최대 전방 거리"), + ("Max Occluder Distance", "최대 차폐물 거리"), + ("Max Rear Distance", "최대 후방 거리"), + ("Mesh ID", "메시 ID"), + ("Method", "방식"), + ("Min Occluder Distance", "최소 차폐 거리"), + ("Never", "안 함"), + ("No High-Poly Meshes", "하이 폴리 메시 없음"), + ("Normalization Scale", "정규화 범위"), + ("Normalization Type", "정규화 유형"), + ("Only Same Mesh Name", "같은 메시 이름만"), + ("Output Size", "출력 크기"), + ("Match", "일치"), + ("Skew Correction Method", "왜곡 보정 방법"), + ("Mesh Normals Based", "메시 법선 기반"), + ("Face Normals Based", "면 법선 기반"), + ("Reset Painted Cage", "페인트한 케이지 초기화"), + ("Paint Cage", "케이지 페인트"), + ("Paint Skew Correction", "기울기 보정 페인트"), + ("Per Material", "재질별"), + ("Random", "무작위"), + ("Relative to Bounding Box", "경계 상자 기준"), + ("Relative to Low Mesh", "로우 폴리 메시 기준"), + ("Relative to Min/Max", "최소/최대 기준"), + ("Relative to Ray Distances", "광선 거리 기준"), + ("Remove Cage", "케이지 제거"), + ("Remove Skew Correction", "스큐 보정 제거"), + ("Restore Defaults", "기본값 복원"), + ("Return to Painting Mode", "페인팅 모드로 돌아가기"), + ("Sampling Radius", "샘플링 반경"), + ("Scaling Divisor", "배율 나눗수"), + ("Seams Intensity", "이음새 강도"), + ("Secondary Rays", "보조 광선"), + ("Self Intersection", "자체 교차"), + ("Self Occlusion", "자기 차폐"), + ("Skew Correction", "스큐 보정"), + ("Smooth", "부드러움"), + ("Spread Angle", "확산 각도"), + ("Submesh", "하위 메시"), + ("Use Low Poly Mesh as High Poly Mesh", "로우 폴리 메시를 하이 폴리 메시로 사용"), + ("Value Bounds Max", "값 상한"), + ("Value Bounds Min", "값 하한"), + ("Vertex Color", "정점 색상"), + ("Select the layer content", "레이어 내용 선택"), + ("Paint layer", "페인트 레이어"), + ("Fill layer", "채우기 레이어"), + ("1 effect", "이펙트 1개"), + ("{count} effects", "이펙트 {count}개"), + ("Mask effects", "마스크 이펙트"), + ("Content effects", "콘텐츠 이펙트"), + ("Fold or unfold these effects", "이 이펙트 접기/펼치기"), + ("Remove resolution override", "해상도 재정의 제거"), + ("Texture set resolution", "텍스처 세트 해상도"), + ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Angle span", "각도 범위"), + ("Axis position", "축 위치"), + ("Count", "개수"), + ("Display", "표시"), + ("Hide while painting", "페인팅 중 숨기기"), + ("Manipulator size", "조작기 크기"), + ("Mirror symmetry", "미러 대칭"), + ("Radial settings", "방사형 설정"), + ("Radial symmetry", "방사형 대칭"), + ("Show axis", "축 표시"), + ("Show axis position manipulator", "축 위치 조작기 표시"), + ("Show cursor", "커서 표시"), + ("Show intersection", "교차선 표시"), + ("Show plane", "평면 표시"), + ("Symmetry", "대칭"), + ("Symmetry color display", "대칭 표시 색상"), + ("Symmetry settings", "대칭 설정"), + ("Type", "유형"), + ("Advanced settings", "고급 설정"), + ("Import baked maps", "베이크된 맵 가져오기"), + ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), + ("Add...", "추가..."), + ("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"), + ("Not imported: {files}", "가져오지 않음: {files}"), + ("Baking Visualization", "베이크 시각화"), + ("Show for Selected Texture Set Only", "선택한 텍스처 세트만 표시"), + ("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"), + ("UV Seams", "UV 심"), + ("Project Mesh (LP)", "투영 메시 (LP)"), + ("Edges", "가장자리"), + ("Cavities", "오목한 부분"), + ("Edges and cavities", "가장자리와 오목한 부분"), + ("Raw curvature", "원시 곡률"), + ("Detail sizes", "디테일 크기"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "곡률 맵을 베이크된 그대로 읽습니다. 모드나 크기를 바꾸면 디테일 크기가 켜집니다.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "클릭하면 아래에 있는 것을 채우고, 드래그한 사각형은 커지면서 선택한 것을 채웁니다", + ), + ("Contained center: fill polygons whose center is in the rectangle", "중심 포함: 중심이 사각형 안에 있는 폴리곤을 채웁니다"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "퀵 마스크 편집 중: 채우기로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.", + ), + ("Fill mode", "채우기 모드"), + ("Fill only polygons the camera sees (3D view)", "카메라에 보이는 폴리곤만 채웁니다 (3D 뷰)"), + ("Hit-test", "히트 테스트"), + ("How a rectangle selects polygons", "사각형이 폴리곤을 선택하는 방식"), + ("Intersection: fill polygons the rectangle touches", "교차: 사각형에 닿는 폴리곤을 채웁니다"), + ("Rectangle fill", "사각형 채우기"), + ("Select a paint layer or a layer's mask to fill", "채울 페인트 레이어나 레이어 마스크를 선택하세요"), + ("Selection mode", "선택 모드"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "삼각형은 개별 삼각형, 폴리곤은 사각형과 N각형 전체, 메시는 연결된 지오메트리, UV 아일랜드는 UV 아일랜드를 채웁니다", + ), + ("Visible polygons only", "보이는 폴리곤만"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), + ("The file dialog couldn't be shown: {error}", "파일 대화 상자를 표시할 수 없습니다: {error}"), + ("The project changed while the dialog was open, so nothing was done", "대화 상자가 열려 있는 동안 프로젝트가 변경되어 아무 작업도 수행하지 않았습니다"), + ("Cores kept for the UI", "UI용으로 남겨 둘 코어"), + ("Max RAM while saving", "저장 시 최대 RAM"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "저장은 나머지 코어와 여유 RAM의 이 비율까지만 사용합니다. 최소 한 개의 코어는 항상 작동합니다.", + ), + ("Max project size on open", "열기 시 최대 프로젝트 크기"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", + ), + ("Filter by type", "유형별 필터"), + ("All libraries", "모든 라이브러리"), + ("Browse folders", "폴더 찾아보기"), + ("Starter assets", "기본 에셋"), + ("Your assets", "내 에셋"), + ("Reset query", "쿼리 초기화"), + ("Refresh", "새로 고침"), + ("Saved searches", "저장된 검색"), + ("Save the current search", "현재 검색 저장"), + ("Delete", "삭제"), + ("Filter by path", "경로별 필터"), + ("Hide non-applicable folders", "해당 없는 폴더 숨기기"), + ("Thumbnail size", "썸네일 크기"), + ("Small", "작게"), + ("Medium", "보통"), + ("Large", "크게"), + ("List", "목록"), + ("Procedurals", "프로시저럴"), +]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs new file mode 100644 index 00000000..70d68d21 --- /dev/null +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -0,0 +1,1179 @@ +//! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Fazendo o bake de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Fazendo o bake de {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir o mapa mais recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "A pintura fica em pausa enquanto um bake é exibido. Cancele o bake ou espere ele terminar.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "O que a vista 3D mostra durante o bake: o último mapa concluído, um mapa concluído à escolha ou o material. Mapas ainda não gerados mostram um valor neutro.", + ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), + ("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"), + ("2D view only", "Apenas vista 2D"), + ("32 bits (float)", "32 bits (float)"), + ("3D mesh", "Malha 3D"), + ("3D meshes", "Malhas 3D"), + ( + "3D texture painting: layers, masks, smart materials, mesh map baking and export.", + "Pintura de texturas 3D: camadas, máscaras, materiais inteligentes, bake de mapas de malha e exportação.", + ), + ("3D view only", "Apenas vista 3D"), + ("3D/2D views", "Vistas 3D/2D"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "Uma pasta mescla seus filhos (passagem). Defina a opacidade por canal nas linhas das camadas.", + ), + ("ACES filmic", "ACES fílmico"), + ("Ambient", "Ambiente"), + ("AO intensity", "Intensidade de AO"), + ("About TextureCraft", "Sobre o TextureCraft"), + ("About TextureCraft...", "Sobre o TextureCraft..."), + ( + "Add an anchor point to a layer below to use its stack as a mask.", + "Adicione um ponto de ancoragem a uma camada abaixo para usar sua pilha como máscara.", + ), + ("Add anchor point", "Adicionar ponto de ancoragem"), + ("Add as decal (view center)", "Adicionar como decalque (centro da vista)"), + ("Add black mask", "Adicionar máscara preta"), + ("Add channel", "Adicionar canal"), + ("Add color", "Adicionar cor"), + ("Add compare mask", "Adicionar máscara de comparação"), + ("Add effect", "Adicionar efeito"), + ("Add fill", "Adicionar preenchimento"), + ("Add fill layer", "Adicionar camada de preenchimento"), + ("Add filter", "Adicionar filtro"), + ("Add folder", "Adicionar pasta"), + ("Add generator", "Adicionar gerador"), + ("Add levels", "Adicionar níveis"), + ("Add mask", "Adicionar máscara"), + ("Add mask with color selection", "Adicionar máscara com seleção de cor"), + ("Add output", "Adicionar saída"), + ("Add paint", "Adicionar pintura"), + ("Add paint layer", "Adicionar camada de pintura"), + ("Add smart material from the shelf", "Adicionar material inteligente da prateleira"), + ("Add to the layer content", "Adicionar ao conteúdo da camada"), + ("Add to the mask", "Adicionar à máscara"), + ("Add white mask", "Adicionar máscara branca"), + ("Adjustments", "Ajustes"), + ( + "Aligned: the offset set by the first stroke is kept. V + click sets a new source.", + "Alinhado: o deslocamento definido pelo primeiro traço é mantido. V + clique define uma nova origem.", + ), + ("Alignment", "Alinhamento"), + ("Alignment and culling", "Alinhamento e descarte"), + ("All layers", "Todas as camadas"), + ("Alpha", "Alpha"), + ("Alphas", "Alphas"), + ("Also bound to {item} ({menu})", "Também atribuído a {item} ({menu})"), + ("Alt + LMB drag", "Alt + arrastar com botão esquerdo"), + ("Always", "Sempre"), + ("Ambient Occlusion", "Oclusão de ambiente"), + ("Ambient occlusion", "Oclusão de ambiente"), + ("Amount", "Quantidade"), + ("Anchor point", "Ponto de ancoragem"), + ("Anchor: {name}", "Âncora: {name}"), + ("Anchor: {name} ({channel})", "Âncora: {name} ({channel})"), + ("Angle", "Ângulo"), + ("Angle (degrees)", "Ângulo (graus)"), + ("Angle fade from", "Atenuação de ângulo a partir de"), + ("Angle fade to", "Atenuação de ângulo até"), + ("Angle jitter", "Variação de ângulo"), + ("Anisotropy angle", "Ângulo de anisotropia"), + ("Anisotropy level", "Nível de anisotropia"), + ("Antialiasing", "Antisserrilhamento"), + ("Aperture", "Abertura"), + ("Apply", "Aplicar"), + ("ArtCraft website...", "Site da ArtCraft..."), + ("Assets", "Recursos"), + ("Auto", "Auto"), + ("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"), + ("Autosave every", "Salvar automaticamente a cada"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "Salvamentos automáticos, materiais inteligentes, predefinições, modelos e layouts da interface vão para a pasta de dados. Uma nova pasta vale após reiniciar; os arquivos já salvos ficam onde estão.", + ), + ("Axis", "Eixo"), + ("Back to painting", "Voltar à pintura"), + ("Backface culling", "Descarte de faces traseiras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Faça o bake de um mapa de ID (F8) para coletar cores da malha."), + ("Bake Mesh Maps", "Bake de mapas de malha"), + ("Bake mesh maps", "Fazer bake dos mapas de malha"), + ( + "Bake mesh maps (F8) for curvature, AO and thickness based generators.", + "Faça o bake dos mapas de malha (F8) para geradores baseados em curvatura, AO e espessura.", + ), + ("Baked Lighting", "Iluminação pré-calculada"), + ("Baking", "Bake"), + ("Base color", "Cor base"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "Cor base é a cor difusa, Especular é a cor F0 e Brilho é 1 - rugosidade (adicione esses canais nas configurações do conjunto de texturas).", + ), + ("Base color, Metallic, Roughness and Specular level.", "Cor base, Metálico, Rugosidade e Nível especular."), + ("Based on each texture set's size", "Com base no tamanho de cada conjunto de texturas"), + ("Basic settings", "Configurações básicas"), + ("Bent Normals", "Normais curvadas"), + ("Bevel", "Chanfro"), + ("Black", "Preto"), + ("Blending", "Mesclagem"), + ("Blending mode of the displayed channel", "Modo de mesclagem do canal exibido"), + ("Blur", "Desfoque"), + ("Blur Directional", "Desfoque direcional"), + ("Blur and sharpen", "Desfoque e nitidez"), + ("Bounces", "Rebatimentos"), + ("Bricks", "Tijolos"), + ("Brush", "Pincel"), + ("Brush size", "Tamanho do pincel"), + ("Brush size down / up", "Diminuir / aumentar o pincel"), + ("Brushed lines", "Linhas escovadas"), + ("Built-in (read-only): duplicate it to edit", "Embutido (somente leitura): duplique-o para editar"), + ("Built-in templates are read-only: duplicate one to edit it", "Os modelos embutidos são somente leitura: duplique um para editá-lo"), + ("Built-in: {mesh}", "Embutida: {mesh}"), + ("Cage: {name}", "Cage: {name}"), + ("Camera", "Câmera"), + ("Colors", "Cores"), + ("Go to camera 1", "Ir para a câmera 1"), + ("Go to camera 2", "Ir para a câmera 2"), + ("Go to camera 3", "Ir para a câmera 3"), + ("Go to camera 4", "Ir para a câmera 4"), + ("Go to camera 5", "Ir para a câmera 5"), + ("Go to camera 6", "Ir para a câmera 6"), + ("Go to camera 7", "Ir para a câmera 7"), + ("Go to camera 8", "Ir para a câmera 8"), + ("Go to camera 9", "Ir para a câmera 9"), + ("Camera settings", "Configurações da câmera"), + ("Cancel", "Cancelar"), + ("Cancel the stroke", "Cancelar o traço"), + ("Cell size (texels at 2K)", "Tamanho da célula (texels em 2K)"), + ("Cells", "Células"), + ("Channel", "Canal"), + ("Channel source: uniform value, procedural, image or anchor", "Origem do canal: valor uniforme, procedural, imagem ou âncora"), + ("Channels", "Canais"), + ("Check for Updates...", "Verificar atualizações..."), + ("Checker", "Xadrez"), + ("Clamp", "Limitar"), + ("Clear", "Limpar"), + ("Clear mask", "Limpar máscara"), + ("Clear recent projects", "Limpar projetos recentes"), + ("Click a mesh part to show or hide the selected layer on it.", "Clique em uma parte da malha para mostrar ou ocultar nela a camada selecionada."), + ("Click the mesh to pick its material into the brush", "Clique na malha para capturar o material dela no pincel"), + ("Click the mesh to place the decal", "Clique na malha para posicionar o decalque"), + ("Click, then press the new shortcut (Esc cancels)", "Clique e pressione o novo atalho (Esc cancela)"), + ("Clone", "Clonar"), + ("Close", "Fechar"), + ("Closed path", "Caminho fechado"), + ("Cloud", "Nuvem"), + ("Clouds", "Nuvens"), + ("Coat normal", "Normal do verniz"), + ("Coat roughness", "Rugosidade do verniz"), + ("Coat weight", "Peso do verniz"), + ("Color", "Cor"), + ("Color Balance", "Equilíbrio de cores"), + ("Color burn", "Superexposição de cor"), + ("Color dodge", "Subexposição de cor"), + ( + "Color of the light that travels under the surface (each channel goes as far as its value)", + "Cor da luz que viaja sob a superfície (cada canal vai tão longe quanto seu valor)", + ), + ("Color picker", "Conta-gotas"), + ("Color selection", "Seleção de cor"), + ("Color to replace", "Cor a substituir"), + ("Colors near the first shift towards the second, keeping their shading.", "As cores próximas da primeira passam para a segunda, mantendo o sombreamento."), + ( + "Colors read as gray. Add a levels or blur effect above to shape the result.", + "As cores são lidas como cinza. Adicione um efeito de níveis ou desfoque acima para ajustar o resultado.", + ), + ("Combine with the layer's height", "Combinar com a altura da camada"), + ("Compare mask", "Máscara de comparação"), + ("Compositing", "Composição"), + ("Constant", "Constante"), + ("Constants", "Constantes"), + ("Contrast", "Contraste"), + ("Contrast/Luminosity", "Contraste/Luminosidade"), + ("Converted maps", "Mapas convertidos"), + ("Copy RGB values", "Copiar os valores RGB"), + ("Copy effect", "Copiar efeito"), + ("Copy from", "Copiar de"), + ("Copy layer(s)", "Copiar camada(s)"), + ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"), + ("Copy to all texture sets", "Copiar para todos os conjuntos de texturas"), + ("Copy what the texture set shows", "Copiar o que o conjunto de texturas exibe"), + ("Couldn't encode the render", "Não foi possível codificar a renderização"), + ("Couldn't export textures: {error}", "Não foi possível exportar as texturas: {error}"), + ("Couldn't export the mesh: {error}", "Não foi possível exportar a malha: {error}"), + ("Couldn't export the template: {error}", "Não foi possível exportar o modelo: {error}"), + ("Couldn't import {name}: {error}", "Não foi possível importar {name}: {error}"), + ("Couldn't open {name}: {error}", "Não foi possível abrir {name}: {error}"), + ("Couldn't read the render back from the GPU", "Não foi possível ler a renderização de volta da GPU"), + ("Couldn't save the render: {error}", "Não foi possível salvar a renderização: {error}"), + ("Couldn't save {name}: {error}", "Não foi possível salvar {name}: {error}"), + ("Count per stamp", "Quantidade por carimbo"), + ("Crate", "Caixote"), + ("Create", "Criar"), + ("Create smart material", "Criar material inteligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+arrastar com botão direito em uma vista ajusta o tamanho e a dureza; Ctrl+arrastar com botão esquerdo, o fluxo e o ângulo.", + ), + ("Cube", "Cubo"), + ("Current layer", "Camada atual"), + ("Curvature", "Curvatura"), + ("Cut effect", "Recortar efeito"), + ("Cut layer(s)", "Recortar camada(s)"), + ("Cyan / red", "Ciano / vermelho"), + ("Cylinder", "Cilindro"), + ("Cylindrical projection", "Projeção cilíndrica"), + ( + "Dark to light: the content's luminance picks a color along these stops.", + "Do escuro ao claro: a luminância do conteúdo escolhe uma cor ao longo destas paradas.", + ), + ("Darken (Min)", "Escurecer (Mín)"), + ("Data folder", "Pasta de dados"), + ("Decal", "Decalque"), + ("Decal projection", "Projeção de decalque"), + ("Default", "Padrão"), + ("Default camera", "Câmera padrão"), + ("Delete the selected template", "Excluir o modelo selecionado"), + ("Delete this camera", "Excluir esta câmera"), + ("Deleted template \"{name}\"", "Modelo \"{name}\" excluído"), + ("Denoise", "Remover ruído"), + ("Depth", "Profundidade"), + ("Depth of field", "Profundidade de campo"), + ("Depth of field (viewport and Rendering mode)", "Profundidade de campo (viewport e modo Renderização)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "Profundidade do plano nítido ao longo da vista (0: o centro de órbita)"), + ("Details saved to {file}", "Detalhes salvos em {file}"), + ("Difference", "Diferença"), + ("Dilation + default background color", "Dilatação + cor de fundo padrão"), + ("Dilation + transparent", "Dilatação + transparente"), + ("Dilation infinite", "Dilatação infinita"), + ("DirectX normal map", "Mapa normal DirectX"), + ("Dirt", "Sujeira"), + ("Disable", "Desativado"), + ("Dismiss", "Fechar"), + ("Displacement (height channel)", "Deslocamento (canal de altura)"), + ("Display Settings", "Configurações de exibição"), + ("Display material", "Exibir material"), + ("Display next channel", "Exibir próximo canal"), + ("Display next mesh map", "Exibir próximo mapa de malha"), + ("Display previous channel", "Exibir canal anterior"), + ("Display previous mesh map", "Exibir mapa de malha anterior"), + ("Distance", "Distância"), + ("Distort", "Distorcer"), + ("Divide", "Divisão"), + ("Document resolution", "Resolução do documento"), + ("Documentation...", "Documentação..."), + ("Done on CPU: {n} / {max} samples, {s} s", "Concluído na CPU: {n} / {max} amostras, {s} s"), + ("Done on GPU: {n} / {max} samples, {s} s", "Concluído na GPU: {n} / {max} amostras, {s} s"), + ("Double-click to rename", "Clique duas vezes para renomear"), + ("Download as", "Baixar como"), + ("Downloaded {name}", "{name} baixado"), + ("Drag onto an output channel", "Arraste para um canal de saída"), + ( + "Drags the layer stack's values along the stroke into the selected layer.", + "Arrasta os valores da pilha de camadas ao longo do traço para a camada selecionada.", + ), + ( + "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", + "Desenha {name} do conjunto de texturas \"{set}\". As edições na origem aparecem em todas as instâncias.", + ), + ( + "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", + "Arraste o quadro para mover o decalque, um canto para redimensioná-lo e a alça redonda para girá-lo", + ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Solte aqui uma imagem do painel Recursos para usá-la como este mapa de malha"), + ("Dry streaks", "Estrias secas"), + ("Duplicate effect", "Duplicar efeito"), + ("Duplicate layer(s)", "Duplicar camada(s)"), + ("Duplicate the selected template", "Duplicar o modelo selecionado"), + ("Edge Detect", "Detecção de bordas"), + ("Edit", "Editar"), + ("Edit keyboard shortcuts...", "Editar atalhos de teclado..."), + ("Edit quick mask", "Editar máscara rápida"), + ("Editing quick mask: paint where painting is allowed (U to finish)", "Editando a máscara rápida: pinte onde a pintura é permitida (U para concluir)"), + ( + "Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", + "Editando a máscara rápida: os traços pintam onde a pintura é permitida. Pressione U para concluir.", + ), + ("Emissive", "Emissivo"), + ("Enable or disable the effect", "Ativar ou desativar o efeito"), + ("Enable quick mask", "Ativar máscara rápida"), + ("Environment blur", "Desfoque do ambiente"), + ("Environment exposure (EV)", "Exposição do ambiente (EV)"), + ("Environment map", "Mapa de ambiente"), + ("Environment opacity", "Opacidade do ambiente"), + ("Environment rotation", "Rotação do ambiente"), + ("Environment settings", "Configurações do ambiente"), + ("Environment: {name}", "Ambiente: {name}"), + ("Environments", "Ambientes"), + ("Eraser", "Borracha"), + ("Exclusion", "Exclusão"), + ("Expand or collapse the folder", "Expandir ou recolher a pasta"), + ("Export", "Exportar"), + ("Export Mesh...", "Exportar malha..."), + ("Export Textures...", "Exportar texturas..."), + ("Export mesh", "Exportar malha"), + ("Export template", "Exportar modelo"), + ("Export templates", "Modelos de exportação"), + ("Export textures", "Exportar texturas"), + ("Export the selected template (.json)", "Exportar o modelo selecionado (.json)"), + ("Exported mesh to {path}", "Malha exportada para {path}"), + ("Exported template \"{name}\" to {path}", "Modelo \"{name}\" exportado para {path}"), + ("Exported {n} textures to {folder}", "{n} texturas exportadas para {folder}"), + ("F0 from specular level", "F0 a partir do nível especular"), + ("Fabric weave", "Trama de tecido"), + ("Field of view (deg)", "Campo de visão (graus)"), + ("File", "Arquivo"), + ("File name without extension; variables insert names", "Nome do arquivo sem extensão; variáveis inserem nomes"), + ("File type", "Tipo de arquivo"), + ("Fill", "Preenchimento"), + ("Fill the closed path (lasso)", "Preencher o caminho fechado (laço)"), + ("Fill the path (close it first)", "Preencher o caminho (feche-o primeiro)"), + ("Filter", "Filtro"), + ("Filter the remaining noise while keeping edges and texture detail", "Filtrar o ruído restante preservando bordas e detalhes de textura"), + ("Filters", "Filtros"), + ("Fine noise", "Ruído fino"), + ("Fingerprints", "Impressões digitais"), + ("Enter a finite number", "Insira um número finito"), + ("Double-click or press Enter to edit", "Clique duas vezes ou pressione Enter para editar"), + ("Fit the input range to the histogram", "Ajustar o intervalo de entrada ao histograma"), + ("Flatten layer", "Achatar camada"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Inverte o canal verde da imagem, para mapas normais feitos com Y apontando para baixo", + ), + ("Flow", "Fluxo"), + ("Flow and opacity", "Fluxo e opacidade"), + ("Flow jitter", "Variação de fluxo"), + ("Focus distance", "Distância de foco"), + ("Folder", "Pasta"), + ("Folders", "Pastas"), + ("Follow path", "Seguir caminho"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "Para todo o projeto: como as imagens de mapa normal usadas como mapas de malha são lidas (atribua-as de novo após uma mudança), e o padrão para exportação", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Livre e de código aberto (MIT OR Apache-2.0), escrito em Rust."), + ("From template", "Do modelo"), + ("From template / project", "Do modelo / projeto"), + ("Full", "Completa"), + ("GPU error: {error}", "Erro de GPU: {error}"), + ("Geometry mask", "Máscara de geometria"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "Especular GGX com visibilidade Smith correlacionada à altura, difuso Lambert, iluminação baseada em imagem com soma dividida, irradiância por harmônicos esféricos e atenuação no horizonte.", + ), + ("Gamma", "Gama"), + ("General export parameters", "Parâmetros gerais de exportação"), + ("General properties", "Propriedades gerais"), + ("Generator", "Gerador"), + ("Geometry and UVs only", "Apenas geometria e UVs"), + ("Glossiness", "Brilho"), + ("Glossiness from roughness", "Brilho a partir da rugosidade"), + ("Glow", "Brilho"), + ("Gradient", "Gradiente"), + ("Gradient Map", "Mapa de gradiente"), + ("Gravity", "Gravidade"), + ("Gray", "Cinza"), + ("Gray + A", "Cinza + A"), + ("Gray 50%", "Cinza 50%"), + ("Grayscale", "Escala de cinza"), + ("Group layer(s)", "Agrupar camada(s)"), + ("Grunge", "Grunge"), + ("HDR environments", "Ambientes HDR"), + ("High Pass", "Passa-alta"), + ("HSL Perceptive", "HSL perceptivo"), + ("Half", "Metade"), + ("Hammered", "Martelado"), + ("Hard light", "Luz direta"), + ("Hardness", "Dureza"), + ("Height", "Altura"), + ("Height offset", "Deslocamento de altura"), + ("Height to normal strength", "Intensidade de altura para normal"), + ("Help", "Ajuda"), + ("Hide UI", "Ocultar interface"), + ("High", "Alto"), + ("High poly: {name}", "High poly: {name}"), + ("Highlights", "Realces"), + ("Histogram Range", "Intervalo do histograma"), + ("Histogram Scan", "Varredura do histograma"), + ("Histogram Shift", "Deslocamento do histograma"), + ("History", "Histórico"), + ( + "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", + "Segure S: arrastar com botão esquerdo gira, com botão direito redimensiona e com botão do meio move o estêncil.", + ), + ("Hold V and click the mesh to set the clone source", "Segure V e clique na malha para definir a origem da clonagem"), + ( + "Hold V and click the mesh to set the source, then paint elsewhere to copy it.", + "Segure V e clique na malha para definir a origem, depois pinte em outro lugar para copiá-la.", + ), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "Até onde a luz viaja sob a superfície, como fração do tamanho da malha (onde o canal Peso de dispersão está pintado)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "Quanto as superfícies transmissivas desviam a luz (onde o canal Transmissão está pintado): água 1.33, vidro 1.5, diamante 2.42", + ), + ("Hue shift (degrees)", "Deslocamento de matiz (graus)"), + ("ID", "ID"), + ("Image: {name}", "Imagem: {name}"), + ("Images", "Imagens"), + ("Import HDR...", "Importar HDR..."), + ("Import a template (.json)", "Importar um modelo (.json)"), + ("Import an image (File > Import resources) to project it onto the mesh.", "Importe uma imagem (Arquivo > Importar recursos) para projetá-la na malha."), + ("Import resources...", "Importar recursos..."), + ("Import MaterialX material...", "Importar material MaterialX..."), + ("MaterialX materials", "Materiais MaterialX"), + ("Import...", "Importar..."), + ("Imported template \"{name}\"", "Modelo \"{name}\" importado"), + ("Imported {name}", "{name} importado"), + ("Index of refraction", "Índice de refração"), + ("Input high", "Entrada alta"), + ("Input low", "Entrada baixa"), + ("Input maps", "Mapas de entrada"), + ("Insert a variable", "Inserir uma variável"), + ("Instance", "Instância"), + ("Instantiate across texture sets", "Instanciar entre conjuntos de texturas"), + ("Intensity (texels at 2K)", "Intensidade (texels em 2K)"), + ("Interface", "Interface"), + ("Interface scale", "Escala da interface"), + ("Inverse Subtract", "Subtração inversa"), + ("Inverse divide", "Divisão inversa"), + ("Invert", "Inverter"), + ("Invert mask", "Inverter máscara"), + ("Invert mask background", "Inverter fundo da máscara"), + ("Invert mask value", "Inverter valor da máscara"), + ("Invert quick mask", "Inverter máscara rápida"), + ("Jitters", "Variações"), + ("Join the ArtCraft community on Discord", "Participe da comunidade ArtCraft no Discord"), + ("Join the community (Discord)...", "Participar da comunidade (Discord)..."), + ("Key light (shadow-casting light, direct only)", "Luz principal (projeta sombras, apenas direta)"), + ("Keyboard", "Teclado"), + ("Keyboard shortcuts", "Atalhos de teclado"), + ("Light azimuth (degrees)", "Azimute da luz (graus)"), + ("Light elevation (degrees)", "Elevação da luz (graus)"), + ("Light intensity", "Intensidade da luz"), + ("LMB", "Botão esquerdo"), + ("Language", "Idioma"), + ("Layer mask", "Máscara de camada"), + ("Layer memory: {mb} MB", "Memória das camadas: {mb} MB"), + ("Layers", "Camadas"), + ("Lazy mouse", "Lazy mouse"), + ("Lazy mouse distance", "Distância do lazy mouse"), + ("Leather grain", "Grão de couro"), + ("Lens size: how quickly things blur away from the focus distance", "Tamanho da lente: quão rápido os objetos desfocam fora da distância de foco"), + ("Level", "Nível"), + ("Levels", "Níveis"), + ("Lifetime (steps)", "Duração (passos)"), + ("Light / direction", "Luz / direção"), + ("Lighten (Max)", "Clarear (Máx)"), + ("Lightness", "Claridade"), + ("Linear", "Linear"), + ("Linear burn", "Superexposição linear"), + ("Linear dodge (Add)", "Subexposição linear (Adição)"), + ("Linear light", "Luz linear"), + ("List of exports", "Lista de exportações"), + ("Load UI Layout", "Carregar layout da interface"), + ("Loaded UI layout {path}", "Layout da interface carregado de {path}"), + ("Log", "Log"), + ("Low", "Baixo"), + ("Luminosity", "Luminosidade"), + ("MMB drag / Alt + MMB", "Arrastar com botão do meio / Alt + botão do meio"), + ("Made by the ArtCraft team and community.", "Feito pela equipe e pela comunidade ArtCraft."), + ("Magenta / green", "Magenta / verde"), + ("Main shader", "Shader principal"), + ("Marble veins", "Veios de mármore"), + ("Mask", "Máscara"), + ("Mask Editor: Edge wear", "Editor de máscara: Desgaste de bordas"), + ("Mask value (gray)", "Valor da máscara (cinza)"), + ("Mask with height", "Mascarar com altura"), + ("MatFinish Grind", "MatFinish Esmerilhado"), + ("MatFinish Hammered", "MatFinish Martelado"), + ("MatFinish Raw", "MatFinish Bruto"), + ("MatFinish Sanded", "MatFinish Lixado"), + ("Material", "Material"), + ("Material ball", "Esfera de material"), + ("Material finish", "Acabamento de material"), + ("Materials", "Materiais"), + ("Maximum", "Máximo"), + ("Mesh fill", "Preenchimento de malha"), + ("Mesh map: {map}", "Mapa de malha: {map}"), + ("Mesh maps", "Mapas de malha"), + ("Mesh maps baked", "Bake dos mapas de malha concluído"), + ("Meshes", "Malhas"), + ("Metallic", "Metálico"), + ("Midtones", "Tons médios"), + ("Minimum", "Mínimo"), + ("Minimum size (%)", "Tamanho mínimo (%)"), + ("Missing (bake to create)", "Ausente (faça o bake para criar)"), + ("Mixed AO", "AO combinada"), + ("Mode", "Modo"), + ("More in Assets > Alphas: click one, or drag it here", "Mais em Recursos > Alphas: clique em um ou arraste-o para cá"), + ("Mosaic", "Mosaico"), + ("Move down", "Mover para baixo"), + ("Move up", "Mover para cima"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "Desloca a superfície pelo canal de altura em uma cópia mais fina da malha, com a intensidade de altura para normal (apenas na viewport: a pintura segue a superfície base)", + ), + ("Multiply", "Multiplicação"), + ("My smart materials", "Meus materiais inteligentes"), + ("Name", "Nome"), + ("New project", "Novo projeto"), + ("New project...", "Novo projeto..."), + ("New template", "Novo modelo"), + ("No GPU renderer available", "Nenhum renderizador de GPU disponível"), + ("No font on this system can show this language", "Nenhuma fonte deste sistema consegue exibir este idioma"), + ( + "No outputs yet: add one above, then drag input maps onto its channels.", + "Nenhuma saída ainda: adicione uma acima e arraste mapas de entrada para os canais dela.", + ), + ("No padding (passthrough)", "Sem margem (passagem direta)"), + ("Noise amount", "Quantidade de ruído"), + ("Noise scale", "Escala do ruído"), + ("None", "Nenhum"), + ("Normal", "Normal"), + ("Normal DirectX", "Normal DirectX"), + ("Normal Invert", "Inverter normal"), + ("Normal OpenGL", "Normal OpenGL"), + ("Normal from height", "Normal a partir da altura"), + ("Normal map combine", "Combinação de mapa normal"), + ("Normal map detail", "Detalhe de mapa normal"), + ("Color space", "Espaço de cor"), + ("Normal map format", "Formato do mapa normal"), + ("Normal map inverse detail", "Detalhe inverso de mapa normal"), + ("Normal: painting uses the flat normal", "Normal: a pintura usa a normal plana"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memória de GPU insuficiente para mostrar por completo {count} conjuntos de texturas ({names}): reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", + ), + ("Not exported: no source in this texture set", "Não exportado: sem origem neste conjunto de texturas"), + ("Not saved: {error}", "Não salvo: {error}"), + ("Off", "Desligado"), + ("Offset", "Deslocamento"), + ("Offset right", "Deslocamento à direita"), + ("Offset up", "Deslocamento para cima"), + ("Offset {axis}", "Deslocamento {axis}"), + ( + "Offsets the textures by the height channel, at the height to normal strength", + "Desloca as texturas pelo canal de altura, com a intensidade de altura para normal", + ), + ("On", "Ligado"), + ("Opacity", "Opacidade"), + ("Open sample project...", "Abrir projeto de exemplo..."), + ("Open...", "Abrir..."), + ("Opened {name}", "{name} aberto"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "Canais opcionais adicionam verniz (Peso do verniz, Rugosidade do verniz, Normal do verniz), lustro (Peso do lustro, cor, rugosidade), anisotropia (Nível de anisotropia, ângulo), dispersão subsuperficial (Peso de dispersão) e transmissão (Transmissão).", + ), + ("Orbit", "Orbitar"), + ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), + ("Output directory", "Pasta de saída"), + ("Output high", "Saída alta"), + ("Output low", "Saída baixa"), + ("Output template", "Modelo de saída"), + ("Output templates", "Modelos de saída"), + ("Overlay", "Sobrepor"), + ("Overlay opacity", "Opacidade da sobreposição"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidade (TextureCraft)"), + ("Pick color", "Coletar cor"), + ("PNG image", "Imagem PNG"), + ("Padding", "Margem"), + ("Paint", "Pintura"), + ("Paint chips", "Lascas de tinta"), + ("Paint on the mesh to edit the layer content.", "Pinte na malha para editar o conteúdo da camada."), + ( + "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", + "Pinte na malha para editar esta máscara. Use o valor de máscara da aba Material para cinza.", + ), + ("Paint with the current tool", "Pintar com a ferramenta atual"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "Pixels das camadas pintadas {pixels} MB, canais compostos {composites} MB, cache de composição {cache} MB", + ), + ("Painting", "Pintura"), + ("Pan", "Deslocar"), + ("Parallax occlusion (height channel)", "Oclusão de paralaxe (canal de altura)"), + ( + "Partial mask values follow the layer's height: high parts show first", + "Valores parciais de máscara seguem a altura da camada: as partes altas aparecem primeiro", + ), + ("Particle brush (slides down the surface)", "Pincel de partículas (desliza pela superfície)"), + ("Particle brush: particles slide down the surface", "Pincel de partículas: as partículas deslizam pela superfície"), + ("Particles", "Partículas"), + ("Passthrough", "Passagem"), + ("Paste as instance", "Colar como instância"), + ("Paste effect", "Colar efeito"), + ("Paste layer(s)", "Colar camada(s)"), + ("Path", "Caminho"), + ("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Caminho: clicar adiciona um ponto, clicar na curva insere um, arrastar o move, Enter aplica, Esc cancela", + ), + ("Pattern scale", "Escala do padrão"), + ("Perlin noise", "Ruído Perlin"), + ("Pick focus in the viewport", "Escolher o foco na viewport"), + ("Pin light", "Luz pontual"), + ("Place on the surface", "Posicionar na superfície"), + ("Place path points on the mesh", "Posicione os pontos do caminho na malha"), + ("Planar projection", "Projeção planar"), + ("Plane", "Plano"), + ("Polygon fill", "Preenchimento de polígonos"), + ("Pores", "Poros"), + ("Position", "Posição"), + ("Position gradient", "Gradiente de posição"), + ("Position jitter", "Variação de posição"), + ("Posterize", "Posterizar"), + ("Press a key...", "Pressione uma tecla..."), + ("Project", "Projeto"), + ("Project Configuration...", "Configuração do projeto..."), + ("Project opened", "Projeto aberto"), + ("Project template", "Modelo de projeto"), + ("Projection", "Projeção"), + ("Projects and meshes", "Projetos e malhas"), + ("Properties", "Propriedades"), + ("Quarter", "Um quarto"), + ("Quick mask", "Máscara rápida"), + ("Quit", "Sair"), + ("Radius (texels at 2K)", "Raio (texels em 2K)"), + ("RENDERING", "RENDERIZAÇÃO"), + ("Range", "Intervalo"), + ("Rebind any menu item, tool or command", "Reatribuir qualquer item de menu, ferramenta ou comando"), + ("Recent projects", "Projetos recentes"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "Registra a pilha até esta camada. Efeitos de preenchimento em máscaras (e camadas de preenchimento) acima podem lê-la como origem.", + ), + ("Redo", "Refazer"), + ("Reimport mesh", "Reimportar malha"), + ("Remove", "Remover"), + ("Remove channel", "Remover canal"), + ("Remove effect", "Remover efeito"), + ("Remove last", "Remover último"), + ("Remove layer", "Remover camada"), + ("Remove layer(s)", "Remover camada(s)"), + ("Remove mask", "Remover máscara"), + ("Remove point", "Remover ponto"), + ("Remove resource", "Remover recurso"), + ("Remove the shortcut", "Remover o atalho"), + ("Remove this output", "Remover esta saída"), + ("Remove unused resources...", "Remover recursos não usados..."), + ("Rename the selected template", "Renomear o modelo selecionado"), + ("Render on the CPU", "Renderizar na CPU"), + ("Rendering", "Renderização"), + ("Rendering (path traced)", "Renderização (path tracing)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "Renderizando na CPU: {n} / {max} amostras, {s} s"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "Renderizando na GPU: {n} / {max} amostras, {s} s"), + ("Rendering, path traced", "Renderização com path tracing"), + ("Replace", "Substituir"), + ("Replace Color", "Substituir cor"), + ("Replacement color", "Cor de substituição"), + ("Report a bug...", "Relatar um bug..."), + ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), + ("Reset", "Redefinir"), + ("Reset UI", "Redefinir interface"), + ("Reset all", "Redefinir tudo"), + ("Reset to defaults", "Redefinir para o padrão"), + ("Reset to {shortcut}", "Redefinir para {shortcut}"), + ("Resizing", "Redimensionando"), + ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), + ("Return to this step", "Voltar a esta etapa"), + ("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"), + ("Rotation", "Rotação"), + ("Rotation (degrees)", "Rotação (graus)"), + ("Roughness", "Rugosidade"), + ("Roughness from glossiness", "Rugosidade a partir do brilho"), + ("Round", "Redondo"), + ("Rounded cube", "Cubo arredondado"), + ("Samples", "Amostras"), + ("Saturation", "Saturação"), + ("Save", "Salvar"), + ("Save UI Layout", "Salvar layout da interface"), + ("Save a copy...", "Salvar uma cópia..."), + ("Save as...", "Salvar como..."), + ("Save current layout...", "Salvar layout atual..."), + ("Save render...", "Salvar renderização..."), + ("Save view as camera", "Salvar vista como câmera"), + ("Saved UI layout {path}", "Layout da interface salvo em {path}"), + ("Saved {path}", "{path} salvo"), + ("Saving UI layouts to files is available in the desktop app", "Salvar layouts da interface em arquivos está disponível no aplicativo para desktop"), + ("Scale", "Escala"), + ("Scale / tiling", "Escala / repetição"), + ("Scatter color", "Cor de dispersão"), + ("Scatter radius", "Raio de dispersão"), + ("Scattering weight", "Peso de dispersão"), + ("Scratches", "Arranhões"), + ("Screen", "Tela"), + ("Screenshot of the viewport", "Captura de tela da viewport"), + ("Search", "Pesquisar"), + ("Search commands or keys", "Pesquisar comandos ou teclas"), + ("Seed", "Semente"), + ("Select a layer", "Selecione uma camada"), + ("Select an output template", "Selecione um modelo de saída"), + ("Select source", "Selecionar origem"), + ("Select the mask (Alt+click: show it in the viewport)", "Selecionar a máscara (Alt+clique: exibi-la na viewport)"), + ("Select...", "Selecionar..."), + ("Settings", "Configurações"), + ("Settings...", "Configurações..."), + ("Shader Settings", "Configurações do shader"), + ("Shader instance", "Instância do shader"), + ("Shadows", "Sombras"), + ("Sharpen", "Nitidez"), + ("Sheen color", "Cor do lustro"), + ("Sheen color × weight", "Cor do lustro × peso"), + ("Sheen roughness", "Rugosidade do lustro"), + ("Sheen weight", "Peso do lustro"), + ("Shift + wheel", "Shift + roda do mouse"), + ("Shortcuts list...", "Lista de atalhos..."), + ("Show on all parts", "Mostrar em todas as partes"), + ("Show UV wireframe in the 2D view", "Exibir wireframe das UVs na vista 2D"), + ("Show entire mesh", "Exibir malha inteira"), + ("Show log...", "Exibir log..."), + ("Show or hide the layer", "Exibir ou ocultar a camada"), + ("Show or hide the texture set", "Exibir ou ocultar o conjunto de texturas"), + ("Show wireframe in the 3D view", "Exibir wireframe na vista 3D"), + ("Signed addition (AddSub)", "Adição com sinal (AddSub)"), + ("Size", "Tamanho"), + ("Size in screen space", "Tamanho no espaço da tela"), + ("Size jitter", "Variação de tamanho"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "Tamanho das texturas exibidas na viewport: valores menores usam menos memória de GPU com conjuntos de texturas grandes. A pintura e a exportação mantêm a resolução completa.", + ), + ("Slope Blur", "Desfoque de inclinação"), + ("Slope scale", "Escala da inclinação"), + ("Smart masks", "Máscaras inteligentes"), + ("Smart material saved to {path}", "Material inteligente salvo em {path}"), + ("Smart materials", "Materiais inteligentes"), + ("Smudge", "Borrar"), + ("Soft light", "Luz suave"), + ("Softness", "Suavidade"), + ("Source", "Origem"), + ("Source U {u} V {v}", "Origem U {u} V {v}"), + ("Spacing", "Espaçamento"), + ("Specular", "Especular"), + ("Specular level", "Nível especular"), + ("Sphere", "Esfera"), + ("Spherical projection", "Projeção esférica"), + ("Spray", "Spray"), + ("Square", "Quadrado"), + ("Stamp depth", "Profundidade do carimbo"), + ("Star", "Estrela"), + ("Starting render...", "Iniciando renderização..."), + ("Stencil", "Estêncil"), + ("Steps", "Passos"), + ("Streaks", "Estrias"), + ("Strength", "Intensidade"), + ("Stripes", "Listras"), + ("Stroke opacity", "Opacidade do traço"), + ("Subsampling 2x2", "Subamostragem 2x2"), + ("Subsampling 4x4", "Subamostragem 4x4"), + ("Subsampling 8x8", "Subamostragem 8x8"), + ("Subsurface scattering", "Dispersão subsuperficial"), + ("Subtract", "Subtração"), + ("Tangent | Wrap", "Tangente | Envolver"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antisserrilhamento temporal (refina a vista 3D enquanto está parada)"), + ("Texture Sets", "Conjuntos de texturas"), + ("Texture Set Settings", "Configurações do conjunto de texturas"), + ("Texture resolution", "Resolução das texturas"), + ("Texture set channels", "Canais do conjunto de texturas"), + ("Texture sets", "Conjuntos de texturas"), + ("TextureCraft had to close:", "O TextureCraft precisou ser fechado:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metálico Rugosidade"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - Especular Brilho"), + ("TextureCraft project", "Projeto TextureCraft"), + ("TextureCraft project or mesh", "Projeto TextureCraft ou malha"), + ("Textures", "Texturas"), + ("Textures embedded; for game engines and most viewers", "Texturas incorporadas; para engines de jogos e a maioria dos visualizadores"), + ("Textures packaged; for USD tools and AR Quick Look", "Texturas empacotadas; para ferramentas USD e AR Quick Look"), + ("The GPU couldn't render this scene: {error}", "A GPU não conseguiu renderizar esta cena: {error}"), + ("The bake worker stopped", "O processo de bake parou"), + ("The eraser removes paint from the enabled channels.", "A borracha remove a pintura dos canais ativados."), + ("The first stroke sets the offset from the source.", "O primeiro traço define o deslocamento em relação à origem."), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "O alpha da imagem recorta a forma do decalque; faces voltadas para trás e superfícies além da sua profundidade ficam intactas.", + ), + ("The next click in the 3D view moves the decal there", "O próximo clique na vista 3D move o decalque para lá"), + ("The resize worker stopped", "O processo de redimensionamento parou"), + ("Thickness", "Espessura"), + ("Thin areas", "Áreas finas"), + ("Threshold", "Limiar"), + ("Tile", "Repetir"), + ("Tiles", "Ladrilhos"), + ("Tint", "Tonalizar"), + ("Toggle mask", "Alternar máscara"), + ("Tolerance", "Tolerância"), + ("Tone mapping", "Mapeamento de tons"), + ("Tools", "Ferramentas"), + ("Torus", "Toro"), + ("Transmission", "Transmissão"), + ("Tri-planar projection", "Projeção triplanar"), + ("Triangle fill", "Preenchimento de triângulos"), + ("UDIM plane", "Plano UDIM"), + ("UDIM tiles painted by this texture set, each at the set's size", "Tiles UDIM pintados por este conjunto de texturas, cada um no tamanho do conjunto"), + ("UI layout", "Layout da interface"), + ("UI layout: {error}", "Layout da interface: {error}"), + ("UI layouts", "Layouts da interface"), + ("UI {ms} ms", "Interface {ms} ms"), + ("USD binary, textures alongside", "USD binário, texturas ao lado"), + ("USD text, textures alongside", "USD em texto, texturas ao lado"), + ("USDZ with textures", "USDZ com texturas"), + ("UV checker", "Xadrez UV"), + ("UV island fill", "Preenchimento de ilhas UV"), + ("UV transformations", "Transformações UV"), + ("UV projection", "Projeção UV"), + ("UV tiles", "Tiles UV"), + ("UV tiles (UDIM)", "Tiles UV (UDIM)"), + ("Undo", "Desfazer"), + ("Uniform value", "Valor uniforme"), + ("Use an equirectangular .hdr or .exr image as the environment", "Usar uma imagem equirretangular .hdr ou .exr como ambiente"), + ("Use the control channel or `texturecraft-cli render` for screenshots", "Use o canal de controle ou `texturecraft-cli render` para capturas de tela"), + ("Value", "Valor"), + ("Version {version}", "Versão {version}"), + ("Version: {version} ({gpu})", "Versão: {version} ({gpu})"), + ("View through this camera", "Ver por esta câmera"), + ("Viewer settings", "Configurações do visualizador"), + ("Viewport", "Viewport"), + ("Viewport and brush (fixed)", "Viewport e pincel (fixos)"), + ("Views", "Vistas"), + ("Vivid light", "Luz brilhante"), + ("Voronoi", "Voronoi"), + ("Warp", "Deformar"), + ("Warp Directional", "Deformar direcional"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ com MTL, texturas ao lado"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "O WebGPU não está disponível neste navegador, então o TextureCraft usa WebGL2: o modo de renderização faz path tracing na CPU (mais lento) e conjuntos de texturas grandes aparecem em resolução reduzida. As versões atuais do Chrome, Edge e Safari têm WebGPU.", + ), + ("Wheel / Alt + RMB drag", "Roda do mouse / Alt + arrastar com botão direito"), + ("White", "Branco"), + ("Width", "Largura"), + ("Width (texels at 2K)", "Largura (texels em 2K)"), + ("Window", "Janela"), + ("Wood grain", "Veio de madeira"), + ("Works in texture space, like the blur: it does not cross UV seams.", "Funciona no espaço de textura, como o desfoque: não atravessa costuras de UV."), + ("World Space Normal", "Normal no espaço do mundo"), + ("Yellow / blue", "Amarelo / azul"), + ("Zoom", "Zoom"), + ("a missing layer", "uma camada ausente"), + ("aniso", "aniso"), + ("aniso angle", "âng aniso"), + ("ao", "ao"), + ("coat", "verniz"), + ("coat nrm", "vern nrm"), + ("coat rough", "vern rug"), + ("color", "cor"), + ("emiss", "emiss"), + ("glTF binary with textures", "glTF binário com texturas"), + ("gloss", "brilho"), + ("height", "altura"), + ("metal", "metal"), + ("min", "min"), + ("missing", "ausente"), + ("missing source", "origem ausente"), + ("no GPU", "sem GPU"), + ("none", "nenhum"), + ("nrm", "nrm"), + ("off", "desligado"), + ("op", "opac"), + ("rough", "rugos"), + ("scatter", "disp"), + ("sheen", "lustro"), + ("sheen color", "cor lust"), + ("sheen rough", "rug lust"), + ("spec", "espec"), + ("specular", "especular"), + ("transm", "transm"), + ("{action} (undone)", "{action} (desfeito)"), + ( + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", + "{file}: adicionar acima da camada selecionada (ou arraste-o para a pilha de camadas ou para a viewport)", + ), + ("{name} copy", "Cópia de {name}"), + ("{n} bits", "{n} bits"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "{n} pontos de controle. Clique na malha (ou na vista 2D) para adicionar pontos e arraste-os para ajustar; clique no primeiro ponto para fechar o caminho. Enter pinta o caminho com o pincel (um caminho fechado e preenchido preenche o interior), Esc cancela.", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} itens compartilham um atalho; o primeiro listado prevalece."), + ("{pattern} (scale {scale}, seed {seed})", "{pattern} (escala {scale}, semente {seed})"), + ("Template name", "Nome do modelo"), + ("Save current project as template", "Salvar o projeto atual como modelo"), + ("Distribution", "Distribuição"), + ("Cosine", "Cosseno"), + ("Uniform", "Uniforme"), + ("Normalization", "Normalização"), + // Settings › Interface: brightness and accent color. + ("Brightness", "Brilho"), + ("Dark", "Escuro"), + ("Medium dark", "Médio escuro"), + ("Medium light", "Médio claro"), + ("Light", "Claro"), + ("Accent color", "Cor de destaque"), + ("Copper", "Cobre"), + ("Coral", "Coral"), + ("Blue", "Azul"), + ("Violet", "Violeta"), + ("Green", "Verde"), + ("Amber", "Âmbar"), + ("Pink", "Rosa"), + ("Minimize", "Minimizar"), + ("Maximize", "Maximizar"), + ("Restore", "Restaurar"), + ("Title bar", "Barra de título"), + ("System title bar (applies on restart)", "Barra de título do sistema (aplicada ao reiniciar)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", + ), + ("Brushes", "Pincéis"), + ("Brush name", "Nome do pincel"), + ("Save current brush", "Salvar o pincel atual"), + ("Start window", "Janela inicial"), + ("Show at startup", "Mostrar ao iniciar"), + ("Continue with the sample project", "Continuar com o projeto de exemplo"), + ("No recent projects yet", "Nenhum projeto recente ainda"), + ("Text", "Texto"), + ("Font", "Fonte"), + ("Style", "Estilo"), + ("Use as brush alpha", "Usar como alpha do pincel"), + ("Place as decal", "Colocar como decalque"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clique: liga ou desliga este canal. Alt+clique: só este canal"), + ("Show all", "Mostrar tudo"), + ("Hide all", "Ocultar tudo"), + ("Invert show/hide", "Inverter mostrar/ocultar"), + ("Show or hide texture sets", "Mostrar ou ocultar conjuntos de texturas"), + ("Focus: show only the active texture set", "Foco: mostrar só o conjunto de texturas ativo"), + ("Unsaved changes", "Alterações não salvas"), + ("Don't save", "Não salvar"), + ("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"), + ("Radius", "Raio"), + ("Remove skew correction", "Remover a correção de inclinação"), + ("Twill weave", "Tecido sarja"), + ("Save the changes to {name} first?", "Salvar primeiro as alterações em {name}?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Os caminhos continuam editáveis: escolha um para mover seus pontos ou mudar seu pincel e material, e a subcamada é repintada na hora. Adicione caminhos com a ferramenta Caminho.", + ), + ("Import material...", "Importar material..."), + ("MaterialCraft material", "Material do MaterialCraft"), + ("Cooked at {size} px", "Calculado em {size} px"), + ("Preset", "Predefinição"), + ("Re-cook", "Recalcular"), + ("Open in MaterialCraft", "Abrir no MaterialCraft"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "Aberto no MaterialCraft: use lá Arquivo > Enviar para o TextureCraft para trazer suas alterações", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "Os parâmetros mudam no app para desktop, com o MaterialCraft instalado"), + ("Add High-Poly Meshes", "Adicionar malhas de alta resolução"), + ("All", "Todos"), + ("Apply Diffusion", "Aplicar difusão"), + ("Attenuation", "Atenuação"), + ("Auto Tonemapping", "Mapeamento tonal automático"), + ("Average Normals", "Normais médias"), + ("BBox", "Caixa delimitadora"), + ("BSphere", "Esfera delimitadora"), + ("Mesh Map Bakers", "Bakers de mapas de malha"), + ("Common Settings", "Configurações comuns"), + ("Mesh Map Settings", "Configurações de mapas de malha"), + ("Check All", "Marcar todos"), + ("No Parameters", "Sem parâmetros"), + ("Bake Selected Textures ({n})", "Fazer bake das texturas selecionadas ({n})"), + ("By Mesh Name", "Por nome da malha"), + ("Cage", "Gaiola"), + ("Cage Scene", "Cena da gaiola"), + ("Cage Type", "Tipo de gaiola"), + ("Color Generator", "Gerador de cores"), + ("Color Source", "Origem da cor"), + ("Common Parameters", "Parâmetros comuns"), + ("Custom File", "Arquivo personalizado"), + ("Details", "Detalhes"), + ("Dilation Width", "Largura da dilatação"), + ("Distance-Based", "Baseada em distância"), + ("Edge Contrast", "Contraste das arestas"), + ("Edge Distance", "Distância das arestas"), + ("Edge Protection", "Proteção das arestas"), + ("Enable Seams", "Ativar costuras"), + ("File ID", "ID do arquivo"), + ("Full Scene", "Cena inteira"), + ("Generate from Mesh", "Gerar a partir da malha"), + ("Generate from Normal Map", "Gerar a partir do mapa de normais"), + ("Ground Plane", "Plano do solo"), + ("Ground Plane Offset", "Deslocamento do solo"), + ("High Poly Mesh Suffix", "Sufixo da malha high poly"), + ("High Poly Scene", "Cena de alta resolução"), + ("High-Poly Parameters", "Parâmetros de alta resolução"), + ("Hue Shift", "Deslocamento de matiz"), + ("Ignore Backface", "Ignorar faces traseiras"), + ("Ignore Backface Suffix", "Sufixo para ignorar faces traseiras"), + ("Include in Bake", "Incluir no bake"), + ("Load Cage", "Carregar gaiola"), + ("Lock Output Size", "Bloquear tamanho de saída"), + ("Low Poly Mesh Suffix", "Sufixo da malha low poly"), + ("Manual", "Manual"), + ("Material Color", "Cor do material"), + ("Max Frontal Distance", "Distância frontal máxima"), + ("Max Occluder Distance", "Distância máxima do oclusor"), + ("Max Rear Distance", "Distância traseira máxima"), + ("Mesh ID", "ID da malha"), + ("Method", "Método"), + ("Min Occluder Distance", "Distância mínima do oclusor"), + ("Never", "Nunca"), + ("No High-Poly Meshes", "Nenhuma malha de alta resolução"), + ("Normalization Scale", "Escala de normalização"), + ("Normalization Type", "Tipo de normalização"), + ("Only Same Mesh Name", "Somente o mesmo nome de malha"), + ("Output Size", "Tamanho de saída"), + ("Match", "Correspondência"), + ("Skew Correction Method", "Método de Correção de Distorção"), + ("Mesh Normals Based", "Baseado nas Normais da Malha"), + ("Face Normals Based", "Baseado nas Normais das Faces"), + ("Reset Painted Cage", "Redefinir Gaiola Pintada"), + ("Paint Cage", "Pintar gaiola"), + ("Paint Skew Correction", "Pintar correção de inclinação"), + ("Per Material", "Por material"), + ("Random", "Aleatório"), + ("Relative to Bounding Box", "Relativo à caixa delimitadora"), + ("Relative to Low Mesh", "Relativo à malha de baixa resolução"), + ("Relative to Min/Max", "Relativo ao mínimo/máximo"), + ("Relative to Ray Distances", "Relativo às distâncias dos raios"), + ("Remove Cage", "Remover gaiola"), + ("Remove Skew Correction", "Remover a correção de inclinação"), + ("Restore Defaults", "Restaurar padrões"), + ("Return to Painting Mode", "Voltar ao modo de pintura"), + ("Sampling Radius", "Raio de amostragem"), + ("Scaling Divisor", "Divisor de escala"), + ("Seams Intensity", "Intensidade das costuras"), + ("Secondary Rays", "Raios secundários"), + ("Self Intersection", "Autointerseção"), + ("Self Occlusion", "Autooclusão"), + ("Skew Correction", "Correção de inclinação"), + ("Smooth", "Suave"), + ("Spread Angle", "Ângulo de dispersão"), + ("Submesh", "Submalha"), + ("Use Low Poly Mesh as High Poly Mesh", "Usar a malha low poly como malha high poly"), + ("Value Bounds Max", "Limite máximo"), + ("Value Bounds Min", "Limite mínimo"), + ("Vertex Color", "Cor do vértice"), + ("Select the layer content", "Selecionar o conteúdo da camada"), + ("Paint layer", "Camada de pintura"), + ("Fill layer", "Camada de preenchimento"), + ("1 effect", "1 efeito"), + ("{count} effects", "{count} efeitos"), + ("Mask effects", "Efeitos da máscara"), + ("Content effects", "Efeitos do conteúdo"), + ("Fold or unfold these effects", "Recolher ou expandir estes efeitos"), + ("Remove resolution override", "Remover resolução personalizada"), + ("Texture set resolution", "Resolução do conjunto de texturas"), + ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Angle span", "Amplitude do ângulo"), + ("Axis position", "Posição do eixo"), + ("Count", "Quantidade"), + ("Display", "Exibição"), + ("Hide while painting", "Ocultar ao pintar"), + ("Manipulator size", "Tamanho do manipulador"), + ("Mirror symmetry", "Simetria espelhada"), + ("Radial settings", "Configurações radiais"), + ("Radial symmetry", "Simetria radial"), + ("Show axis", "Mostrar eixo"), + ("Show axis position manipulator", "Mostrar manipulador da posição do eixo"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar interseção"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetria"), + ("Symmetry color display", "Cor de exibição da simetria"), + ("Symmetry settings", "Configurações de simetria"), + ("Type", "Tipo"), + ("Advanced settings", "Configurações avançadas"), + ("Import baked maps", "Importar mapas com bake"), + ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), + ("Add...", "Adicionar..."), + ("Baked maps imported: {count}", "Mapas com bake importados: {count}"), + ("Not imported: {files}", "Não importados: {files}"), + ("Baking Visualization", "Visualização do bake"), + ("Show for Selected Texture Set Only", "Mostrar apenas para o conjunto de texturas selecionado"), + ("High Definition Mesh (HP)", "Malha de alta resolução (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malha de projeção (LP)"), + ("Edges", "Bordas"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordas e cavidades"), + ("Raw curvature", "Curvatura bruta"), + ("Detail sizes", "Tamanhos de detalhe"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lê o mapa de curvatura como foi assado: mudar o modo ou um tamanho ativa os tamanhos de detalhe.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Um clique preenche o que está embaixo; um retângulo arrastado preenche o que seleciona enquanto cresce", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contido: preencher os polígonos cujo centro está no retângulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando a máscara rápida: os preenchimentos pintam onde a pintura é permitida. Pressione U para concluir.", + ), + ("Fill mode", "Modo de preenchimento"), + ("Fill only polygons the camera sees (3D view)", "Preencher apenas os polígonos que a câmera vê (vista 3D)"), + ("Hit-test", "Teste de seleção"), + ("How a rectangle selects polygons", "Como um retângulo seleciona polígonos"), + ("Intersection: fill polygons the rectangle touches", "Interseção: preencher os polígonos que o retângulo toca"), + ("Rectangle fill", "Preenchimento retangular"), + ("Select a paint layer or a layer's mask to fill", "Selecione uma camada de pintura ou uma máscara de camada para preencher"), + ("Selection mode", "Modo de seleção"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triângulo preenche triângulos isolados, Polígono quads e n-gons inteiros, Malha a geometria conectada, Ilha UV as ilhas UV", + ), + ("Visible polygons only", "Apenas polígonos visíveis"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada", + ), + ("The file dialog couldn't be shown: {error}", "Não foi possível mostrar a caixa de diálogo de arquivos: {error}"), + ("The project changed while the dialog was open, so nothing was done", "O projeto mudou enquanto a caixa de diálogo estava aberta, então nada foi feito"), + ("Cores kept for the UI", "Núcleos reservados para a interface"), + ("Max RAM while saving", "RAM máx. ao salvar"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Salvar usa os outros núcleos e no máximo esta parte da RAM livre. Pelo menos um núcleo sempre trabalha.", + ), + ("Max project size on open", "Tamanho máximo ao abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", + ), + ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas as bibliotecas"), + ("Browse folders", "Navegar pelas pastas"), + ("Starter assets", "Recursos incluídos"), + ("Your assets", "Seus recursos"), + ("Reset query", "Redefinir consulta"), + ("Refresh", "Atualizar"), + ("Saved searches", "Pesquisas salvas"), + ("Save the current search", "Salvar a pesquisa atual"), + ("Delete", "Excluir"), + ("Filter by path", "Filtrar por caminho"), + ("Hide non-applicable folders", "Ocultar pastas não aplicáveis"), + ("Thumbnail size", "Tamanho da miniatura"), + ("Small", "Pequeno"), + ("Medium", "Médio"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurais"), +]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs new file mode 100644 index 00000000..0b582484 --- /dev/null +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -0,0 +1,1104 @@ +//! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "正在烘焙{map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "正在烘焙{map} ({n}/{total}),纹理集 {set}/{sets}"), + ("Follow Newest Map", "跟随最新贴图"), + ("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", "显示烘焙时已暂停绘制。请取消烘焙,或等待其完成。"), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "烘焙过程中 3D 视图显示的内容:最新完成的贴图、任意已完成的贴图,或材质。尚未烘焙的贴图显示中性值。", + ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), + ("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"), + ("2D view only", "仅 2D 视图"), + ("32 bits (float)", "32 位(浮点)"), + ("3D mesh", "3D 网格"), + ("3D meshes", "3D 网格"), + ("3D texture painting: layers, masks, smart materials, mesh map baking and export.", "3D 纹理绘制:图层、遮罩、智能材质、网格贴图烘焙与导出。"), + ("3D view only", "仅 3D 视图"), + ("3D/2D views", "3D/2D 视图"), + ( + "A folder blends its children (pass-through). Set per-channel opacity in the layer rows.", + "文件夹会混合其子图层(穿透)。请在图层行中设置各通道的不透明度。", + ), + ("ACES filmic", "ACES 电影"), + ("Ambient", "环境光"), + ("AO intensity", "AO 强度"), + ("About TextureCraft", "关于 TextureCraft"), + ("About TextureCraft...", "关于 TextureCraft..."), + ("Add an anchor point to a layer below to use its stack as a mask.", "在下方图层上添加锚点,以将其堆栈用作遮罩。"), + ("Add anchor point", "添加锚点"), + ("Add as decal (view center)", "添加为贴花(视图中心)"), + ("Add black mask", "添加黑色遮罩"), + ("Add channel", "添加通道"), + ("Add color", "添加颜色"), + ("Add compare mask", "添加比较遮罩"), + ("Add effect", "添加效果"), + ("Add fill", "添加填充"), + ("Add fill layer", "添加填充图层"), + ("Add filter", "添加滤镜"), + ("Add folder", "添加文件夹"), + ("Add generator", "添加生成器"), + ("Add levels", "添加色阶"), + ("Add mask", "添加遮罩"), + ("Add mask with color selection", "添加颜色选择遮罩"), + ("Add output", "添加输出"), + ("Add paint", "添加绘画"), + ("Add paint layer", "添加绘画图层"), + ("Add smart material from the shelf", "从资产架添加智能材质"), + ("Add to the layer content", "添加到图层内容"), + ("Add to the mask", "添加到遮罩"), + ("Add white mask", "添加白色遮罩"), + ("Adjustments", "调整"), + ("Aligned: the offset set by the first stroke is kept. V + click sets a new source.", "对齐:保留第一笔设定的偏移。按住 V 并单击可设置新的源。"), + ("Alignment", "对齐"), + ("Alignment and culling", "对齐与剔除"), + ("All layers", "所有图层"), + ("Alpha", "Alpha"), + ("Alphas", "Alpha"), + ("Also bound to {item} ({menu})", "同时绑定到 {item}({menu})"), + ("Alt + LMB drag", "Alt + 左键拖动"), + ("Always", "始终"), + ("Ambient Occlusion", "环境光遮蔽"), + ("Ambient occlusion", "环境光遮蔽"), + ("Amount", "数量"), + ("Anchor point", "锚点"), + ("Anchor: {name}", "锚点:{name}"), + ("Anchor: {name} ({channel})", "锚点:{name}({channel})"), + ("Angle", "角度"), + ("Angle (degrees)", "角度(度)"), + ("Angle fade from", "角度衰减起点"), + ("Angle fade to", "角度衰减终点"), + ("Angle jitter", "角度抖动"), + ("Anisotropy angle", "各向异性角度"), + ("Anisotropy level", "各向异性强度"), + ("Antialiasing", "抗锯齿"), + ("Aperture", "光圈"), + ("Apply", "应用"), + ("ArtCraft website...", "ArtCraft 网站..."), + ("Assets", "资产"), + ("Auto", "自动"), + ("Automatic (from the mesh UVs)", "自动(基于网格 UV)"), + ("Autosave every", "自动保存间隔"), + ( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + "自动保存、智能材质、预设、模板和界面布局都保存在数据文件夹中。新文件夹在重启后生效;已保存的文件保留在原处。", + ), + ("Axis", "轴"), + ("Back to painting", "返回绘画"), + ("Backface culling", "背面剔除"), + ("Bake an ID map (F8) to pick colors from the mesh.", "烘焙 ID 贴图(F8)以从网格上拾取颜色。"), + ("Bake Mesh Maps", "烘焙网格贴图"), + ("Bake mesh maps", "烘焙网格贴图"), + ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "烘焙网格贴图(F8)以用于基于曲率、AO 和厚度的生成器。"), + ("Baked Lighting", "烘焙光照"), + ("Baking", "烘焙"), + ("Base color", "基础色"), + ( + "Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).", + "基础色为漫反射颜色,高光为 F0 颜色,光泽度为 1 - 粗糙度(请在纹理集设置中添加这些通道)。", + ), + ("Base color, Metallic, Roughness and Specular level.", "基础色、金属度、粗糙度和高光强度。"), + ("Based on each texture set's size", "基于各纹理集的尺寸"), + ("Basic settings", "基本设置"), + ("Bent Normals", "弯曲法线"), + ("Bevel", "斜角"), + ("Black", "黑色"), + ("Blending", "混合"), + ("Blending mode of the displayed channel", "所显示通道的混合模式"), + ("Blur", "模糊"), + ("Blur Directional", "方向模糊"), + ("Blur and sharpen", "模糊与锐化"), + ("Bounces", "反弹次数"), + ("Bricks", "砖块"), + ("Brush", "笔刷"), + ("Brush size", "笔刷大小"), + ("Brush size down / up", "减小 / 增大笔刷大小"), + ("Brushed lines", "拉丝"), + ("Built-in (read-only): duplicate it to edit", "内置(只读):创建副本后即可编辑"), + ("Built-in templates are read-only: duplicate one to edit it", "内置模板为只读:创建副本后即可编辑"), + ("Built-in: {mesh}", "内置:{mesh}"), + ("Cage: {name}", "笼体:{name}"), + ("Camera", "相机"), + ("Colors", "颜色"), + ("Go to camera 1", "转到相机 1"), + ("Go to camera 2", "转到相机 2"), + ("Go to camera 3", "转到相机 3"), + ("Go to camera 4", "转到相机 4"), + ("Go to camera 5", "转到相机 5"), + ("Go to camera 6", "转到相机 6"), + ("Go to camera 7", "转到相机 7"), + ("Go to camera 8", "转到相机 8"), + ("Go to camera 9", "转到相机 9"), + ("Camera settings", "相机设置"), + ("Cancel", "取消"), + ("Cancel the stroke", "取消笔画"), + ("Cell size (texels at 2K)", "单元大小(2K 下的纹素数)"), + ("Cells", "细胞"), + ("Channel", "通道"), + ("Channel source: uniform value, procedural, image or anchor", "通道来源:统一值、程序纹理、图像或锚点"), + ("Channels", "通道"), + ("Check for Updates...", "检查更新..."), + ("Checker", "棋盘格"), + ("Clamp", "钳制"), + ("Clear", "清除"), + ("Clear mask", "清除遮罩"), + ("Clear recent projects", "清除最近的项目"), + ("Click a mesh part to show or hide the selected layer on it.", "单击网格部件,可在其上显示或隐藏所选图层。"), + ("Click the mesh to pick its material into the brush", "单击网格,将其材质吸取到笔刷中"), + ("Click the mesh to place the decal", "单击网格以放置贴花"), + ("Click, then press the new shortcut (Esc cancels)", "单击后按下新的快捷键(Esc 取消)"), + ("Clone", "仿制"), + ("Close", "关闭"), + ("Closed path", "闭合路径"), + ("Cloud", "云"), + ("Clouds", "云雾"), + ("Coat normal", "清漆法线"), + ("Coat roughness", "清漆粗糙度"), + ("Coat weight", "清漆权重"), + ("Color", "颜色"), + ("Color Balance", "色彩平衡"), + ("Color burn", "颜色加深"), + ("Color dodge", "颜色减淡"), + ("Color of the light that travels under the surface (each channel goes as far as its value)", "在表面下传播的光的颜色(各通道的传播距离取决于其值)"), + ("Color picker", "拾色器"), + ("Color selection", "颜色选择"), + ("Color to replace", "要替换的颜色"), + ("Colors near the first shift towards the second, keeping their shading.", "接近第一种颜色的颜色会在保留明暗的同时转向第二种颜色。"), + ("Colors read as gray. Add a levels or blur effect above to shape the result.", "颜色按灰度读取。可在上方添加色阶或模糊效果来调整结果。"), + ("Combine with the layer's height", "与图层高度合并"), + ("Compare mask", "比较遮罩"), + ("Compositing", "合成"), + ("Constant", "常量"), + ("Constants", "常量"), + ("Contrast", "对比度"), + ("Contrast/Luminosity", "对比度/亮度"), + ("Converted maps", "转换贴图"), + ("Copy RGB values", "复制 RGB 值"), + ("Copy effect", "复制效果"), + ("Copy from", "复制自"), + ("Copy layer(s)", "复制图层"), + ("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"), + ("Copy to all texture sets", "复制到所有纹理集"), + ("Copy what the texture set shows", "复制纹理集显示的内容"), + ("Couldn't encode the render", "无法编码渲染结果"), + ("Couldn't export textures: {error}", "无法导出纹理:{error}"), + ("Couldn't export the mesh: {error}", "无法导出网格:{error}"), + ("Couldn't export the template: {error}", "无法导出模板:{error}"), + ("Couldn't import {name}: {error}", "无法导入 {name}:{error}"), + ("Couldn't open {name}: {error}", "无法打开 {name}:{error}"), + ("Couldn't read the render back from the GPU", "无法从 GPU 读回渲染结果"), + ("Couldn't save the render: {error}", "无法保存渲染结果:{error}"), + ("Couldn't save {name}: {error}", "无法保存 {name}:{error}"), + ("Count per stamp", "每个笔印的数量"), + ("Crate", "箱子"), + ("Create", "创建"), + ("Create smart material", "创建智能材质"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "在视图中按住 Ctrl 右键拖动可调整大小和硬度,Ctrl 左键拖动可调整流量和角度。", + ), + ("Cube", "立方体"), + ("Current layer", "当前图层"), + ("Curvature", "曲率"), + ("Cut effect", "剪切效果"), + ("Cut layer(s)", "剪切图层"), + ("Cyan / red", "青色 / 红色"), + ("Cylinder", "圆柱体"), + ("Cylindrical projection", "圆柱投影"), + ("Dark to light: the content's luminance picks a color along these stops.", "从暗到亮:内容的亮度沿这些色标选取颜色。"), + ("Darken (Min)", "变暗(最小值)"), + ("Data folder", "数据文件夹"), + ("Decal", "贴花"), + ("Decal projection", "贴花投影"), + ("Default", "默认"), + ("Default camera", "默认相机"), + ("Delete the selected template", "删除所选模板"), + ("Delete this camera", "删除此相机"), + ("Deleted template \"{name}\"", "已删除模板“{name}”"), + ("Denoise", "降噪"), + ("Depth", "深度"), + ("Depth of field", "景深"), + ("Depth of field (viewport and Rendering mode)", "景深(视口和渲染模式)"), + ("Depth of the sharp plane along the view (0: the orbit center)", "清晰平面沿视线方向的深度(0:轨道中心)"), + ("Details saved to {file}", "详细信息已保存到 {file}"), + ("Difference", "差值"), + ("Dilation + default background color", "扩张 + 默认背景色"), + ("Dilation + transparent", "扩张 + 透明"), + ("Dilation infinite", "无限扩张"), + ("DirectX normal map", "DirectX 法线贴图"), + ("Dirt", "污垢"), + ("Disable", "禁用"), + ("Dismiss", "关闭"), + ("Displacement (height channel)", "置换(高度通道)"), + ("Display Settings", "显示设置"), + ("Display material", "显示材质"), + ("Display next channel", "显示下一个通道"), + ("Display next mesh map", "显示下一个网格贴图"), + ("Display previous channel", "显示上一个通道"), + ("Display previous mesh map", "显示上一个网格贴图"), + ("Distance", "距离"), + ("Distort", "扭曲"), + ("Divide", "划分"), + ("Document resolution", "文档分辨率"), + ("Documentation...", "文档..."), + ("Done on CPU: {n} / {max} samples, {s} s", "已在 CPU 上完成:{n} / {max} 采样,{s} 秒"), + ("Done on GPU: {n} / {max} samples, {s} s", "已在 GPU 上完成:{n} / {max} 采样,{s} 秒"), + ("Double-click to rename", "双击以重命名"), + ("Download as", "下载为"), + ("Downloaded {name}", "已下载 {name}"), + ("Drag onto an output channel", "拖到输出通道上"), + ("Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "拖动边框移动贴花,拖动角缩放,拖动圆形手柄旋转"), + ("Drags the layer stack's values along the stroke into the selected layer.", "沿笔画将图层堆栈的值拖入所选图层。"), + ("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"), + ("Drop an image from the Assets panel here to use it as this mesh map", "将资产面板中的图像拖放到此处,用作此网格贴图"), + ("Dry streaks", "干笔条纹"), + ("Duplicate effect", "创建效果副本"), + ("Duplicate layer(s)", "创建图层副本"), + ("Duplicate the selected template", "创建所选模板的副本"), + ("Edge Detect", "边缘检测"), + ("Edit", "编辑"), + ("Edit keyboard shortcuts...", "编辑键盘快捷键..."), + ("Edit quick mask", "编辑快速遮罩"), + ("Editing quick mask: paint where painting is allowed (U to finish)", "正在编辑快速遮罩:在允许绘画的区域绘制(按 U 完成)"), + ("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:笔画绘制在允许绘画的区域。按 U 完成。"), + ("Emissive", "自发光"), + ("Enable or disable the effect", "启用或禁用效果"), + ("Enable quick mask", "启用快速遮罩"), + ("Environment blur", "环境模糊"), + ("Environment exposure (EV)", "环境曝光(EV)"), + ("Environment map", "环境贴图"), + ("Environment opacity", "环境不透明度"), + ("Environment rotation", "环境旋转"), + ("Environment settings", "环境设置"), + ("Environment: {name}", "环境:{name}"), + ("Environments", "环境"), + ("Eraser", "橡皮擦"), + ("Exclusion", "排除"), + ("Expand or collapse the folder", "展开或折叠文件夹"), + ("Export", "导出"), + ("Export Mesh...", "导出网格..."), + ("Export Textures...", "导出纹理..."), + ("Export mesh", "导出网格"), + ("Export template", "输出模板"), + ("Export templates", "输出模板"), + ("Export textures", "导出纹理"), + ("Export the selected template (.json)", "导出所选模板(.json)"), + ("Exported mesh to {path}", "已将网格导出到 {path}"), + ("Exported template \"{name}\" to {path}", "已将模板“{name}”导出到 {path}"), + ("Exported {n} textures to {folder}", "已将 {n} 个纹理导出到 {folder}"), + ("F0 from specular level", "由高光强度生成 F0"), + ("Fabric weave", "织物编织"), + ("Field of view (deg)", "视野(度)"), + ("File", "文件"), + ("File name without extension; variables insert names", "不含扩展名的文件名;变量会插入对应名称"), + ("File type", "文件类型"), + ("Fill", "填充"), + ("Fill the closed path (lasso)", "填充闭合路径(套索)"), + ("Fill the path (close it first)", "填充路径(请先闭合)"), + ("Filter", "滤镜"), + ("Filter the remaining noise while keeping edges and texture detail", "在保留边缘和纹理细节的同时过滤剩余噪点"), + ("Filters", "滤镜"), + ("Fine noise", "细噪波"), + ("Fingerprints", "指纹"), + ("Enter a finite number", "请输入有限数值"), + ("Double-click or press Enter to edit", "双击或按 Enter 键编辑"), + ("Fit the input range to the histogram", "使输入范围适合直方图"), + ("Flatten layer", "合并图层"), + ("Flips the image's green channel, for normal maps made with Y pointing down", "翻转图像的绿色通道,用于 Y 轴朝下制作的法线贴图"), + ("Flow", "流量"), + ("Flow and opacity", "流量与不透明度"), + ("Flow jitter", "流量抖动"), + ("Focus distance", "对焦距离"), + ("Folder", "文件夹"), + ("Folders", "文件夹"), + ("Follow path", "跟随路径"), + ( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + "整个项目:设为网格贴图的法线贴图图像的读取方式(更改后请重新设置),以及导出的默认值", + ), + ("Free and open source (MIT OR Apache-2.0), written in Rust.", "免费开源(MIT OR Apache-2.0),使用 Rust 编写。"), + ("From template", "基于模板"), + ("From template / project", "基于模板 / 项目"), + ("Full", "完整"), + ("GPU error: {error}", "GPU 错误:{error}"), + ("Geometry mask", "几何遮罩"), + ( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + "GGX 高光与高度相关的 Smith 可见性项、Lambert 漫反射、拆分求和的基于图像的光照,以及球谐辐照度与地平线衰减。", + ), + ("Gamma", "伽马"), + ("General export parameters", "常规导出参数"), + ("General properties", "常规属性"), + ("Generator", "生成器"), + ("Geometry and UVs only", "仅几何体和 UV"), + ("Glossiness", "光泽度"), + ("Glossiness from roughness", "由粗糙度生成光泽度"), + ("Glow", "辉光"), + ("Gradient", "渐变"), + ("Gradient Map", "渐变映射"), + ("Gravity", "重力"), + ("Gray", "灰度"), + ("Gray + A", "灰度 + A"), + ("Gray 50%", "50% 灰"), + ("Grayscale", "灰度"), + ("Group layer(s)", "将图层编组"), + ("Grunge", "污渍"), + ("HDR environments", "HDR 环境"), + ("High Pass", "高反差保留"), + ("HSL Perceptive", "HSL 感知"), + ("Half", "1/2"), + ("Hammered", "锤纹"), + ("Hard light", "强光"), + ("Hardness", "硬度"), + ("Height", "高度"), + ("Height offset", "高度偏移"), + ("Height to normal strength", "高度转法线强度"), + ("Help", "帮助"), + ("Hide UI", "隐藏界面"), + ("High", "高"), + ("High poly: {name}", "高模:{name}"), + ("Highlights", "高光"), + ("Histogram Range", "直方图范围"), + ("Histogram Scan", "直方图扫描"), + ("Histogram Shift", "直方图偏移"), + ("History", "历史记录"), + ("Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", "按住 S:左键拖动旋转,右键拖动缩放,中键拖动移动模板。"), + ("Hold V and click the mesh to set the clone source", "按住 V 并单击网格以设置仿制源"), + ("Hold V and click the mesh to set the source, then paint elsewhere to copy it.", "按住 V 并单击网格以设置源,然后在其他位置绘画进行复制。"), + ( + "How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)", + "光在表面下传播的距离,以网格尺寸的比例表示(在绘制了散射权重通道的区域)", + ), + ( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "透射表面使光弯曲的程度(在绘制了透射通道的区域):水 1.33,玻璃 1.5,钻石 2.42", + ), + ("Hue shift (degrees)", "色相偏移(度)"), + ("ID", "ID"), + ("Image: {name}", "图像:{name}"), + ("Images", "图像"), + ("Import HDR...", "导入 HDR..."), + ("Import a template (.json)", "导入模板(.json)"), + ("Import an image (File > Import resources) to project it onto the mesh.", "导入图像(文件 > 导入资源)以将其投影到网格上。"), + ("Import resources...", "导入资源..."), + ("Import MaterialX material...", "导入 MaterialX 材质..."), + ("MaterialX materials", "MaterialX 材质"), + ("Import...", "导入..."), + ("Imported template \"{name}\"", "已导入模板“{name}”"), + ("Imported {name}", "已导入 {name}"), + ("Index of refraction", "折射率"), + ("Input high", "输入高"), + ("Input low", "输入低"), + ("Input maps", "输入贴图"), + ("Insert a variable", "插入变量"), + ("Instance", "实例"), + ("Instantiate across texture sets", "跨纹理集实例化"), + ("Intensity (texels at 2K)", "强度(2K 下的纹素数)"), + ("Interface", "界面"), + ("Interface scale", "界面缩放"), + ("Inverse Subtract", "反向减去"), + ("Inverse divide", "反向划分"), + ("Invert", "反相"), + ("Invert mask", "反相遮罩"), + ("Invert mask background", "反相遮罩背景"), + ("Invert mask value", "反相遮罩值"), + ("Invert quick mask", "反相快速遮罩"), + ("Jitters", "抖动"), + ("Join the ArtCraft community on Discord", "加入 Discord 上的 ArtCraft 社区"), + ("Join the community (Discord)...", "加入社区(Discord)..."), + ("Key light (shadow-casting light, direct only)", "主光源(投射阴影,仅直接光照)"), + ("Keyboard", "键盘"), + ("Keyboard shortcuts", "键盘快捷键"), + ("Light azimuth (degrees)", "光源方位角(度)"), + ("Light elevation (degrees)", "光源仰角(度)"), + ("Light intensity", "光照强度"), + ("LMB", "左键"), + ("Language", "语言"), + ("Layer mask", "图层遮罩"), + ("Layer memory: {mb} MB", "图层内存:{mb} MB"), + ("Layers", "图层"), + ("Lazy mouse", "平滑跟随"), + ("Lazy mouse distance", "平滑跟随距离"), + ("Leather grain", "皮革纹理"), + ("Lens size: how quickly things blur away from the focus distance", "镜头大小:远离对焦距离时物体变模糊的速度"), + ("Level", "级别"), + ("Levels", "色阶"), + ("Lifetime (steps)", "寿命(步数)"), + ("Light / direction", "光照 / 方向"), + ("Lighten (Max)", "变亮(最大值)"), + ("Lightness", "明度"), + ("Linear", "线性"), + ("Linear burn", "线性加深"), + ("Linear dodge (Add)", "线性减淡(添加)"), + ("Linear light", "线性光"), + ("List of exports", "导出列表"), + ("Load UI Layout", "加载界面布局"), + ("Loaded UI layout {path}", "已加载界面布局 {path}"), + ("Log", "日志"), + ("Low", "低"), + ("Luminosity", "亮度"), + ("MMB drag / Alt + MMB", "中键拖动 / Alt + 中键"), + ("Made by the ArtCraft team and community.", "由 ArtCraft 团队和社区打造。"), + ("Magenta / green", "洋红 / 绿色"), + ("Main shader", "主着色器"), + ("Marble veins", "大理石纹"), + ("Mask", "遮罩"), + ("Mask Editor: Edge wear", "遮罩编辑器:边缘磨损"), + ("Mask value (gray)", "遮罩值(灰度)"), + ("Mask with height", "用高度遮罩"), + ("MatFinish Grind", "表面处理:研磨"), + ("MatFinish Hammered", "表面处理:锤纹"), + ("MatFinish Raw", "表面处理:原始"), + ("MatFinish Sanded", "表面处理:砂磨"), + ("Material", "材质"), + ("Material ball", "材质球"), + ("Material finish", "材质表面处理"), + ("Materials", "材质"), + ("Maximum", "最大值"), + ("Mesh fill", "网格填充"), + ("Mesh map: {map}", "网格贴图:{map}"), + ("Mesh maps", "网格贴图"), + ("Mesh maps baked", "网格贴图已烘焙"), + ("Meshes", "网格"), + ("Metallic", "金属度"), + ("Midtones", "中间调"), + ("Minimum", "最小值"), + ("Minimum size (%)", "最小尺寸(%)"), + ("Missing (bake to create)", "缺失(烘焙以创建)"), + ("Mixed AO", "混合 AO"), + ("Mode", "模式"), + ("More in Assets > Alphas: click one, or drag it here", "“资产 > Alpha”中有更多:单击选择一个,或将其拖到此处"), + ("Mosaic", "马赛克"), + ("Move down", "下移"), + ("Move up", "上移"), + ( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + "在更精细的网格副本上按高度通道移动表面,强度与高度转法线相同(仅视口:绘制仍沿原始表面)", + ), + ("Multiply", "正片叠底"), + ("My smart materials", "我的智能材质"), + ("Name", "名称"), + ("New project", "新建项目"), + ("New project...", "新建项目..."), + ("New template", "新建模板"), + ("No GPU renderer available", "没有可用的 GPU 渲染器"), + ("No font on this system can show this language", "此系统上没有可显示该语言的字体"), + ("No outputs yet: add one above, then drag input maps onto its channels.", "尚无输出:请在上方添加一个,然后将输入贴图拖到其通道上。"), + ("No padding (passthrough)", "无扩边(直通)"), + ("Noise amount", "噪波量"), + ("Noise scale", "噪波缩放"), + ("None", "无"), + ("Normal", "法线"), + ("Normal DirectX", "法线 DirectX"), + ("Normal Invert", "法线反转"), + ("Normal OpenGL", "法线 OpenGL"), + ("Normal from height", "由高度生成法线"), + ("Normal map combine", "法线贴图合并"), + ("Normal map detail", "法线贴图细节"), + ("Color space", "色彩空间"), + ("Normal map format", "法线贴图格式"), + ("Normal map inverse detail", "法线贴图反向细节"), + ("Normal: painting uses the flat normal", "法线:绘画使用平坦法线"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 内存不足,无法完整显示纹理集“{name}”:请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 内存不足,无法完整显示 {count} 个纹理集({names}):请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", + ), + ("Not exported: no source in this texture set", "未导出:此纹理集中没有来源"), + ("Not saved: {error}", "未保存:{error}"), + ("Off", "关"), + ("Offset", "偏移"), + ("Offset right", "向右偏移"), + ("Offset up", "向上偏移"), + ("Offset {axis}", "偏移 {axis}"), + ("Offsets the textures by the height channel, at the height to normal strength", "按高度通道偏移纹理,偏移量取决于高度转法线强度"), + ("On", "开"), + ("Opacity", "不透明度"), + ("Open sample project...", "打开示例项目..."), + ("Open...", "打开..."), + ("Opened {name}", "已打开 {name}"), + ( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + "可选通道可添加清漆(清漆权重、清漆粗糙度、清漆法线)、绒光(绒光权重、颜色、粗糙度)、各向异性(各向异性强度、角度)、次表面散射(散射权重)和透射(透射)。", + ), + ("Orbit", "环绕"), + ("Orthographic", "正交"), + ("Perspective", "透视"), + ("Output directory", "输出目录"), + ("Output high", "输出高"), + ("Output low", "输出低"), + ("Output template", "输出模板"), + ("Output templates", "输出模板"), + ("Overlay", "叠加"), + ("Overlay opacity", "叠加层不透明度"), + ("PBR - Metallic Roughness (TextureCraft)", "PBR - 金属度/粗糙度(TextureCraft)"), + ("Pick color", "拾取颜色"), + ("PNG image", "PNG 图像"), + ("Padding", "扩边"), + ("Paint", "绘画"), + ("Paint chips", "掉漆"), + ("Paint on the mesh to edit the layer content.", "在网格上绘画以编辑图层内容。"), + ("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "在网格上绘画以编辑此遮罩。灰度请使用“材质”选项卡中的遮罩值。"), + ("Paint with the current tool", "使用当前工具绘画"), + ( + "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", + "已绘制图层像素 {pixels} MB,合成通道 {composites} MB,合成缓存 {cache} MB", + ), + ("Painting", "绘画"), + ("Pan", "平移"), + ("Parallax occlusion (height channel)", "视差遮蔽(高度通道)"), + ("Partial mask values follow the layer's height: high parts show first", "部分遮罩值跟随图层高度:较高部分先显示"), + ("Particle brush (slides down the surface)", "粒子笔刷(沿表面向下滑动)"), + ("Particle brush: particles slide down the surface", "粒子笔刷:粒子沿表面向下滑动"), + ("Particles", "粒子"), + ("Passthrough", "穿透"), + ("Paste as instance", "粘贴为实例"), + ("Paste effect", "粘贴效果"), + ("Paste layer(s)", "粘贴图层"), + ("Path", "路径"), + ("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "路径:单击添加点,单击曲线插入点,拖动移动点,Enter 应用,Esc 取消", + ), + ("Pattern scale", "图案缩放"), + ("Perlin noise", "柏林噪波"), + ("Pick focus in the viewport", "在视口中拾取焦点"), + ("Pin light", "点光"), + ("Place on the surface", "放置在表面上"), + ("Place path points on the mesh", "在网格上放置路径点"), + ("Planar projection", "平面投影"), + ("Plane", "平面"), + ("Polygon fill", "多边形填充"), + ("Pores", "毛孔"), + ("Position", "位置"), + ("Position gradient", "位置渐变"), + ("Position jitter", "位置抖动"), + ("Posterize", "色调分离"), + ("Press a key...", "请按下一个键..."), + ("Project", "项目"), + ("Project Configuration...", "项目配置..."), + ("Project opened", "项目已打开"), + ("Project template", "项目模板"), + ("Projection", "投影"), + ("Projects and meshes", "项目和网格"), + ("Properties", "属性"), + ("Quarter", "1/4"), + ("Quick mask", "快速遮罩"), + ("Quit", "退出"), + ("Radius (texels at 2K)", "半径(2K 下的纹素数)"), + ("RENDERING", "渲染"), + ("Range", "范围"), + ("Rebind any menu item, tool or command", "重新绑定任意菜单项、工具或命令"), + ("Recent projects", "最近的项目"), + ( + "Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.", + "记录截至此图层的堆栈。上方遮罩(及填充图层)中的填充效果可将其作为来源读取。", + ), + ("Redo", "重做"), + ("Reimport mesh", "重新导入网格"), + ("Remove", "移除"), + ("Remove channel", "移除通道"), + ("Remove effect", "移除效果"), + ("Remove last", "移除最后一个"), + ("Remove layer", "移除图层"), + ("Remove layer(s)", "移除图层"), + ("Remove mask", "移除遮罩"), + ("Remove point", "移除点"), + ("Remove resource", "移除资源"), + ("Remove the shortcut", "移除快捷键"), + ("Remove this output", "移除此输出"), + ("Remove unused resources...", "移除未使用的资源..."), + ("Rename the selected template", "重命名所选模板"), + ("Render on the CPU", "在 CPU 上渲染"), + ("Rendering", "渲染"), + ("Rendering (path traced)", "渲染(路径追踪)"), + ("Rendering on CPU: {n} / {max} samples, {s} s", "正在 CPU 上渲染:{n} / {max} 采样,{s} 秒"), + ("Rendering on GPU: {n} / {max} samples, {s} s", "正在 GPU 上渲染:{n} / {max} 采样,{s} 秒"), + ("Rendering, path traced", "渲染,路径追踪"), + ("Replace", "替换"), + ("Replace Color", "替换颜色"), + ("Replacement color", "替换后的颜色"), + ("Report a bug...", "报告错误..."), + ("Rescan the library folder", "重新扫描库文件夹"), + ("Reset", "重置"), + ("Reset UI", "重置界面"), + ("Reset all", "全部重置"), + ("Reset to defaults", "恢复默认值"), + ("Reset to {shortcut}", "重置为 {shortcut}"), + ("Resizing", "正在调整大小"), + ("Restore every default shortcut", "恢复所有默认快捷键"), + ("Return to this step", "返回到此步骤"), + ("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"), + ("Rotation", "旋转"), + ("Rotation (degrees)", "旋转(度)"), + ("Roughness", "粗糙度"), + ("Roughness from glossiness", "由光泽度生成粗糙度"), + ("Round", "圆形"), + ("Rounded cube", "圆角立方体"), + ("Samples", "采样"), + ("Saturation", "饱和度"), + ("Save", "保存"), + ("Save UI Layout", "保存界面布局"), + ("Save a copy...", "保存副本..."), + ("Save as...", "另存为..."), + ("Save current layout...", "保存当前布局..."), + ("Save render...", "保存渲染结果..."), + ("Save view as camera", "将视图保存为相机"), + ("Saved UI layout {path}", "已保存界面布局 {path}"), + ("Saved {path}", "已保存 {path}"), + ("Saving UI layouts to files is available in the desktop app", "将界面布局保存到文件的功能仅在桌面版中可用"), + ("Scale", "缩放"), + ("Scale / tiling", "缩放 / 平铺"), + ("Scatter color", "散射颜色"), + ("Scatter radius", "散射半径"), + ("Scattering weight", "散射权重"), + ("Scratches", "划痕"), + ("Screen", "滤色"), + ("Screenshot of the viewport", "视口截图"), + ("Search", "搜索"), + ("Search commands or keys", "搜索命令或按键"), + ("Seed", "随机种子"), + ("Select a layer", "选择图层"), + ("Select an output template", "选择输出模板"), + ("Select source", "选择来源"), + ("Select the mask (Alt+click: show it in the viewport)", "选择遮罩(Alt+单击:在视口中显示)"), + ("Select...", "选择..."), + ("Settings", "设置"), + ("Settings...", "设置..."), + ("Shader Settings", "着色器设置"), + ("Shader instance", "着色器实例"), + ("Shadows", "阴影"), + ("Sharpen", "锐化"), + ("Sheen color", "绒光颜色"), + ("Sheen color × weight", "绒光颜色 × 权重"), + ("Sheen roughness", "绒光粗糙度"), + ("Sheen weight", "绒光权重"), + ("Shift + wheel", "Shift + 滚轮"), + ("Shortcuts list...", "快捷键列表..."), + ("Show on all parts", "在所有部件上显示"), + ("Show UV wireframe in the 2D view", "在 2D 视图中显示 UV 线框"), + ("Show entire mesh", "显示整个网格"), + ("Show log...", "显示日志..."), + ("Show or hide the layer", "显示或隐藏图层"), + ("Show or hide the texture set", "显示或隐藏纹理集"), + ("Show wireframe in the 3D view", "在 3D 视图中显示线框"), + ("Signed addition (AddSub)", "有符号相加(AddSub)"), + ("Size", "大小"), + ("Size in screen space", "屏幕空间大小"), + ("Size jitter", "大小抖动"), + ( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + "视口显示的纹理尺寸:较低的设置在大型纹理集上占用更少的 GPU 显存。绘画和导出仍使用完整分辨率。", + ), + ("Slope Blur", "坡度模糊"), + ("Slope scale", "坡度缩放"), + ("Smart masks", "智能遮罩"), + ("Smart material saved to {path}", "智能材质已保存到 {path}"), + ("Smart materials", "智能材质"), + ("Smudge", "涂抹"), + ("Soft light", "柔光"), + ("Softness", "柔和度"), + ("Source", "来源"), + ("Source U {u} V {v}", "源 U {u} V {v}"), + ("Spacing", "间距"), + ("Specular", "高光"), + ("Specular level", "高光强度"), + ("Sphere", "球体"), + ("Spherical projection", "球面投影"), + ("Spray", "喷溅"), + ("Square", "方形"), + ("Stamp depth", "笔印深度"), + ("Star", "星形"), + ("Starting render...", "正在开始渲染..."), + ("Stencil", "模板"), + ("Steps", "步数"), + ("Streaks", "条纹"), + ("Strength", "强度"), + ("Stripes", "条带"), + ("Stroke opacity", "笔画不透明度"), + ("Subsampling 2x2", "2x2 子采样"), + ("Subsampling 4x4", "4x4 子采样"), + ("Subsampling 8x8", "8x8 子采样"), + ("Subsurface scattering", "次表面散射"), + ("Subtract", "减去"), + ("Tangent | Wrap", "切线 | 包裹"), + ("Temporal anti-aliasing (refines the 3D view while it is still)", "时间抗锯齿(在 3D 视图静止时逐步细化)"), + ("Texture Sets", "纹理集"), + ("Texture Set Settings", "纹理集设置"), + ("Texture resolution", "纹理分辨率"), + ("Texture set channels", "纹理集通道"), + ("Texture sets", "纹理集"), + ("TextureCraft had to close:", "TextureCraft 不得不关闭:"), + ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - 金属度/粗糙度"), + ("TextureCraft PBR - Specular Glossiness", "TextureCraft PBR - 高光/光泽度"), + ("TextureCraft project", "TextureCraft 项目"), + ("TextureCraft project or mesh", "TextureCraft 项目或网格"), + ("Textures", "纹理"), + ("Textures embedded; for game engines and most viewers", "嵌入纹理;适用于游戏引擎和大多数查看器"), + ("Textures packaged; for USD tools and AR Quick Look", "打包纹理;适用于 USD 工具和 AR Quick Look"), + ("The GPU couldn't render this scene: {error}", "GPU 无法渲染此场景:{error}"), + ("The bake worker stopped", "烘焙进程已停止"), + ("The eraser removes paint from the enabled channels.", "橡皮擦会从已启用的通道中移除颜料。"), + ("The first stroke sets the offset from the source.", "第一笔会设定与源的偏移。"), + ( + "The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.", + "图像的 Alpha 决定贴花的形状;背向的面和超出其深度的表面不受影响。", + ), + ("The next click in the 3D view moves the decal there", "在 3D 视图中下一次单击会将贴花移到该处"), + ("The resize worker stopped", "调整大小的进程已停止"), + ("Thickness", "厚度"), + ("Thin areas", "薄区域"), + ("Threshold", "阈值"), + ("Tile", "平铺"), + ("Tiles", "瓷砖"), + ("Tint", "着色"), + ("Toggle mask", "切换遮罩"), + ("Tolerance", "容差"), + ("Tone mapping", "色调映射"), + ("Tools", "工具"), + ("Torus", "圆环"), + ("Transmission", "透射"), + ("Tri-planar projection", "三平面投影"), + ("Triangle fill", "三角形填充"), + ("UDIM plane", "UDIM 平面"), + ("UDIM tiles painted by this texture set, each at the set's size", "此纹理集绘制的 UDIM 图块,每个都使用纹理集的尺寸"), + ("UI layout", "界面布局"), + ("UI layout: {error}", "界面布局:{error}"), + ("UI layouts", "界面布局"), + ("UI {ms} ms", "界面 {ms} ms"), + ("USD binary, textures alongside", "USD 二进制,纹理单独存放"), + ("USD text, textures alongside", "USD 文本,纹理单独存放"), + ("USDZ with textures", "带纹理的 USDZ"), + ("UV checker", "UV 棋盘格"), + ("UV island fill", "UV 岛填充"), + ("UV transformations", "UV 变换"), + ("UV projection", "UV 投影"), + ("UV tiles", "UV 图块"), + ("UV tiles (UDIM)", "UV 图块(UDIM)"), + ("Undo", "撤销"), + ("Uniform value", "统一值"), + ("Use an equirectangular .hdr or .exr image as the environment", "使用等距柱状投影的 .hdr 或 .exr 图像作为环境"), + ("Use the control channel or `texturecraft-cli render` for screenshots", "截图请使用控制通道或 `texturecraft-cli render`"), + ("Value", "值"), + ("Version {version}", "版本 {version}"), + ("Version: {version} ({gpu})", "版本:{version}({gpu})"), + ("View through this camera", "通过此相机查看"), + ("Viewer settings", "查看器设置"), + ("Viewport", "视口"), + ("Viewport and brush (fixed)", "视口与笔刷(固定)"), + ("Views", "视图"), + ("Vivid light", "亮光"), + ("Voronoi", "沃罗诺伊"), + ("Warp", "变形"), + ("Warp Directional", "方向变形"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ(含 MTL),纹理单独存放"), + ( + "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", + "此浏览器不支持 WebGPU,因此 TextureCraft 使用 WebGL2 运行:渲染模式在 CPU 上进行路径追踪(较慢),大型纹理集以降低的分辨率显示。最新版 Chrome、Edge 和 Safari 支持 WebGPU。", + ), + ("Wheel / Alt + RMB drag", "滚轮 / Alt + 右键拖动"), + ("White", "白色"), + ("Width", "宽度"), + ("Width (texels at 2K)", "宽度(2K 下的纹素数)"), + ("Window", "窗口"), + ("Wood grain", "木纹"), + ("Works in texture space, like the blur: it does not cross UV seams.", "在纹理空间中工作,与模糊相同:不会跨越 UV 接缝。"), + ("World Space Normal", "世界空间法线"), + ("Yellow / blue", "黄色 / 蓝色"), + ("Zoom", "缩放"), + ("a missing layer", "缺失的图层"), + ("aniso", "各向"), + ("aniso angle", "各向角"), + ("ao", "AO"), + ("coat", "清漆"), + ("coat nrm", "清漆法"), + ("coat rough", "清漆糙"), + ("color", "颜色"), + ("emiss", "发光"), + ("glTF binary with textures", "带纹理的 glTF 二进制"), + ("gloss", "光泽"), + ("height", "高度"), + ("metal", "金属"), + ("min", "分钟"), + ("missing", "缺失"), + ("missing source", "缺少来源"), + ("no GPU", "无 GPU"), + ("none", "无"), + ("nrm", "法线"), + ("off", "关"), + ("op", "不透明"), + ("rough", "粗糙"), + ("scatter", "散射"), + ("sheen", "绒光"), + ("sheen color", "绒光色"), + ("sheen rough", "绒光糙"), + ("spec", "高光强"), + ("specular", "高光"), + ("transm", "透射"), + ("{action} (undone)", "{action}(已撤销)"), + ("{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}:添加到所选图层上方(或将其拖入图层堆栈或视口)"), + ("{name} copy", "{name} 副本"), + ("{n} bits", "{n} 位"), + ( + "{n} control points. Click the mesh (or the 2D view) to add points and drag them to adjust; click the first point to close the path. Enter paints it with the brush (a closed, filled path fills its inside), Esc cancels.", + "{n} 个控制点。单击网格(或 2D 视图)添加控制点,拖动可调整;单击第一个点可闭合路径。按 Enter 用笔刷绘制路径(闭合且填充的路径会填充内部),按 Esc 取消。", + ), + ("{n} items share a shortcut; the first one listed wins.", "{n} 个项目共用一个快捷键;列表中第一个生效。"), + ("{pattern} (scale {scale}, seed {seed})", "{pattern}(缩放 {scale},种子 {seed})"), + ("Template name", "模板名称"), + ("Save current project as template", "将当前项目保存为模板"), + ("Distribution", "分布"), + ("Cosine", "余弦"), + ("Uniform", "均匀"), + ("Normalization", "归一化"), + // Settings › Interface: brightness and accent color. + ("Brightness", "亮度"), + ("Dark", "深色"), + ("Medium dark", "中等深色"), + ("Medium light", "中等浅色"), + ("Light", "浅色"), + ("Accent color", "强调色"), + ("Copper", "铜色"), + ("Coral", "珊瑚色"), + ("Blue", "蓝色"), + ("Violet", "紫罗兰色"), + ("Green", "绿色"), + ("Amber", "琥珀色"), + ("Pink", "粉色"), + ("Minimize", "最小化"), + ("Maximize", "最大化"), + ("Restore", "还原"), + ("Title bar", "标题栏"), + ("System title bar (applies on restart)", "系统标题栏(重启后生效)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", + ), + ("Brushes", "笔刷库"), + ("Brush name", "笔刷名称"), + ("Save current brush", "保存当前笔刷"), + ("Start window", "启动窗口"), + ("Show at startup", "启动时显示"), + ("Continue with the sample project", "继续使用示例项目"), + ("No recent projects yet", "暂无最近的项目"), + ("Text", "文字"), + ("Font", "字体"), + ("Style", "样式"), + ("Use as brush alpha", "用作笔刷 Alpha"), + ("Place as decal", "作为贴花放置"), + ("Click: turn this channel on or off. Alt+click: this channel only", "单击:打开或关闭此通道。Alt+单击:仅此通道"), + ("Show all", "全部显示"), + ("Hide all", "全部隐藏"), + ("Invert show/hide", "反转显示/隐藏"), + ("Show or hide texture sets", "显示或隐藏纹理集"), + ("Focus: show only the active texture set", "聚焦:仅显示当前纹理集"), + ("Unsaved changes", "未保存的更改"), + ("Don't save", "不保存"), + ("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"), + ("Radius", "半径"), + ("Remove skew correction", "移除倾斜校正"), + ("Twill weave", "斜纹织物"), + ("Save the changes to {name} first?", "是否先保存对 {name} 的更改?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "路径始终可编辑:选择一条路径来移动其控制点或更改其笔刷和材质,子图层会立即重绘。使用路径工具添加路径。", + ), + ("Import material...", "导入材质..."), + ("MaterialCraft material", "MaterialCraft 材质"), + ("Cooked at {size} px", "已按 {size} px 计算"), + ("Preset", "预设"), + ("Re-cook", "重新计算"), + ("Open in MaterialCraft", "在 MaterialCraft 中打开"), + ( + "Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back", + "已在 MaterialCraft 中打开:在其中使用“文件 > 发送到 TextureCraft”即可带回更改", + ), + ("Parameters change in the desktop app, with MaterialCraft installed", "参数可在安装了 MaterialCraft 的桌面版中修改"), + ("Add High-Poly Meshes", "添加高模网格"), + ("All", "全部"), + ("Apply Diffusion", "应用扩散"), + ("Attenuation", "衰减"), + ("Auto Tonemapping", "自动色调映射"), + ("Average Normals", "平均法线"), + ("BBox", "包围盒"), + ("BSphere", "包围球"), + ("Mesh Map Bakers", "网格贴图烘焙器"), + ("Common Settings", "通用设置"), + ("Mesh Map Settings", "网格贴图设置"), + ("Check All", "全选"), + ("No Parameters", "无参数"), + ("Bake Selected Textures ({n})", "烘焙所选纹理({n})"), + ("By Mesh Name", "按网格名称"), + ("Cage", "笼形"), + ("Cage Scene", "笼形场景"), + ("Cage Type", "笼形类型"), + ("Color Generator", "颜色生成器"), + ("Color Source", "颜色来源"), + ("Common Parameters", "通用参数"), + ("Custom File", "自定义文件"), + ("Details", "细节"), + ("Dilation Width", "扩张宽度"), + ("Distance-Based", "基于距离"), + ("Edge Contrast", "边缘对比度"), + ("Edge Distance", "边缘距离"), + ("Edge Protection", "边缘保护"), + ("Enable Seams", "启用接缝"), + ("File ID", "文件 ID"), + ("Full Scene", "整个场景"), + ("Generate from Mesh", "从网格生成"), + ("Generate from Normal Map", "从法线贴图生成"), + ("Ground Plane", "地平面"), + ("Ground Plane Offset", "地平面偏移"), + ("High Poly Mesh Suffix", "高模网格后缀"), + ("High Poly Scene", "高模场景"), + ("High-Poly Parameters", "高模参数"), + ("Hue Shift", "色相偏移"), + ("Ignore Backface", "忽略背面"), + ("Ignore Backface Suffix", "忽略背面后缀"), + ("Include in Bake", "包含在烘焙中"), + ("Load Cage", "加载笼形"), + ("Lock Output Size", "锁定输出尺寸"), + ("Low Poly Mesh Suffix", "低模网格后缀"), + ("Manual", "手动"), + ("Material Color", "材质颜色"), + ("Max Frontal Distance", "最大前向距离"), + ("Max Occluder Distance", "最大遮挡物距离"), + ("Max Rear Distance", "最大后向距离"), + ("Mesh ID", "网格 ID"), + ("Method", "方法"), + ("Min Occluder Distance", "最小遮挡距离"), + ("Never", "从不"), + ("No High-Poly Meshes", "无高模网格"), + ("Normalization Scale", "归一化范围"), + ("Normalization Type", "归一化类型"), + ("Only Same Mesh Name", "仅相同网格名称"), + ("Output Size", "输出尺寸"), + ("Match", "匹配"), + ("Skew Correction Method", "偏斜校正方法"), + ("Mesh Normals Based", "基于网格法线"), + ("Face Normals Based", "基于面法线"), + ("Reset Painted Cage", "重置绘制的笼形"), + ("Paint Cage", "绘制笼形"), + ("Paint Skew Correction", "绘制倾斜校正"), + ("Per Material", "按材质"), + ("Random", "随机"), + ("Relative to Bounding Box", "相对于包围盒"), + ("Relative to Low Mesh", "相对于低模网格"), + ("Relative to Min/Max", "相对于最小值/最大值"), + ("Relative to Ray Distances", "相对于射线距离"), + ("Remove Cage", "移除笼形"), + ("Remove Skew Correction", "移除倾斜校正"), + ("Restore Defaults", "恢复默认值"), + ("Return to Painting Mode", "返回绘画模式"), + ("Sampling Radius", "采样半径"), + ("Scaling Divisor", "缩放除数"), + ("Seams Intensity", "接缝强度"), + ("Secondary Rays", "二次光线"), + ("Self Intersection", "自相交"), + ("Self Occlusion", "自遮蔽"), + ("Skew Correction", "倾斜校正"), + ("Smooth", "平滑"), + ("Spread Angle", "扩散角度"), + ("Submesh", "子网格"), + ("Use Low Poly Mesh as High Poly Mesh", "将低模用作高模"), + ("Value Bounds Max", "值上限"), + ("Value Bounds Min", "值下限"), + ("Vertex Color", "顶点颜色"), + ("Select the layer content", "选择图层内容"), + ("Paint layer", "绘画图层"), + ("Fill layer", "填充图层"), + ("1 effect", "1 个效果"), + ("{count} effects", "{count} 个效果"), + ("Mask effects", "遮罩效果"), + ("Content effects", "内容效果"), + ("Fold or unfold these effects", "折叠或展开这些效果"), + ("Remove resolution override", "移除分辨率覆盖"), + ("Texture set resolution", "纹理集分辨率"), + ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Angle span", "角度范围"), + ("Axis position", "轴位置"), + ("Count", "数量"), + ("Display", "显示"), + ("Hide while painting", "绘制时隐藏"), + ("Manipulator size", "操纵器大小"), + ("Mirror symmetry", "镜像对称"), + ("Radial settings", "径向设置"), + ("Radial symmetry", "径向对称"), + ("Show axis", "显示轴"), + ("Show axis position manipulator", "显示轴位置操纵器"), + ("Show cursor", "显示光标"), + ("Show intersection", "显示交线"), + ("Show plane", "显示平面"), + ("Symmetry", "对称"), + ("Symmetry color display", "对称显示颜色"), + ("Symmetry settings", "对称设置"), + ("Type", "类型"), + ("Advanced settings", "高级设置"), + ("Import baked maps", "导入已烘焙贴图"), + ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), + ("Add...", "添加..."), + ("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"), + ("Not imported: {files}", "未导入:{files}"), + ("Baking Visualization", "烘焙可视化"), + ("Show for Selected Texture Set Only", "仅显示所选纹理集"), + ("High Definition Mesh (HP)", "高模网格 (HP)"), + ("UV Seams", "UV 接缝"), + ("Project Mesh (LP)", "投射网格 (LP)"), + ("Edges", "边缘"), + ("Cavities", "凹陷"), + ("Edges and cavities", "边缘和凹陷"), + ("Raw curvature", "原始曲率"), + ("Detail sizes", "细节尺寸"), + ("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", "按烘焙原样读取曲率贴图:更改模式或尺寸会启用细节尺寸。"), + ("A click fills what is under it; a dragged rectangle fills what it selects as it grows", "单击填充其下方的内容;拖出的矩形在扩大时填充其选中的内容"), + ("Contained center: fill polygons whose center is in the rectangle", "包含中心:填充中心位于矩形内的多边形"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:填充绘制在允许绘画的区域。按 U 完成。"), + ("Fill mode", "填充模式"), + ("Fill only polygons the camera sees (3D view)", "仅填充相机可见的多边形(3D 视图)"), + ("Hit-test", "命中测试"), + ("How a rectangle selects polygons", "矩形选择多边形的方式"), + ("Intersection: fill polygons the rectangle touches", "相交:填充矩形触及的多边形"), + ("Rectangle fill", "矩形填充"), + ("Select a paint layer or a layer's mask to fill", "选择要填充的绘画图层或图层遮罩"), + ("Selection mode", "选择模式"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形填充单个三角形,多边形填充整个四边形和 n 边形,网格填充相连的几何体,UV 岛填充 UV 岛", + ), + ("Visible polygons only", "仅可见多边形"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), + ("The file dialog couldn't be shown: {error}", "无法显示文件对话框:{error}"), + ("The project changed while the dialog was open, so nothing was done", "对话框打开期间项目已更改,因此未执行任何操作"), + ("Cores kept for the UI", "为界面保留的核心数"), + ("Max RAM while saving", "保存时的最大内存"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存使用其余核心,并最多占用这一比例的可用内存。至少始终有一个核心工作。", + ), + ("Max project size on open", "打开项目的大小上限"), + ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), + ("Filter by type", "按类型筛选"), + ("All libraries", "所有库"), + ("Browse folders", "浏览文件夹"), + ("Starter assets", "内置资源"), + ("Your assets", "我的资源"), + ("Reset query", "重置查询"), + ("Refresh", "刷新"), + ("Saved searches", "已保存的搜索"), + ("Save the current search", "保存当前搜索"), + ("Delete", "删除"), + ("Filter by path", "按路径筛选"), + ("Hide non-applicable folders", "隐藏不适用的文件夹"), + ("Thumbnail size", "缩略图大小"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "列表"), + ("Procedurals", "程序纹理"), +]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..1196947d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,8 @@ mod bake_job; pub mod bake_mode; mod bake_scene; +#[cfg(not(target_arch = "wasm32"))] +mod brush_preset_save; mod color_selection_editor; pub mod control; mod decal_drop; @@ -20,7 +22,9 @@ pub mod export_templates; pub mod file_dialogs; mod filter_slot; pub mod fonts; +mod generator_panel; pub mod gpu; +mod grid_tile; pub mod i18n; pub mod id_color_pick; pub mod keymap; @@ -46,8 +50,16 @@ pub mod render_mode; mod resource_picker; mod resource_picker_item; mod running_bake; +pub mod saved_search; +mod screen_color_pick; pub mod shelf; +mod shelf_entry; +mod shelf_folders; +pub mod shelf_panes; pub mod shelf_preview; +mod shelf_tabs; +mod shelf_toolbar; +pub mod shelf_view; mod soft_box; pub mod state; pub mod symmetry; @@ -327,7 +339,7 @@ impl TextureCraftApp { } let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -393,6 +405,15 @@ impl TextureCraftApp { return; }; + if job.mesh_id != self.session.mesh_id { + // The mesh was swapped under the job: stop it and drop its result. + if let Some(running) = &job.current { + running.progress.cancel.store(true, Ordering::Relaxed); + } + self.bake = None; + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); if let Some(running) = &job.current { let set_index = running.set_index; @@ -550,7 +571,7 @@ fn spawn_worker(name: &str, f: impl FnOnce() -> T + Send + 's let _ = tx.send(f()); }); if let Err(e) = spawned { - // The receiver reports a stopped worker. + // The receiver reports a stopped worker log::warn!("could not start {name}: {e}"); } rx @@ -558,7 +579,7 @@ fn spawn_worker(name: &str, f: impl FnOnce() -> T + Send + 's #[cfg(target_arch = "wasm32")] fn spawn_worker(_name: &str, f: impl FnOnce() -> T + Send + 'static) -> std::sync::mpsc::Receiver { - // shortcut: no threads on the web; the work runs on the UI thread (the window pauses). + // Web builds run the work synchronously because threads are unavailable let (tx, rx) = std::sync::mpsc::channel(); let _ = tx.send(f()); rx @@ -673,6 +694,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.poll_resize(ctx); self.poll_link_cooks(ctx); + self.thumbs.sync_images(&self.session.images, self.session.revision); // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); if focused && !self.focused { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 72d78b34..b5bafea5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -4,6 +4,7 @@ use egui::{Key, Modifiers}; use serde_json::{Value, json}; +use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::i18n::tr; @@ -110,7 +111,7 @@ fn is_ui(id: &str) -> bool { id.starts_with("ui.") } -/// Whether an item can run now. +/// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if let Some(panel) = crate::docking::view_panel(id) { return panel.available_in(app.ui.mode); @@ -123,7 +124,14 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if is_ui(id) { return true; } - texturecraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok()) + + // Scripts may pick any tool, but the shelf and its shortcuts offer only those that can act + let tool = id.strip_prefix("tool.").and_then(|tool_id| Tool::ALL.into_iter().find(|tool| tool.id() == tool_id)); + if tool.is_some_and(|tool| !app.session.tool_usable(tool)) { + return false; + } + + texturecraft_engine::find(id).is_some_and(|command| (command.enabled)(&app.session).is_ok()) } /// Whether an id is implemented at all (parity report). diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 9b753b74..7e6469d6 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -153,44 +153,84 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { preview } -/// Preview the brush along an S curve in an `n`-pixel square -pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { - let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = n as f32 * 0.11; - let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); - let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); - let mut cover = vec![0f32; n * n]; - // Stable jitter keeps the preview reproducible - let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; - let step = (b.spacing * 2.0 * radius).max(0.5); +/// Preview the brush along an S curve in a `size_px` square +pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage { + // Leave room around the S curve and cap work for a single preview + const STROKE_RADIUS_FRACTION: f32 = 0.11; + const CURVE_SAMPLE_STEP: f32 = 0.002; + const MIN_STAMP_SPACING_PX: f32 = 0.5; + const MAX_STAMPS: u32 = 2000; + const CURVE_HORIZONTAL_INSET: f32 = 0.15; + const CURVE_HORIZONTAL_SPAN: f32 = 0.7; + const CURVE_WAVE_AMPLITUDE: f32 = 0.22; + + let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let radius = size_px as f32 * STROKE_RADIUS_FRACTION; + let shape = Shape { alpha: brush.alpha, image, library, level: 0 }.at_radius(radius); + + // The horizontal inset and vertical wave keep the S curve inside the swatch + let curve = |t: f32| { + ( + size_px as f32 * (CURVE_HORIZONTAL_INSET + CURVE_HORIZONTAL_SPAN * t), + size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()), + ) + }; + let mut cover = vec![0f32; size_px * size_px]; + + // Odd multipliers decorrelate reproducible jitter across stamps and channels + let jitter_sample = |stamp_index: u32, channel: u32| { + (stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32 + }; + let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX); let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); let mut last = curve(0.0); - while t <= 1.0 && i < 2000 { + + while t <= 1.0 && i < MAX_STAMPS { let p = curve(t); travelled += (p.0 - last.0).hypot(p.1 - last.1); last = p; - t += 0.002; + t += CURVE_SAMPLE_STEP; if travelled < step { continue; } travelled = 0.0; i += 1; - let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); - let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); - let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); - let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); + let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1)); + let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; + let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2); + let (cx, cy) = ( + p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0), + p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0), + ); + let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5)); let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); - let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); + let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px)); + let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px)); for y in y0..y1 { for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); - let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; - let c = &mut cover[y * n + x]; - *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); + let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius); + let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow; + let coverage = &mut cover[y * size_px + x]; + *coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0)); } } } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) + ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect()) +} + +/// Environment `name`'s panorama across a `size²` swatch, transparent above and below +pub fn environment_image(name: &str, size: usize) -> ColorImage { + let panorama = texturecraft_render::ibl::environment(name, u32::try_from(size).unwrap_or(u32::MAX)); + let (width, height) = (panorama.width as usize, panorama.height as usize); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let top = size.saturating_sub(height) / 2; + for (y, row) in panorama.data.chunks(width.max(1)).enumerate() { + for (x, linear) in row.iter().enumerate().take(size) { + let Some(pixel) = image.pixels.get_mut((top + y) * size + x) else { continue }; + + let [r, g, b] = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + *pixel = Color32::from_rgb(r, g, b); + } + } + image } diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index c979e3e4..e58901b4 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -206,7 +206,13 @@ mod tests { let mut answers = HashMap::new(); let start = Instant::now(); - while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { + // Instrumented orb baking can take several minutes on coverage runners. + let timeout = if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + Duration::from_secs(120) + }; + while answers.len() < requests_sent && start.elapsed() < timeout { answers.extend(worker.poll()); std::thread::sleep(Duration::from_millis(10)); } diff --git a/crates/ui-egui/src/saved_search.rs b/crates/ui-egui/src/saved_search.rs new file mode 100644 index 00000000..ec6181b8 --- /dev/null +++ b/crates/ui-egui/src/saved_search.rs @@ -0,0 +1,12 @@ +//! A shelf query the user saved in the Saved searches pane + +use serde::{Deserialize, Serialize}; + +/// The search text, tab and library folder of a saved shelf query, under the name it lists as +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SavedSearch { + pub name: String, + pub filter: String, + pub tab: usize, + pub path: Vec, +} diff --git a/crates/ui-egui/src/screen_color_pick.rs b/crates/ui-egui/src/screen_color_pick.rs new file mode 100644 index 00000000..3cd752d5 --- /dev/null +++ b/crates/ui-egui/src/screen_color_pick.rs @@ -0,0 +1,94 @@ +//! An eyedropper button: after it is pressed, the next click anywhere in the window picks the color shown there + +use std::sync::{Arc, Mutex}; + +use egui::{Id, Pos2, Ui}; +use egui_phosphor::regular as icon; + +use crate::widgets::icon_button; + +/// Where the pick in progress is kept between frames +const PICK_ID: &str = "screen_color_pick"; + +/// Where a screenshot callback leaves the sampled sRGB color for the button that asked for it +type SampledSlot = Arc>>; + +/// The pick in progress: which button started it, and the color its screenshot sampled once that arrives +#[derive(Clone, Default)] +struct ScreenColorPick { + target: Option, + /// Filled by the screenshot callback with the target and the sRGB color under the click + sampled: SampledSlot, +} + +/// An eyedropper button for the linear RGB color `linear`, `size` points square; a picked color lands in `linear` a frame or two after the click +pub fn eyedropper(ui: &mut Ui, id: Id, linear: &mut [f32; 3], tooltip: &str, size: f32) { + let key = Id::unique(PICK_ID); + let mut pick: ScreenColorPick = ui.data(|data| data.get_temp(key)).unwrap_or_default(); + let picking = pick.target == Some(id); + + let button = icon_button(ui, icon::EYEDROPPER, tooltip, picking, size); + if button.clicked() { + pick.target = if picking { None } else { Some(id) }; + } else if picking { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + let (clicked, escaped, pointer) = + ui.input(|input| (input.pointer.primary_clicked(), input.key_pressed(egui::Key::Escape), input.pointer.interact_pos())); + if escaped { + pick.target = None; + } else if clicked && let Some(point) = pointer { + request_sample(ui.ctx(), id, point, pick.sampled.clone()); + pick.target = None; + } + } + + let landed = pick.sampled.lock().ok().and_then(|mut sampled| sampled.take_if(|(target, _)| *target == id)); + if let Some((_, srgb)) = landed { + *linear = srgb.map(|channel| texturecraft_engine::texel::srgb_to_linear(f32::from(channel) / 255.0)); + } + + ui.data_mut(|data| data.insert_temp(key, pick)); +} + +/// Screenshot the next frame and put the color at `point` (in points) into `sampled` for `target` +fn request_sample(ctx: &egui::Context, target: Id, point: Pos2, sampled: SampledSlot) { + let pixels_per_point = ctx.pixels_per_point(); + let repaint = ctx.clone(); + let callback = egui::ScreenshotCallback::new(move |image| { + if let (Some(color), Ok(mut slot)) = (pixel_at(&image, point, pixels_per_point), sampled.lock()) { + *slot = Some((target, color)); + } + repaint.request_repaint(); + }); + ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback)); + ctx.request_repaint(); +} + +/// The sRGB color of `image` under `point` (in points at `pixels_per_point`); `None` outside it +fn pixel_at(image: &egui::ColorImage, point: Pos2, pixels_per_point: f32) -> Option<[u8; 3]> { + let (x, y) = ((point.x * pixels_per_point).floor(), (point.y * pixels_per_point).floor()); + let [width, height] = image.size; + if !(x >= 0.0 && y >= 0.0 && (x as usize) < width && (y as usize) < height) { + return None; + } + + let color = image.pixels.get(y as usize * width + x as usize)?; + Some([color.r(), color.g(), color.b()]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pixel_under_the_point_is_sampled_at_the_display_scale() { + let mut image = egui::ColorImage::filled([4, 2], egui::Color32::BLACK); + image.pixels[4 + 3] = egui::Color32::from_rgb(10, 20, 30); + + assert_eq!(pixel_at(&image, egui::pos2(1.6, 0.6), 2.0), Some([10, 20, 30])); + assert_eq!(pixel_at(&image, egui::pos2(0.2, 0.2), 2.0), Some([0, 0, 0])); + for outside in [egui::pos2(-0.1, 0.0), egui::pos2(2.0, 0.0), egui::pos2(0.0, 1.0), egui::pos2(f32::NAN, 0.0)] { + assert_eq!(pixel_at(&image, outside, 2.0), None, "{outside:?}"); + } + } +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9a36df2a..c32de5f6 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -1,40 +1,49 @@ -//! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart -//! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. -//! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas -//! and textures drag onto the layer stack, a layer row, the viewport or the brush properties -//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu +//! The Assets panel: built-in, saved and project assets in one grid by type, library and search, dragged onto the layer stack, the views or the brush use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::ProceduralKind; -use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; -use texturecraft_engine::paint::alphas; -use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; -use texturecraft_engine::smart_masks::SMART_MASKS; -use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; +use crate::shelf_entry::ShelfEntry; use crate::shelf_preview::ShelfPreview; +use crate::shelf_view::ShelfView; use crate::theme::Tokens; use crate::thumbs::Thumbs; -use crate::widgets::{dnd_release, icon_button}; +use crate::widgets::dnd_release; -/// A shelf tile's size in points -const TILE_WIDTH: f32 = 72.0; -const TILE_HEIGHT: f32 = 86.0; +/// The gap between tiles in points (their sizes are [`ShelfView`]'s) +const TILE_GAP: f32 = 2.0; +/// The gap after a grid or a list of rows, in points +const SECTION_GAP: f32 = 6.0; +/// The gap between the type row and asset grid, in points +const TYPE_GRID_GAP: f32 = 4.0; +/// The saved material hint's font size, in points +#[cfg(not(target_arch = "wasm32"))] +const HINT_SIZE: f32 = 10.0; +/// The name of a saved material whose file name isn't text +const SAVED_MATERIAL_NAME: &str = "material"; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; -/// The thumbnail's size in a tile and its center below the tile's top, in points -const THUMBNAIL_SIZE: f32 = 56.0; -const THUMBNAIL_CENTER_Y: f32 = 32.0; +/// The last clicked or right-clicked tile's [`ShelfEntry::identity`], kept in egui's memory under this id +const SELECTED_TILE: &str = "shelf_selected_tile"; +/// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points +const SELECTED_OUTLINE_WIDTH: f32 = 1.5; +const IN_USE_OUTLINE_WIDTH: f32 = 1.0; +/// The randomness badge's dot radius, dot spacing and inset from the thumbnail's corner, in points +const BADGE_DOT_RADIUS: f32 = 1.3; +const BADGE_DOT_SPACING: f32 = 3.6; +const BADGE_INSET: f32 = 2.5; +/// The randomness badge's dot colour and its rim's width (points) and colour +const BADGE_DOT_FILL: Color32 = Color32::from_gray(205); +const BADGE_DOT_RIM: f32 = 0.8; +const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170); /// Loading icon size relative to the thumbnail width, and its opacity over the dim text color const LOADING_ICON_SCALE: f32 = 0.9; const LOADING_ICON_OPACITY: f32 = 0.5; @@ -56,22 +65,21 @@ pub(crate) enum Tab { Filters, Brushes, Alphas, - Procedurals, - Environments, + /// Procedural patterns and the project's images Textures, + Environments, } -/// The shelf tabs: icon and (English, translated where shown) name. -pub(crate) const TABS: [(Tab, &str, &str); 9] = [ +/// The shelf tabs: icon and (English, translated where shown) name +pub(crate) const TABS: [(Tab, &str, &str); 8] = [ (Tab::Materials, ic::SPHERE, "Materials"), (Tab::Smart, ic::STACK, "Smart materials"), (Tab::Masks, ic::CIRCLE_HALF, "Smart masks"), (Tab::Filters, ic::FUNNEL, "Filters"), (Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"), (Tab::Alphas, ic::SHAPES, "Alphas"), - (Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"), - (Tab::Environments, ic::SUN_HORIZON, "Environments"), (Tab::Textures, ic::IMAGE, "Textures"), + (Tab::Environments, ic::SUN_HORIZON, "Environments"), ]; /// A shelf asset: built in (by id), a saved smart material (file path) or an image resource. @@ -117,7 +125,7 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { && content && let Some(name) = unpainted_paint_layer(app) { - // Otherwise the filter seems to do nothing: it has nothing to change yet. + // Otherwise the filter seems to do nothing: it has nothing to change yet app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false); } return; @@ -223,55 +231,106 @@ 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 tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let mut tab = app.ui.shelf_tab.min(TABS.len() - 1); - let searching = !app.ui.shelf_filter.is_empty(); + let filter = app.ui.shelf_filter.to_lowercase(); + scan_library(app); + scan_brushes(app); + let all = ShelfEntry::all(app); + let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all)); - ui.horizontal_wrapped(|ui| { - let button_size = ui.spacing().interact_size.y; - ui.spacing_mut().item_spacing = vec2(2.0, 2.0); - for (i, (_, icon, label)) in TABS.iter().enumerate() { - if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() { - tab = i; - app.ui.shelf_filter.clear(); - } + // A folder that is gone (its last image removed) shows everything again + if !paths.iter().any(|path| path.starts_with(&app.ui.shelf_path)) { + app.ui.shelf_path.clear(); + } + + let folder = app.ui.shelf_path.clone(); + let picked_tab = app.ui.shelf_tab; + let searched: Vec = all.into_iter().filter(|entry| entry.matches(&filter)).collect(); + let mut applicable = crate::shelf_folders::paths(searched.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))); + let matching: Vec = searched.into_iter().filter(|entry| entry.in_folder(&folder)).collect(); + let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + + // Saved smart materials list under the grid rather than as tiles, so they count apart + let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + let saved_materials_matching = saved_materials_matching(app, &filter); + if in_user_library && let Some(smart) = TABS.iter().position(|(tab, _, _)| *tab == Tab::Smart).and_then(|smart| counts.get_mut(smart)) { + *smart += saved_materials_matching; + } + if saved_materials_matching > 0 && crate::shelf_tabs::shows(picked_tab, Tab::Smart) { + applicable.push(vec![crate::shelf_entry::USER.to_string()]); + } + + crate::shelf_folders::breadcrumb(app, ui, &paths); + search_field(app, ui); + crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu); + ui.add_space(TYPE_GRID_GAP); + + let tab = app.ui.shelf_tab; + let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); + let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); + entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); + + // The toolbar has its own strip at the panel's bottom, so nothing above it can push it out + let area = ui.available_rect_before_wrap(); + let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top()); + let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top)); + let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect).layout(egui::Layout::left_to_right(egui::Align::Min)), |ui| { + if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) { + ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(vec2(width, grid_rect.height())); + crate::shelf_panes::column(app, ui, &paths, &applicable); + }); + ui.separator(); } - }); - app.ui.shelf_tab = tab; + // Saved smart materials are files in the user's library, without folders of their own + let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); + grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter); + }); + ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); + drag_preview(&ctx); +} + +/// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` +fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { + let view = app.ui.shelf_view; + let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE))); + egui::ScrollArea::vertical() + .id_salt("shelf_scroll") + .auto_shrink([false, false]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible) + .max_height(height) + .show(ui, |ui| { + tiles(ui, |ui| { + for entry in entries { + let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str())); + entry_tile(app, ui, ctx, entry, view, is_selected); + } + }); + if saved_materials { + library(app, ui, filter); + } + }); +} + +/// How many of the user's saved smart materials match `filter` (none until the library is read) +fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize { + app.library.iter().flatten().filter(|path| matches(filter, &[saved_material_name(path)])).count() +} + +/// The search field: a live filter on names (and categories) with a clear button while it has text +fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); - ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY)); - }); - ui.add_space(4.0); - - let filter = app.ui.shelf_filter.to_lowercase(); - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - // Searching shows matches from every tab, each under its tab's name - for (i, (t, _, title)) in TABS.iter().enumerate() { - if filter.is_empty() && i != tab { - continue; - } - - let title = tr(title); - match t { - Tab::Materials => materials(app, ui, &ctx, &filter, false, title), - Tab::Smart => { - materials(app, ui, &ctx, &filter, true, title); - library(app, ui, &filter); - } - Tab::Masks => smart_masks(app, ui, &ctx, &filter, title), - Tab::Filters => filters(app, ui, &ctx, &filter, title), - Tab::Brushes => brushes(app, ui, &ctx, &filter, title), - Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title), - Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title), - Tab::Environments => environments(app, ui, &filter, title), - Tab::Textures => textures(app, ui, &ctx, &filter, title), - } + let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x }; + let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width); + ui.add(field); + if !app.ui.shelf_filter.is_empty() && ui.add(egui::Button::new(ic::X).frame(false)).on_hover_text(tr("Clear")).clicked() { + app.ui.shelf_filter.clear(); } }); - drag_preview(&ctx); } /// The dragged asset's name next to the pointer. @@ -290,11 +349,6 @@ pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } -fn title(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(text).strong().color(tk.text_strong)); -} - pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); @@ -303,10 +357,10 @@ pub(crate) fn header(ui: &mut Ui, text: &str) { pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP); body(ui); }); - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } /// The distinct categories of `items`, in order of first appearance. @@ -320,46 +374,38 @@ pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) out } -/// Built-in materials or smart materials, grouped by category -fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = - MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); - if shown.is_empty() { +/// Read the user's saved smart materials (desktop library folder) unless they are already listed +#[cfg(not(target_arch = "wasm32"))] +fn scan_library(app: &mut TextureCraftApp) { + if app.library.is_some() { return; } - title(ui, name); - for category in categories(&shown, |material| material.category) { - header(ui, category); - tiles(ui, |ui| { - for material in shown.iter().filter(|material| material.category == category) { - let texture = app.thumbs.material(ctx, material.id); - let asset = Asset::Material(material.id); - if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); - } + let saved_material = |path: &std::path::PathBuf| path.extension().is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT); + let mut files: Vec = + std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_material).collect()).unwrap_or_default(); + files.sort(); + app.library = Some(files); } -/// The user's saved smart materials (desktop library folder). +#[cfg(target_arch = "wasm32")] +fn scan_library(_: &mut TextureCraftApp) {} + +/// A saved smart material's name: its file name without the extension +fn saved_material_name(path: &std::path::Path) -> &str { + path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME) +} + +/// The user's saved smart materials matching `filter`, as rows under the grid #[cfg(not(target_arch = "wasm32"))] fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { - let tk = Tokens::get(ui.ctx()); - if app.library.is_none() { - let mut files: Vec = std::fs::read_dir(crate::library_dir()) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tcmat" || x == MCMAT_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.library = Some(files); - } + let tokens = Tokens::get(ui.ctx()); let files = app.library.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("material").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); + let shown: Vec<_> = files.iter().filter(|path| matches(filter, &[saved_material_name(path)])).collect(); if !filter.is_empty() && shown.is_empty() { return; } + ui.horizontal(|ui| { header(ui, tr("My smart materials")); if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { @@ -367,276 +413,174 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { } }); if files.is_empty() { - ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(10.0).color(tk.text_dim)); + ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(HINT_SIZE).color(tokens.text_dim)); } - for f in shown { - let (label, asset) = (name(f), Asset::Library(f.display().to_string())); - // MaterialCraft materials (sent from MaterialCraft) show a graph. - let glyph = if f.extension().is_some_and(|x| x == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; - let r = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { + + for path in shown { + let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string())); + + // MaterialCraft materials (sent from MaterialCraft) show a graph + let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; + let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { ui.label(crate::i18n::trf( "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", - &[("file", &f.display())], + &[("file", &path.display())], )); }); - if r.drag_started() { - r.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); + if response.drag_started() { + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); } - if r.clicked() { + if response.clicked() { apply(app, &asset); } } - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = SMART_MASKS.iter().filter(|m| matches(filter, &[m.label, m.id])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - tiles(ui, |ui| { - for m in shown { - let tex = app.thumbs.smart_mask(ctx, m.id); - let asset = Asset::SmartMask(m.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); -} - -/// The filter library, grouped: a click adds the filter to the selected layer's content (or its -/// mask when the mask is selected), a drop onto a layer to that layer's content. -fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = FILTERS.iter().filter(|f| matches(filter, &[f.label, f.group, f.id, tr(f.label), tr(f.group)])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - for group in categories(&shown, |f| f.group) { - header(ui, tr(group)); - tiles(ui, |ui| { - for f in shown.iter().filter(|f| f.group == group) { - let tex = app.thumbs.filter(ctx, f.id); - let asset = Asset::Filter(f.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); - } -} - -/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke -/// (alpha, spacing, flow, jitters…) and keeps its size. -fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect(); - if !shown.is_empty() { - title(ui, name); - for cat in categories(&shown, |p| p.category) { - header(ui, cat); - tiles(ui, |ui| { - for p in shown.iter().filter(|p| p.category == cat) { - let tex = app.thumbs.brush_preset(ctx, p); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() { - app.run("brush.preset.apply", json!({"preset": p.id})); - } - } - }); - } - } - my_brushes(app, ui, filter); -} - -/// The user's saved brush presets (desktop brushes folder) and saving the current brush there. +/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { +fn scan_brushes(app: &mut TextureCraftApp) { use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; - let dir = crate::user_dir("brushes"); - if app.brushes.is_none() { - let mut files: Vec = std::fs::read_dir(&dir) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.brushes = Some(files); - } - let files = app.brushes.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); - if !filter.is_empty() && shown.is_empty() { + + if app.brushes.is_some() { return; } - ui.horizontal(|ui| { - header(ui, tr("My brushes")); - if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { - app.brushes = None; - } - }); - for f in shown { - if ui - .add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f)))) - .on_hover_text(tr("Use this brush (keeps its size)")) - .clicked() - { - app.run("brush.preset.load", json!({"path": f.display().to_string()})); - } - } - ui.horizontal(|ui| { - let id = ui.make_persistent_id("brush_preset_name"); - let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); - ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0)); - let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); - if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { - let path = dir.join(format!("{file}.{BRUSH_EXT}")); - // A folder that can't be made fails the save, which reports it. - let _ = std::fs::create_dir_all(&dir); - if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { - new_name.clear(); - app.brushes = None; - } - } - ui.data_mut(|d| d.insert_temp(id, new_name)); - }); - ui.add_space(6.0); + + let mut files: Vec = std::fs::read_dir(crate::user_dir("brushes")) + .map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect()) + .unwrap_or_default(); + files.sort(); + app.brushes = Some(files); } #[cfg(target_arch = "wasm32")] -fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} +fn scan_brushes(_: &mut TextureCraftApp) {} -/// The built-in alpha library, grouped by category; the brush's alpha is outlined. -fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let tk = Tokens::get(ctx); - let shown: Vec<&'static alphas::LibraryAlpha> = alphas::library().iter().filter(|a| matches(filter, &[&a.label, a.category, &a.id])).collect(); - if shown.is_empty() { +/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { + // An image removed this frame has nothing to show + if let ShelfEntry::Image(name) = entry + && !app.session.images.contains_key(name) + { return; } - title(ui, name); - let brush = &app.session.tool.brush; - let current = if brush.alpha_image.is_none() { brush.alpha_library.clone() } else { None }; - for cat in categories(&shown, |a| a.category) { - header(ui, cat); - tiles(ui, |ui| { - for &a in shown.iter().filter(|a| a.category == cat) { - let tex = app.thumbs.alpha(ctx, a); - let asset = Asset::Alpha(&a.id); - let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset)); - if current.as_deref() == Some(a.id.as_str()) { - ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - if r.clicked() { - apply(app, &asset); - } + + let texture = entry.thumbnail(app, ctx); + let asset = entry.asset(); + let session = &app.session; + let response = tile_in_view( + ui, + &mut app.thumbs, + texture.as_ref(), + |thumbs| match entry { + ShelfEntry::SavedBrush(path) => Some(thumbs.saved_brush_preview(path, &session.images)), + _ => entry.preview(session), + }, + entry.label(), + asset.as_ref(), + view, + ); + + if selected || entry.in_use(app) { + let tokens = Tokens::get(ctx); + let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH }; + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tokens.accent), egui::StrokeKind::Inside); + } + + if entry.includes_randomness() { + randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); + } + + if response.clicked() || response.secondary_clicked() { + let (kind, id) = entry.identity(); + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(SELECTED_TILE), (kind.to_string(), id.to_string()))); + } + if response.clicked() { + entry.activate(app); + } + + if let ShelfEntry::Image(name) = entry { + response.context_menu(|ui| { + if ui.button(tr("Add as decal (view center)")).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } + if ui.button(tr("Remove resource")).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); } }); } } -fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec = ProceduralKind::ALL.into_iter().filter(|k| matches(filter, &[k.label(), tr(k.label())])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - tiles(ui, |ui| { - for k in shown { - let tex = app.thumbs.procedural(ctx, k); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() { - app.run("layer.add.fill", json!({"name": k.label()})); - app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); - } - } - }); -} - -fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str) { - let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - for env in shown { - let on = app.session.doc.project.display.environment == **env; - if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() { - app.run("display.set", json!({"environment": env})); - } - } - ui.add_space(6.0); -} - -fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let tk = Tokens::get(ctx); - let names: Vec = app.session.doc.resources.keys().filter(|n| matches(filter, &[n])).cloned().collect(); - if !filter.is_empty() && names.is_empty() { - return; - } - ui.horizontal(|ui| { - title(ui, name); - if ui.small_button(tr("Import...")).clicked() { - crate::menus::invoke(app, ctx, "resource.import"); - } - }); - if names.is_empty() { - ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim)); - } - tiles(ui, |ui| { - for name in names { - let Some(img) = app.session.images.get(&name).cloned() else { continue }; - - let tex = app.thumbs.image(ctx, &name, &img); - let asset = Asset::Texture(name.clone()); - let preview = || ShelfPreview::Image(name.clone(), img); - let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset)); - if r.clicked() { - apply(app, &asset); - } - r.context_menu(|ui| { - if ui.button(tr("Add as decal (view center)")).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); - } - if ui.button(tr("Remove resource")).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); - } - }); - } - }); -} - -/// Asset tile with optional dragging and a larger hover preview +/// Asset tile with optional dragging and a larger hover preview, at the medium size pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, - tex: Option<&egui::TextureHandle>, + texture: Option<&egui::TextureHandle>, preview: impl FnOnce() -> ShelfPreview, label: &str, drag: Option<&Asset>, ) -> egui::Response { - let tk = Tokens::get(ui.ctx()); + tile_in_view(ui, thumbs, texture, |_| Some(preview()), label, drag, ShelfView::Medium) +} + +/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover +fn tile_in_view( + ui: &mut Ui, + thumbs: &mut Thumbs, + texture: Option<&egui::TextureHandle>, + preview: impl FnOnce(&mut Thumbs) -> Option, + label: &str, + drag: Option<&Asset>, + view: ShelfView, +) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag - && resp.drag_started() + && response.drag_started() { - resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); } let painter = ui.painter(); - if resp.hovered() || resp.dragged() { - painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); + if response.hovered() || response.dragged() { + painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover); } - let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); - thumbnail(painter, tex, image_rect, &tk); - let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN); - painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); - let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; - resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) + let image_rect = view.thumbnail_rect(rect); + thumbnail(painter, texture, image_rect, &tokens); + if view.name_beside() { + let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP; + let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + } else { + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text); + } + + let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; + response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) +} + +/// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness +fn randomness_badge(painter: &egui::Painter, thumbnail: egui::Rect) { + let corner = thumbnail.right_bottom() - vec2(BADGE_INSET, BADGE_INSET); + for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] { + painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR)); + } +} + +/// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name) +fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color)); + job.wrap = egui::text::TextWrapping::truncate_at_width(width); + job } /// Start rendering during the popup delay once the pointer rests @@ -689,3 +633,25 @@ fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<& ui.label(label); }); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_long_label_stays_on_one_line_ending_in_an_ellipsis() { + let width = 60.0; + let mut laid_out = None; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE))); + }); + + // The font atlas upload is not under test + output.textures_delta.clear(); + let galley = laid_out.unwrap(); + + assert_eq!(galley.rows.len(), 1); + assert!(galley.size().x <= width); + assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); + } +} diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs new file mode 100644 index 00000000..2ea615a6 --- /dev/null +++ b/crates/ui-egui/src/shelf_entry.rs @@ -0,0 +1,270 @@ +//! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies + +use std::path::PathBuf; + +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; +use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; +use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{Asset, Tab, apply}; +use crate::shelf_preview::ShelfPreview; + +/// The name of a saved brush whose file name isn't text +const SAVED_BRUSH_NAME: &str = "brush"; + +/// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines +const SEED_PROBES: usize = 4; +const SEED_PROBE_OFFSET: f32 = 0.13; +/// A smaller difference between the two seeds' samples is rounding +const SEED_TOLERANCE: f32 = 1e-4; + +/// The libraries' ids: the open project's images, the built-in assets, the user's saved assets +pub(crate) const PROJECT: &str = "project"; +pub(crate) const STARTER: &str = "starter"; +pub(crate) const USER: &str = "user"; +/// The libraries in the picker's order: id and (English, translated where shown) name +pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")]; + +/// A shelf tile's asset +pub(crate) enum ShelfEntry { + Material(&'static SmartMaterial), + SmartMask(&'static SmartMask), + Filter(&'static FilterDef), + Brush(&'static BrushPreset), + /// A brush preset file the user saved + SavedBrush(PathBuf), + Alpha(&'static LibraryAlpha), + Procedural(ProceduralKind), + /// A built-in lighting environment, by name + Environment(&'static str), + /// An image resource of the project, by name + Image(String), +} + +impl ShelfEntry { + /// Every built-in asset, the user's saved brushes and the project's images + pub(crate) fn all(app: &TextureCraftApp) -> Vec { + let built_in = MATERIALS + .iter() + .map(ShelfEntry::Material) + .chain(SMART_MASKS.iter().map(ShelfEntry::SmartMask)) + .chain(FILTERS.iter().map(ShelfEntry::Filter)) + .chain(PRESETS.iter().map(ShelfEntry::Brush)) + .chain(alphas::library().iter().map(ShelfEntry::Alpha)) + .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) + .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); + let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush); + let images = app.session.doc.resources.keys().filter(|name| app.session.images.contains_key(*name)).cloned().map(ShelfEntry::Image); + built_in.chain(saved).chain(images).collect() + } + + /// The tab that lists the asset + pub(crate) fn tab(&self) -> Tab { + match self { + ShelfEntry::Material(material) if material.smart => Tab::Smart, + ShelfEntry::Material(_) => Tab::Materials, + ShelfEntry::SmartMask(_) => Tab::Masks, + ShelfEntry::Filter(_) => Tab::Filters, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes, + ShelfEntry::Alpha(_) => Tab::Alphas, + ShelfEntry::Procedural(_) => Tab::Textures, + ShelfEntry::Environment(_) => Tab::Environments, + ShelfEntry::Image(_) => Tab::Textures, + } + } + + /// The asset's identity across frames: its kind and id + pub(crate) fn identity(&self) -> (&'static str, &str) { + match self { + ShelfEntry::Material(material) => ("material", material.id), + ShelfEntry::SmartMask(mask) => ("mask", mask.id), + ShelfEntry::Filter(filter) => ("filter", filter.id), + ShelfEntry::Brush(preset) => ("brush", preset.id), + ShelfEntry::SavedBrush(path) => ("saved-brush", path.to_str().unwrap_or_default()), + ShelfEntry::Alpha(alpha) => ("alpha", &alpha.id), + ShelfEntry::Procedural(kind) => ("procedural", kind.label()), + ShelfEntry::Environment(name) => ("environment", name), + ShelfEntry::Image(name) => ("image", name), + } + } + + /// Where the asset lives: its library id ([`LIBRARIES`]), its type's folder, then its category if it has one (names in English, shown through `tr`) + pub(crate) fn path(&self) -> Vec<&str> { + let (library, folder, category) = match self { + ShelfEntry::Material(material) if material.smart => (STARTER, "Smart materials", Some(material.category)), + ShelfEntry::Material(material) => (STARTER, "Materials", Some(material.category)), + ShelfEntry::SmartMask(_) => (STARTER, "Smart masks", None), + ShelfEntry::Filter(filter) => (STARTER, "Filters", Some(filter.group)), + ShelfEntry::Brush(preset) => (STARTER, "Brushes", Some(preset.category)), + ShelfEntry::SavedBrush(_) => (USER, "Brushes", None), + ShelfEntry::Alpha(alpha) => (STARTER, "Alphas", Some(alpha.category)), + ShelfEntry::Procedural(_) => (STARTER, "Procedurals", None), + ShelfEntry::Environment(_) => (STARTER, "Environments", None), + ShelfEntry::Image(_) => (PROJECT, "Textures", None), + }; + [library, folder].into_iter().chain(category).collect() + } + + /// Whether the asset is in folder `path` (a library id, then folder names) or below it + pub(crate) fn in_folder(&self, path: &[String]) -> bool { + let own = self.path(); + path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have) + } + + /// The name under the tile, translated where the asset's name is + pub(crate) fn label(&self) -> &str { + match self { + ShelfEntry::Material(material) => material.label, + ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME), + ShelfEntry::SmartMask(mask) => mask.label, + ShelfEntry::Filter(filter) => tr(filter.label), + ShelfEntry::Brush(preset) => preset.label, + ShelfEntry::Alpha(alpha) => &alpha.label, + ShelfEntry::Procedural(kind) => tr(kind.label()), + ShelfEntry::Environment(name) => name, + ShelfEntry::Image(name) => name, + } + } + + /// Whether `filter` (lowercase) matches the asset's name, id or category, in English or translated + pub(crate) fn matches(&self, filter: &str) -> bool { + let texts: &[&str] = match self { + ShelfEntry::Material(material) => &[material.label, material.category, material.id], + ShelfEntry::SavedBrush(_) => &[self.label()], + ShelfEntry::SmartMask(mask) => &[mask.label, mask.id], + ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)], + ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], + ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id], + ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())], + ShelfEntry::Environment(name) => &[name], + ShelfEntry::Image(name) => &[name], + }; + crate::shelf::matches(filter, texts) + } + + /// The thumbnail, or None while it renders + pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option { + match self { + ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id), + ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), + ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), + ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), + ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path, &app.session.images), + ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), + ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), + ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), + ShelfEntry::Image(name) => { + let image = app.session.images.get(name).cloned()?; + Some(app.thumbs.image(ctx, name, &image)) + } + } + } + + /// What the hover popup renders; None for an image that is gone + pub(crate) fn preview(&self, session: &Session) -> Option { + Some(match self { + ShelfEntry::Material(material) => ShelfPreview::material(material.id), + ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), + ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), + ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), + ShelfEntry::SavedBrush(path) => ShelfPreview::saved_brush(path, &session.images), + ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), + ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), + ShelfEntry::Environment(name) => ShelfPreview::Environment(name), + ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), session.images.get(name).cloned()?), + }) + } + + /// The drag payload's asset; brushes and procedurals don't drag + pub(crate) fn asset(&self) -> Option { + match self { + ShelfEntry::Material(material) => Some(Asset::Material(material.id)), + ShelfEntry::SmartMask(mask) => Some(Asset::SmartMask(mask.id)), + ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), + ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), + ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, + } + } + + /// Whether the tile is outlined as in use: the brush's library alpha, the shown environment + pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool { + match self { + ShelfEntry::Alpha(alpha) => { + let brush = &app.session.tool.brush; + brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + } + ShelfEntry::Environment(name) => app.session.doc.project.display.environment == *name, + _ => false, + } + } + + /// Whether applying the asset gives a different result per random seed (the tile's dots badge) + pub(crate) fn includes_randomness(&self) -> bool { + match self { + ShelfEntry::Procedural(kind) => SEEDED_PROCEDURALS.contains(kind), + _ => false, + } + } + + /// What a click on the tile does + pub(crate) fn activate(&self, app: &mut TextureCraftApp) { + match self { + ShelfEntry::Brush(preset) => { + app.run("brush.preset.apply", json!({"preset": preset.id})); + } + ShelfEntry::SavedBrush(path) => { + app.run("brush.preset.load", json!({"path": path.display().to_string()})); + } + ShelfEntry::Procedural(kind) => { + app.run("layer.add.fill", json!({"name": kind.label()})); + app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); + } + ShelfEntry::Environment(name) => { + app.run("display.set", json!({"environment": name})); + } + entry => { + if let Some(asset) = entry.asset() { + apply(app, &asset); + } + } + } + } +} + +/// The procedurals whose pattern depends on the seed, worked out once +static SEEDED_PROCEDURALS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| ProceduralKind::ALL.into_iter().filter(|kind| seed_changes(*kind)).collect()); + +/// Whether procedural `kind` samples differently under two seeds +fn seed_changes(kind: ProceduralKind) -> bool { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let sample = |seed: u32, i: usize| { + let uv = Vec2::new((i % SEED_PROBES) as f32 / SEED_PROBES as f32, (i / SEED_PROBES) as f32 / SEED_PROBES as f32) + SEED_PROBE_OFFSET; + procedural(&Procedural { seed, ..Procedural::new(kind) }, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }) + }; + (0..SEED_PROBES * SEED_PROBES).any(|i| (sample(1, i) - sample(2, i)).abs() > SEED_TOLERANCE) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_seeded_procedurals_include_randomness() { + let seeded = &*SEEDED_PROCEDURALS; + assert!(seeded.contains(&ProceduralKind::Clouds), "{seeded:?}"); + assert!(!seeded.contains(&ProceduralKind::Checker), "{seeded:?}"); + } +} diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs new file mode 100644 index 00000000..e581f480 --- /dev/null +++ b/crates/ui-egui/src/shelf_folders.rs @@ -0,0 +1,95 @@ +//! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree + +use std::collections::BTreeSet; + +use egui::{RichText, Ui}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_entry::{LIBRARIES, ShelfEntry}; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The breadcrumb arrows' size relative to an icon button +const ARROW_SCALE: f32 = 0.8; + +/// The folder paths of `entries`, each a library id then folder names +pub(crate) fn paths<'a>(entries: impl IntoIterator) -> Vec> { + let unique_paths: BTreeSet> = entries.into_iter().map(ShelfEntry::path).collect(); + + unique_paths.into_iter().map(|segments| segments.into_iter().map(str::to_string).collect()).collect() +} + +/// `paths` and every library, even one with nothing in it (the picker always lists them all) +pub(crate) fn with_every_library(mut paths: Vec>) -> Vec> { + paths.extend(LIBRARIES.iter().map(|(id, _)| vec![id.to_string()])); + paths.sort(); + paths.dedup(); + paths +} + +/// The folders right below `prefix` (libraries in their usual order, folders by name) +pub(crate) fn children(paths: &[Vec], prefix: &[String]) -> Vec { + let mut children = Vec::new(); + for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) { + if let Some(child) = path.get(prefix.len()) + && !children.contains(child) + { + children.push(child.clone()); + } + } + + if prefix.is_empty() { + children.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); + } + children +} + +/// A folder's shown name: libraries by their name, folders (type and category names) translated +pub(crate) fn name(level: usize, segment: &str) -> &str { + match LIBRARIES.iter().find(|(id, _)| *id == segment) { + Some((_, library)) if level == 0 => tr(library), + _ => tr(segment), + } +} + +/// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside +pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let tokens = Tokens::get(ui.ctx()); + let size = ui.spacing().interact_size.y * ARROW_SCALE; + let mut picked: Option> = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = ui.spacing().item_spacing.x * 0.5; + let path = app.ui.shelf_path.clone(); + for level in 0..=path.len() { + let options = children(paths, &path[..level]); + if level > 0 && options.is_empty() { + break; + } + + let current = path.get(level); + let response = icon_button(ui, egui_phosphor::regular::CARET_RIGHT, tr("Browse folders"), false, size); + egui::Popup::menu(&response).show(|ui| { + if level == 0 && ui.selectable_label(current.is_none(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + for option in &options { + if ui.selectable_label(current == Some(option), name(level, option)).clicked() { + picked = Some(path[..level].iter().cloned().chain([option.clone()]).collect()); + } + } + }); + + let shown = match current { + Some(segment) => name(level, segment), + None if level == 0 => tr("All libraries"), + None => continue, + }; + ui.label(RichText::new(shown).strong().color(tokens.text_strong)); + } + }); + + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs new file mode 100644 index 00000000..b643d21f --- /dev/null +++ b/crates/ui-egui/src/shelf_panes.rs @@ -0,0 +1,175 @@ +//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::saved_search::SavedSearch; +use crate::shelf::TABS; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The panes' column width as a fraction of the panel, and its least width in points +const COLUMN_FRACTION: f32 = 0.45; +const COLUMN_MIN_WIDTH: f32 = 110.0; +/// Maximum share of the column used by saved searches while both panes are open +const SAVED_SEARCHES_HEIGHT_FRACTION: f32 = 0.45; +/// The pane header's caption size in points +const HEADER_SIZE: f32 = 10.0; + +/// Which side panes are open +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfPanes { + pub saved_searches: bool, + pub filter_by_path: bool, + /// Filter by path lists only the folders with assets matching the search and tab + pub hide_non_applicable: bool, +} + +/// The toolbar's buttons that open and close the panes +pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let panes = &mut app.ui.shelf_panes; + if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() { + panes.saved_searches = !panes.saved_searches; + } + if icon_button(ui, ic::TREE_STRUCTURE, tr("Filter by path"), panes.filter_by_path, size).clicked() { + panes.filter_by_path = !panes.filter_by_path; + } +} + +/// The width of the panes' column in a panel `width` wide, or None while no pane is open +pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option { + let panes = &app.ui.shelf_panes; + (panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) +} + +/// The open panes, top to bottom; the tree shows `paths`, or `applicable` while it hides folders with nothing matching +pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec], applicable: &[Vec]) { + // Names past the narrow column end in "…" rather than breaking mid-word + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + if app.ui.shelf_panes.saved_searches { + saved_searches(app, ui); + } + if app.ui.shelf_panes.filter_by_path { + if app.ui.shelf_panes.saved_searches { + ui.separator(); + } + let shown = if app.ui.shelf_panes.hide_non_applicable { applicable } else { paths }; + filter_by_path(app, ui, shown); + } +} + +/// "All libraries", then each library's folders as a tree; a click shows that folder +fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let size = ui.spacing().interact_size.y; + header(ui, tr("Filter by path"), |ui| { + let hiding = app.ui.shelf_panes.hide_non_applicable; + if icon_button(ui, ic::EYE_SLASH, tr("Hide non-applicable folders"), hiding, size).clicked() { + app.ui.shelf_panes.hide_non_applicable = !hiding; + } + }); + + let mut picked = None; + egui::ScrollArea::vertical().id_salt("shelf_path_tree").auto_shrink([false, true]).show(ui, |ui| { + if ui.selectable_label(app.ui.shelf_path.is_empty(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + folders(ui, paths, &[], &app.ui.shelf_path, &mut picked); + }); + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} + +/// The folders below `prefix`: one with folders inside opens and closes, a click on a name picks it +fn folders(ui: &mut Ui, paths: &[Vec], prefix: &[String], current: &[String], picked: &mut Option>) { + for child in crate::shelf_folders::children(paths, prefix) { + let path: Vec = prefix.iter().cloned().chain([child.clone()]).collect(); + let name = crate::shelf_folders::name(prefix.len(), &child); + let selected = current == path.as_slice(); + if crate::shelf_folders::children(paths, &path).is_empty() { + ui.indent(("shelf_path_leaf", &path), |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }); + continue; + } + + let id = ui.make_persistent_id(("shelf_path", &path)); + let open_by_default = current.starts_with(&path); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, open_by_default) + .show_header(ui, |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }) + .body(|ui| folders(ui, paths, &path, current, picked)); + } +} + +/// A pane's caption with a button at its right +fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button); + }); +} + +/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one +fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { + let size = ui.spacing().interact_size.y; + let current = current_query(app); + header(ui, tr("Saved searches"), |ui| { + if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() && !app.ui.shelf_saved_searches.contains(¤t) { + app.ui.shelf_saved_searches.push(current.clone()); + } + }); + + let everything = current.filter.is_empty() && current.path.is_empty() && current.tab == crate::shelf_tabs::NO_TYPE; + if ui.selectable_label(everything, tr("All")).clicked() { + crate::shelf_toolbar::reset_query(app); + } + + let mut deleted = None; + let max_height = if app.ui.shelf_panes.filter_by_path { ui.available_height() * SAVED_SEARCHES_HEIGHT_FRACTION } else { ui.available_height() }; + let row_height = ui.spacing().interact_size.y; + let total_rows = app.ui.shelf_saved_searches.len(); + egui::ScrollArea::vertical().id_salt("shelf_saved_searches").max_height(max_height).show_rows(ui, row_height, total_rows, |ui, visible_rows| { + for i in visible_rows { + let Some(saved) = app.ui.shelf_saved_searches.get(i) else { continue }; + + let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path; + let response = ui.selectable_label(same, &saved.name); + if response.clicked() { + (app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone()); + } + response.context_menu(|ui| { + if ui.button(tr("Delete")).clicked() { + deleted = Some(i); + ui.close(); + } + }); + } + }); + + if let Some(i) = deleted { + app.ui.shelf_saved_searches.remove(i); + } +} + +/// The shelf's query, named after its search text, else its folder, else its tab +fn current_query(app: &TextureCraftApp) -> SavedSearch { + let (filter, tab, path) = (app.ui.shelf_filter.clone(), app.ui.shelf_tab, app.ui.shelf_path.clone()); + let name = if !filter.is_empty() { + filter.clone() + } else if let Some(folder) = path.last() { + crate::shelf_folders::name(path.len() - 1, folder).to_string() + } else { + TABS.get(tab).map_or(tr("All"), |(_, _, label)| tr(label)).to_string() + }; + SavedSearch { name, filter, tab, path } +} diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index b512f250..65639daf 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -1,9 +1,11 @@ //! Shelf assets and their preview renderers +use std::path::PathBuf; use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::compose::ImageStore; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; @@ -11,9 +13,14 @@ use texturecraft_engine::paint::alphas::LibraryAlpha; use texturecraft_engine::paint::presets::BrushPreset; use texturecraft_engine::preview; -use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; +use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview}; + +/// Larger brush preset files aren't read (the `brush.preset.load` command's limit) +#[cfg(not(target_arch = "wasm32"))] +const MAX_SAVED_BRUSH_BYTES: u64 = 1 << 20; /// The asset a shelf tile previews +#[derive(Clone)] pub enum ShelfPreview { /// A built-in plain material on a sphere Material(&'static str), @@ -29,11 +36,22 @@ pub enum ShelfPreview { Alpha(&'static LibraryAlpha), /// A brush preset's stroke along an S curve Brush(&'static BrushPreset), + /// A brush preset file the user saved, its stroke along an S curve + SavedBrush { path: PathBuf, settings: Option, image: Option> }, /// An image resource by name Image(String, Arc), + /// A built-in lighting environment's panorama + Environment(&'static str), } impl ShelfPreview { + /// Resolve a saved brush's image alpha while the project images are available + pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { + let settings = read_saved_brush(path); + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)).cloned(); + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings, image } + } + /// Smart materials preview on the orb, plain materials on a sphere pub fn material(id: &'static str) -> ShelfPreview { match materials::find(id) { @@ -52,7 +70,9 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::SavedBrush { path, .. } => format!("saved-brush:{}", path.display()), ShelfPreview::Image(name, _) => format!("image:{name}"), + ShelfPreview::Environment(name) => format!("environment:{name}"), } } @@ -65,12 +85,39 @@ impl ShelfPreview { ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), - ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size, None)), + ShelfPreview::SavedBrush { settings, image, .. } => { + let settings = settings.as_ref()?; + if settings.alpha_image.is_some() && image.is_none() { + return None; + } + Some(stroke_preview(settings, size, image.as_deref())) + } ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + ShelfPreview::Environment(name) => Some(environment_image(name, size)), } } } +/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files) +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option { + use std::io::Read as _; + + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|file| file.take(MAX_SAVED_BRUSH_BYTES + 1).read_to_end(&mut bytes)).ok()?; + if bytes.len() as u64 > MAX_SAVED_BRUSH_BYTES { + return None; + } + + serde_json::from_slice::(&bytes).ok().map(|settings| settings.sanitized()) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option { + None +} + #[cfg(test)] mod tests { use texturecraft_engine::filter_lib::FILTERS; @@ -93,6 +140,7 @@ mod tests { ShelfPreview::Alpha(&alphas::library()[0]), ShelfPreview::Brush(&PRESETS[0]), ShelfPreview::Image("image".into(), Arc::new(image)), + ShelfPreview::Environment(texturecraft_engine::core::project::ENVIRONMENTS[0]), ]; for preview in previews { let key = preview.key(); @@ -117,4 +165,15 @@ mod tests { assert_eq!(on_the_orb, material.smart, "{}", material.id); } } + + #[test] + fn saved_brush_preview_uses_its_project_image_alpha() { + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let transparent = Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[1.0, 1.0, 1.0, 0.0]; 4], srgb: false }); + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings.clone()), image: Some(transparent) }; + + assert!(preview.image(64).is_some_and(|image| image.pixels.iter().all(|pixel| pixel.r() == 0))); + let missing = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings), image: None }; + assert!(missing.image(64).is_none()); + } } diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs new file mode 100644 index 00000000..5898a943 --- /dev/null +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -0,0 +1,72 @@ +//! The shelf's type row: one icon per type (none picked shows every type), greyed without matches, one dropdown when narrow + +use egui::{Ui, vec2}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{TABS, Tab}; +use crate::widgets::{icon_button, icon_dropdown_button}; + +/// The gap between the row's icons in points +const ICON_GAP: f32 = 2.0; +/// The size of the dot that marks the collapsed row's dropdown while a type is picked, in points +const FILTER_DOT_RADIUS: f32 = 2.5; + +/// `app.ui.shelf_tab` while no type is picked: every type shows +pub(crate) const NO_TYPE: usize = TABS.len(); + +/// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) { + let size = ui.spacing().interact_size.y; + + // The type icons and one icon after them + let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP); + let mut picked = app.ui.shelf_tab.min(NO_TYPE); + + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(ICON_GAP, ICON_GAP); + if ui.available_width() >= row_width { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + // The picked type stays clickable so it can be unpicked + let empty = i != picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled_ui(!empty, |ui| icon_button(ui, icon, tr(label), i == picked, size)).inner.clicked() { + picked = if i == picked { NO_TYPE } else { i }; + } + } + } else { + collapsed(ui, &mut picked, counts, size); + } + + let rest = ui.available_width() - size; + ui.add_space(rest.max(0.0)); + trailing(app, ui, size); + }); + app.ui.shelf_tab = picked; +} + +/// One dropdown listing the types, dotted while one is picked +fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) { + let filtering = *picked != NO_TYPE; + let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size); + let response = response.on_hover_text(tr("Filter by type")); + if filtering { + let tokens = crate::theme::Tokens::get(ui.ctx()); + let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS); + ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tokens.accent); + } + + egui::Popup::menu(&response).show(|ui| { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + let empty = i != *picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled(!empty, egui::Button::selectable(i == *picked, format!("{icon} {}", tr(label)))).clicked() { + *picked = if i == *picked { NO_TYPE } else { i }; + ui.close(); + } + } + }); +} + +/// Whether `tab` (an index into [`TABS`], or [`NO_TYPE`]) shows assets of type `kind` +pub(crate) fn shows(tab: usize, kind: Tab) -> bool { + TABS.get(tab).is_none_or(|(shown, _, _)| *shown == kind) +} diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs new file mode 100644 index 00000000..5e185bf9 --- /dev/null +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -0,0 +1,50 @@ +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right + +use egui::Ui; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// The gap above the toolbar in points +const GAP_ABOVE: f32 = 4.0; + +/// The toolbar's height for a `ui` (one icon button and the gap above it) +pub(crate) fn height(ui: &Ui) -> f32 { + ui.spacing().interact_size.y + GAP_ABOVE +} + +/// The toolbar +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + let size = ui.spacing().interact_size.y; + ui.add_space(GAP_ABOVE); + ui.horizontal(|ui| { + crate::shelf_panes::toggles(app, ui, size); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), "resource.import"); + } + if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() { + reset_query(app); + } + if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() { + refresh(app); + } + }); + }); +} + +/// Show every asset again: no search, no type picked, all libraries +pub(crate) fn reset_query(app: &mut TextureCraftApp) { + app.ui.shelf_filter.clear(); + app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE; + app.ui.shelf_path.clear(); +} + +/// Read the user's saved assets from disk again and redraw their thumbnails +fn refresh(app: &mut TextureCraftApp) { + app.library = None; + app.brushes = None; + app.thumbs.forget_saved_files(); +} diff --git a/crates/ui-egui/src/shelf_view.rs b/crates/ui-egui/src/shelf_view.rs new file mode 100644 index 00000000..036c498b --- /dev/null +++ b/crates/ui-egui/src/shelf_view.rs @@ -0,0 +1,83 @@ +//! How the shelf shows its assets: small, medium or large tiles, or a list (the menu at the type row's end) + +use egui::{Rect, Ui, Vec2, vec2}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::grid_tile::GridTile; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// A list row's height and its thumbnail's size, in points +const LIST_ROW_HEIGHT: f32 = 30.0; +const LIST_THUMBNAIL_SIZE: f32 = 26.0; +/// The gap between a list row's thumbnail and its name, in points +pub(crate) const LIST_NAME_GAP: f32 = 6.0; + +/// The shelf's tile size, or the list +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ShelfView { + Small, + /// A 68 x 78 grid step, as in the reference + #[default] + Medium, + Large, + List, +} + +/// The views in the menu's order: icon and (English, translated where shown) name +const VIEWS: [(ShelfView, &str, &str); 4] = [ + (ShelfView::Small, ic::GRID_NINE, "Small"), + (ShelfView::Medium, ic::GRID_FOUR, "Medium"), + (ShelfView::Large, ic::SQUARE, "Large"), + (ShelfView::List, ic::LIST, "List"), +]; + +impl ShelfView { + /// A grid tile's measurements; None for the list + fn grid(self) -> Option { + match self { + ShelfView::Small => Some(GridTile { width: 50.0, height: 58.0, thumbnail_size: 44.0, thumbnail_center_y: 23.0 }), + ShelfView::Medium => Some(GridTile { width: 66.0, height: 76.0, thumbnail_size: 60.0, thumbnail_center_y: 31.0 }), + ShelfView::Large => Some(GridTile { width: 88.0, height: 100.0, thumbnail_size: 82.0, thumbnail_center_y: 42.0 }), + ShelfView::List => None, + } + } + + /// A tile's size in a grid `width` points wide (a list row spans it) + pub(crate) fn tile_size(self, width: f32) -> Vec2 { + match self.grid() { + Some(tile) => vec2(tile.width, tile.height), + None => vec2(width.max(LIST_ROW_HEIGHT), LIST_ROW_HEIGHT), + } + } + + /// Where the thumbnail goes in the tile `rect` + pub(crate) fn thumbnail_rect(self, rect: Rect) -> Rect { + match self.grid() { + Some(tile) => Rect::from_center_size(rect.center_top() + vec2(0.0, tile.thumbnail_center_y), vec2(tile.thumbnail_size, tile.thumbnail_size)), + None => Rect::from_center_size(rect.left_center() + vec2(LIST_ROW_HEIGHT * 0.5, 0.0), vec2(LIST_THUMBNAIL_SIZE, LIST_THUMBNAIL_SIZE)), + } + } + + /// Whether the name sits right of the thumbnail (a list) rather than under it + pub(crate) fn name_beside(self) -> bool { + self == ShelfView::List + } +} + +/// The view menu button: its icon is the current view's +pub(crate) fn menu(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let current = app.ui.shelf_view; + let icon = VIEWS.iter().find(|(view, _, _)| *view == current).map_or(ic::GRID_FOUR, |(_, icon, _)| icon); + let response = icon_button(ui, icon, tr("Thumbnail size"), false, size); + egui::Popup::menu(&response).show(|ui| { + for (view, icon, label) in VIEWS { + if ui.selectable_label(view == current, format!("{icon} {}", tr(label))).clicked() { + app.ui.shelf_view = view; + ui.close(); + } + } + }); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e52a2907..4b0c321d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -5,6 +5,9 @@ use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; +use crate::saved_search::SavedSearch; +use crate::shelf_panes::ShelfPanes; +use crate::shelf_view::ShelfView; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -264,7 +267,7 @@ fn default_split_ratio() -> f32 { 0.5 } /// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` -const BAKE_LAYOUT_VERSION: u32 = 1; +const BAKE_LAYOUT_VERSION: u32 = 2; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { @@ -297,9 +300,21 @@ pub struct UiState { /// Channel whose blending the layer rows show. pub layer_channel: Channel, pub shelf_filter: String, - /// The asset shelf's open tab. + /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] pub shelf_tab: usize, + /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) + #[serde(default)] + pub shelf_path: Vec, + /// The asset shelf's tile size, or its list + #[serde(default)] + pub shelf_view: ShelfView, + /// The asset shelf's open side panes + #[serde(default)] + pub shelf_panes: ShelfPanes, + /// The asset shelf's saved queries, in the order they were saved + #[serde(default)] + pub shelf_saved_searches: Vec, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -329,8 +344,8 @@ pub struct UiState { /// How the 3D view shows symmetry #[serde(default)] pub symmetry: crate::symmetry::SymmetryDisplay, - /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) - #[serde(default)] + /// The Baking Visualization panel's settings, under a key of their own since the reference defaults: older saved ones start over + #[serde(default, rename = "baking_visualization")] pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } @@ -357,17 +372,21 @@ impl UiState { self.bake_layout_version = BAKE_LAYOUT_VERSION; } - /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export - /// settings and recent files. + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, settings, files and shelf query pub fn adopt_layout(&mut self, layout: UiState) { let keep = std::mem::replace(self, layout); self.new_project = keep.new_project; self.export = keep.export; self.recent = keep.recent; - self.shelf_filter = keep.shelf_filter; self.prefs = keep.prefs; self.keymap = keep.keymap; self.rename = None; + + // The shelf's search, type and folder are one query, and saved searches are the user's own + self.shelf_filter = keep.shelf_filter; + self.shelf_tab = keep.shelf_tab; + self.shelf_path = keep.shelf_path; + self.shelf_saved_searches = keep.shelf_saved_searches; } } @@ -390,6 +409,10 @@ impl Default for UiState { layer_channel: Channel::BaseColor, shelf_filter: String::new(), shelf_tab: 0, + shelf_path: Vec::new(), + shelf_view: ShelfView::default(), + shelf_panes: ShelfPanes::default(), + shelf_saved_searches: Vec::new(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, @@ -419,13 +442,27 @@ mod tests { ui.keymap.insert("file.save".into(), "F5".into()); let mut layout = UiState::default(); layout.dock.close(crate::docking::Panel::Assets); + ui.adopt_layout(layout); + assert!(!ui.dock.is_open(crate::docking::Panel::Assets)); assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); } + #[test] + fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() { + let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; + let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() }; + ui.shelf_saved_searches.push(saved.clone()); + + ui.adopt_layout(UiState::default()); + + assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice())); + assert_eq!(ui.shelf_saved_searches, [saved]); + } + #[test] fn the_data_folder_is_an_absolute_choice_or_documents_texturecraft() { let default = crate::data_folder(""); diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 9c492896..a3964660 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -29,9 +29,10 @@ pub(crate) fn applies_to(tool: Tool) -> bool { matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Clone | Tool::Path) } -/// Whether the 3D view shows symmetry now +/// Whether the 3D view shows symmetry now: not while the active tool can't act on the selection pub(crate) fn shown(app: &TextureCraftApp) -> bool { - app.ui.mode == crate::state::Mode::Painting && applies_to(app.session.tool.tool) && app.session.tool.brush.symmetry.any() + let tool = app.session.tool.tool; + app.ui.mode == crate::state::Mode::Painting && applies_to(tool) && app.session.tool_usable(tool) && app.session.tool.brush.symmetry.any() } /// The world axes any active mirror plane or radial axis can move along, even while symmetry is disabled diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d0067411..9a7bda37 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -3,11 +3,14 @@ //! Smart masks, smart materials and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; +use texturecraft_engine::compose::{ImageRes, ImageStore}; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::paint::presets::BrushPreset; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; use crate::preview_image::{aces, image_preview, shade}; @@ -21,20 +24,32 @@ const PER_FRAME: usize = 2; /// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; /// Shelf procedural swatch size in pixels -const PROCEDURAL_PX: usize = 56; +const PROCEDURAL_PX: usize = 64; /// Shelf alpha and brush stroke swatch size in pixels const SWATCH_PX: usize = 64; /// Image resource preview size in pixels const IMAGE_PX: usize = 64; +/// The [`ShelfPreview::key`] prefix of the user's saved files +const SAVED_FILE_KEY_PREFIX: &str = "saved-"; +/// Largest stencil preview dimension in pixels +const STENCIL_MAX_SIZE_PX: f32 = 1024.0; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; +/// Parsed settings, weak image identity and preview revision for a saved brush +type SavedBrushCacheEntry = (Option, Option>, u64); + /// The shelf's and the brush panel's preview textures #[derive(Default)] pub struct Thumbs { /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, - images: HashMap, + /// Parsed settings, weak image identity and preview revision for each saved brush + saved_brush_previews: HashMap, + /// Refresh generation; queued results from earlier generations must not match new requests + saved_files_epoch: u64, + images: HashMap, TextureHandle)>, + images_revision: Option, /// (frame, thumbnails rendered in it) budget: (u64, usize), /// Renders the orb thumbnails and the big previews @@ -49,34 +64,57 @@ pub struct Thumbs { impl Thumbs { /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) - pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { + pub fn stencil(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { let key = format!("stencil:{name}"); - if let Some(t) = self.images.get(&key) { - return t.clone(); + if let Some((cached_image, texture)) = self.images.get(&key) + && cached_image.ptr_eq(&Arc::downgrade(image)) + { + return texture.clone(); } - let scale = (1024.0 / img.width.max(img.height).max(1) as f32).min(1.0); - let (w, h) = (((img.width as f32 * scale) as usize).max(1), ((img.height as f32 * scale) as usize).max(1)); - let mut ci = ColorImage::filled([w, h], Color32::TRANSPARENT); + + let scale = (STENCIL_MAX_SIZE_PX / image.width.max(image.height).max(1) as f32).min(1.0); + let (w, h) = (((image.width as f32 * scale) as usize).max(1), ((image.height as f32 * scale) as usize).max(1)); + let mut color_image = ColorImage::filled([w, h], Color32::TRANSPARENT); for y in 0..h { for x in 0..w { - let s = img.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); - let enc = |v: f32| if img.srgb { (v.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(v) * 255.0) as u8 }; - ci.pixels[y * w + x] = Color32::from_rgba_unmultiplied(enc(s[0]), enc(s[1]), enc(s[2]), (s[3].clamp(0.0, 1.0) * 255.0) as u8); + let sample = image.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); + let encode = |value: f32| { + if image.srgb { (value.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(value) * 255.0) as u8 } + }; + color_image.pixels[y * w + x] = + Color32::from_rgba_unmultiplied(encode(sample[0]), encode(sample[1]), encode(sample[2]), (sample[3].clamp(0.0, 1.0) * 255.0) as u8); } } - let t = ctx.load_texture(key.clone(), ci, TextureOptions::LINEAR); - self.images.insert(key, t.clone()); - t + + let texture = ctx.load_texture(key.clone(), color_image, TextureOptions::LINEAR); + self.images.insert(key, (Arc::downgrade(image), texture.clone())); + texture } /// Cached preview of an image resource (64 px, letterboxed) - pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { - if let Some(t) = self.images.get(name) { - return t.clone(); + pub fn image(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { + if let Some((cached_image, texture)) = self.images.get(name) + && cached_image.ptr_eq(&Arc::downgrade(image)) + { + return texture.clone(); } - let t = ctx.load_texture(format!("res_{name}"), image_preview(img, IMAGE_PX), TextureOptions::LINEAR); - self.images.insert(name.to_string(), t.clone()); - t + + let texture = ctx.load_texture(format!("res_{name}"), image_preview(image, IMAGE_PX), TextureOptions::LINEAR); + self.images.insert(name.to_string(), (Arc::downgrade(image), texture.clone())); + texture + } + + /// Release previews for deleted or replaced resources after a session change + pub fn sync_images(&mut self, images: &ImageStore, revision: u64) { + if self.images_revision == Some(revision) { + return; + } + + self.images_revision = Some(revision); + self.images.retain(|key, (cached_image, _)| { + let name = key.strip_prefix("stencil:").unwrap_or(key); + images.get(name).is_some_and(|image| cached_image.ptr_eq(&Arc::downgrade(image))) + }); } /// Render within the frame budget; deferred thumbnails request a repaint @@ -117,7 +155,7 @@ impl Thumbs { fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { self.receive(ctx); - let key = worker_key(&preview, size_px); + let key = self.worker_key(&preview, size_px); if !self.rendered.contains_key(&key) && self.may_request(ctx) { let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); @@ -166,7 +204,7 @@ impl Thumbs { /// Request a hover preview and evict the least recently shown beyond the cache limit pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { - let key = worker_key(&preview, size_px); + let key = self.worker_key(&preview, size_px); self.big_shown.retain(|k| *k != key); self.big_shown.push_back(key); while self.big_shown.len() > BIG_PREVIEWS_KEPT { @@ -181,7 +219,7 @@ impl Thumbs { /// The big preview of `preview` if the worker already rendered it (requests nothing) pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { self.receive(ctx); - self.ready(&worker_key(preview, size_px)) + self.ready(&self.worker_key(preview, size_px)) } /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres @@ -192,6 +230,16 @@ impl Thumbs { } } + /// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk + pub fn forget_saved_files(&mut self) { + self.saved_files_epoch = self.saved_files_epoch.wrapping_add(1); + let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX); + self.shelf.retain(|key, _| current(key)); + self.rendered.retain(|key, _| current(key)); + self.big_shown.retain(current); + self.saved_brush_previews.clear(); + } + /// Smart mask thumbnail; None until the worker returns it pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) @@ -212,17 +260,69 @@ impl Thumbs { self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } + /// A lighting environment's panorama + pub fn environment(&mut self, ctx: &egui::Context, name: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX) + } + + /// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable + pub fn saved_brush(&mut self, ctx: &egui::Context, path: &Path, images: &ImageStore) -> Option { + let key = format!("saved-brush:{}", path.display()); + let cached_preview = self.saved_brush_previews.contains_key(path).then(|| self.saved_brush_preview(path, images)); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); + } + if !self.spend_budget(ctx, 1) { + return None; + } + + let preview = cached_preview.unwrap_or_else(|| self.saved_brush_preview(path, images)); + let image = preview.image(SWATCH_PX).unwrap_or_else(|| ColorImage::filled([SWATCH_PX, SWATCH_PX], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Reuse parsed settings until refresh; rebuild previews when their project image changes + pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview { + let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None, 0)); + let (settings, previous_image, revision) = cached; + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)); + let image_changed = match (previous_image.as_ref(), image) { + (Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)), + (None, None) => false, + _ => true, + }; + *previous_image = image.map(Arc::downgrade); + if image_changed { + *revision = revision.wrapping_add(1); + let key = format!("saved-brush:{}", path.display()); + let rendered_prefix = format!("{key}@"); + self.shelf.remove(&key); + self.rendered.retain(|rendered, _| !rendered.starts_with(&rendered_prefix)); + self.big_shown.retain(|rendered| !rendered.starts_with(&rendered_prefix)); + } + + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() } + } + + /// A saved-brush key also identifies the refresh and image version of its request + fn worker_key(&self, preview: &ShelfPreview, size_px: usize) -> String { + let key = format!("{}@{size_px}", preview.key()); + if let ShelfPreview::SavedBrush { path, .. } = preview { + let revision = self.saved_brush_previews.get(path).map_or(0, |(_, _, revision)| *revision); + format!("{key}#{}:{revision}", self.saved_files_epoch) + } else { + key + } + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// The key of a worker-rendered preview: one per asset and size -fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { - format!("{}@{size_px}", preview.key()) -} - /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). pub fn paint_sphere(p: &Painter, c: Pos2, r: f32, base: [f32; 3]) { let mut mesh = egui::Mesh::default(); @@ -276,3 +376,186 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use crate::orb_shape::OrbShape; + + static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + + #[test] + fn saved_brush_refresh_discards_old_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("refreshed.tcbrush"), settings: None, image: None }; + + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + thumbs.forget_saved_files(); + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, None), (old_key, Some(ColorImage::filled([8, 8], Color32::RED)))]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, &preview, 8).is_none(), "an old completion must not replace the current failed result"); + } + + #[test] + fn saved_brush_image_replacement_preserves_current_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let path = PathBuf::from("changed-alpha.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + thumbs.saved_brush_previews.insert(path.clone(), (Some(settings), None, 0)); + let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let mut images: ImageStore = [("alpha.png".into(), image(0.2))].into(); + + let old_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, old_preview, 8).is_none()); + images.insert("alpha.png".into(), image(0.8)); + let current_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, current_preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, Some(ColorImage::filled([8, 8], Color32::RED))), (old_key, None)]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, ¤t_preview, 8).is_some(), "the current completion must survive an old failure"); + } + + #[test] + fn saved_brush_file_read_waits_for_the_thumbnail_budget() { + let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + thumbs.budget = (context.cumulative_pass_nr(), PER_FRAME); + + assert!(thumbs.saved_brush(&context, &path, &ImageStore::new()).is_none()); + assert!(thumbs.saved_brush_previews.is_empty(), "a deferred thumbnail has not read its file"); + + std::fs::remove_file(&path).unwrap(); + } + + #[test] + fn saved_brush_settings_are_read_once_until_refresh() { + let path = + std::env::temp_dir().join(format!("texturecraft-brush-preview-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let mut thumbs = Thumbs::default(); + let images = ImageStore::new(); + + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. })); + std::fs::remove_file(&path).unwrap(); + assert!( + matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }), + "cached settings avoid a second file read" + ); + + thumbs.forget_saved_files(); + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: None, .. }), "refresh reads the file again"); + } + + #[test] + fn saved_brush_cache_releases_old_images_on_change_and_refresh() { + const IMAGE_SIDE: u32 = 512; + const IMAGE_TEXELS: usize = IMAGE_SIDE as usize * IMAGE_SIDE as usize; + const IMAGE_BYTES: usize = IMAGE_TEXELS * std::mem::size_of::<[f32; 4]>(); + + let mut thumbs = Thumbs::default(); + let first_path = PathBuf::from("first.tcbrush"); + let second_path = PathBuf::from("second.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let old_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[1.0; 4]; IMAGE_TEXELS], srgb: false }); + let other_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.5; 4]; IMAGE_TEXELS], srgb: false }); + let old_weak = Arc::downgrade(&old_image); + let other_weak = Arc::downgrade(&other_image); + assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + + thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None, 0)); + thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None, 0)); + let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into(); + drop(thumbs.saved_brush_preview(&first_path, &images)); + images.insert("alpha.png".into(), other_image.clone()); + drop(thumbs.saved_brush_preview(&second_path, &images)); + drop(old_image); + drop(other_image); + assert!(old_weak.upgrade().is_none(), "cached settings do not retain a replaced image"); + assert!(other_weak.upgrade().is_some(), "the project still owns its current image"); + eprintln!( + "saved brush cache after first replacement: 0 of {IMAGE_BYTES} old image bytes retained, {} current image strong owners", + Arc::strong_count(&images["alpha.png"]) + ); + + let replacement = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.0; 4]; IMAGE_TEXELS], srgb: false }); + images.insert("alpha.png".into(), replacement); + drop(thumbs.saved_brush_preview(&first_path, &images)); + assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image"); + eprintln!("saved brush cache after second replacement: 0 of {IMAGE_BYTES} previous image bytes retained"); + + thumbs.forget_saved_files(); + assert!(thumbs.saved_brush_previews.is_empty(), "refresh releases parsed brush settings"); + } + + #[test] + fn replacing_an_image_rebuilds_its_preview() { + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + + let first_image = image(0.2); + let replacement_image = image(0.8); + let first = thumbs.image(&context, "sample.png", &first_image); + let second = thumbs.image(&context, "sample.png", &replacement_image); + + assert_ne!(first.id(), second.id(), "a replaced resource must update its preview"); + } + + #[test] + fn removing_resources_releases_their_previews() { + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + let mut images = ImageStore::new(); + for index in 0..3 { + let name = format!("image-{index}"); + images.insert(name, Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[index as f32; 4]; 4], srgb: false })); + } + + for (name, image) in &images { + drop(thumbs.image(&context, name, image)); + } + let cached_pixel_bytes = |thumbs: &Thumbs| thumbs.images.values().map(|(_, texture)| texture.size()[0] * texture.size()[1] * 4).sum::(); + let before_count = thumbs.images.len(); + let before_pixel_bytes = cached_pixel_bytes(&thumbs); + images.remove("image-0"); + images.remove("image-1"); + thumbs.sync_images(&images, 1); + let after_count = thumbs.images.len(); + let after_pixel_bytes = cached_pixel_bytes(&thumbs); + + eprintln!("cached previews: {before_count} -> {after_count}; texture pixel bytes: {before_pixel_bytes} -> {after_pixel_bytes}"); + assert_eq!((before_count, after_count), (3, 1)); + assert!(after_pixel_bytes < before_pixel_bytes); + assert!(thumbs.images.contains_key("image-2")); + + images.insert("image-3".into(), Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[0.7; 4]; 4], srgb: false })); + drop(thumbs.image(&context, "image-3", &images["image-3"])); + thumbs.sync_images(&images, 2); + assert_eq!(thumbs.images.len(), 2); + + images.clear(); + thumbs.sync_images(&images, 3); + eprintln!("cached previews after clearing resources: {}", thumbs.images.len()); + assert!(thumbs.images.is_empty()); + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9c0013bc..ce998917 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -17,29 +17,36 @@ const BAR_SPACING: f32 = 10.0; const COMPACT_BAR_SPACING: f32 = 4.0; const BAR_SEPARATOR_WIDTH: f32 = 6.0; -pub fn tool_icon(t: Tool) -> &'static str { - match t { +/// Height of the top bar, in points +const BAR_HEIGHT: f32 = 40.0; + +/// Padding inside the top bar card on its left and right, in points +const BAR_PADDING: egui::Margin = egui::Margin::symmetric(8, 0); + +pub fn tool_icon(tool: Tool) -> &'static str { + match tool { Tool::Paint => ic::PAINT_BRUSH, Tool::Eraser => ic::ERASER, - Tool::Projection => ic::PROJECTOR_SCREEN, + Tool::Projection => ic::CUBE_FOCUS, Tool::PolygonFill => ic::POLYGON, Tool::Smudge => ic::FINGERPRINT, Tool::Clone => ic::STAMP, Tool::ColorPicker => ic::EYEDROPPER, - Tool::Path => ic::PATH, - Tool::GeometryMask => ic::CUBE_FOCUS, + Tool::Path => ic::PEN_NIB_STRAIGHT, + Tool::GeometryMask => ic::SELECTION_SLASH, } } /// Keep mode buttons visible, with painting controls scrolling as space runs out pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); - egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { + egui::Panel::top("paint_bar").exact_size(BAR_HEIGHT).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, BAR_PADDING, |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let button_size = ui.spacing().interact_size.y; let mode_width = 3.0 * button_size + 2.0 * BAR_SPACING; let separator_width = BAR_SEPARATOR_WIDTH + 2.0 * BAR_SPACING; + // Leave room for both scroll arrows and at least one button of content let minimum_strip_width = 3.0 * button_size + 2.0 * BAR_SPACING; let scroll_views = @@ -54,7 +61,9 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); if !scroll_views { view_buttons(app, ui); - ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if app.session.tool_usable(app.session.tool.tool) { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + } } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { @@ -183,9 +192,15 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: scroll_area.show(ui, |ui| { ui.scroll_with_delta(vec2(scroll_delta, 0.0)); ui.horizontal_centered(|ui| { - tool_controls(app, ui, tokens); + // A tool that can't act on the selection leaves the bar, as the shelf greys it + let tool_usable = app.session.tool_usable(app.session.tool.tool); + if tool_usable { + tool_controls(app, ui, tokens); + } if scroll_views { - ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if tool_usable { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + } let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height()); ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui)); } @@ -344,41 +359,90 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// Shelf order of the tools; their shortcut keys follow `Tool::ALL` +const SHELF_TOOLS: [Tool; 9] = + [Tool::Paint, Tool::Eraser, Tool::Path, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::GeometryMask]; + +/// The tools Baking keeps on its shelf, greyed +const BAKING_SHELF_TOOLS: [Tool; 3] = [Tool::Paint, Tool::Eraser, Tool::PolygonFill]; + +/// Width of the tool shelf, in points +const SHELF_WIDTH: f32 = 40.0; + +/// Size of a shelf button, in points +const SHELF_BUTTON_SIZE: f32 = 28.0; + +/// Vertical gap between shelf buttons, in points +const SHELF_BUTTON_SPACING: f32 = 3.0; + +/// Space on each side of the lines between shelf groups, in points +const SHELF_GROUP_GAP: f32 = 6.0; + +/// Padding inside the shelf card around its buttons, in points (sides, then top and bottom) +const SHELF_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); + pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); - egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { - ui.spacing_mut().item_spacing.y = 3.0; - ui.add_enabled_ui(app.ui.mode == Mode::Painting, |ui| { - for tool in Tool::ALL { - let selected = app.ui.mode == Mode::Painting && app.session.tool.tool == tool; - let hint = tip(&app.ui.keymap, tr(tool.label()), &format!("tool.{}", tool.id())); - if icon_button(ui, tool_icon(tool), &hint, selected, 28.0).clicked() { + egui::Panel::left("tool_shelf").resizable(false).exact_size(SHELF_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + // The tools start level with the panels' contents, below their tab strips + let top = GUTTER + crate::docking::TAB_HEIGHT as i8; + card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top, bottom: GUTTER }, SHELF_PADDING, |ui| { + ui.spacing_mut().item_spacing.y = SHELF_BUTTON_SPACING; + + // Rendering has nothing to paint, so its shelf keeps only the buttons below the tools + let tools: &[Tool] = match app.ui.mode { + Mode::Painting => &SHELF_TOOLS, + Mode::Baking => &BAKING_SHELF_TOOLS, + Mode::Rendering => &[], + }; + if !tools.is_empty() { + for &tool in tools { + let command = format!("tool.{}", tool.id()); + let hint = tip(&app.ui.keymap, tr(tool.label()), &command); + let (usable, selected) = match app.ui.mode { + // In bake mode Paint is the cage or skew brush while one of them is being painted + Mode::Baking => { + let bake_brush = tool == Tool::Paint && app.ui.bake_paint_brush.on; + (bake_brush, bake_brush) + } + // A greyed tool never shows as selected, even while it stays equipped + _ => { + let usable = crate::menus::enabled(app, &command); + (usable, usable && app.session.tool.tool == tool) + } + }; + let button = ui.add_enabled_ui(usable, |ui| icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(tr(tool.label())).clicked() && app.ui.mode == Mode::Painting { app.run("tool.select", json!({"tool": tool.id()})); } } - ui.add_space(6.0); + ui.add_space(SHELF_GROUP_GAP); ui.separator(); - ui.add_space(6.0); - let quick_mask = &app.session.quick_mask; - for (command, icon, label, selected) in [ - ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled), - ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing), - ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), selected, 28.0).clicked() { - app.run(command, json!({})); - } - } + ui.add_space(SHELF_GROUP_GAP); + } - ui.add_space(6.0); - ui.separator(); - ui.add_space(6.0); - if icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, 28.0).clicked() { - app.ui.dock.focus(Panel::Assets); + let quick_mask = &app.session.quick_mask; + for (command, icon, label, selected) in [ + ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled), + ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing), + ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted), + ] { + let hint = tip(&app.ui.keymap, label, command); + let button = ui.add_enabled_ui(crate::menus::enabled(app, command), |ui| icon_button(ui, icon, &hint, selected, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(label).clicked() { + app.run(command, json!({})); } - }); + } + + ui.add_space(SHELF_GROUP_GAP); + ui.separator(); + ui.add_space(SHELF_GROUP_GAP); + let painting = app.ui.mode == Mode::Painting; + if ui.add_enabled_ui(painting, |ui| icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, SHELF_BUTTON_SIZE)).inner.clicked() + { + app.ui.dock.focus(Panel::Assets); + } }); }); } diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index dcce58df..7bd1a539 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -13,6 +13,9 @@ const STORAGE_STEM: &str = "ui"; /// eframe storage key under which earlier builds kept the UI state, as RON const RON_STORAGE_KEY: &str = "ui"; +/// Textures moved from index 8 to index 6 when procedurals joined that type +const LEGACY_TEXTURES_TAB: usize = 8; +const TEXTURES_TAB: usize = 6; /// Maximum encoded UI state size for both reads and writes; typical states are a few kilobytes const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; @@ -65,7 +68,7 @@ impl UiStateStore { return None; } - let ui = serde_json::from_slice::(&bytes).ok(); + let ui = decode_json_ui(&bytes); if !ui.as_ref().is_some_and(fully_read) { self.unreadable = Some((bytes, "json")); } @@ -75,7 +78,10 @@ impl UiStateStore { /// Preserve the original RON when decoding loses either dock, even if other settings load fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { let text = storage.get_string(RON_STORAGE_KEY)?; - let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + let mut ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if let Some(ui) = &mut ui { + migrate_shelf_tab(ui, ron_has_shelf_path(&text)); + } if !ui.as_ref().is_some_and(fully_read) { self.unreadable = Some((text.into_bytes(), "ron")); } @@ -158,9 +164,52 @@ impl UiStateStore { } } +/// Old saved states have no shelf path, so their former Textures index needs remapping +fn migrate_shelf_tab(ui: &mut UiState, has_shelf_path: bool) { + if ui.shelf_tab == LEGACY_TEXTURES_TAB && !has_shelf_path { + ui.shelf_tab = TEXTURES_TAB; + } +} + +/// Decode JSON settings and map the old Textures index only when its new fields are absent +fn decode_json_ui(bytes: &[u8]) -> Option { + let mut ui = serde_json::from_slice::(bytes).ok()?; + if ui.shelf_tab == LEGACY_TEXTURES_TAB { + let has_shelf_path = serde_json::from_slice::(bytes) + .ok() + .and_then(|state| state.as_object().map(|fields| fields.contains_key("shelf_path"))) + .unwrap_or(true); + migrate_shelf_tab(&mut ui, has_shelf_path); + } + Some(ui) +} + +/// Ignore user text while looking for the field in legacy RON settings +fn ron_has_shelf_path(text: &str) -> bool { + let bytes = text.as_bytes(); + let mut quoted = false; + let mut escaped = false; + for (index, byte) in bytes.iter().enumerate() { + if quoted { + if escaped { + escaped = false; + } else if *byte == b'\\' { + escaped = true; + } else if *byte == b'"' { + quoted = false; + } + } else if *byte == b'"' { + quoted = true; + } else if bytes[index..].starts_with(b"shelf_path:") && (index == 0 || matches!(bytes[index - 1], b',' | b'(' | b' ' | b'\n')) { + return true; + } + } + false +} + /// The UI state saved in `file`, if it reads pub fn read(file: &Path) -> Option { - serde_json::from_slice(&read_bytes(file).ok()?).ok() + decode_json_ui(&read_bytes(file).ok()?) } /// eframe's browser storage reports write failures only through logging, so verify before discarding old settings @@ -311,6 +360,20 @@ pub(crate) mod tests { assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); } + #[test] + fn legacy_ron_textures_index_migrates_to_the_combined_type() { + let mut storage = MemoryStorage::default(); + let legacy = include_str!("../tests/fixture/ui_state_before_json.ron") + .replace("shelf_tab:0", "shelf_tab:8") + .replace("shelf_filter:\"\"", "shelf_filter:\"shelf_path:\""); + assert!(legacy.contains("shelf_tab:8") && !ron_has_shelf_path(&legacy)); + storage.values.insert(RON_STORAGE_KEY.into(), legacy); + + let loaded = UiStateStore::default().load(Some(&storage)).expect("the legacy state loads"); + + assert_eq!(loaded.shelf_tab, TEXTURES_TAB); + } + #[test] fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { let folder = test_folder("unreadable"); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index fa1e6c4b..20736bdd 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -263,7 +263,7 @@ 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 }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4ac469eb..6fd29db0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -46,7 +46,13 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { && app.ui.bake_paint_brush.on && !app.session.bake_meshes.high.is_empty() && app.session.doc.project.texture_sets.get(app.session.ts()).is_some_and(|texture_set| { - !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased + let settings = &texture_set.bake; + match app.ui.bake_paint_brush.target { + texturecraft_engine::core::BakePaintTarget::Skew => settings.skew_applies(), + texturecraft_engine::core::BakePaintTarget::Cage => { + !settings.high_poly.use_low_as_high && settings.cage.kind == texturecraft_engine::core::CageType::DistanceBased + } + } }); app.ui.bake_paint_brush.on = bake_painting; @@ -54,12 +60,25 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { crate::toolbar::paint_bar(app, ui); } + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + // A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture. + let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) { + ui.data_mut(|data| { + let endpoint = data.get_temp(stroke_end); + data.remove::(stroke_end); + endpoint + }) + } else { + None + }; + finish_unavailable_tool_gestures(app, pending_2d_endpoint); crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); let aux_view = match app.session.view { _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => Some(crate::gpu::AuxView::QuickMask), ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), + _ if mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)), _ => None, }; let mut sync = PendingSync(Some(aux_view)); @@ -78,6 +97,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let divider_x = split_divider_x(app, ui, full); let left = Rect::from_min_max(full.min, pos2(divider_x - SPLIT_LINE_HALF_WIDTH, full.max.y)); let right = Rect::from_min_max(pos2(divider_x + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max); + // Each view draws only on its side, so overlays such as the texture set name stay out of a narrow neighbour let clip = ui.clip_rect(); ui.set_clip_rect(left.intersect(clip)); @@ -100,6 +120,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } if mode == crate::state::Mode::Baking { crate::bake_mode::bake_bar(app, ui.ctx(), full); + crate::bake_mode::bake_warnings(app, ui.ctx(), full); } // Keep drawing until the 3D view finishes accumulating anti-aliasing samples @@ -178,9 +199,30 @@ const RUBBER_BAND_GAP: f32 = 4.0; /// Opacity of the UV tile outlines in the 2D view const UV_TILE_OUTLINE_ALPHA: u8 = 40; +/// Width of the UV tile outlines, in points +const UV_TILE_OUTLINE_WIDTH: f32 = 1.0; + +/// The texture set name in the 2D view's bottom-right corner: its inset from the corner and its text size, in points +const SET_NAME_INSET: egui::Vec2 = vec2(10.0, 10.0); +const SET_NAME_TEXT_SIZE: f32 = 11.0; + /// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; +/// The bake brush cursor's outline: width in points and white alpha +const BAKE_PAINT_CURSOR_STROKE: f32 = 1.0; +const BAKE_PAINT_CURSOR_ALPHA: u8 = 200; + +/// A UDIM tile label: its offset from the tile's top-left corner and its text size, in points +const UV_TILE_LABEL_OFFSET: egui::Vec2 = vec2(6.0, 4.0); +const UV_TILE_LABEL_SIZE: f32 = 11.0; + +/// The projection stencil's dashed outline: width, white alpha, dash and gap, in points +const STENCIL_OUTLINE_STROKE: f32 = 1.0; +const STENCIL_OUTLINE_ALPHA: u8 = 120; +const STENCIL_OUTLINE_DASH: f32 = 5.0; +const STENCIL_OUTLINE_GAP: f32 = 4.0; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -219,18 +261,25 @@ fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) { ui.interact(zone, split_divider_id(ui), Sense::drag()).on_hover_and_drag_cursor(egui::CursorIcon::ResizeHorizontal); } +/// The shader's view modes (`Shade::view_mode`): the material, one channel, the aux texture (mesh map, mask or quick mask), the UV checker +const VIEW_MODE_MATERIAL: u32 = 0; +const VIEW_MODE_CHANNEL: u32 = 1; +const VIEW_MODE_AUX_TEXTURE: u32 = 2; +const VIEW_MODE_UV_CHECKER: u32 = 3; + fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { - _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (2, 0), - ViewMode::Material => (0, 0), - ViewMode::Channel(selected_channel) => (1, selected_channel.index() as u32), - ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0), - ViewMode::UvChecker => (3, 0), + _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (VIEW_MODE_AUX_TEXTURE, 0), + ViewMode::Material => (VIEW_MODE_MATERIAL, 0), + ViewMode::Channel(selected_channel) => (VIEW_MODE_CHANNEL, selected_channel.index() as u32), + ViewMode::MeshMap(_) | ViewMode::Mask(_) => (VIEW_MODE_AUX_TEXTURE, 0), + ViewMode::UvChecker => (VIEW_MODE_UV_CHECKER, 0), }; let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + // Polygon fill shows the polygons it fills without changing the saved wireframe toggles - let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; + let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, @@ -316,7 +365,7 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); let bake = bake_visualization(app); - frame.shade.bake = bake.filter(|_| frame.kind == ViewKind::Scene); + frame.shade.bake = bake; let scene = match (sync.0.take(), app.gpu.as_mut()) { (Some(aux), Some(gpu_link)) => { let sync_start_ms = crate::now_ms(); @@ -364,14 +413,16 @@ const VIEW_HEADER_TOP_GAP: f32 = 8.0; /// Width of each of the two pickers const VIEW_PICKER_WIDTH: f32 = 130.0; +/// Where `view_header` draws its pickers in a view of `rect`; `None` when the view is too narrow. +fn view_header_rect(rect: Rect) -> Option { + (rect.width() >= VIEW_HEADER_WIDTH).then(|| { + Rect::from_min_size(rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP), vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)) + }) +} + /// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { - if rect.width() < VIEW_HEADER_WIDTH { - return; - } - - let header_min = rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP); - let header = Rect::from_min_size(header_min, vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)); + let Some(header) = view_header_rect(rect) else { return }; let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); let current = texturecraft_engine::camera_cmds::current(&app.session); @@ -392,28 +443,38 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { } }); + // Bake mode lights the project mesh with the neutral material unless the painted one is asked for + let baking = app.ui.mode == crate::state::Mode::Baking; + let neutral = baking && app.session.view == ViewMode::Material && app.ui.bake_visualization.neutral_shown; let label = match app.session.view { + _ if neutral => "Neutral Material".to_owned(), ViewMode::MeshMap(map) => crate::i18n::baked_map_label(map).to_owned(), _ => app.session.view.label(), }; let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut child, |ui| { - if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() { + if baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() { + app.ui.bake_visualization.neutral_shown = true; + app.run("viewport.view", json!({"mode": "material"})); + } + if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() { + // Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone + app.ui.bake_visualization.neutral_shown &= !baking; app.run("viewport.view", json!({"mode": "material"})); } ui.separator(); + if baking { + mesh_map_entries(app, ui); + return; + } + for channel in channels { if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { app.run("viewport.view", json!({"mode": channel.id()})); } } ui.separator(); - for map in BakedMap::ALL { - let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); - if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() { - app.run("viewport.view", json!({"mode": format!("map:{}", map.id())})); - } - } + mesh_map_entries(app, ui); ui.separator(); if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { app.run("viewport.view", json!({"mode": "uvChecker"})); @@ -421,6 +482,16 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { }); } +/// The view picker's entries that show one baked mesh map +fn mesh_map_entries(app: &mut TextureCraftApp, ui: &mut Ui) { + for map in BakedMap::ALL { + let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() { + app.run("viewport.view", json!({"mode": format!("map:{}", map.id())})); + } + } +} + fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { let tk = Tokens::get(ui.ctx()); let o = pos2(rect.left() + 28.0, rect.bottom() - 28.0); @@ -488,7 +559,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Navigation; S + drag moves the projection stencil instead, below let delta = ui.input(|input| input.pointer.delta()); let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); - let stencil_drag = s_held && app.session.tool.stencil.is_some(); + + // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise + let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; + let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); if stencil_drag || adjusting { // The stencil or the brush changes instead of the camera } else if response.dragged_by(PointerButton::Middle) { @@ -510,8 +584,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { if shift && app.ui.mode == crate::state::Mode::Painting { - let brush = &mut app.session.tool.brush; - brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + // A tool that can't act keeps its size: its controls are hidden + if tool_acts(app) { + let brush = &mut app.session.tool.brush; + brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } } else { app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); } @@ -537,7 +614,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Stencil: S + left drag turns it, S + right drag scales it, S + middle drag moves it - if s_held && let Some(stencil) = app.session.tool.stencil.as_mut() { + if s_held + && stencil_moves + && let Some(stencil) = app.session.tool.stencil.as_mut() + { if response.dragged_by(PointerButton::Primary) { stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0); } else if response.dragged_by(PointerButton::Secondary) { @@ -636,7 +716,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let symmetry_handle = !app.session.stroke_active() && crate::symmetry::manipulator_hovered(app, ui, rect); // Painting - let painting = app.ui.mode == crate::state::Mode::Painting + let painting = tool_acts(app) && !popup && !alt && !adjusting @@ -716,7 +796,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began let mut symmetry_cursor = None; - if app.ui.mode == crate::state::Mode::Painting + if tool_acts(app) && !navigating && response.hovered() && brush_tool(app.session.tool.tool) @@ -746,7 +826,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - if app.ui.mode == crate::state::Mode::Painting && path_tool { + if tool_acts(app) && path_tool { path_overlay(app, ui, rect, &response, false, show); } crate::symmetry::overlay(app, ui, rect, symmetry_cursor); @@ -781,7 +861,7 @@ fn bake_visualization(app: &TextureCraftApp) -> Option) { ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside); } -/// V held with the Clone tool in painting mode: clicks set the clone source. +/// V held with the Clone tool in painting mode: clicks set the clone source fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { - app.ui.mode == crate::state::Mode::Painting - && app.session.tool.tool == Tool::Clone - && ui.input(|i| i.key_down(egui::Key::V)) - && !ui.ctx().egui_wants_keyboard_input() + tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(egui::Key::V)) && !ui.ctx().egui_wants_keyboard_input() } /// Crosshair where the Clone tool reads from. fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { - let tk = Tokens::get(ui.ctx()); - let Some(c) = project(app, rect, pos) else { return }; - let p = ui.painter_at(rect); - for (w, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, tk.viewport_accent)] { - p.circle_stroke(c, 7.0, Stroke::new(w, color)); - p.line_segment([c - vec2(11.0, 0.0), c + vec2(11.0, 0.0)], Stroke::new(w, color)); - p.line_segment([c - vec2(0.0, 11.0), c + vec2(0.0, 11.0)], Stroke::new(w, color)); + let tokens = Tokens::get(ui.ctx()); + let Some(center) = project(app, rect, pos) else { return }; + + let painter = ui.painter_at(rect); + for (stroke_width, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, tokens.viewport_accent)] { + painter.circle_stroke(center, 7.0, Stroke::new(stroke_width, color)); + painter.line_segment([center - vec2(11.0, 0.0), center + vec2(11.0, 0.0)], Stroke::new(stroke_width, color)); + painter.line_segment([center - vec2(0.0, 11.0), center + vec2(0.0, 11.0)], Stroke::new(stroke_width, color)); + } +} + +/// Whether the active tool can act on the selection now: a greyed tool ignores clicks, keys and drags in the views +fn tool_acts(app: &TextureCraftApp) -> bool { + app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool) +} + +/// Both views must close gestures even when the selection disables their input handlers. +fn finish_unavailable_tool_gestures(app: &mut TextureCraftApp, pending_2d_endpoint: Option) { + if !tool_acts(app) { + if app.session.stroke_active() { + match app.session.end_stroke() { + Ok(()) => { + if let Some(endpoint) = pending_2d_endpoint { + app.last_paint_uv = Some(endpoint); + } + } + Err(error) => app.toast(error.to_string(), true), + } + } + app.session.end_polygon_fill_box(); } } @@ -1507,15 +1608,13 @@ fn brush_tool(t: Tool) -> bool { matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) } -/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a -/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True -/// while Ctrl is held with a brush tool and no stroke is under way. -fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool { - let held = - app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command); - if held && let Some(right) = brush_drag_button(resp) { - adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta())); +/// Ctrl (Cmd on macOS) + drag changes the brush instead of painting: true while it applies (see `adjust_brush`) +fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) -> bool { + let held = tool_acts(app) && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|input| input.modifiers.command); + if held && let Some(right) = brush_drag_button(response) { + adjust_brush(&mut app.session.tool.brush, right, ui.input(|input| input.pointer.delta())); } + held } @@ -1527,23 +1626,28 @@ fn brush_drag_button(resp: &egui::Response) -> Option { /// While a Ctrl+drag changes the brush, its values beside where the drag began (drawn over the /// view; the tool bar and Properties show them too). -fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjusting: bool) { - let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return }; - let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return }; - // The pointer would cover the values; the brush cursor stays where the drag began. - ui.ctx().set_cursor_icon(egui::CursorIcon::None); - let b = &app.session.tool.brush; - let text = if right { - format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0) +fn brush_readout(app: &TextureCraftApp, ui: &Ui, response: &egui::Response, adjusting: bool) { + let Some(right_drag) = brush_drag_button(response).filter(|_| adjusting) else { return }; + let Some(press_origin) = ui.input(|input| input.pointer.press_origin()) else { return }; + + // Keep the values clear of the pointer and the brush cursor at its press origin + if ui.input(|input| input.pointer.latest_pos()).is_some_and(|pointer| response.rect.contains(pointer)) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } + + let brush = &app.session.tool.brush; + let text = if right_drag { + format!("{} {:.1} {} {:.0}", tr("Size"), brush.size / 0.25 * 100.0, tr("Hardness"), brush.hardness * 100.0) } else { - format!("{} {:.0} {} {:.0}°", tr("Flow"), b.flow * 100.0, tr("Angle"), b.angle) + format!("{} {:.0} {} {:.0}°", tr("Flow"), brush.flow * 100.0, tr("Angle"), brush.angle) }; - let tk = Tokens::get(ui.ctx()); - let p = ui.painter_at(resp.rect); - let g = p.layout_no_wrap(text, egui::FontId::proportional(12.0), tk.text_strong); - let r = Rect::from_min_size(at + vec2(18.0, -30.0), g.size()).expand2(vec2(6.0, 3.0)); - p.rect_filled(r, 3.0, tk.panel); - p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong); + + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(response.rect); + let galley = painter.layout_no_wrap(text, egui::FontId::proportional(12.0), tokens.text_strong); + let readout_rect = Rect::from_min_size(press_origin + vec2(18.0, -30.0), galley.size()).expand2(vec2(6.0, 3.0)); + painter.rect_filled(readout_rect, 3.0, tokens.panel); + painter.galley(readout_rect.min + vec2(6.0, 3.0), galley, tokens.text_strong); } /// Size fraction, hardness and flow change per point of a Ctrl+drag @@ -1619,9 +1723,9 @@ fn pen_pressure(ui: &Ui) -> f32 { ui.data_mut(|d| d.insert_temp(id, f)); f } - // A pen lifts with no pressure, and a tap paints on that frame: keep its contact pressure. + // A pen lifts with no pressure, so keep its contact pressure for a tap Some((egui::TouchPhase::End, None)) => ui.data(|d| d.get_temp(id)).unwrap_or(1.0), - // A touch without pressure (a finger) must not inherit an earlier pen's. + // A finger must not inherit an earlier pen's pressure Some((egui::TouchPhase::Start, None)) => { ui.data_mut(|d| d.remove_temp::(id)); 1.0 @@ -1660,8 +1764,8 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Conversions between the view's points and the texture set's UV space - let ts = app.session.ts(); - let set = app.session.doc.project.texture_sets.get(ts); + let texture_set_index = app.session.ts(); + let set = app.session.doc.project.texture_sets.get(texture_set_index); let [scale_x, scale_y] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |texture_set| texture_set.size())); let pan = app.ui.uv_pan; let to_uv = |pointer: egui::Pos2| { @@ -1708,7 +1812,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Painting in UV space - let painting = app.ui.mode == crate::state::Mode::Painting + let painting = tool_acts(app) && app.properties_popup.is_none() && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) && !alt @@ -1738,7 +1842,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let frame = Frame { view_id: VIEW_2D, size: frame_size_in_pixels(ui, rect), - kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, + kind: ViewKind::Uv { ts: texture_set_index, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, camera: app.session.camera, shade: shade(app), visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), @@ -1750,8 +1854,10 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); - let set = app.session.doc.project.texture_sets.get(ts); - let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside); + let set = app.session.doc.project.texture_sets.get(texture_set_index); + let outline = |tile: Rect| { + painter.rect_stroke(tile, 0.0, Stroke::new(UV_TILE_OUTLINE_WIDTH, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside) + }; match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { Some((texture_set, grid)) => { for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { @@ -1761,10 +1867,10 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let tile = Rect::from_two_pos(to_screen(u0, v0), to_screen(u0 + tile_scale / grid.cols as f32, v0 + tile_scale / grid.rows as f32)); outline(tile); painter.text( - tile.left_top() + vec2(6.0, 4.0), + tile.left_top() + UV_TILE_LABEL_OFFSET, egui::Align2::LEFT_TOP, udim.to_string(), - egui::FontId::proportional(11.0), + egui::FontId::proportional(UV_TILE_LABEL_SIZE), tokens.viewport_text, ); } @@ -1773,7 +1879,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin outline(Rect::from_two_pos(to_screen(0.0, 0.0), to_screen(1.0, 1.0))); } } - if app.ui.mode == crate::state::Mode::Painting && path_tool { + if tool_acts(app) && path_tool { path_overlay(app, ui, rect, &response, true, show); } @@ -1792,15 +1898,63 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); if bake_paint_on && let Some(hover) = response.hover_pos() { let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS); - painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); + painter.circle_stroke(hover, radius, Stroke::new(BAKE_PAINT_CURSOR_STROKE, Color32::from_white_alpha(BAKE_PAINT_CURSOR_ALPHA))); } } + // Match the 3D view's stamp size and hardness + let show_brush_cursor = tool_acts(app) && !alt && !v_held; + let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)); + if show_brush_cursor + && !path_tool + && brush_tool(app.session.tool.tool) + && !response.dragged_by(PointerButton::Middle) + // Egui keeps hover during drags; adjustment may continue outside the view + && (adjusting || pointer_in_view) + // Keep the brush outline at the press origin while adjusting + && let Some(cursor_center) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } + // Header pickers need the normal pointer + && !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(cursor_center)) + { + // Match the pressure-scaled radius used by continue_stroke_uv + let radius_points = + (to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(BRUSH_CURSOR_MIN_RADIUS_POINTS); + if pointer_in_view { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } + brush_cursor_2d(&painter, cursor_center, radius_points, app.session.tool.brush.hardness); + } brush_readout(app, ui, &response, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); - let name = app.session.doc.project.texture_sets.get(ts).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); - ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); + let name = app.session.doc.project.texture_sets.get(texture_set_index).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); + let name_position = rect.right_bottom() - SET_NAME_INSET; + ui.painter().text(name_position, egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(SET_NAME_TEXT_SIZE), tokens.viewport_text); +} + +/// Smallest visible 2D brush outline, in points +const BRUSH_CURSOR_MIN_RADIUS_POINTS: f32 = 1.5; + +/// Hardness ring segments, balancing smoothness and per-frame shape work +const BRUSH_CURSOR_RING_SEGMENTS: usize = 48; + +/// Smaller hardness rings overlap the center dot +const BRUSH_CURSOR_MIN_RING_HARDNESS: f32 = 0.05; + +/// The brush outline and hardness ring around `center`, with `radius_points` in screen points +fn brush_cursor_2d(painter: &egui::Painter, center: egui::Pos2, radius_points: f32, hardness: f32) { + painter.circle_stroke(center, radius_points, Stroke::new(2.5, Color32::from_black_alpha(140))); + painter.circle_stroke(center, radius_points, Stroke::new(1.2, Color32::from_white_alpha(230))); + if hardness > BRUSH_CURSOR_MIN_RING_HARDNESS { + let inner_ring: Vec = (0..=BRUSH_CURSOR_RING_SEGMENTS) + .map(|point_index| { + let angle = point_index as f32 / BRUSH_CURSOR_RING_SEGMENTS as f32 * std::f32::consts::TAU; + center + vec2(angle.cos(), angle.sin()) * radius_points * hardness + }) + .collect(); + painter.add(egui::Shape::dashed_line(&inner_ring, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); + } + painter.circle_filled(center, 1.5, Color32::WHITE); } /// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. @@ -1837,7 +1991,13 @@ fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, if response.clicked_by(PointerButton::Primary) || response.drag_stopped_by(PointerButton::Primary) { let finishing = app.session.stroke_active(); match app.session.end_stroke() { - Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)), + Ok(()) if finishing => { + app.last_paint_uv = ui.data_mut(|data| { + let endpoint = data.get_temp(stroke_end); + data.remove::(stroke_end); + endpoint + }); + } Ok(()) => {} Err(error) => app.toast(error.to_string(), true), } @@ -1900,6 +2060,33 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t mod tests { use super::*; + #[test] + fn unavailable_tools_finish_strokes_and_box_fills() { + use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives}; + + for tool in [Tool::Paint, Tool::PolygonFill] { + let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.session.tool.tool = tool; + let history = app.session.history_labels().len(); + if tool == Tool::Paint { + app.session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + assert!(app.session.stroke_active()); + } else { + assert!(app.session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0); + } + app.session.target = StackTarget::Effect(LayerId(u64::MAX)); + assert!(!tool_acts(app)); + finish_unavailable_tool_gestures(app, None); + assert!(!app.session.stroke_active()); + assert_eq!(app.session.history_labels().len(), history + 1); + assert_eq!(app.session.end_polygon_fill_box(), 0, "the interrupted box is already closed"); + finish_unavailable_tool_gestures(app, None); + assert_eq!(app.session.history_labels().len(), history + 1, "cleanup records the gesture only once"); + } + } + #[test] fn stored_surfaces_release_after_a_frame_without_paths() { use texturecraft_engine::{core::EffectKind, execute, geom::primitives}; @@ -2094,7 +2281,7 @@ mod tests { let app = harness.state_mut(); app.ui.mode = crate::state::Mode::Baking; let before = bake_visualization(app).unwrap(); - assert!(before.high_poly && before.cage); + assert!(before.high_poly.shown && before.cage_shown()); app.start_bake(vec![0]); diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6860bdc4..1703abde 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -125,9 +125,11 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { result_sender.send(Ok(output)).unwrap(); let app = harness.state_mut(); app.start_bake(vec![0]); + let mesh_id = app.session.mesh_id; app.bake = Some(BakeJob { queue: Vec::new(), total: 1, + mesh_id, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs new file mode 100644 index 00000000..6c54d052 --- /dev/null +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -0,0 +1,158 @@ +//! The 2D view hides the system pointer and draws the brush outline under it while painting. + +use egui::{CursorIcon, Event, Pos2, Shape, TouchDeviceId, TouchId, TouchPhase}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +fn cursor(harness: &Harness<'_, TextureCraftApp>) -> CursorIcon { + harness.output().platform_output.cursor_icon +} + +#[test] +fn painting_in_the_2d_view_replaces_the_pointer_with_the_brush_outline() { + let mut harness = harness(); + let center = egui::pos2(800.0, 480.0); + harness.hover_at(center); + harness.run_steps(3); + assert_eq!(cursor(&harness), CursorIcon::None, "the brush outline replaces the pointer"); + harness.hover_at(egui::pos2(2.0, 2.0)); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is back"); +} + +#[test] +fn outside_painting_the_2d_view_keeps_the_normal_pointer() { + let mut harness = harness(); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + let center = egui::pos2(800.0, 480.0); + harness.hover_at(center); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None); +} + +#[test] +fn unavailable_paint_tool_keeps_the_pointer_and_hides_the_2d_brush_outline() { + let mut harness = harness(); + let fill = execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill, "target": "content"})).unwrap(); + + let pointer = egui::pos2(800.0, 480.0); + harness.hover_at(pointer); + harness.run_steps(3); + + assert_ne!(cursor(&harness), CursorIcon::None, "a fill layer cannot take the paint tool"); + assert!(rings_at(&harness, pointer).is_empty(), "an unavailable brush has no outline"); +} + +/// Radii of the white brush-outline rings (stroke 1.2) around `center` in the last frame. +fn rings_at(harness: &Harness<'_, TextureCraftApp>, center: Pos2) -> Vec { + fn walk(shape: &Shape, center: Pos2, out: &mut Vec) { + match shape { + Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, center, out)), + Shape::Circle(circle) if (circle.stroke.width - 1.2).abs() < 1e-3 && circle.center.distance(center) < 0.5 => out.push(circle.radius), + _ => {} + } + } + let mut out = Vec::new(); + harness.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, center, &mut out)); + out +} + +#[test] +fn the_view_header_keeps_the_normal_pointer_and_gets_no_brush_outline() { + let mut harness = harness(); + // The header starts 8 points below the view edge and is 22 points high + let view_top = (0..200).map(|y| y as f32).find(|&y| { + harness.hover_at(egui::pos2(300.0, y)); + harness.run_steps(2); + cursor(&harness) == CursorIcon::None + }); + let top = view_top.expect("the view has a top edge"); + let header = egui::pos2(800.0, top + 8.0 + 11.0); + harness.hover_at(header); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None, "over the pickers the pointer stays"); + assert!(rings_at(&harness, header).is_empty(), "no brush outline over the pickers"); + let below = egui::pos2(800.0, top + 120.0); + harness.hover_at(below); + harness.run_steps(3); + assert_eq!(cursor(&harness), CursorIcon::None, "below the header the brush outline is back"); + assert!(!rings_at(&harness, below).is_empty()); +} + +#[test] +fn a_light_pen_shows_the_smaller_footprint_it_paints() { + let mut harness = harness(); + harness.state_mut().session.tool.brush.size = 0.05; + harness.state_mut().session.tool.brush.min_size = 0.5; + let center = egui::pos2(800.0, 600.0); + harness.hover_at(center); + harness.run_steps(3); + let full = rings_at(&harness, center); + assert_eq!(full.len(), 1, "one outline at full pressure"); + // Half pressure gives 0.75 of the full radius with this minimum size + let events = &mut harness.input_mut().events; + events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: center, force: Some(0.5) }); + events.push(Event::PointerMoved(center)); + harness.step(); + let light = rings_at(&harness, center); + assert_eq!(light.len(), 1); + assert!((light[0] / full[0] - 0.75).abs() < 1e-3, "half pressure shows 0.75 of the radius: {} vs {}", light[0], full[0]); +} + +#[test] +fn dragging_out_of_the_2d_view_brings_the_system_pointer_back() { + let mut harness = harness(); + let center = egui::pos2(800.0, 480.0); + harness.hover_at(center); + harness.run_steps(3); + assert_eq!(cursor(&harness), CursorIcon::None, "inside the view the brush outline replaces the pointer"); + // Drag from the view to its upper-left outside corner + harness.event(Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + harness.run_steps(2); + assert_eq!(cursor(&harness), CursorIcon::None, "still inside while dragging"); + let outside = egui::pos2(2.0, 2.0); + harness.hover_at(outside); + harness.run_steps(3); + assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible even during a drag"); + assert!(rings_at(&harness, outside).is_empty(), "no brush outline outside the view"); + harness.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + harness.run_steps(2); +} + +#[test] +fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { + let mut harness = harness(); + let center = egui::pos2(800.0, 480.0); + let ctrl = egui::Modifiers::COMMAND; + harness.hover_at(center); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(ctrl)); + harness.event(Event::PointerButton { pos: center, button: egui::PointerButton::Secondary, pressed: true, modifiers: ctrl }); + harness.run_steps(2); + // The outline stays anchored while the pointer is hidden inside the view + harness.hover_at(center + egui::vec2(10.0, 0.0)); + harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "anchored outline while the pointer is in the view"); + assert_eq!(cursor(&harness), CursorIcon::None); + // Outside the view, the outline stays anchored and the system pointer returns + harness.hover_at(egui::pos2(2.0, 2.0)); + harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "the outline stays at the press origin outside the view"); + assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible"); + harness.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl }); + harness.event(Event::ModifiersChanged(egui::Modifiers::NONE)); + harness.run_steps(2); +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs new file mode 100644 index 00000000..60f6f03e --- /dev/null +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -0,0 +1,43 @@ +//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps +//! the mesh meanwhile, the job is cancelled and its result is dropped. + +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use egui_kittest::Harness; +use texturecraft_engine::bake::Progress; +use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; + +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let progress = Arc::new(Progress::new()); + let (tx, receiver) = std::sync::mpsc::channel(); + let (maps_tx, maps) = std::sync::mpsc::channel(); + let id = mesh_id(h.state().session.mesh_id); + // Leak the sender so the channel stays empty instead of closed. + std::mem::forget(tx); + std::mem::forget(maps_tx); + let running = + RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; + h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); + (h, progress) +} + +#[test] +fn a_job_on_a_swapped_mesh_is_cancelled_and_dropped() { + let (mut h, progress) = harness_with_job(|current| current + 1); + h.step(); + assert!(h.state().bake.is_none(), "the job is dropped"); + assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop"); +} + +#[test] +fn a_job_on_the_current_mesh_keeps_running() { + let (mut h, progress) = harness_with_job(|current| current); + h.step(); + assert!(h.state().bake.is_some(), "the job stays"); + assert!(!progress.cancel.load(Ordering::Relaxed)); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 1b330244..787f8645 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -187,9 +187,9 @@ fn texture_set_resolution_controls_are_independent_from_bake_output() { let mut harness = harness(Some(BakedMap::AmbientOcclusion)); let before = harness.state().session.doc.project.clone(); let active_set = harness.state().session.ts(); - harness.get_all_by_value("256 × 256").nth(1).unwrap().click(); + harness.get_all_by_value("256x256").nth(1).unwrap().click(); harness.run_steps(3); - click(&mut harness, "128 × 128"); + click(&mut harness, "128x128"); wait_for_resolution(&mut harness, 1, 128); let session = &harness.state().session; @@ -226,33 +226,33 @@ fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { harness.run_steps(4); let before = harness.state().session.doc.project.clone(); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); let resolution_position = harness.get_by_label("UV tile 1002 resolution").rect().center(); harness.hover_at(resolution_position); harness.run_steps(3); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + assert_eq!(harness.get_all_by_value("256x256").count(), 2); harness.hover_at(egui::pos2(900.0, 500.0)); harness.run_steps(3); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); harness.get_by_label("UV tile 1002 resolution").click(); harness.run_steps(3); - click(&mut harness, "128 × 128"); - harness.get_by_value("128 × 128*"); + click(&mut harness, "128x128"); + harness.get_by_value("128x128*"); let texture_set = &harness.state().session.doc.project.texture_sets[0]; assert_eq!(texture_set.resolution, 256); assert_eq!(texture_set.tile_resolution(1001), 256); assert_eq!(texture_set.tile_resolution(1002), 128); assert_eq!(texture_set.bake, before.texture_sets[0].bake); - harness.get_by_value("128 × 128*").click(); + harness.get_by_value("128x128*").click(); harness.run_steps(3); click(&mut harness, "Remove resolution override"); assert_eq!(harness.state().session.doc.project, before); - assert!(harness.query_by_value("128 × 128*").is_none()); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + assert!(harness.query_by_value("128x128*").is_none()); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); harness.state_mut().session.undo().unwrap(); harness.run_steps(3); - harness.get_by_value("128 × 128*"); + harness.get_by_value("128x128*"); harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); @@ -277,14 +277,14 @@ fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { harness.run_steps(4); harness.get_by_label("1001"); - harness.get_by_value("256 × 256"); + harness.get_by_value("256x256"); harness.get_by_label("1002"); - harness.get_by_value("128 × 128*"); + harness.get_by_value("128x128*"); click_checkbox(&mut harness, "1002"); assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); - assert!(!harness.get_by_label("Bake Selected Textures (1)").accesskit_node().is_disabled()); + assert!(!harness.get_by_label("Bake (7)").accesskit_node().is_disabled(), "7 checked maps on the one tile left"); click_checkbox(&mut harness, "1001"); - assert!(harness.get_by_label("Bake Selected Textures (0)").accesskit_node().is_disabled()); + assert!(harness.get_by_label("Bake (0)").accesskit_node().is_disabled()); harness.state_mut().session.undo().unwrap(); harness.state_mut().session.undo().unwrap(); harness.run_steps(3); @@ -479,24 +479,45 @@ fn curvature_controls_follow_the_method_and_notes_visibility_rules() { } #[test] -fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { +fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { let mut harness = harness(None); harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); - assert!(harness.query_by_label("Cage Type").is_none()); - assert!(harness.query_by_label("Skew Correction").is_none()); + + // Without a high poly everything that needs one shows greyed, as in the reference + for needs_high in ["Match", "Max Frontal Distance", "Edge Protection"] { + assert!(harness.get_by_label(needs_high).accesskit_node().is_disabled(), "{needs_high} is greyed"); + } + harness.get_by_label("The cage applies once a high poly mesh is loaded."); + harness.get_by_label("Skew Correction applies once a high poly mesh is loaded."); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "nothing selected to remove"); harness.state_mut().session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); harness.run_steps(3); - harness.get_by_label("Max Frontal Distance"); + assert!(!harness.get_by_label("Max Frontal Distance").accesskit_node().is_disabled()); + assert!(harness.query_by_label("The cage applies once a high poly mesh is loaded.").is_none()); harness.get_by_label("Skew Correction"); + harness.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; + harness.run_steps(3); + assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); + harness.get_by_label("Skew Correction needs Average Normals turned on in the cage settings."); + harness.state_mut().session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + harness.run_steps(3); + harness.get_by_label("Skew Correction is not available while the low poly mesh is used as the high poly mesh."); + harness.get_by_label("The cage is not used while the low poly mesh is used as the high poly mesh."); + assert!(harness.get_by_label("Paint Cage").accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + (settings.cage.average_normals, settings.high_poly.use_low_as_high) = (true, false); + harness.run_steps(3); + assert!(!harness.get_by_label("Edge Protection").accesskit_node().is_disabled()); click(&mut harness, "Cage Type"); click(&mut harness, "Custom File"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); harness.get_by_label("Cage Scene"); assert!(harness.query_by_label("Max Frontal Distance").is_none()); - assert!(harness.query_by_label("Skew Correction").is_none()); + assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); + harness.get_by_label("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself."); for button_size in [20.0, 28.0] { harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); @@ -506,3 +527,117 @@ fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { } } } + +#[test] +fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + let session = &mut harness.state_mut().session; + session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let mesh = session.mesh.clone(); + session.bake_meshes.cage = Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), bytes: Default::default(), mesh, base_color: Vec::new() }); + let settings = &mut session.doc.project.texture_sets[0].bake; + (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); + harness.run_steps(3); + + assert!(harness.get_by_label("Load Cage").accesskit_node().is_disabled(), "the cage does not apply"); + assert!(!harness.get_by_label("Remove Cage").accesskit_node().is_disabled()); + click(&mut harness, "Remove Cage"); + assert!(harness.state().session.bake_meshes.cage.is_none()); +} + +#[test] +fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() { + let mut harness = harness(None); + assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode starts on the neutral material"); + harness.get_by_value("Neutral Material").click(); + harness.run_steps(3); + assert!(harness.query_by_label("UV checker").is_none(), "bake mode lists lighting and mesh maps only"); + harness.get_by_label("Material").click(); + harness.run_steps(3); + assert!(!harness.state().ui.bake_visualization.neutral_shown); + harness.get_by_value("Material"); +} + +#[test] +fn the_baking_visualization_panel_opens_like_the_reference_at_first_launch() { + let harness = harness(None); + for shown in ["Show for Selected Texture Set Only", "Mesh", "Matching Error", "Cage Surface", "Cage Wireframe Opacity"] { + harness.get_by_label(shown); + } + for closed in ["Missing Seams on Hard Edges", "Project Mesh", "Roughness"] { + assert!(harness.query_by_label(closed).is_none(), "{closed} sits in a section that starts closed"); + } + assert!(harness.state().ui.bake_visualization.missing_seams.shown, "missing seams are ticked in every reference capture"); +} + +#[test] +fn texture_set_names_show_in_full_beside_their_resolution() { + let mut harness = harness(None); + harness.state_mut().session.doc.project.texture_sets[0].name = "LowerTorso".into(); + harness.state_mut().ui.dock.focus(Panel::TextureSetList); + harness.run_steps(3); + + // "LowerTorso" is about 75 points wide; cut short it collapses to an ellipsis of about 20 + const FULL_NAME_MIN_WIDTH: f32 = 60.0; + + // The breadcrumb names the set too; the list row is the top-most + let row = harness.get_all_by_label("LowerTorso").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap(); + let width = row.rect().width(); + assert!(width >= FULL_NAME_MIN_WIDTH, "the name is not cut short: {width}"); +} + +#[test] +fn the_high_poly_scene_is_a_list_with_add_and_remove() { + let mut harness = harness(None); + harness.state_mut().session.add_high_poly_bytes("Gunhigh.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_label("Add High-Poly Meshes"); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "− waits for a selection"); + + harness.get_by_label("Gunhigh.obj").click(); + harness.run_steps(3); + harness.get_by_label("Remove").click(); + harness.run_steps(3); + assert!(harness.state().session.bake_meshes.high.is_empty()); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled()); +} + +#[test] +fn the_eye_greys_the_baking_meshes_and_holds_the_project_mesh() { + let mut harness = harness(None); + assert!(!harness.get_by_label("Mesh").accesskit_node().is_disabled(), "the eye starts off"); + harness.get_by_label("Hide Baking Meshes").click(); + harness.run_steps(3); + + for greyed in ["Mesh", "Matching Error", "Cage Surface", "Cage Wireframe Opacity"] { + assert!(harness.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed} is greyed"); + } + assert!(harness.state().ui.bake_visualization.project_mesh.shown); + + // The header, not its "Reset Project Mesh (LP)" button further right + let header = harness.get_all_by_label_contains("Project Mesh (LP)").min_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap(); + header.click(); + harness.run_steps(3); + assert!(harness.get_by_label("Project Mesh").accesskit_node().is_disabled(), "the project mesh stays on"); + assert!(!harness.get_by_label("Roughness").accesskit_node().is_disabled(), "the neutral material stays editable"); +} + +#[test] +fn picking_material_while_painting_keeps_bake_modes_neutral_material() { + let mut harness = harness(None); + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(3); + + // Painting mode shows the 3D and 2D views, each with a view menu; the 3D view's comes first + harness.get_all_by_value("Material").next().unwrap().click(); + harness.run_steps(3); + + // The menu entry, not the dropdown that shows the same word + let entry = harness.get_all_by_label("Material").find(|node| node.accesskit_node().role() != Role::ComboBox).unwrap(); + entry.click(); + harness.run_steps(3); + + assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); +} diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index eb80adf6..360dca82 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -272,8 +272,11 @@ fn color_selection_snapshots_and_quick_mask_pick() { let center = harness.state().viewport_rect.center(); harness.hover_at(center + egui::vec2(80.0, 0.0)); let expected = save(&mut harness, "color-selection-picking"); + + execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); let with_quick_mask = save(&mut harness, "color-selection-picking-quick-mask"); + assert_eq!( with_quick_mask.get_pixel(center.x as u32, center.y as u32), expected.get_pixel(center.x as u32, center.y as u32), @@ -281,14 +284,18 @@ fn color_selection_snapshots_and_quick_mask_pick() { ); click_at(&mut harness, center); + assert!(harness.state().session.quick_mask.editing, "picking preserves quick-mask editing"); save(&mut harness, "color-selection-quick-mask-restored"); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; harness.get_by_label(&pick_color_label()).click(); save(&mut harness, "color-selection-picking-2d"); click_at(&mut harness, center); + assert!(harness.state().picking_id_color.is_none()); + execute(&mut harness.state_mut().session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); save(&mut harness, "color-selection-no-id-map"); } diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 218eb0cc..fdd04351 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one reorders its stack. +//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -12,16 +12,16 @@ fn id(v: Value, key: &str) -> u64 { } /// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. -fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { - let start = h.get_by_label(from).rect().center(); - let r = h.get_by_label(to).rect(); - let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 }); - h.drag_at(start); - h.run_steps(2); - h.hover_at(end); - h.run_steps(2); - h.drop_at(end); - h.run_steps(3); +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { + let start = harness.get_by_label(from).rect().center(); + let row_rect = harness.get_by_label(to).rect(); + let end = egui::pos2(row_rect.center().x, if below { row_rect.bottom() - 4.0 } else { row_rect.top() + 4.0 }); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); } #[test] @@ -32,17 +32,88 @@ fn dragging_an_effect_row_reorders_its_stack() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); - assert_eq!(order(&h), [a, b, c]); - // The rows list the top first: C, B, A. A dropped on C's upper half goes to the top. - drag(&mut h, "Effect A", "Effect C", false); - assert_eq!(order(&h), [b, c, a]); - // A dropped on B's lower half goes back to the bottom. - drag(&mut h, "Effect A", "Effect B", true); - assert_eq!(order(&h), [a, b, c]); - // C dropped on A's upper half lands between A and B. - drag(&mut h, "Effect C", "Effect A", false); - assert_eq!(order(&h), [a, c, b]); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(order(&harness), [a, b, c]); + + // Rows show C, B, A; dropping A above C moves it to the top + drag(&mut harness, "Effect A", "Effect C", false); + assert_eq!(order(&harness), [b, c, a]); + + // Dropping A below B returns it to the bottom + drag(&mut harness, "Effect A", "Effect B", true); + assert_eq!(order(&harness), [a, b, c]); + + // Dropping C above A places it between A and B + drag(&mut harness, "Effect C", "Effect A", false); + assert_eq!(order(&harness), [a, c, b]); +} + +/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows. +#[test] +fn an_effect_row_sets_its_blend_mode_and_opacity() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect, effect_of(&harness).id.0); + + // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field + let row = harness.get_by_label("Effect A").rect(); + let pair_right = row.right() - 4.0; + let pair_left = pair_right - 82.0; + let mode_at = egui::pos2(pair_left + 20.0, row.center().y); + harness.drag_at(mode_at); + harness.drop_at(mode_at); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply); + + let history = harness.state().session.history_labels().len(); + let opacity_at = egui::pos2(pair_right - 20.0, row.center().y); + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); +} + +/// A drag whose first frame leaves the opacity unchanged still starts its own undo step: undo keeps the blend mode set before it +#[test] +fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + + let history = harness.state().session.history_labels().len(); + let opacity_at = harness.get_by_label("Opacity of Effect A").rect().center(); + // Equal right and down movement adds nothing to the value: the drag starts without a change + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at + egui::vec2(8.0, 8.0)); + harness.run_steps(2); + assert_eq!(effect_of(&harness).opacity, 1.0, "the drag started without changing the opacity"); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "the drag lowered the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(effect_of(&harness).opacity, 1.0); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); } diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index a26ac303..3a4a2e63 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -1,5 +1,4 @@ -//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged -//! or clicked to. +//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all). use egui::accesskit::Role; use egui_kittest::Harness; @@ -9,79 +8,82 @@ use texturecraft_engine::core::{EffectKind, LayerId}; use texturecraft_ui_egui::TextureCraftApp; /// The sample session with its first generator effect selected, and that effect's id. -fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { +fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session .doc .project .layers .values() - .find_map(|l| { - let mask = l.mask.iter().flat_map(|m| m.effects.iter()); - l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id)) + .find_map(|layer| { + let mask_effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()); + layer.content_effects.iter().chain(mask_effects).find(|effect| matches!(effect.kind, EffectKind::Generator(_))).map(|effect| (layer.id, effect.id)) }) .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - (h, effect) + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + (harness, effect) } -fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { - h.state().session.doc.project.effect(effect).unwrap().1.opacity +fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.global.balance, + _ => panic!("a generator"), + } } /// The track under the slider labelled `label` (the row below the label). -fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { - let l = h.get_by_label(label).rect(); - egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0)) +fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { + let label_rect = harness.get_by_label(label).rect(); + egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0)) } #[test] -fn dragging_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - assert_eq!(opacity(&h, effect), 1.0); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect)); +fn dragging_a_slider_applies_it() { + let (mut harness, effect) = selected_generator(); + assert_eq!(balance(&harness, effect), 0.5); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); } /// A generator slider applies while it is dragged (the texture follows the pointer), and the /// whole drag is one undo step. #[test] fn dragging_a_generator_slider_applies_live_as_one_undo_step() { - let (mut h, effect) = harness(); - let level = |h: &Harness<'_, TextureCraftApp>| match &h.state().session.doc.project.effect(effect).unwrap().1.kind { - EffectKind::Generator(g) => g.level, + let (mut harness, effect) = selected_generator(); + let level = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.level, _ => panic!("a generator"), }; - let steps = h.state().session.history_labels().len(); - let t = track(&h, "Level"); - let at = |x: f32| egui::pos2(t.left() + x, t.center().y); - h.drag_at(at(10.0)); - h.run_steps(2); + let steps = harness.state().session.history_labels().len(); + let track_rect = track(&harness, "Level"); + let point_at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y); + harness.drag_at(point_at(10.0)); + harness.run_steps(2); let mut last = 0.0; for x in [60.0, 160.0] { - h.hover_at(at(x)); - h.run_steps(2); - assert!(level(&h) > last && level(&h) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&h)); - last = level(&h); + harness.hover_at(point_at(x)); + harness.run_steps(2); + assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); + last = level(&harness); } - h.drop_at(at(160.0)); - h.run_steps(3); - assert_eq!(level(&h), last); - assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); + harness.drop_at(point_at(160.0)); + harness.run_steps(3); + assert_eq!(level(&harness), last); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } /// The combo box in the row of the levels editor's Reset button. -fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = h.get_by_label("Reset").rect().center().y; - h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let row = harness.get_by_label("Reset").rect().center().y; + harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } /// A content levels effect offers a channel for its histogram; picking one keeps it selected. @@ -90,102 +92,102 @@ fn content_levels_pick_the_histogram_channel() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel"); - channel_picker(&h).click(); - h.run_steps(2); - h.get_by_label("Roughness").click(); - h.run_steps(3); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays"); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); + channel_picker(&harness).click(); + harness.run_steps(2); + harness.get_by_label("Roughness").click(); + harness.run_steps(3); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays"); } #[test] -fn clicking_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - let t = track(&h, "Opacity"); - let at = egui::pos2(t.left() + 20.0, t.center().y); - h.drag_at(at); - h.drop_at(at); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect)); +fn clicking_a_slider_track_applies_it() { + let (mut harness, effect) = selected_generator(); + let track_rect = track(&harness, "Global balance"); + let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); } /// The number field in the row of the slider labelled `label`. -fn number_field<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = h.get_by_label(label).rect().center().y; - h.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Focus the opacity field and press `keys`, then type `text`, one key per frame like a person. -fn type_opacity(h: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { - number_field(h, "Opacity").focus(); - h.run_steps(2); - for k in keys { - h.key_press(*k); - h.run_steps(1); +/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person. +fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { + number_field(harness, "Global balance").focus(); + harness.run_steps(2); + for key in keys { + harness.key_press(*key); + harness.run_steps(1); } - for c in text.chars() { - number_field(h, "Opacity").type_text(&c.to_string()); - h.run_steps(1); + for character in text.chars() { + number_field(harness, "Global balance").type_text(&character.to_string()); + harness.run_steps(1); } } #[test] fn a_value_typed_in_the_number_field_applies() { - let (mut h, effect) = harness(); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.25); - assert_eq!(h.state().session.history_labels().len(), steps + 1); + let (mut harness, effect) = selected_generator(); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.25); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); } /// Dragging the track while the number field has focus drops what was typed there: leaving the /// field afterwards does not undo the drag. #[test] fn a_track_drag_drops_text_typed_in_the_number_field() { - let (mut h, effect) = harness(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "5"); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - let dragged = opacity(&h, effect); - assert!(dragged < 0.5, "the drag applies: {dragged}"); - // Leave whatever has focus: a click on empty space. - h.drag_at(egui::pos2(5.0, 1390.0)); - h.drop_at(egui::pos2(5.0, 1390.0)); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), dragged, "the text typed before the drag stays dropped"); + let (mut harness, effect) = selected_generator(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5"); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + let dragged = balance(&harness, effect); + assert!(dragged < 0.25, "the drag applies: {dragged}"); + // Leave whatever has focus: a click on empty space + harness.drag_at(egui::pos2(5.0, 1390.0)); + harness.drop_at(egui::pos2(5.0, 1390.0)); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); } /// Leaving the number field without typing, or with Escape, keeps the value (not the rounded /// text the field shows) and makes no undo step. #[test] fn leaving_the_number_field_unchanged_keeps_the_value() { - let (mut h, effect) = harness(); - texturecraft_engine::execute(&mut h.state_mut().session, "effect.set", &json!({"effect": effect.0, "opacity": 0.333})).unwrap(); - h.run_steps(2); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[], ""); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333, "left without typing"); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "9"); - assert_eq!(number_field(&h, "Opacity").value().as_deref(), Some("0.39")); - assert!(number_field(&h, "Opacity").is_focused()); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333); - // Typing the value it already has is no edit either. - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(h.state().session.history_labels().len(), steps); + let (mut harness, effect) = selected_generator(); + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "balance": 0.333})).unwrap(); + harness.run_steps(2); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[], ""); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333, "left without typing"); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); + assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); + assert!(number_field(&harness, "Global balance").is_focused()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333); + // Typing the value it already has is no edit either + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(harness.state().session.history_labels().len(), steps); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs new file mode 100644 index 00000000..d09cfc0c --- /dev/null +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -0,0 +1,141 @@ +//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, Source}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::theme::Brightness; + +/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. +fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + session.camera.pitch = 0.5; + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + (harness, LayerId(effect)) +} + +fn generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generator { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + _ => panic!("expected a generator"), + } +} + +/// Drags the track under slider `label` to the right. +fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_label(label).rect(); + let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0); + let end = start + egui::vec2(120.0, 0.0); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); +} + +#[test] +fn global_blur_applies_as_one_undo_step() { + let (mut harness, effect) = harness(false); + let history = harness.state().session.history_labels().len(); + drag_slider(&mut harness, "Global blur"); + assert!(generator(&harness, effect).global.blur > 0.0); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + harness.state_mut().session.undo().unwrap(); + assert_eq!(generator(&harness, effect).global.blur, 0.0); +} + +#[test] +fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { + let (mut harness, effect) = harness(false); + let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.run_steps(3); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); +} + +#[test] +fn changing_kind_in_the_panel_preserves_the_effect() { + let (mut harness, effect) = harness(false); + let history = harness.state().session.history_labels().len(); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Curvature")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Dirt").click(); + harness.run_steps(3); + + assert_eq!(generator(&harness, effect).kind, GeneratorKind::Dirt); + assert_eq!(harness.state().session.history_labels().len(), history + 1); +} + +#[test] +fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { + let (mut harness, effect) = harness(false); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Uniform value").click(); + harness.run_steps(3); + assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_)))); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Mesh map").click(); + harness.run_steps(3); + assert!(generator(&harness, effect).inputs.is_empty()); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn generator_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, effect) = harness(true); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap(); + + for section in ["Attributes", "Resolution"] { + harness.get_by_label(section).click(); + harness.run_steps(3); + } + harness.run_steps(6); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-panel-sections-open-{name}.png"))).unwrap(); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + + let edits = json!({"effect": effect.0, "blur": 0.3, "balance": 0.6, "contrast": 0.4, "resolutionFactor": -2}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.state_mut().session.update(); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-adjusted.png")).unwrap(); + + // The effect row with its blend mode and opacity, in the layer stack + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7597d587..50e4458e 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -58,9 +58,9 @@ fn mask_and_content_thumbnails_select_their_own_target() { 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 still selects that effect. - let r = h.get_by_label("Effect A").rect(); - click(&mut h, egui::pos2(r.right() - 40.0, r.center().y)); + // Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity) + let row = h.get_by_label("Effect A").rect(); + click(&mut h, row.center()); assert!(matches!(h.state().session.target, StackTarget::Effect(_))); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..41b4c8cc 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,6 +1,7 @@ //! One integration-test executable avoids linking the same dependencies for every feature. //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. +mod bake_job_mesh; mod bake_mode; mod brush_drag; mod brush_section_reset; @@ -14,6 +15,7 @@ mod file_dialogs; mod fill_channel_image; mod fill_projection_section; mod filter_picker; +mod generator_panel; mod history_panel; mod layer_clipboard; mod layer_rename; @@ -29,11 +31,13 @@ mod properties_popup; mod rail; mod shelf_drop; mod shelf_hover_preview; +mod shelf_panel; mod shift_lines_2d; mod shortcut_keys; mod skew_paint; mod split_divider; mod start_window; +mod tool_availability; mod toolbar; mod symmetry; diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c7ad071a..237de107 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -20,20 +20,22 @@ const REST: f32 = 0.1; /// Real time the worker gets to render const WORKER_TIMEOUT: Duration = Duration::from_secs(60); -/// Open the Materials tab and find two labels unique to shelf tiles +/// Open the Materials tab and find the first two labels (the grid is sorted by name) unique to shelf tiles fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder() + let mut harness = Harness::builder() .with_size(egui::vec2(1600.0, 960.0)) .with_step_dt(step_seconds) .with_pixels_per_point(pixels_per_point) .build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.shelf_tab = MATERIALS_TAB; - h.run_steps(4); + harness.state_mut().ui.shelf_tab = MATERIALS_TAB; + harness.run_steps(4); - let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect(); + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + let unique: Vec<_> = plain.into_iter().filter(|material| harness.query_all_by_label(material.label).count() == 1).take(2).collect(); assert_eq!(unique.len(), 2, "two materials with unique names"); - (h, unique) + (harness, unique) } /// Largest drawn texture in pixels, excluding fonts and images below `min_width` points @@ -155,6 +157,15 @@ fn high_dpi_smart_material_hover_stays_within_the_renderer_limit() { check_high_dpi_orb_hover(1, "Steel Painted Worn"); } +// Coverage instrumentation makes the 512px software-rendered preview substantially slower. +fn high_dpi_worker_timeout() -> Duration { + if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + WORKER_TIMEOUT + } +} + fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; @@ -166,7 +177,7 @@ fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { let expected = Some([MAX_PREVIEW_SIZE_PX; 2]); let started = Instant::now(); - while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < WORKER_TIMEOUT { + while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < high_dpi_worker_timeout() { harness.run_steps(1); std::thread::sleep(Duration::from_millis(20)); } diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs new file mode 100644 index 00000000..a33068b7 --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -0,0 +1,316 @@ +//! The Assets panel's layout: columns at the reference width, type row, size menu, breadcrumb, side panes and toolbar + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::saved_search::SavedSearch; +use texturecraft_ui_egui::shelf_view::ShelfView; + +/// The reference's capture window: its Assets panel shows four columns there +const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0); +/// A window whose default Assets panel is too narrow for the full type row +const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0); +/// The types' positions in the shelf's type row (its table is crate-private) +const MATERIALS_TYPE: usize = 0; +const SMART_MASKS_TYPE: usize = 2; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; +const ENVIRONMENTS_TYPE: usize = 7; +/// How far the saved brush's spacing differs from the current brush's, so loading it shows +const SAVED_SPACING_CHANGE: f32 = 0.25; +/// Tile columns the reference shows at its panel width +const REFERENCE_COLUMNS: usize = 4; + +/// The sample project with the shelf on the Materials type +fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; + harness.run_steps(4); + harness +} + +/// The plain materials in the grid's order (by name) +fn plain_materials() -> Vec<&'static SmartMaterial> { + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + plain +} + +/// A clickable node labelled `label` (its tooltip, once shown, has the same label) +fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")) +} + +#[test] +fn the_default_panel_shows_the_reference_column_count() { + let harness = shelf(REFERENCE_WINDOW); + let tops: Vec = plain_materials().iter().take(REFERENCE_COLUMNS + 1).map(|material| harness.get_by_label(material.label).rect().top()).collect(); + + assert!(tops[..REFERENCE_COLUMNS].iter().all(|top| *top == tops[0]), "the first {REFERENCE_COLUMNS} tiles share a row: {tops:?}"); + assert!(tops[REFERENCE_COLUMNS] > tops[0], "the next tile starts a row: {tops:?}"); +} + +#[test] +fn a_click_on_the_picked_type_shows_every_type() { + let mut harness = shelf(REFERENCE_WINDOW); + let mask = SMART_MASKS[0].label; + assert!(harness.query_by_label(mask).is_none(), "the Materials type hides smart masks"); + + button(&harness, "Materials").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(mask).is_some(), "no type picked shows smart masks too"); +} + +#[test] +fn the_search_narrows_the_picked_type_and_greys_types_without_matches() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials().into_iter().find(|material| material.label.to_lowercase().contains("rust")).unwrap(); + let mask = SMART_MASKS.iter().find(|mask| mask.label.to_lowercase().contains("rust")).unwrap(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(mask.label).is_some(), "the matching mask shows"); + assert!(harness.query_by_label(material.label).is_none(), "a matching material of another type does not"); + assert!(button(&harness, "Environments").accesskit_node().is_disabled(), "no environment matches"); + assert!(!button(&harness, "Materials").accesskit_node().is_disabled()); + + button(&harness, "Materials").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.shelf_filter, "rust", "picking a type keeps the search"); + assert!(harness.query_by_label(material.label).is_some()); +} + +#[test] +fn unavailable_project_images_do_not_make_textures_match() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().session.doc.resources.insert("unavailable-preview.png".into(), vec![0].into()); + harness.state_mut().ui.shelf_filter = "unavailable-preview.png".into(); + harness.run_steps(3); + + assert!(button(&harness, "Textures").accesskit_node().is_disabled()); + assert!(harness.query_by_label("unavailable-preview.png").is_none()); +} + +#[test] +fn the_breadcrumb_arrow_picks_a_library() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + + button(&harness, "Browse folders").click(); + harness.run_steps(2); + for library in ["Project", "Starter assets", "Your assets"] { + assert!(harness.query_by_label(library).is_some(), "the list offers {library}"); + } + harness.get_by_label("Project").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_path, ["project"]); + assert!(harness.query_by_label(material).is_none(), "built-in materials are not in the project"); +} + +#[test] +fn the_thumbnail_size_menu_switches_to_the_list() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + let tile_width = harness.get_by_label(material).rect().width(); + + button(&harness, "Thumbnail size").click(); + harness.run_steps(2); + harness.get_by_label_contains("List").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_view, ShelfView::List); + assert!(harness.get_by_label(material).rect().width() > tile_width * 2.0, "a list row spans the panel"); +} + +#[test] +fn reset_query_shows_every_asset_again() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_path = vec!["starter".into()]; + harness.run_steps(2); + + button(&harness, "Reset query").click(); + harness.run_steps(3); + + let ui = &harness.state().ui; + assert!(ui.shelf_filter.is_empty() && ui.shelf_path.is_empty()); + assert!(harness.query_by_label(SMART_MASKS[0].label).is_some(), "every type shows"); +} + +#[test] +fn refresh_reads_the_saved_brushes_again() { + let mut harness = shelf(REFERENCE_WINDOW); + let stale = vec![std::path::PathBuf::from("gone.tcbrush")]; + harness.state_mut().brushes = Some(stale.clone()); + harness.run_steps(1); + + button(&harness, "Refresh").click(); + harness.run_steps(3); + + assert_ne!(harness.state().brushes, Some(stale), "the brushes folder was read again"); + assert!(harness.query_by_label("Import resources...").is_some(), "the toolbar has the import button"); +} + +#[test] +fn a_saved_search_restores_its_query() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Saved searches").click(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.run_steps(3); + + button(&harness, "Save the current search").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1); + harness.state_mut().ui.shelf_filter.clear(); + harness.run_steps(2); + + harness.get_by_label("rust").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_filter, "rust"); + + harness.get_by_label("rust").click_secondary(); + harness.run_steps(2); + // The context menu opens last, so its Delete is the newest node with that label + harness.get_all_by_label("Delete").last().unwrap().click(); + harness.run_steps(2); + assert!(harness.state().ui.shelf_saved_searches.is_empty()); +} + +#[test] +fn filter_by_path_picks_a_folder() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Filter by path").click(); + harness.run_steps(3); + + harness.get_by_label("Starter assets").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_path, ["starter"]); +} + +#[test] +fn many_saved_searches_keep_the_path_filter_reachable() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.state_mut().ui.shelf_saved_searches = (0..100) + .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .collect(); + harness.run_steps(3); + + let heading = harness.get_by_label("FILTER BY PATH").rect(); + assert!(heading.bottom() < NARROW_WINDOW.y, "the path pane heading stays on screen: {heading:?}"); + assert!(harness.query_by_label("Starter assets").is_some(), "the folder tree remains reachable"); +} + +#[test] +fn a_long_saved_search_list_can_select_the_last_query() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_saved_searches = (0..1000) + .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .collect(); + harness.run_steps(3); + assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); + + harness.get_by_label("search 0").hover(); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -50_000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(3); + harness.get_by_label("search 999").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_filter, "filter 999"); +} + +#[test] +fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.run_steps(3); + + for label in ["Refresh", "Reset query", "Import resources...", "Saved searches", "Filter by path"] { + let rect = button(&harness, label).rect(); + assert!(rect.bottom() <= NARROW_WINDOW.y, "{label} is inside the window: {rect:?}"); + } + assert!(harness.query_by_label("Filter by type").is_some(), "the type row folds into one dropdown"); + assert!(harness.query_by_label("Environments").is_none()); +} + +#[test] +fn an_environment_tile_switches_the_lighting() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = ENVIRONMENTS_TYPE; + harness.run_steps(3); + let shown = harness.state().session.doc.project.display.environment.clone(); + let other = ENVIRONMENTS.iter().find(|name| **name != shown).unwrap(); + + harness.get_by_label(other).click(); + harness.run_steps(2); + + assert_eq!(harness.state().session.doc.project.display.environment, *other); +} + +#[test] +fn a_saved_brush_is_a_tile_that_loads_the_preset() { + let mut harness = shelf(REFERENCE_WINDOW); + let mut saved = harness.state().session.tool.brush.clone(); + saved.spacing += SAVED_SPACING_CHANGE; + let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id())); + std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); + harness.state_mut().brushes = Some(vec![path.clone()]); + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + harness.get_by_label(path.file_stem().unwrap().to_str().unwrap()).click(); + harness.run_steps(2); + std::fs::remove_file(&path).unwrap(); + + assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke"); +} + +#[test] +fn saved_smart_materials_keep_their_type_pickable_in_your_assets() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().library = Some(vec![std::path::PathBuf::from("Mine.tcmat")]); + harness.state_mut().ui.shelf_path = vec!["user".into()]; + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + assert!(!button(&harness, "Smart materials").accesskit_node().is_disabled(), "a saved smart material is in Your assets"); + assert!(button(&harness, "Materials").accesskit_node().is_disabled(), "no plain material is"); +} + +#[test] +fn saved_smart_materials_are_read_whatever_the_type_and_after_a_refresh() { + let mut harness = shelf(REFERENCE_WINDOW); + assert!(harness.state().library.is_some(), "read on the Materials type"); + + button(&harness, "Refresh").click(); + harness.run_steps(2); + + assert!(harness.state().library.is_some(), "read again after a refresh"); +} + +#[test] +fn procedurals_are_in_the_textures_type() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some()); +} diff --git a/crates/ui-egui/tests/it/shift_lines_2d.rs b/crates/ui-egui/tests/it/shift_lines_2d.rs index a6e6175d..08537f4f 100644 --- a/crates/ui-egui/tests/it/shift_lines_2d.rs +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use serde_json::json; use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::{StackTarget, core::LayerId}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::ViewLayout; @@ -179,6 +180,42 @@ fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() { assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO)); } +#[test] +fn a_forced_2d_completion_moves_the_next_line_start() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.hover_at(CANCELLED_DRAG_FROM); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: CANCELLED_DRAG_FROM, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(CANCELLED_DRAG_TO); + harness.run_steps(2); + assert!(harness.state().session.stroke_active(), "the 2D drag is still active"); + + harness.state_mut().session.target = StackTarget::Effect(LayerId(u64::MAX)); + harness.run_steps(1); + assert!(!harness.state().session.stroke_active(), "the unavailable tool finishes the drag"); + harness.state_mut().session.target = StackTarget::Content; + harness.event(Event::PointerButton { pos: CANCELLED_DRAG_TO, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + let (before_line, width) = alpha(&harness); + click(&mut harness, SECOND_CLICK, true); + let (after_line, _) = alpha(&harness); + let line = added(&before_line, &after_line); + + let dab_centre = |point| { + let mut reference = uv_view_app(); + let (blank, width) = alpha(&reference); + click(&mut reference, point, false); + let (painted, _) = alpha(&reference); + centre(&added(&blank, &painted), width) + }; + let expected_middle = (dab_centre(CANCELLED_DRAG_TO) + dab_centre(SECOND_CLICK)) * 0.5; + assert!(painted_at(&line, width, expected_middle), "Shift+click starts at the forced completion endpoint"); +} + #[test] fn a_new_project_does_not_reuse_the_previous_projects_line_start() { let mut harness = uv_view_app(); diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index bfcc3e3e..dd3b5d02 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -6,6 +6,10 @@ use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; +/// A stroke inside the 2D view, right of bake mode's two settings columns +const STROKE_START: egui::Pos2 = egui::pos2(700.0, 500.0); +const STROKE_END: egui::Pos2 = egui::pos2(900.0, 500.0); + /// A bake-mode app with a high poly, the 2D view, and Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -24,34 +28,47 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let mut h = harness(); h.get_by_label("Skew Correction"); assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on); - // Off: a drag in the view paints nothing. - h.drag_at(egui::pos2(600.0, 500.0)); - h.hover_at(egui::pos2(800.0, 500.0)); - h.drop_at(egui::pos2(800.0, 500.0)); + + // Off: a drag in the view paints nothing + h.drag_at(STROKE_START); + h.hover_at(STROKE_END); + h.drop_at(STROKE_END); h.run_steps(3); assert!(h.state().session.doc.bake_paint.is_empty(), "the brush is off"); - // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke. + // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke h.get_by_label("Paint Skew Correction").scroll_to_me(); h.run_steps(3); h.get_by_label("Paint Skew Correction").click(); h.run_steps(3); assert!(h.state().ui.bake_paint_brush.on); h.get_by_label("Radius"); - h.drag_at(egui::pos2(600.0, 500.0)); + h.drag_at(STROKE_START); h.run_steps(2); - h.hover_at(egui::pos2(800.0, 500.0)); + h.hover_at(STROKE_END); h.run_steps(2); - h.drop_at(egui::pos2(800.0, 500.0)); + h.drop_at(STROKE_END); h.run_steps(3); let map = h.state().session.doc.bake_paint.get(&(0, texturecraft_engine::core::BakePaintTarget::Skew)).cloned().expect("the stroke made a skew map"); let painted = map.values.iter().filter(|v| **v > 0.5).count(); assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); - // Removing it from the panel clears the map. + // Removing it from the panel clears the map h.get_by_label("Remove Skew Correction").scroll_to_me(); h.run_steps(3); h.get_by_label("Remove Skew Correction").click(); h.run_steps(3); assert!(h.state().session.doc.bake_paint.is_empty()); } + +#[test] +fn turning_average_normals_off_stops_the_skew_brush() { + let mut h = harness(); + h.state_mut().ui.bake_paint_brush.on = true; + h.run_steps(2); + assert!(h.state().ui.bake_paint_brush.on, "skew correction applies with the default cage"); + + h.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; + h.run_steps(2); + assert!(!h.state().ui.bake_paint_brush.on, "the bake would leave the skew map out"); +} diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index e0a487fc..4e8c0364 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -157,6 +157,26 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { assert_eq!(restored.split_ratio, 0.5); } +#[test] +fn old_textures_tab_index_migrates_without_changing_new_all_types() { + let mut storage = MemoryStorage::default(); + let mut state = UiState::default(); + state.shelf_tab = 8; + UiStateStore::default().save(&state, &mut storage); + + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(8)); + + let mut legacy: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + legacy.as_object_mut().unwrap().remove("shelf_path"); + legacy.as_object_mut().unwrap().insert("shelf_filter".into(), "shelf_path".into()); + storage.0.insert("ui.json".into(), legacy.to_string()); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(6)); + + state.shelf_tab = 0; + UiStateStore::default().save(&state, &mut storage); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(0)); +} + #[test] fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { // Zoomed in, a 2D sliver needs a zoom far past the one the view starts with diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs new file mode 100644 index 00000000..77fd888f --- /dev/null +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -0,0 +1,270 @@ +//! The shelf greys tools that can't act on the selection; the top bar and Properties follow it + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; +use texturecraft_engine::{Session, StackTarget, Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::theme::Brightness; + +fn add_layer(session: &mut Session, command: &str) -> u64 { + execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn select(session: &mut Session, layer: u64, target: Value) { + execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap(); +} + +fn select_nothing(session: &mut Session) { + let set = session.ts(); + session.selected.remove(&set); + session.target = StackTarget::Content; +} + +fn app_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness +} + +/// Selects a new fill layer's content with `tool` equipped +fn select_fill_content(harness: &mut Harness<'_, TextureCraftApp>, tool: Tool) { + let session = &mut harness.state_mut().session; + let fill = add_layer(session, "layer.add.fill"); + select(session, fill, json!("content")); + session.tool.tool = tool; + harness.run_steps(4); +} + +fn shelf_button_disabled(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.get_by_label(label).accesskit_node().is_disabled() +} + +fn shelf_button_selected(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +fn shows_text(harness: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + harness.output().shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(found) if found.galley.text() == text)) +} + +#[test] +fn a_fill_layer_greys_the_paint_tools_and_shows_its_own_properties() { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + harness.run_steps(4); + + assert!(!shelf_button_disabled(&harness, "Paint (1)")); + assert!(shelf_button_selected(&harness, "Paint (1)")); + assert!(shows_text(&harness, "Size"), "the brush controls are in the top bar"); + + select_fill_content(&mut harness, Tool::PolygonFill); + + assert!(shelf_button_disabled(&harness, "Paint (1)")); + assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); + assert!(!shelf_button_selected(&harness, "Polygon fill (4)"), "the equipped tool doesn't show as selected while greyed"); + assert!(!shelf_button_disabled(&harness, "Geometry mask (8)")); + assert!(shows_text(&harness, "Properties - Fill"), "a fill layer shows its fill whatever the tool"); + assert!(!shows_text(&harness, "Size"), "a tool that can't act leaves the top bar"); +} + +#[test] +fn shortcuts_skip_the_tools_the_shelf_greys() { + let mut harness = app_harness(); + select_fill_content(&mut harness, Tool::Paint); + + harness.key_press(egui::Key::Num2); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.tool, Tool::Paint, "Eraser can't act on a fill layer"); + + harness.key_press(egui::Key::P); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.tool, Tool::ColorPicker); +} + +/// Drag with the left button across the middle of the 3D view, as a stroke would +fn drag_across_the_view(harness: &mut Harness<'_, TextureCraftApp>) { + const STEPS: usize = 4; + const STEP_POINTS: f32 = 15.0; + + let center = harness.state().viewport_rect.center(); + let modifiers = egui::Modifiers::NONE; + harness.hover_at(center); + harness.event(egui::Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(2); + + for step in 1..=STEPS { + harness.hover_at(center + egui::vec2(STEP_POINTS * step as f32, 0.0)); + harness.run_steps(1); + } + + let end = center + egui::vec2(STEP_POINTS * STEPS as f32, 0.0); + harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(3); +} + +#[test] +fn a_tool_that_cant_act_ignores_the_view() { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + harness.run_steps(4); + + let steps_before = harness.state().session.history_labels().len(); + drag_across_the_view(&mut harness); + + assert!(harness.state().session.history_labels().len() > steps_before, "the drag reaches the mesh and paints a paint layer"); + + for tool in [Tool::Paint, Tool::PolygonFill, Tool::Path] { + select_fill_content(&mut harness, tool); + let steps_before = harness.state().session.history_labels().len(); + drag_across_the_view(&mut harness); + + let state = harness.state(); + assert!(state.toasts.is_empty(), "{tool:?} on a fill layer: no error toast, got {:?}", state.toasts.first().map(|toast| &toast.text)); + assert_eq!(state.session.history_labels().len(), steps_before, "{tool:?} on a fill layer changes nothing"); + assert!(state.session.tool.path.points.is_empty(), "{tool:?} places no path points"); + } +} + +#[test] +fn bake_painting_turns_on_the_shelf_paint_tool() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + assert!(shelf_button_disabled(&harness, "Paint (1)"), "nothing is being painted yet"); + + harness.state_mut().ui.bake_paint_brush.on = true; + harness.run_steps(4); + + assert!(harness.state().ui.bake_paint_brush.on, "the high poly allows bake painting"); + assert!(!shelf_button_disabled(&harness, "Paint (1)"), "Paint is the bake brush while it paints"); + assert!(shelf_button_disabled(&harness, "Eraser (2)")); + assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); +} + +#[test] +fn nothing_selected_asks_for_a_layer() { + let mut harness = app_harness(); + select_nothing(&mut harness.state_mut().session); + harness.run_steps(4); + + assert!(shows_text(&harness, "Select a layer to paint on")); + assert!(shelf_button_disabled(&harness, "Geometry mask (8)")); +} + +#[test] +fn baking_keeps_three_greyed_tools_and_rendering_none() { + let mut harness = app_harness(); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + for label in ["Paint (1)", "Eraser (2)", "Polygon fill (4)"] { + assert!(shelf_button_disabled(&harness, label), "{label}"); + } + assert!(harness.query_by_label("Path (7)").is_none()); + + harness.state_mut().ui.mode = Mode::Rendering; + harness.run_steps(4); + + assert!(harness.query_by_label("Paint (1)").is_none()); +} + +#[test] +#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] +fn tool_availability_snapshots() { + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { + return; + }; + + std::fs::create_dir_all(&directory).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + for (brightness, suffix) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(8); + harness.render().unwrap().save(directory.join(format!("{name}-{suffix}.png"))).unwrap(); + } + }; + + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + session.tool.tool = Tool::Paint; + save(&mut harness, "paint-layer"); + + let session = &mut harness.state_mut().session; + let fill = add_layer(session, "layer.add.fill"); + select(session, fill, json!("content")); + session.tool.tool = Tool::PolygonFill; + save(&mut harness, "fill-content-polygon-fill"); + + let session = &mut harness.state_mut().session; + execute(session, "effect.add.filter", &json!({"layer": paint, "target": "content", "filter": "blur"})).unwrap(); + let filter = session.doc.project.layer(texturecraft_engine::core::LayerId(paint)).unwrap().content_effects.last().unwrap().id.0; + select(session, paint, json!(filter)); + session.tool.tool = Tool::Paint; + save(&mut harness, "filter"); + + let session = &mut harness.state_mut().session; + execute(session, "mask.add.black", &json!({"layer": paint})).unwrap(); + select(session, paint, json!("mask")); + session.tool.tool = Tool::Smudge; + save(&mut harness, "mask-smudge"); + + let session = &mut harness.state_mut().session; + let folder = add_layer(session, "layer.add.group"); + select(session, folder, json!("content")); + session.tool.tool = Tool::Paint; + save(&mut harness, "folder"); + + select_nothing(&mut harness.state_mut().session); + save(&mut harness, "nothing-selected"); + + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, "baking"); + + harness.state_mut().ui.mode = Mode::Rendering; + save(&mut harness, "rendering"); +} + +#[test] +fn unavailable_effect_tools_hide_their_properties() { + for path in [false, true] { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let layer = add_layer(session, "layer.add.paint"); + select(session, layer, json!("content")); + let (effect, usable, blocked) = if path { + let result = execute(session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + (result["committed"]["effect"].as_u64().unwrap(), Tool::Path, Tool::Paint) + } else { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + let result = execute(session, "effect.add.paint", &json!({"layer": layer, "target": "mask"})).unwrap(); + (result["effect"].as_u64().unwrap(), Tool::Paint, Tool::Smudge) + }; + select(session, layer, json!(effect)); + session.tool.tool = usable; + harness.run_steps(4); + assert!(shows_text(&harness, "Size")); + harness.state_mut().session.tool.tool = blocked; + harness.run_steps(4); + assert!(!shows_text(&harness, "Size"), "unavailable effect tools hide brush controls"); + if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { + let directory = std::path::PathBuf::from(directory); + std::fs::create_dir_all(&directory).unwrap(); + let name = if path { "unavailable-path-effect.png" } else { "unavailable-mask-paint-effect.png" }; + harness.render().unwrap().save(directory.join(name)).unwrap(); + } + } +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index fbcecb49..d4374926 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -282,16 +282,16 @@ fn bake_uv_tiles_snapshot() { harness.state_mut().ui.mode = Mode::Baking; save(&mut harness, &output_dir, "bake-uv-tiles"); - harness.get_by_value("128 × 128*").click(); + harness.get_by_value("128x128*").click(); save(&mut harness, &output_dir, "bake-tile-resolution-menu"); harness.get_by_label("Remove resolution override").click(); save(&mut harness, &output_dir, "bake-tile-resolution-inherited"); - assert!(harness.query_by_value("128 × 128*").is_none()); + assert!(harness.query_by_value("128x128*").is_none()); assert!(harness.state().session.doc.project.texture_sets[0].tile_resolutions.is_empty()); let inherited_resolution = harness.get_by_label("UV tile 1002 resolution").rect().center(); harness.hover_at(inherited_resolution); save(&mut harness, &output_dir, "bake-tile-resolution-hover"); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + assert_eq!(harness.get_all_by_value("256x256").count(), 2); harness.hover_at(egui::pos2(900.0, 500.0)); harness.state_mut().session.undo().unwrap(); harness.run_steps(3); diff --git a/docs/architecture.md b/docs/architecture.md index 2ddcd76b..8d5deb43 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -121,10 +121,10 @@ on the CPU by `render::displace` from the composited height. A fill can carry a `MaterialLink` (`core::layer`): a MaterialCraft graph whose cooked maps are the fill's image sources. `engine::link_cmds` imports `.mcmat` files (`formats::mcmat`), keeps the -`.mcraft` package as a resource, and re-cooks by running `materialcraft-cli` with the link's +`.mcraft` or `.sbs` source as a resource, and re-cooks its named graph by running `materialcraft-cli` with the link's values, the texture set's resolution and its baked mesh maps (`LinkJob::run`, on a worker thread in the UI). Every cook stores its maps under fresh resource names, so undo, redo and the decoded -image cache never disagree. The apps share the file format and the command line, never code. +image cache never disagree. The apps share the `craft-mcmat` format library and the command line; neither depends on the other app. ## Commands and automation diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f255a509..0ead3445 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -325,8 +325,9 @@ of a second. A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is documented in MaterialCraft's `docs/control-protocol.md` § Portable materials) becomes a fill layer whose channel sources are its cooked maps and whose `link` (shown by `project.inspect`) holds the -graph's exposed inputs, presets and image inputs. The apps share the format and the command line, -not code. +graph's exposed inputs, presets and image inputs. Both apps use the shared `craft-mcmat` container. +Versions 1 and 2 are accepted; version 1 contains a legacy JSON `.mcraft` source that current +MaterialCraft cannot reopen, so its cooked maps remain usable but re-cooking needs a compatible older version. | Command | Params | |---|---| @@ -334,9 +335,9 @@ not code. | `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` | | `material.link.preset` | `{layer?, name, cook?: true}` | | `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) | -| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` package, to open in MaterialCraft | +| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` or `.sbs` source, to open in MaterialCraft | -Re-cooks run `materialcraft-cli run file.exportMaterial {path, size, values, inputs}`: +Re-cooks use `materialcraft-cli batch` to open the saved graph by name and run `file.exportMaterial` with its size, values and inputs: `$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`, diff --git a/docs/features.md b/docs/features.md index a99bdba5..4b6928ee 100644 --- a/docs/features.md +++ b/docs/features.md @@ -16,7 +16,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA stroke and keep the size; save your own brushes there too. - **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the stencil), polygon fill (triangle, UV island or the whole mesh), **path** and **lasso fill**, a - **particle brush**, **smudge**, **clone** (V + click sets the source), color picker, Shift+click + **particle brush**, **smudge**, **clone** (V + click sets the source), material picker, Shift+click straight lines, and painting directly in the **2D UV view**. - **Geometry decals:** drop an image on the surface, then move, scale and turn its frame; it stays an editable fill layer. @@ -82,7 +82,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. - Reimport a changed mesh and your painted strokes stay on the surface. + Reimport a changed mesh and your painted strokes stay on the surface. The + `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md index 098b6ae1..fbe4f69d 100644 --- a/docs/helpful-pr-review-guidelines.md +++ b/docs/helpful-pr-review-guidelines.md @@ -8,7 +8,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Review-only requests call for findings; requests to fix or improve also authorize focused local edits - A review may conclude that no changes are needed. If the PR meets the applicable standards and no actionable issues are found, leave it unchanged. Do not invent findings, add unnecessary tests, or make edits merely to produce a diff. Report what was checked and any remaining validation limits - Apply all review standards across the entire affected method, including existing code and relevant tests -- Complete naming, spacing, and comment cleanup throughout it +- Read and apply [CODE_STYLE.md](../CODE_STYLE.md) throughout that scope - Make additional correctness or performance changes when supported by evidence and appropriate validation - Separate substantial changes that address an independent problem, explaining why - Apply the same scope to standalone functions and inspect relevant callers when verifying behavior @@ -27,6 +27,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi ## Optimization and simplicity - Prefer the smallest complete solution that is efficient and easy to understand +- Keep control flow direct and share repeated logic when it makes the code simpler - Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access - For loops, batches, and streaming operations, trace allocations and buffer lifetimes across multiple iterations, including outputs retained from earlier iterations. Identify work that belongs once per operation rather than once per item, using the full selection when making retention decisions - Consider caching, batching, and parallelism when measurements justify their complexity and memory cost @@ -35,39 +36,6 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations - Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity -## Clarity, naming, and spacing - -- Clean up the functions or methods being changed and their relevant tests within the scope above -- Use descriptive names that explain purpose; include units where useful -- Avoid cryptic abbreviations, misleading names, and unexplained production constants -- Keep control flow direct and share repeated logic when it makes the code simpler -- Use a single blank line to separate logical steps, such as input preparation, validation, computation, mutation, and result construction, when those steps are distinct -- Keep closely related statements together; avoid spacing that fragments a single operation or inserts a blank line after every declaration -- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before the next statement -- Keep comments attached to the code they explain; put a blank line before a comment introducing a new step, with no blank line between the comment and that step -- Keep documentation and attributes attached to their declarations -- Separate function definitions with one blank line; avoid extra empty lines immediately inside braces or between every field, argument, or statement -- Group tests into preparation, action, and verification with blank lines where those phases are distinct; keep related assertions together -- Apply this spacing consistently throughout affected functions, methods, and tests, and follow the repository's formatter for mechanical formatting - -## Source organization - -- Keep each class, enum, or struct in its own source file, with its implementation beside it -- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust -- Use singular folder names, such as `map`, `setting`, or `tracing` -- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file -- Apply these preferences to new types and source organization changes within scope; follow mandatory repository layout rules and leave unrelated existing structure alone - -## Comments - -- Use short, single-line comments; adjacent comment lines should each express a concise point -- Avoid block comments and wrapped prose in ordinary implementation comments -- Explain intent or a non-obvious constraint rather than narrating the code -- No trailing punctuation on ordinary code comments -- Preserve explanations of guards and invariants; remove stale or redundant comments without losing necessary rationale -- API documentation, required license headers, and examples may use their conventional multiline formatting and punctuation -- Apply these standards to both production code and tests - ## Validation and reporting - Run relevant tests and required repository checks with the project's expected toolchain diff --git a/docs/testing-ci.md b/docs/testing-ci.md index 7db9ae07..4fb8d5fd 100644 --- a/docs/testing-ci.md +++ b/docs/testing-ci.md @@ -12,6 +12,31 @@ Run a feature module with a test-name filter, for example: cargo test -p texturecraft-engine --test it bake:: ``` +For faster optimized local verification, run the same workspace tests and doctests +with the `verify` profile: + +```sh +cargo test --workspace --profile verify +``` + +`verify` inherits the release profile's optimization level and runtime checks, but +uses 16 codegen units and `lto = false`. Cargo retains thin LTO within each crate +without repeating cross-crate LTO for every test executable. The existing test +selection and ignore attributes still apply. Keep the target directory between +runs so Cargo can reuse unchanged build artifacts. + +To compile the normal application binaries alongside the test binaries before +running them: + +```sh +cargo build --workspace --bins --tests --profile verify +cargo test --workspace --profile verify +``` + +This profile is for local verification. Use `--release` for release validation and +performance measurements; its compiler settings remain unchanged. The regular +debug test profile and CI gates also remain unchanged. + The standalone engine `session` target and UI `ui_snapshots` target remain available for the commands in `AGENTS.md`. Existing ignore attributes are unchanged. Tests in the shared executable can run concurrently across modules; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ccbdc2c7..2ff6178a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -15,7 +15,7 @@ usage: cargo xtask commands: layers enforce the crate dependency layering (xtask/src/layers.rs) wasm cargo check --target wasm32-unknown-unknown for the wasm crates and the web app - ci fmt --check, clippy -D warnings, test, layers, wasm (stops at the first failure) + ci fmt --check, layers, clippy -D warnings, test, wasm (stops at the first failure) version [set X.Y.Z[-pre]] print the workspace version, or set it (Cargo.toml + Cargo.lock) ico ... @@ -154,11 +154,12 @@ fn cmd_ci() -> Result<(), String> { } }; type Step = (&'static str, Box Result<(), String>>); + // Reject invalid dependency layering before spending time compiling and running the workspace. let steps: Vec = vec![ ("fmt", Box::new(cargo_step(&["fmt", "--all", "--", "--check"]))), + ("layers", Box::new(cmd_layers)), ("clippy", Box::new(cargo_step(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]))), ("test", Box::new(cargo_step(&["test", "--workspace"]))), - ("layers", Box::new(cmd_layers)), ("wasm", Box::new(cmd_wasm)), ]; for (i, (name, step)) in steps.iter().enumerate() {