mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-24 00:10:45 +01:00
Merge main into PR 234
This commit is contained in:
commit
a5f09109ea
130 files changed
+9722
-828
No files matched your search
Generated
+547
-15
@@ -412,6 +412,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.10.0"
|
||||
@@ -448,6 +454,15 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -691,6 +706,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
@@ -704,7 +729,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"core-graphics-types",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
@@ -717,19 +742,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"raw-window-handle",
|
||||
"rfd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -749,10 +796,44 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"craft-keymap",
|
||||
"craft-quit",
|
||||
"egui",
|
||||
"muda",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -770,10 +851,36 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
"egui",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"ureq",
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -790,6 +897,15 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.8"
|
||||
@@ -821,6 +937,16 @@ version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -861,6 +987,22 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch"
|
||||
version = "0.2.0"
|
||||
@@ -920,6 +1062,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
|
||||
[[package]]
|
||||
name = "dyn-clone"
|
||||
version = "1.0.20"
|
||||
@@ -1171,7 +1319,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1252,6 +1400,16 @@ version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.14"
|
||||
@@ -1447,6 +1605,16 @@ dependencies = [
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gethostname"
|
||||
version = "1.1.0"
|
||||
@@ -1457,6 +1625,17 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
@@ -1728,6 +1907,22 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
@@ -2103,6 +2298,16 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyboard-types"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "khronos-egl"
|
||||
version = "6.0.0"
|
||||
@@ -2322,6 +2527,24 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dpi",
|
||||
"keyboard-types",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"png",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "30.0.1"
|
||||
@@ -2427,6 +2650,12 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -2776,6 +3005,12 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
|
||||
|
||||
[[package]]
|
||||
name = "orbclient"
|
||||
version = "0.3.55"
|
||||
@@ -2812,7 +3047,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2978,6 +3213,19 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
||||
|
||||
[[package]]
|
||||
name = "plist"
|
||||
version = "1.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"indexmap",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
@@ -3062,6 +3310,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||
|
||||
[[package]]
|
||||
name = "presser"
|
||||
version = "0.3.1"
|
||||
@@ -3136,6 +3390,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
@@ -3320,6 +3583,20 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.17",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "3.5.1"
|
||||
@@ -3414,7 +3691,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3427,6 +3704,80 @@ dependencies = [
|
||||
"rustix 1.1.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
|
||||
dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"jni",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-platform-verifier-android",
|
||||
"rustls-webpki",
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier-android"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
@@ -3442,6 +3793,15 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "1.2.3"
|
||||
@@ -3480,6 +3840,29 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"security-framework-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework-sys"
|
||||
version = "2.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "self_cell"
|
||||
version = "1.3.0"
|
||||
@@ -3491,6 +3874,10 @@ name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "send_wrapper"
|
||||
@@ -3572,6 +3959,17 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -3743,6 +4141,12 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
@@ -3788,6 +4192,16 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tar"
|
||||
version = "0.4.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
|
||||
dependencies = [
|
||||
"filetime",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -3795,10 +4209,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.5",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3814,6 +4228,8 @@ dependencies = [
|
||||
name = "texturecraft"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"craft-menu",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
"image",
|
||||
@@ -3925,7 +4341,7 @@ dependencies = [
|
||||
"half",
|
||||
"image",
|
||||
"lz4_flex",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3992,7 +4408,11 @@ name = "texturecraft-ui-egui"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-dialogs",
|
||||
"craft-keymap",
|
||||
"craft-quit",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -4084,6 +4504,36 @@ dependencies = [
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||
dependencies = [
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.5"
|
||||
@@ -4266,6 +4716,12 @@ version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "uds_windows"
|
||||
version = "1.2.1"
|
||||
@@ -4313,6 +4769,41 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "3.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"flate2",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"rustls-platform-verifier",
|
||||
"ureq-proto",
|
||||
"utf8-zero",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq-proto"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urlencoding"
|
||||
version = "2.1.3"
|
||||
@@ -4328,6 +4819,12 @@ dependencies = [
|
||||
"utf_types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8-zero"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.1.0"
|
||||
@@ -4382,6 +4879,16 @@ dependencies = [
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "verifysign"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9"
|
||||
dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -4562,7 +5069,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"quote",
|
||||
]
|
||||
|
||||
@@ -4598,6 +5105,15 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.1.12"
|
||||
@@ -4793,7 +5309,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5096,7 +5612,7 @@ dependencies = [
|
||||
"calloop",
|
||||
"cfg_aliases",
|
||||
"concurrent-queue",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"core-graphics",
|
||||
"cursor-icon",
|
||||
"dpi",
|
||||
@@ -5141,6 +5657,16 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.55.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winresource"
|
||||
version = "0.1.34"
|
||||
@@ -5457,6 +5983,12 @@ dependencies = [
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
|
||||
+12
-2
@@ -63,9 +63,19 @@ getrandom = "0.3"
|
||||
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
|
||||
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
|
||||
# MIT OR Apache-2.0, pinned to one rev.
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] }
|
||||
# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs).
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs).
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs).
|
||||
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs).
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs).
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs).
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
|
||||
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
|
||||
[patch.crates-io]
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
<img alt="MCP server for agents" src="https://img.shields.io/badge/agents-MCP%20server-555555?style=flat-square">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-555555?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_texturecraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/texturecraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
</p>
|
||||
|
||||
|
||||
@@ -30,6 +30,12 @@ ron = "0.12"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winit = { version = "0.30", default-features = false }
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
|
||||
# The update helper is a copy of this program (`main`).
|
||||
craft-update = { workspace = true }
|
||||
|
||||
# Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
craft-menu = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
@@ -11,11 +11,17 @@ mod window_frame;
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_ui_egui::titlebar::TitleBar;
|
||||
use texturecraft_ui_egui::ui_state_store;
|
||||
use texturecraft_ui_egui::{TextureCraftApp, UiState};
|
||||
|
||||
/// The app name eframe keeps the settings under (`eframe::storage_dir`).
|
||||
const APP_NAME: &str = "TextureCraft";
|
||||
|
||||
/// The window's size when it opens, in points.
|
||||
const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0];
|
||||
/// The smallest size the window can be resized to, in points.
|
||||
const MIN_SIZE: [f32; 2] = [960.0, 600.0];
|
||||
|
||||
const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png");
|
||||
|
||||
fn version() -> String {
|
||||
@@ -115,13 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Interface › System title bar, read from the saved settings before the window opens
|
||||
/// (eframe hands the app its storage only afterwards). Missing or unreadable: off.
|
||||
fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool {
|
||||
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron")));
|
||||
let saved = file.and_then(|f| std::fs::read_to_string(f).ok());
|
||||
let kv = saved.and_then(|s| ron::from_str::<std::collections::HashMap<String, String>>(&s).ok());
|
||||
kv.and_then(|kv| ron::from_str::<UiState>(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
|
||||
/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off
|
||||
fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool {
|
||||
if let Some(ui) = ui_file.and_then(ui_state_store::read) {
|
||||
return ui.prefs.system_title_bar;
|
||||
}
|
||||
|
||||
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
|
||||
let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
|
||||
let entries = saved.and_then(|text| ron::from_str::<std::collections::HashMap<String, String>>(&text).ok());
|
||||
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
|
||||
}
|
||||
|
||||
/// The app with the window chrome that needs the native window: the Windows borderless guard, and
|
||||
@@ -161,7 +170,17 @@ impl eframe::App for Shell {
|
||||
}
|
||||
}
|
||||
|
||||
/// A script driving the app gets no network check and no update prompt over its window.
|
||||
fn checks_for_updates_at_start(control: Option<u16>) -> bool {
|
||||
control.is_none()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
let args = match parse_args() {
|
||||
Ok(Some(a)) => a,
|
||||
Ok(None) => return,
|
||||
@@ -170,21 +189,25 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// Errors before the window opens speak the system's language; the app then applies the saved one.
|
||||
// Errors before the window opens speak the system's language; the app then applies the saved one
|
||||
texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language());
|
||||
let prev = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
// A message box needs the main thread on macOS; other threads' panics are only logged.
|
||||
// A message box needs the main thread on macOS; other threads' panics are only logged
|
||||
fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main"));
|
||||
prev(info);
|
||||
}));
|
||||
let session = initial_session(&args);
|
||||
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor
|
||||
// overwrite the user's saved UI layout and settings: state goes to a throwaway folder.
|
||||
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files
|
||||
let persistence_path =
|
||||
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
|
||||
let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref()));
|
||||
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]);
|
||||
let ui_file =
|
||||
persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json")));
|
||||
if let Some(file) = &ui_file {
|
||||
let _ = ui_state_store::FILE.set(file.clone());
|
||||
}
|
||||
let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref()));
|
||||
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
@@ -195,7 +218,7 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
let control = args.control;
|
||||
// The start window offers new, open and recent projects, unless a file was given or a script drives the app.
|
||||
// The start window offers new, open and recent projects, unless a file was given or a script drives the app
|
||||
let start = args.file.is_none() && control.is_none();
|
||||
let r = eframe::run_native(
|
||||
APP_NAME,
|
||||
@@ -205,10 +228,16 @@ fn main() {
|
||||
if let Some(w) = cc.winit_window() {
|
||||
set_taskbar_icon(w);
|
||||
}
|
||||
// winit's Quit ends the process without asking; this menu's asks like the close button.
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) {
|
||||
log::warn!("the app menu could not be installed: {e}");
|
||||
}
|
||||
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
app.title_bar = title_bar;
|
||||
app.ui.windows.start = start && app.ui.prefs.start_window;
|
||||
app.set_startup_update_check(checks_for_updates_at_start(control));
|
||||
if let Some(port) = control {
|
||||
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
|
||||
}
|
||||
@@ -274,6 +303,12 @@ mod tests {
|
||||
assert_eq!(args.gpu.as_deref(), Some("3080"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_run_without_a_control_port_checks_for_updates_at_start() {
|
||||
assert!(checks_for_updates_at_start(None));
|
||||
assert!(!checks_for_updates_at_start(Some(9000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_invalid_gpu_args() {
|
||||
assert!(parse_args_from(["--gpu".to_string()]).is_err());
|
||||
@@ -296,19 +331,27 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_title_bar_setting_is_read_from_eframes_settings_file() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
|
||||
fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() {
|
||||
let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
|
||||
let json_path = ron_path.with_extension("json");
|
||||
for on in [false, true] {
|
||||
let mut ui = UiState::default();
|
||||
ui.prefs.system_title_bar = on;
|
||||
// Written as eframe writes it: a pretty RON map of RON strings.
|
||||
// Written as eframe writes it: a pretty RON map of RON strings
|
||||
let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]);
|
||||
std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
|
||||
assert_eq!(saved_system_title_bar(Some(&path)), on);
|
||||
std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
|
||||
assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on);
|
||||
|
||||
ui.prefs.system_title_bar = !on;
|
||||
std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap();
|
||||
assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first");
|
||||
}
|
||||
std::fs::write(&path, "not ron").unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&path)));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&path)));
|
||||
|
||||
std::fs::write(&json_path, "not json").unwrap();
|
||||
std::fs::write(&ron_path, "not ron").unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
|
||||
std::fs::remove_file(&json_path).unwrap();
|
||||
std::fs::remove_file(&ron_path).unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
|
||||
}
|
||||
}
|
||||
@@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError {
|
||||
AutomationError::Io(format!("{op} `{path}` failed: {e}"))
|
||||
}
|
||||
|
||||
/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`,
|
||||
/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped
|
||||
/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command
|
||||
/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is
|
||||
/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the
|
||||
/// embedded mesh).
|
||||
/// Host keys a command reads or writes a file through, at the top level or in each `files` entry
|
||||
const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"];
|
||||
|
||||
/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools
|
||||
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
|
||||
let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null()));
|
||||
let ok = match id {
|
||||
let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path));
|
||||
|
||||
// `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path
|
||||
let allowed = match id {
|
||||
"file.close" | "file.removeUnused" => true,
|
||||
"file.reimportMesh" => !has_path,
|
||||
_ => !id.starts_with("file.") && !has_path,
|
||||
};
|
||||
if ok {
|
||||
if allowed {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(bad(format!(
|
||||
@@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `params` names a host path or folder at its own top level
|
||||
fn names_host_path(params: &Value) -> bool {
|
||||
HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -243,6 +248,18 @@ mod tests {
|
||||
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_file_paths_are_denied() {
|
||||
let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]});
|
||||
assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err());
|
||||
|
||||
let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]});
|
||||
assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err());
|
||||
|
||||
let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]});
|
||||
assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok());
|
||||
}
|
||||
|
||||
/// Every registry command documenting a host path must be classified (fails when a new
|
||||
/// path-taking command is added without an automation policy).
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws
|
||||
|
||||
mod cage_shell;
|
||||
mod high_poly_reach;
|
||||
mod ray_frame;
|
||||
mod ray_start;
|
||||
mod vertex_reach;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use cage_shell::CORNERS;
|
||||
pub use cage_shell::CageShell;
|
||||
pub use high_poly_reach::HighPolyReach;
|
||||
pub(crate) use ray_frame::RayFrame;
|
||||
pub use ray_start::RayStart;
|
||||
pub use vertex_reach::VertexReach;
|
||||
@@ -0,0 +1,65 @@
|
||||
use super::{RayFrame, RayStart};
|
||||
use crate::{BakeError, BakeRequest, MeshExtent};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::surface_at;
|
||||
|
||||
/// Barycentric coordinates of a triangle's three corners
|
||||
pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
|
||||
|
||||
/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CageShell {
|
||||
/// Low-poly position of each triangle corner, three per triangle
|
||||
pub positions: Vec<Vec3>,
|
||||
pub starts: Vec<RayStart>,
|
||||
/// Corner pairs along the low poly's polygon edges, for the wireframe
|
||||
pub edges: Vec<[u32; 2]>,
|
||||
/// World units per unit of the max frontal distance setting
|
||||
pub cage_units: f32,
|
||||
}
|
||||
|
||||
impl CageShell {
|
||||
/// The cage of `request`'s texture set, from the same ray starts the bake uses
|
||||
pub fn new(request: &BakeRequest) -> Result<CageShell, BakeError> {
|
||||
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
|
||||
let (frame, mesh) = (&ray_frame, request.mesh);
|
||||
let triangles: Vec<usize> = mesh.triangles_of(request.material).collect();
|
||||
let (positions, starts): (Vec<Vec3>, Vec<RayStart>) = triangles
|
||||
.par_iter()
|
||||
.flat_map_iter(|&triangle| {
|
||||
CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) {
|
||||
Some(surface) => (surface.pos, frame.start(&surface, barycentric)),
|
||||
None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }),
|
||||
})
|
||||
})
|
||||
.unzip();
|
||||
|
||||
let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
|
||||
let mut edge_corners = HashMap::new();
|
||||
for (triangle_index, &triangle) in triangles.iter().enumerate() {
|
||||
let Some(vertices) = mesh.tri(triangle) else { continue };
|
||||
|
||||
for corner in 0..3 {
|
||||
let next = (corner + 1) % 3;
|
||||
let (from, to) = (vertices[corner] as u32, vertices[next] as u32);
|
||||
let key = (from.min(to), from.max(to));
|
||||
if wire_edges.contains(&key) {
|
||||
let first_corner = (triangle_index * 3) as u32;
|
||||
edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect();
|
||||
edges.sort_unstable();
|
||||
|
||||
Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units })
|
||||
}
|
||||
|
||||
/// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling
|
||||
pub fn corners(&self, max_frontal: f32) -> Vec<Vec3> {
|
||||
let frontal = max_frontal * self.cage_units;
|
||||
self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::{RayFrame, VertexReach};
|
||||
use crate::map::transfer_keys;
|
||||
use crate::tracing::ANY;
|
||||
use crate::{BakeError, BakeRequest, MeshExtent};
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::MeshMatchMode;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Mesh, surface_at};
|
||||
|
||||
/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct HighPolyReach {
|
||||
/// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly
|
||||
pub vertices: Vec<Option<VertexReach>>,
|
||||
/// World units per unit of the cage distance settings
|
||||
pub cage_units: f32,
|
||||
pub ignore_backface: bool,
|
||||
}
|
||||
|
||||
impl HighPolyReach {
|
||||
/// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there
|
||||
pub fn new(request: &BakeRequest) -> Result<HighPolyReach, BakeError> {
|
||||
let Some(high) = request.high else { return Ok(HighPolyReach::default()) };
|
||||
|
||||
let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
|
||||
let mut in_set = vec![false; request.mesh.triangle_count()];
|
||||
for triangle in request.mesh.triangles_of(request.material) {
|
||||
if let Some(flag) = in_set.get_mut(triangle) {
|
||||
*flag = true;
|
||||
}
|
||||
}
|
||||
|
||||
let winding_normals = winding_normals(high.mesh);
|
||||
let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode {
|
||||
MeshMatchMode::Always => (Vec::new(), Vec::new()),
|
||||
MeshMatchMode::ByMeshName => {
|
||||
let (low_keys, high_keys) = transfer_keys(request);
|
||||
(low_keys, vertex_keys(high.mesh, &high_keys))
|
||||
}
|
||||
};
|
||||
let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY);
|
||||
let frame = &frame;
|
||||
let vertices = high
|
||||
.mesh
|
||||
.positions
|
||||
.par_iter()
|
||||
.zip(&winding_normals)
|
||||
.enumerate()
|
||||
.map(|(vertex, (&high_position, &high_facing))| {
|
||||
let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?;
|
||||
if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?;
|
||||
let ray_key = key(&low_keys, nearest.tri as usize);
|
||||
Some(VertexReach {
|
||||
low_position: surface.pos,
|
||||
start: frame.start(&surface, [nearest.u, nearest.v]),
|
||||
high_position,
|
||||
high_facing,
|
||||
name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface })
|
||||
}
|
||||
|
||||
/// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's
|
||||
pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option<bool> {
|
||||
let reach = self.vertices.get(vertex).copied().flatten()?;
|
||||
Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface))
|
||||
}
|
||||
}
|
||||
|
||||
/// Each vertex's mesh-name key, from the first triangle that uses it
|
||||
fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec<u32> {
|
||||
let mut keys = vec![ANY; mesh.positions.len()];
|
||||
for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) {
|
||||
for &corner in corners {
|
||||
if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) {
|
||||
*key = triangle_key;
|
||||
}
|
||||
}
|
||||
}
|
||||
keys
|
||||
}
|
||||
|
||||
/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front
|
||||
fn winding_normals(mesh: &Mesh) -> Vec<Vec3> {
|
||||
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
|
||||
for corners in mesh.indices.chunks_exact(3) {
|
||||
let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO);
|
||||
let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0]));
|
||||
for &corner in corners {
|
||||
if let Some(normal) = normals.get_mut(corner as usize) {
|
||||
*normal += winding_normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
normals
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use super::RayStart;
|
||||
use crate::MeshExtent;
|
||||
use crate::map::{interpolate, welded};
|
||||
use crate::skew::PreparedSkew;
|
||||
use crate::{BakeError, BakePaintMap, BakeRequest};
|
||||
use texturecraft_core::CageType;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Mesh, Surface};
|
||||
|
||||
/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount
|
||||
pub(crate) struct RayFrame<'a> {
|
||||
mesh: &'a Mesh,
|
||||
ray_normals: Vec<Vec3>,
|
||||
cage: Option<&'a Mesh>,
|
||||
skew: Option<PreparedSkew<'a>>,
|
||||
cage_paint: Option<&'a BakePaintMap>,
|
||||
/// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead
|
||||
ray_epsilon: f32,
|
||||
/// World units per unit of the cage distance settings
|
||||
pub(crate) cage_units: f32,
|
||||
}
|
||||
|
||||
impl<'a> RayFrame<'a> {
|
||||
pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result<RayFrame<'a>, BakeError> {
|
||||
let settings = request.settings;
|
||||
let ray_normals = match settings.cage.average_normals && request.high.is_some() {
|
||||
true => {
|
||||
let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal);
|
||||
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
false => Vec::new(),
|
||||
};
|
||||
|
||||
Ok(RayFrame {
|
||||
mesh: request.mesh,
|
||||
ray_normals,
|
||||
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
|
||||
skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?,
|
||||
cage_paint: request.cage_paint,
|
||||
ray_epsilon: extent.ray_epsilon(),
|
||||
cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 },
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the transfer ray of the low-poly point `surface` at `barycentric` starts
|
||||
pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart {
|
||||
let cage_offset = self
|
||||
.cage
|
||||
.and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
|
||||
.map(|cage_position| surface.pos - cage_position)
|
||||
.filter(|offset| offset.length() > self.ray_epsilon);
|
||||
if let Some(offset) = cage_offset {
|
||||
return RayStart::CageMesh(offset);
|
||||
}
|
||||
|
||||
let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
|
||||
let up = match &self.skew {
|
||||
Some(skew) => skew.correct(self.mesh, surface, averaged_normal),
|
||||
None => averaged_normal,
|
||||
};
|
||||
RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// Where the bake's transfer ray for one low-poly point starts
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum RayStart {
|
||||
/// On the cage mesh: the offset from the cage to the low-poly point
|
||||
CageMesh(Vec3),
|
||||
/// Out along `up` by the frontal distance times `scale` (the painted cage amount)
|
||||
Distance { up: Vec3, scale: f32 },
|
||||
}
|
||||
|
||||
impl RayStart {
|
||||
/// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance
|
||||
pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 {
|
||||
match *self {
|
||||
RayStart::CageMesh(offset) => position - offset,
|
||||
RayStart::Distance { up, scale } => position + up * frontal * scale,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use super::RayStart;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// One high-poly vertex seen from the transfer ray through its nearest low-poly point
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct VertexReach {
|
||||
pub low_position: Vec3,
|
||||
pub start: RayStart,
|
||||
pub high_position: Vec3,
|
||||
/// The side the high poly's triangles face at the vertex, by their winding (not normalized)
|
||||
pub high_facing: Vec3,
|
||||
/// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name)
|
||||
pub name_matches: bool,
|
||||
}
|
||||
|
||||
impl VertexReach {
|
||||
/// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray
|
||||
pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool {
|
||||
let origin = self.start.origin(self.low_position, frontal);
|
||||
let (direction, front) = match self.start {
|
||||
RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()),
|
||||
RayStart::Distance { up, scale } => (-up, frontal * scale),
|
||||
};
|
||||
let along_ray = (self.high_position - origin).dot(direction);
|
||||
|
||||
!self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0)
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,17 @@
|
||||
mod bake_error;
|
||||
mod bake_output;
|
||||
mod bake_request;
|
||||
mod cage;
|
||||
mod high_poly;
|
||||
mod mesh_extent;
|
||||
mod progress;
|
||||
|
||||
pub use bake_error::BakeError;
|
||||
pub use bake_output::BakeOutput;
|
||||
pub use bake_request::BakeRequest;
|
||||
pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach};
|
||||
pub use high_poly::HighPoly;
|
||||
pub(crate) use mesh_extent::MeshExtent;
|
||||
pub use progress::Progress;
|
||||
|
||||
mod map;
|
||||
|
||||
@@ -15,10 +15,13 @@ mod source;
|
||||
mod texel_grid;
|
||||
mod traced;
|
||||
mod transfer;
|
||||
mod transfer_keys;
|
||||
|
||||
pub(crate) use bake_context::BakeContext;
|
||||
pub(crate) use normal_curvature::curvature_from_normal;
|
||||
pub(crate) use sample::Sample;
|
||||
pub(crate) use sampling::{interpolate, welded};
|
||||
pub(crate) use texel_grid::TexelGrid;
|
||||
pub(crate) use traced::Traced;
|
||||
pub(crate) use transfer::Transfer;
|
||||
pub(crate) use transfer_keys::transfer_keys;
|
||||
@@ -1,28 +1,22 @@
|
||||
use super::curvature::Curvature;
|
||||
use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded};
|
||||
use super::sampling::{pack, splitmix64, tangent_normal};
|
||||
use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer};
|
||||
use crate::skew::PreparedSkew;
|
||||
use crate::cage::{RayFrame, RayStart};
|
||||
use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh};
|
||||
use crate::{BakeError, BakeRequest};
|
||||
use crate::{BakeError, BakeRequest, MeshExtent};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
use texturecraft_core::{
|
||||
AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
|
||||
AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
|
||||
};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Hit, Mesh, Surface, surface_at};
|
||||
use texturecraft_geom::{Hit, Surface, surface_at};
|
||||
|
||||
const CURVATURE_CHUNK: usize = 1 << 15;
|
||||
|
||||
pub(crate) struct BakeContext<'a> {
|
||||
low: Source<'a>,
|
||||
high: Option<Source<'a>>,
|
||||
cage: Option<&'a Mesh>,
|
||||
skew: Option<PreparedSkew<'a>>,
|
||||
cage_paint: Option<&'a crate::BakePaintMap>,
|
||||
ray_normals: Vec<Vec3>,
|
||||
ray_frame: RayFrame<'a>,
|
||||
settings: &'a BakeSettings,
|
||||
eps: f32,
|
||||
frontal: f32,
|
||||
rear: f32,
|
||||
position: PositionProjection,
|
||||
@@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> {
|
||||
impl<'a> BakeContext<'a> {
|
||||
pub(crate) fn new(request: &BakeRequest<'a>) -> Result<BakeContext<'a>, BakeError> {
|
||||
let settings = request.settings;
|
||||
let (bounds_min, bounds_max) = request.mesh.bounds();
|
||||
let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6);
|
||||
if !mesh_diagonal.is_finite() {
|
||||
return Err(BakeError::Invalid("mesh bounds are too large".into()));
|
||||
}
|
||||
|
||||
let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6);
|
||||
let mut name_keys = HashMap::new();
|
||||
let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys);
|
||||
let high = request.high.map(|high_mesh| {
|
||||
Source::new(
|
||||
high_mesh.mesh,
|
||||
high_mesh.bvh,
|
||||
high_mesh.base_color,
|
||||
high_mesh.file_ids,
|
||||
&settings.high_poly.high_suffix,
|
||||
&settings.high_poly,
|
||||
&mut name_keys,
|
||||
)
|
||||
});
|
||||
let ray_normals = match settings.cage.average_normals && high.is_some() {
|
||||
true => {
|
||||
let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal);
|
||||
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
false => Vec::new(),
|
||||
};
|
||||
|
||||
let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?;
|
||||
let ray_epsilon = 1e-6 * mesh_diagonal;
|
||||
let extent = MeshExtent::of(request.mesh)?;
|
||||
let (low, high) = Source::of_request(request);
|
||||
let ray_frame = RayFrame::new(request, extent)?;
|
||||
let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon());
|
||||
let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| {
|
||||
let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians();
|
||||
let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 };
|
||||
@@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> {
|
||||
pass.ignore_backface = parameters.ignore_backface;
|
||||
pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName;
|
||||
pass.attenuation = parameters.attenuation;
|
||||
pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset);
|
||||
pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset);
|
||||
}
|
||||
|
||||
let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion);
|
||||
if let Some(pass) = &mut bent {
|
||||
pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface;
|
||||
pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName;
|
||||
}
|
||||
|
||||
let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness);
|
||||
if let Some(pass) = &mut thickness {
|
||||
pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName;
|
||||
}
|
||||
let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 };
|
||||
|
||||
let cage_units = ray_frame.cage_units;
|
||||
Ok(BakeContext {
|
||||
low,
|
||||
high,
|
||||
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
|
||||
skew,
|
||||
cage_paint: request.cage_paint,
|
||||
ray_normals,
|
||||
ray_frame,
|
||||
settings,
|
||||
eps: ray_epsilon,
|
||||
frontal: settings.cage.max_frontal * cage_units,
|
||||
rear: settings.cage.max_rear * cage_units,
|
||||
position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters),
|
||||
@@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> {
|
||||
}
|
||||
|
||||
pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) {
|
||||
let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
|
||||
let cage = self
|
||||
.cage
|
||||
.and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
|
||||
.map(|cage_position| surface.pos - cage_position)
|
||||
.filter(|offset| offset.length() > self.eps);
|
||||
let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv));
|
||||
let (origin, direction, front) = match cage {
|
||||
Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()),
|
||||
None => {
|
||||
let up = match &self.skew {
|
||||
Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal),
|
||||
None => averaged_normal,
|
||||
};
|
||||
(surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale)
|
||||
}
|
||||
let start = self.ray_frame.start(surface, barycentric);
|
||||
let origin = start.origin(surface.pos, self.frontal);
|
||||
let (direction, front) = match start {
|
||||
RayStart::CageMesh(offset) => (offset.normalize(), offset.length()),
|
||||
RayStart::Distance { up, scale } => (-up, self.frontal * scale),
|
||||
};
|
||||
let key = match self.settings.high_poly.match_mode {
|
||||
MeshMatchMode::Always => ANY,
|
||||
|
||||
@@ -3,34 +3,43 @@ use std::ops::{Add, Mul};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Mesh, Surface};
|
||||
|
||||
pub(super) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option<T> {
|
||||
let [a, b, c] = mesh.tri(tri as usize)?;
|
||||
Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2)
|
||||
/// `values` (one per vertex) at `barycentric` in triangle `triangle`
|
||||
pub(crate) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option<T> {
|
||||
let [first, second, third] = mesh.tri(triangle as usize)?;
|
||||
let [second_weight, third_weight] = barycentric;
|
||||
|
||||
Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight)
|
||||
}
|
||||
|
||||
pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
|
||||
let q = diag * 1e-5;
|
||||
let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
|
||||
let (mut pos, mut nrm) = (Vec::new(), Vec::<Vec3>::new());
|
||||
let weld: Vec<u32> = mesh
|
||||
/// Vertices closer than this fraction of the mesh diagonal count as one when welding
|
||||
const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5;
|
||||
|
||||
/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals
|
||||
pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
|
||||
let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL;
|
||||
let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new();
|
||||
let (mut positions, mut normal_sums) = (Vec::new(), Vec::<Vec3>::new());
|
||||
|
||||
let welded_indices: Vec<u32> = mesh
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.map(|(p, n)| {
|
||||
let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64);
|
||||
let id = *ids.entry(key).or_insert_with(|| {
|
||||
pos.push(*p);
|
||||
nrm.push(Vec3::ZERO);
|
||||
(pos.len() - 1) as u32
|
||||
.map(|(position, normal)| {
|
||||
let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64);
|
||||
let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| {
|
||||
positions.push(*position);
|
||||
normal_sums.push(Vec3::ZERO);
|
||||
(positions.len() - 1) as u32
|
||||
});
|
||||
if let Some(acc) = nrm.get_mut(id as usize) {
|
||||
*acc += *n;
|
||||
if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) {
|
||||
*normal_sum += *normal;
|
||||
}
|
||||
id
|
||||
welded_index
|
||||
})
|
||||
.collect();
|
||||
let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
|
||||
(weld, pos, nrm)
|
||||
|
||||
let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect();
|
||||
(welded_indices, positions, normals)
|
||||
}
|
||||
|
||||
pub(super) fn splitmix64(x: u64) -> u64 {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::sampling::{generated_hue, interpolate, splitmix64};
|
||||
use crate::BakeRequest;
|
||||
use crate::tracing::{ANY, TraceMesh};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -21,6 +22,18 @@ pub(super) struct Source<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Source<'a> {
|
||||
/// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part
|
||||
pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option<Source<'a>>) {
|
||||
let settings = &request.settings.high_poly;
|
||||
let mut name_keys = HashMap::new();
|
||||
let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys);
|
||||
let high = request.high.map(|high_mesh| {
|
||||
Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys)
|
||||
});
|
||||
|
||||
(low, high)
|
||||
}
|
||||
|
||||
pub(super) fn new(
|
||||
mesh: &'a Mesh,
|
||||
bvh: &'a Bvh,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use super::source::Source;
|
||||
use crate::BakeRequest;
|
||||
|
||||
/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key
|
||||
pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec<u32>, Vec<u32>) {
|
||||
let (low, high) = Source::of_request(request);
|
||||
(low.key, high.map(|high| high.key).unwrap_or_default())
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use crate::BakeError;
|
||||
use texturecraft_geom::Mesh;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances
|
||||
const MIN_MESH_SIZE: f32 = 1e-6;
|
||||
|
||||
/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal
|
||||
const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6;
|
||||
|
||||
/// The low-poly mesh's size, which scales the bake's relative distances
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct MeshExtent {
|
||||
pub(crate) bounds_min: Vec3,
|
||||
pub(crate) diagonal: f32,
|
||||
/// The bounding box's largest side
|
||||
pub(crate) scale: f32,
|
||||
}
|
||||
|
||||
impl MeshExtent {
|
||||
pub(crate) fn of(mesh: &Mesh) -> Result<MeshExtent, BakeError> {
|
||||
let (bounds_min, bounds_max) = mesh.bounds();
|
||||
let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE);
|
||||
if !diagonal.is_finite() {
|
||||
return Err(BakeError::Invalid("mesh bounds are too large".into()));
|
||||
}
|
||||
|
||||
Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) })
|
||||
}
|
||||
|
||||
/// How far a ray starts past the surface it leaves, in world units
|
||||
pub(crate) fn ray_epsilon(&self) -> f32 {
|
||||
RAY_EPSILON_PER_DIAGONAL * self.diagonal
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::settings;
|
||||
use crate::cage::CORNERS;
|
||||
use crate::map::BakeContext;
|
||||
use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly};
|
||||
use texturecraft_core::{BakedMap, CageType};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
|
||||
|
||||
/// A painted map whose values vary over the UV square
|
||||
fn painted_map() -> BakePaintMap {
|
||||
let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap();
|
||||
map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap();
|
||||
map
|
||||
}
|
||||
|
||||
/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit
|
||||
fn assert_cage_matches_the_ray_origins(request: &BakeRequest) {
|
||||
let shell = CageShell::new(request).unwrap();
|
||||
let corners = shell.corners(request.settings.cage.max_frontal);
|
||||
let context = BakeContext::new(request).unwrap();
|
||||
let triangles: Vec<usize> = request.mesh.triangles_of(request.material).collect();
|
||||
assert_eq!(corners.len(), triangles.len() * 3);
|
||||
|
||||
for (corner_index, corner) in corners.iter().enumerate() {
|
||||
let barycentric = CORNERS[corner_index % 3];
|
||||
let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap();
|
||||
let (ray, _) = context.transfer_ray(&surface, barycentric);
|
||||
assert_eq!(*corner, ray.origin, "corner {corner_index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cage_corners_are_the_bake_ray_origins() {
|
||||
let low = primitives::cube(1.0);
|
||||
let high_mesh = primitives::sphere(0.8, 16, 8);
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
|
||||
let (skew, cage_paint) = (painted_map(), painted_map());
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.max_frontal = 0.03;
|
||||
bake_settings.skew.edge_protection = true;
|
||||
let request = |settings| BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings,
|
||||
high: Some(high),
|
||||
cage: None,
|
||||
skew: Some(&skew),
|
||||
cage_paint: Some(&cage_paint),
|
||||
tiles: (1, 1),
|
||||
};
|
||||
|
||||
assert_cage_matches_the_ray_origins(&request(&bake_settings));
|
||||
let face_normals = {
|
||||
let mut face_normals = bake_settings.clone();
|
||||
face_normals.cage.average_normals = false;
|
||||
face_normals.cage.relative_to_bounding_box = false;
|
||||
face_normals
|
||||
};
|
||||
assert_cage_matches_the_ray_origins(&request(&face_normals));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() {
|
||||
let low = primitives::cube(1.0);
|
||||
let low_bvh = Bvh::new(&low);
|
||||
let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] };
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.relative_to_bounding_box = false;
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(high),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let shell = CageShell::new(&request).unwrap();
|
||||
let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max);
|
||||
|
||||
assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly");
|
||||
// Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis
|
||||
assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance");
|
||||
assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge");
|
||||
|
||||
let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() };
|
||||
let custom_settings = {
|
||||
let mut custom_settings = bake_settings.clone();
|
||||
custom_settings.cage.kind = CageType::CustomFile;
|
||||
custom_settings
|
||||
};
|
||||
let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request };
|
||||
assert_cage_matches_the_ray_origins(&custom);
|
||||
let corners = CageShell::new(&custom).unwrap().corners(0.0);
|
||||
assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is");
|
||||
assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO));
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
use super::settings;
|
||||
use crate::map::{BakeContext, transfer_keys};
|
||||
use crate::tracing::ANY;
|
||||
use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart};
|
||||
use texturecraft_core::{BakedMap, MeshMatchMode};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
|
||||
|
||||
/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them
|
||||
const BOUNDARY: f32 = 1e-4;
|
||||
|
||||
/// How close the ray's hit must be to the vertex to count as reaching it
|
||||
const HIT_TOLERANCE: f32 = 1e-4;
|
||||
|
||||
/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way
|
||||
fn bumpy_high_poly() -> (Mesh, Vec<bool>) {
|
||||
const FLIPPED_FROM_X: f32 = 0.2;
|
||||
|
||||
let mut mesh = primitives::plane(1.0, 40);
|
||||
for position in &mut mesh.positions {
|
||||
position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005;
|
||||
}
|
||||
|
||||
let mut flipped = vec![false; mesh.positions.len()];
|
||||
let mut unflipped = vec![false; mesh.positions.len()];
|
||||
for corners in mesh.indices.chunks_exact_mut(3) {
|
||||
let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::<f32>() / 3.0;
|
||||
if center_x > FLIPPED_FROM_X {
|
||||
corners.swap(1, 2);
|
||||
}
|
||||
for &corner in corners.iter() {
|
||||
if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true }
|
||||
}
|
||||
}
|
||||
// Vertices on the border face both ways: neither answer is right for them
|
||||
let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect();
|
||||
(mesh, mixed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() {
|
||||
let low = primitives::plane(1.0, 8);
|
||||
let (high_mesh, mixed) = bumpy_high_poly();
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
|
||||
let back_facing = |triangle: u32, direction: Vec3| {
|
||||
let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]);
|
||||
(b - a).cross(c - a).dot(direction) > 0.0
|
||||
};
|
||||
let mut checked = [0usize; 2];
|
||||
|
||||
for ignore_backface in [false, true] {
|
||||
for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] {
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.relative_to_bounding_box = false;
|
||||
bake_settings.high_poly.ignore_backface = ignore_backface;
|
||||
(bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear);
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(high),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let reach = HighPolyReach::new(&request).unwrap();
|
||||
let context = BakeContext::new(&request).unwrap();
|
||||
|
||||
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
|
||||
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap());
|
||||
let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") };
|
||||
let height = vertex_reach.high_position.y - vertex_reach.low_position.y;
|
||||
let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY);
|
||||
if near_the_range_end || mixed[vertex] {
|
||||
continue;
|
||||
}
|
||||
|
||||
let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
|
||||
let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
|
||||
let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
|
||||
let hit = high_bvh
|
||||
.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction)));
|
||||
let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
|
||||
assert_eq!(
|
||||
missed, !reaches_the_vertex,
|
||||
"vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}"
|
||||
);
|
||||
checked[usize::from(missed)] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() {
|
||||
let mut low = primitives::plane(1.0, 4);
|
||||
let mut right = primitives::plane(1.0, 4);
|
||||
for position in &mut right.positions {
|
||||
position.x += 2.0;
|
||||
}
|
||||
low.append(&right);
|
||||
assert_eq!(low.materials.len(), 2, "each plane is its own texture set");
|
||||
let mut high_mesh = primitives::plane(3.0, 30);
|
||||
for position in &mut high_mesh.positions {
|
||||
position.x += 1.0;
|
||||
position.y = 0.3;
|
||||
}
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
let request = |material| BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material,
|
||||
settings: &bake_settings,
|
||||
high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap());
|
||||
|
||||
for (vertex, position) in high_mesh.positions.iter().enumerate() {
|
||||
let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some());
|
||||
assert!(owners != (true, true), "vertex {vertex} belongs to one set at most");
|
||||
if position.x < 0.9 {
|
||||
assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set");
|
||||
} else if position.x > 1.1 {
|
||||
assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_by_mesh_name_misses_the_parts_with_another_name() {
|
||||
const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01;
|
||||
|
||||
let mut low = primitives::plane(1.0, 8);
|
||||
low.submeshes[0].name = "part_low".into();
|
||||
let mut high_mesh = primitives::plane(0.5, 10);
|
||||
let mut other_part = primitives::plane(0.5, 10);
|
||||
for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] {
|
||||
for position in &mut mesh.positions {
|
||||
position.x += center_x;
|
||||
position.y = HEIGHT_INSIDE_THE_CAGE;
|
||||
}
|
||||
}
|
||||
high_mesh.append(&other_part);
|
||||
high_mesh.submeshes[0].name = "part_high".into();
|
||||
high_mesh.submeshes[1].name = "other_high".into();
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.relative_to_bounding_box = false;
|
||||
bake_settings.cage.max_frontal = 0.02;
|
||||
bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let reach = HighPolyReach::new(&request).unwrap();
|
||||
let context = BakeContext::new(&request).unwrap();
|
||||
let (_, high_keys) = transfer_keys(&request);
|
||||
|
||||
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
|
||||
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap());
|
||||
// On the line where the two parts meet, a ray reaches either part's triangles
|
||||
if vertex_reach.high_position.x.abs() < BOUNDARY {
|
||||
continue;
|
||||
}
|
||||
|
||||
let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
|
||||
let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
|
||||
let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
|
||||
let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key);
|
||||
let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name);
|
||||
let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
|
||||
assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position);
|
||||
assert_eq!(
|
||||
missed,
|
||||
vertex >= high_mesh.positions.len() - other_part.positions.len(),
|
||||
"only the part named like the low poly is reached: vertex {vertex}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_high_poly_no_vertex_has_a_reach() {
|
||||
let low = primitives::plane(1.0, 4);
|
||||
let low_bvh = Bvh::new(&low);
|
||||
let bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: None,
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
|
||||
let reach = HighPolyReach::new(&request).unwrap();
|
||||
assert!(reach.vertices.is_empty());
|
||||
// Any cage distances: there is no vertex to miss
|
||||
assert_eq!(reach.missed(0, 0.02, 0.01), None);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{RayStart, VertexReach};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25
|
||||
const FRONTAL: f32 = 0.5;
|
||||
const REAR: f32 = 0.25;
|
||||
|
||||
/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage
|
||||
const IGNORED_FRONTAL: f32 = 9.0;
|
||||
|
||||
/// How far past an end of the ray's range a vertex counts as outside it
|
||||
const PAST_THE_END: f32 = 1e-3;
|
||||
|
||||
/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing`
|
||||
fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach {
|
||||
VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() {
|
||||
// A painted cage amount of 2 doubles the frontal distance
|
||||
let starts = [
|
||||
(RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL),
|
||||
(RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0),
|
||||
(RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL),
|
||||
];
|
||||
let (top, bottom) = (FRONTAL, -REAR);
|
||||
// Height, facing, name matches, ignore backface: missed
|
||||
let cases = [
|
||||
(top, Vec3::Y, true, false, false),
|
||||
(bottom, Vec3::Y, true, false, false),
|
||||
(0.0, Vec3::Y, true, false, false),
|
||||
(top + PAST_THE_END, Vec3::Y, true, false, true),
|
||||
(bottom - PAST_THE_END, Vec3::Y, true, false, true),
|
||||
(0.0, Vec3::Y, false, false, true),
|
||||
(0.0, Vec3::NEG_Y, true, false, false),
|
||||
(0.0, Vec3::NEG_Y, true, true, true),
|
||||
(0.0, Vec3::Y, true, true, false),
|
||||
];
|
||||
|
||||
for (start, frontal) in starts {
|
||||
for (height, facing, name_matches, ignore_backface, missed) in cases {
|
||||
let reach = vertex(start, height, facing, name_matches);
|
||||
assert_eq!(
|
||||
reach.missed(frontal, REAR, ignore_backface),
|
||||
missed,
|
||||
"{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,12 @@ use texturecraft_geom::primitives;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[path = "test/cage_shell.rs"]
|
||||
mod cage_shell;
|
||||
|
||||
#[path = "test/high_poly_reach.rs"]
|
||||
mod high_poly_reach;
|
||||
|
||||
#[path = "test/setting.rs"]
|
||||
mod setting;
|
||||
|
||||
@@ -23,6 +29,9 @@ mod normal_map_curvature;
|
||||
#[path = "test/tile_selection.rs"]
|
||||
mod tile_selection;
|
||||
|
||||
#[path = "test/vertex_reach.rs"]
|
||||
mod vertex_reach;
|
||||
|
||||
fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings {
|
||||
with_rays(
|
||||
{
|
||||
|
||||
@@ -395,6 +395,11 @@ pub struct Project {
|
||||
/// it, so parts the file leaves unnamed get the same name (from it) as on import.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mesh_file: String,
|
||||
/// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads
|
||||
/// it again from there, so edits made to the file since are picked up. Empty when unknown
|
||||
/// (built-in meshes, web imports, projects saved before it was kept).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mesh_path: String,
|
||||
pub normal_format: NormalFormat,
|
||||
pub texture_sets: Vec<TextureSet>,
|
||||
pub layers: BTreeMap<LayerId, Layer>,
|
||||
@@ -412,6 +417,7 @@ impl Project {
|
||||
name: name.into(),
|
||||
mesh: mesh.into(),
|
||||
mesh_file: String::new(),
|
||||
mesh_path: String::new(),
|
||||
normal_format: NormalFormat::OpenGl,
|
||||
texture_sets: Vec::new(),
|
||||
layers: BTreeMap::new(),
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use super::MergedHigh;
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach};
|
||||
use texturecraft_core::BakeSettings;
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BakeCageInputs {
|
||||
pub(super) mesh: Arc<Mesh>,
|
||||
pub(super) bvh: Arc<Bvh>,
|
||||
pub(super) material: usize,
|
||||
pub(super) settings: BakeSettings,
|
||||
pub(super) high: MergedHigh,
|
||||
pub(super) cage: Option<Arc<Mesh>>,
|
||||
pub(super) skew: Option<Arc<BakePaintMap>>,
|
||||
pub(super) cage_paint: Option<Arc<BakePaintMap>>,
|
||||
}
|
||||
|
||||
impl BakeCageInputs {
|
||||
/// The cage the 3D view draws: the bake's ray origins at each triangle corner
|
||||
pub fn cage_shell(&self) -> Result<CageShell, BakeError> {
|
||||
CageShell::new(&self.request())
|
||||
}
|
||||
|
||||
/// Where each high-poly vertex sits relative to the bake's transfer rays
|
||||
pub fn high_poly_reach(&self) -> Result<HighPolyReach, BakeError> {
|
||||
HighPolyReach::new(&self.request())
|
||||
}
|
||||
|
||||
fn request(&self) -> BakeRequest<'_> {
|
||||
BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &self.mesh,
|
||||
bvh: &self.bvh,
|
||||
material: self.material,
|
||||
settings: &self.settings,
|
||||
high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }),
|
||||
cage: self.cage.as_deref(),
|
||||
skew: self.skew.as_deref(),
|
||||
cage_paint: self.cage_paint.as_deref(),
|
||||
tiles: (1, 1),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,11 @@ pub struct BakeMeshes {
|
||||
}
|
||||
|
||||
impl BakeMeshes {
|
||||
/// Every high poly appended into one mesh, as bakes see it
|
||||
pub fn merged_high(&self) -> Option<&MergedHigh> {
|
||||
self.merged.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn rebuild(&mut self) {
|
||||
self.merged = (!self.high.is_empty()).then(|| {
|
||||
let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new());
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::MergedHigh;
|
||||
use super::{MergedHigh, StreamedBake, StreamedMap};
|
||||
use crate::{EngineError, Result};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakeSettings;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// A self-contained bake task that can run on another thread.
|
||||
@@ -29,7 +29,69 @@ pub struct BakeTask {
|
||||
}
|
||||
|
||||
impl BakeTask {
|
||||
/// The maps this task makes, in the order [`BakeTask::run_streaming`] finishes them
|
||||
pub fn maps(&self) -> Vec<BakedMap> {
|
||||
self.settings.maps.enabled().collect()
|
||||
}
|
||||
|
||||
/// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
|
||||
/// and return all of them together. Each map is a bake of its own, so with a high poly
|
||||
/// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
|
||||
/// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
|
||||
/// The handed-over buffers are the returned ones too (no copy is made), so a preview that
|
||||
/// keeps them costs no second set of maps. A cancel or an error leaves the maps already
|
||||
/// handed over whole.
|
||||
pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result<StreamedBake> {
|
||||
let maps = self.maps();
|
||||
let total = maps.len();
|
||||
let mut combined: Option<StreamedBake> = None;
|
||||
|
||||
for (index, map) in maps.iter().copied().enumerate() {
|
||||
let mut settings = self.settings.clone();
|
||||
settings.maps.select([map]);
|
||||
let mut output = self.run_with(&settings, progress)?;
|
||||
let Some(data) = output.maps.remove(&map) else { continue };
|
||||
if combined.is_none() {
|
||||
// Retain unchecked maps once, using the full selection rather than this one-map pass.
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?;
|
||||
}
|
||||
|
||||
let data = Arc::new(data);
|
||||
on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() });
|
||||
match &mut combined {
|
||||
Some(combined) => {
|
||||
combined.maps.insert(map, data);
|
||||
}
|
||||
None => {
|
||||
// A resized partial bake also returns unchecked maps that must survive application
|
||||
let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
retained.insert(map, data);
|
||||
combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match combined {
|
||||
Some(output) => Ok(output),
|
||||
None => {
|
||||
let output = self.run(progress)?;
|
||||
Ok(StreamedBake {
|
||||
resolution: output.resolution,
|
||||
height: output.height,
|
||||
maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
|
||||
tracer: output.tracer,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
|
||||
let mut output = self.run_with(&self.settings, progress)?;
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result<BakeOutput> {
|
||||
let high =
|
||||
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
|
||||
let request = BakeRequest {
|
||||
@@ -37,16 +99,118 @@ impl BakeTask {
|
||||
mesh: &self.mesh,
|
||||
bvh: &self.bvh,
|
||||
material: self.material,
|
||||
settings: &self.settings,
|
||||
settings,
|
||||
high,
|
||||
cage: self.cage.as_deref(),
|
||||
skew: self.skew.as_deref(),
|
||||
cage_paint: self.cage_paint.as_deref(),
|
||||
tiles: self.tiles,
|
||||
};
|
||||
|
||||
let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref())
|
||||
.map_err(|error| EngineError::Other(format!("bake failed: {error}")))?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Session, execute};
|
||||
use serde_json::json;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
const PREVIOUS_MAPS: [BakedMap; 3] = [BakedMap::Normal, BakedMap::AmbientOcclusion, BakedMap::Height];
|
||||
const SELECTED_MAPS: [BakedMap; 2] = [BakedMap::AmbientOcclusion, BakedMap::Height];
|
||||
|
||||
fn partial_task(selected: &[BakedMap], resized: bool, excluded: bool) -> BakeTask {
|
||||
let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({"resolution": 64, "rays": 2})).unwrap();
|
||||
if excluded {
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
}
|
||||
let mut task = session.bake_task(0).unwrap();
|
||||
task.tracer = None;
|
||||
task.settings.maps.select(selected.iter().copied());
|
||||
let (width, height) = if resized { (64, 32) } else { (128, 64) };
|
||||
task.previous_maps = BakedMaps {
|
||||
resolution: width,
|
||||
maps: PREVIOUS_MAPS.into_iter().map(|map| (map, Arc::new(vec![0.25; width as usize * height * map.components()]))).collect(),
|
||||
};
|
||||
task
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_allocates_only_truly_unchecked_resized_maps_once() {
|
||||
for (selected, resized, excluded) in [
|
||||
(SELECTED_MAPS.as_slice(), true, true),
|
||||
(PREVIOUS_MAPS.as_slice(), true, true),
|
||||
(SELECTED_MAPS.as_slice(), false, true),
|
||||
(SELECTED_MAPS.as_slice(), true, false),
|
||||
] {
|
||||
let task = partial_task(selected, resized, excluded);
|
||||
let whole = task.run(&Progress::new()).unwrap();
|
||||
super::super::preserve_tiles::take_retained_allocations();
|
||||
let mut allocations = Vec::new();
|
||||
let mut handed_over = Vec::new();
|
||||
let output = task
|
||||
.run_streaming(&Progress::new(), &mut |map| {
|
||||
allocations.extend(super::super::preserve_tiles::take_retained_allocations());
|
||||
assert!(allocations.iter().all(|map| !selected.contains(map)), "maps scheduled to bake must never allocate retained buffers");
|
||||
handed_over.push(map);
|
||||
})
|
||||
.unwrap();
|
||||
allocations.extend(super::super::preserve_tiles::take_retained_allocations());
|
||||
let expected: Vec<_> = PREVIOUS_MAPS.into_iter().filter(|map| resized && excluded && !selected.contains(map)).collect();
|
||||
assert_eq!(allocations, expected, "each truly unchecked resized map must allocate exactly once");
|
||||
assert_eq!(output.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
|
||||
for (map, pixels) in &whole.maps {
|
||||
assert_eq!(*output.maps[map], *pixels, "{map:?} must preserve the ordinary bake's pixels");
|
||||
}
|
||||
for map in handed_over {
|
||||
assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]), "streaming must keep sharing the baked buffer");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_a_partial_stream_does_not_resample_future_maps() {
|
||||
let task = partial_task(&SELECTED_MAPS, true, true);
|
||||
let whole = task.run(&Progress::new()).unwrap();
|
||||
super::super::preserve_tiles::take_retained_allocations();
|
||||
let progress = Progress::new();
|
||||
let mut handed_over = Vec::new();
|
||||
let result = task.run_streaming(&progress, &mut |map| {
|
||||
handed_over.push(map);
|
||||
progress.cancel();
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(handed_over.len(), 1);
|
||||
for map in handed_over {
|
||||
assert_eq!(*map.data, whole.maps[&map.map], "cancellation leaves the handed-over map whole");
|
||||
}
|
||||
assert_eq!(super::super::preserve_tiles::take_retained_allocations(), [BakedMap::Normal]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_streaming_selection_keeps_the_ordinary_bake_behavior() {
|
||||
let task = partial_task(&[], true, true);
|
||||
super::super::preserve_tiles::take_retained_allocations();
|
||||
let whole = task.run(&Progress::new());
|
||||
let expected_allocations = super::super::preserve_tiles::take_retained_allocations();
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| panic!("an empty selection must not stream a map"));
|
||||
assert_eq!(super::super::preserve_tiles::take_retained_allocations(), expected_allocations);
|
||||
match (whole, output) {
|
||||
(Ok(whole), Ok(output)) => {
|
||||
assert_eq!((output.resolution, output.height), (whole.resolution, whole.height));
|
||||
assert_eq!(output.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
|
||||
for (map, pixels) in whole.maps {
|
||||
assert_eq!(*output.maps[&map], pixels);
|
||||
}
|
||||
}
|
||||
(Err(whole), Err(output)) => assert_eq!(whole.to_string(), output.to_string()),
|
||||
_ => panic!("empty streaming and ordinary bakes must agree"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_bake::HighPolyReach;
|
||||
|
||||
/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0
|
||||
/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked
|
||||
/// `vertex_count` is the validated high-poly mesh's vertex count
|
||||
pub fn high_poly_missed(reach: &[Option<HighPolyReach>], distances: &[(f32, f32)], only_set: Option<usize>, vertex_count: usize) -> Vec<f32> {
|
||||
// Ownership is already assigned by HighPolyReach; other sets must not color the vertex
|
||||
let sets: Vec<(&HighPolyReach, f32, f32)> = reach
|
||||
.iter()
|
||||
.zip(distances)
|
||||
.enumerate()
|
||||
.filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set))
|
||||
.filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear)))
|
||||
.collect();
|
||||
(0..vertex_count)
|
||||
.into_par_iter()
|
||||
.map(|vertex| {
|
||||
let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear));
|
||||
f32::from(u8::from(missed.unwrap_or(false)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -8,13 +8,15 @@ use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use texturecraft_core::BakePaintTarget;
|
||||
|
||||
use crate::{BakeMesh, BakeTask};
|
||||
use super::{BakeCageInputs, MergedHigh};
|
||||
use crate::{BakeMesh, BakeTask, StreamedBake};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_bake::tracing::Tracer;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
|
||||
use texturecraft_core::{
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion,
|
||||
};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
@@ -90,8 +92,8 @@ fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn bake_task(&self, ts: usize) -> Result<BakeTask> {
|
||||
let set = self.doc.project.texture_set(ts)?;
|
||||
pub fn bake_task(&self, texture_set: usize) -> Result<BakeTask> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
if !set.has_enabled_bake_tiles() {
|
||||
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
|
||||
}
|
||||
@@ -112,31 +114,22 @@ impl Session {
|
||||
} else {
|
||||
Arc::new(Vec::new())
|
||||
};
|
||||
let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() };
|
||||
let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile {
|
||||
Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose();
|
||||
let skew = painted(BakePaintTarget::Skew)?;
|
||||
let cage_paint = painted(BakePaintTarget::Cage)?;
|
||||
|
||||
let high = self.bake_high(texture_set)?;
|
||||
let cage = self.bake_cage(texture_set, high.is_some())?;
|
||||
let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?;
|
||||
let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?;
|
||||
|
||||
let grid = set.tile_grid();
|
||||
let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
|
||||
let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect();
|
||||
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() };
|
||||
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() };
|
||||
|
||||
let tracer = GPU_TRACER.get().cloned();
|
||||
Ok(BakeTask {
|
||||
low_base_color,
|
||||
ts,
|
||||
mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) {
|
||||
Some(grid) => {
|
||||
let mut mesh = (*self.source).clone();
|
||||
mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array())));
|
||||
Arc::new(mesh)
|
||||
}
|
||||
None => self.mesh.clone(),
|
||||
},
|
||||
ts: texture_set,
|
||||
mesh: self.bake_mesh(texture_set)?,
|
||||
bvh: self.bvh.clone(),
|
||||
material: set.material,
|
||||
settings: set.bake.clone(),
|
||||
@@ -151,6 +144,61 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file
|
||||
pub fn bake_cage_inputs(&self, texture_set: usize) -> Result<Option<BakeCageInputs>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let Some(high) = self.bake_high(texture_set)? else { return Ok(None) };
|
||||
let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) };
|
||||
|
||||
Ok(Some(BakeCageInputs {
|
||||
mesh: self.bake_mesh(texture_set)?,
|
||||
bvh: self.bvh.clone(),
|
||||
material: set.material,
|
||||
settings: set.bake.clone(),
|
||||
high,
|
||||
cage,
|
||||
skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?,
|
||||
cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly
|
||||
fn bake_high(&self, texture_set: usize) -> Result<Option<MergedHigh>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() })
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage
|
||||
fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result<Option<Arc<Mesh>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?;
|
||||
Ok(Some(cage.mesh.clone()))
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly
|
||||
fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result<Option<Arc<BakePaintMap>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high);
|
||||
paint.map(|map| super::layout::paint_for_bake(map, set)).transpose()
|
||||
}
|
||||
|
||||
/// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas
|
||||
fn bake_mesh(&self, texture_set: usize) -> Result<Arc<Mesh>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) {
|
||||
Some(grid) => {
|
||||
let mut mesh = (*self.source).clone();
|
||||
mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array())));
|
||||
Arc::new(mesh)
|
||||
}
|
||||
None => self.mesh.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Store a finished bake as one undo step
|
||||
pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
@@ -159,15 +207,28 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the
|
||||
/// preview that showed them holds the same ones)
|
||||
pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?;
|
||||
self.log.push(format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
|
||||
let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps)
|
||||
}
|
||||
|
||||
fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap<BakedMap, Arc<Vec<f32>>>) -> Result<()> {
|
||||
let entry = self.doc.baked.entry(texture_set).or_default();
|
||||
if entry.resolution != output.resolution || entry.maps.keys().any(|map| entry.height(*map) != output.height) {
|
||||
if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) {
|
||||
entry.maps.clear();
|
||||
}
|
||||
entry.resolution = output.resolution;
|
||||
for (map, pixels) in output.maps {
|
||||
entry.maps.insert(map, Arc::new(pixels));
|
||||
}
|
||||
|
||||
entry.resolution = resolution;
|
||||
entry.maps.extend(maps);
|
||||
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
|
||||
|
||||
mod bake_cage_inputs;
|
||||
mod bake_mesh;
|
||||
mod bake_meshes;
|
||||
mod bake_task;
|
||||
mod high_poly_missed;
|
||||
mod layout;
|
||||
mod merged_high;
|
||||
mod mesh_map_command;
|
||||
mod model_patch;
|
||||
mod paint_command;
|
||||
mod preserve_tiles;
|
||||
mod streamed_bake;
|
||||
mod streamed_map;
|
||||
mod tile_command;
|
||||
|
||||
pub use bake_cage_inputs::BakeCageInputs;
|
||||
pub use bake_mesh::BakeMesh;
|
||||
pub use bake_meshes::BakeMeshes;
|
||||
pub use bake_task::BakeTask;
|
||||
pub use high_poly_missed::high_poly_missed;
|
||||
pub use merged_high::MergedHigh;
|
||||
pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params};
|
||||
pub use model_patch::settings_patch;
|
||||
pub use streamed_bake::StreamedBake;
|
||||
pub use streamed_map::StreamedMap;
|
||||
pub use texturecraft_bake::*;
|
||||
|
||||
use crate::CommandSpec;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use texturecraft_bake::BakeOutput;
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
@@ -29,9 +30,18 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
|
||||
}
|
||||
}
|
||||
|
||||
// Keep unchecked map outputs too when a partial bake changes the atlas dimensions
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retain only maps outside the full task selection, once per completed atlas.
|
||||
/// A one-map streaming pass must not resample maps that are still scheduled to bake.
|
||||
pub(super) fn restore_unchecked(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], selected: &[BakedMap]) -> Result<()> {
|
||||
if excluded_tiles.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let size = (output.resolution, output.height);
|
||||
for map in previous.maps.keys() {
|
||||
if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
|
||||
if selected.contains(map) || output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -42,6 +52,8 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
|
||||
.ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?;
|
||||
let mut pixels = Vec::new();
|
||||
pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?;
|
||||
#[cfg(test)]
|
||||
RETAINED_ALLOCATIONS.with(|allocations| allocations.borrow_mut().push(*map));
|
||||
for y in 0..size.1 {
|
||||
for x in 0..size.0 {
|
||||
let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral());
|
||||
@@ -52,3 +64,15 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Restoration is sequential on the calling thread. Record successful retained-buffer allocations
|
||||
// only in unit tests, without a global allocator or interference from parallel test threads.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static RETAINED_ALLOCATIONS: std::cell::RefCell<Vec<texturecraft_core::BakedMap>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn take_retained_allocations() -> Vec<texturecraft_core::BakedMap> {
|
||||
RETAINED_ALLOCATIONS.with(|allocations| std::mem::take(&mut *allocations.borrow_mut()))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them,
|
||||
/// so the preview and the document hold one buffer per map, never two
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StreamedBake {
|
||||
pub resolution: u32,
|
||||
pub height: u32,
|
||||
pub maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
pub tracer: String,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// One finished map of a streamed bake (see [`crate::BakeTask::run_streaming`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StreamedMap {
|
||||
pub map: BakedMap,
|
||||
/// Position among the maps this bake makes, from 0, and how many there are.
|
||||
pub index: usize,
|
||||
pub total: usize,
|
||||
/// Width and height in texels.
|
||||
pub resolution: u32,
|
||||
pub height: u32,
|
||||
/// Row-major, `map.components()` floats per texel, padded.
|
||||
pub data: Arc<Vec<f32>>,
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon
|
||||
//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in
|
||||
//! the document: nothing enters the undo history until a texture set's bake is applied
|
||||
//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already
|
||||
//! applied keep their results and undo steps. The preview shows one map at a time, raw on the
|
||||
//! model; maps and texture sets not baked yet show their neutral value.
|
||||
|
||||
mod preview_set;
|
||||
mod preview_show;
|
||||
mod stage;
|
||||
|
||||
pub use preview_set::PreviewSet;
|
||||
pub use preview_show::PreviewShow;
|
||||
pub use stage::Stage;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::bake::StreamedMap;
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::session::ViewMode;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// What painting says while a bake preview shows (the app translates it).
|
||||
pub const PAINTING_PAUSED: &str = "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"bake.preview",
|
||||
"Bake preview",
|
||||
[],
|
||||
None,
|
||||
"{show?: \"follow\" (the newest finished map) | \"material\" | \"map:<id>\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)",
|
||||
always,
|
||||
preview
|
||||
)]
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BakePreview {
|
||||
/// The view mode to put back when the preview ends.
|
||||
pub restore: ViewMode,
|
||||
pub show: PreviewShow,
|
||||
pub sets: BTreeMap<usize, PreviewSet>,
|
||||
/// The texture set being baked.
|
||||
pub current: Option<usize>,
|
||||
/// The last map that finished.
|
||||
pub newest: Option<BakedMap>,
|
||||
}
|
||||
|
||||
impl BakePreview {
|
||||
/// The map the view shows, None for the material.
|
||||
pub fn shown(&self) -> Option<BakedMap> {
|
||||
match self.show {
|
||||
PreviewShow::Material => None,
|
||||
PreviewShow::Pin(map) => Some(map),
|
||||
PreviewShow::Follow => self
|
||||
.newest
|
||||
.or_else(|| self.current_set().and_then(|set| set.order.first().copied()))
|
||||
.or_else(|| self.sets.values().find_map(|set| set.order.first().copied())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current_set(&self) -> Option<&PreviewSet> {
|
||||
self.sets.get(&self.current?)
|
||||
}
|
||||
|
||||
/// The map being baked now (None between sets and once the set's maps are all in).
|
||||
pub fn stage(&self) -> Option<Stage> {
|
||||
let texture_set = self.current?;
|
||||
let set = self.sets.get(&texture_set)?;
|
||||
let done = set.baked.maps.len();
|
||||
Some(Stage { texture_set, map: *set.order.get(done)?, position: done + 1, total: set.order.len() })
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Start a preview from each selected texture set's enabled maps, in the same order as
|
||||
/// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before
|
||||
/// changing the preview or view mode. This reads settings without preparing bake geometry.
|
||||
pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> {
|
||||
let orders = sets
|
||||
.iter()
|
||||
.map(|&texture_set| {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok((texture_set, set.bake.maps.enabled().collect()))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
self.bake_preview_begin(orders);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view
|
||||
/// follows the newest map and every set shows neutral values until its maps arrive. The
|
||||
/// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is
|
||||
/// discarded so a later pointer release cannot commit paint during the preview.
|
||||
pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec<BakedMap>)>) {
|
||||
self.cancel_stroke();
|
||||
|
||||
let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore);
|
||||
let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect();
|
||||
|
||||
self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None });
|
||||
self.bake_preview_refresh();
|
||||
}
|
||||
|
||||
/// The texture set whose maps stream in now.
|
||||
pub fn bake_preview_set_current(&mut self, texture_set: usize) {
|
||||
if let Some(preview) = &mut self.bake_preview {
|
||||
preview.current = Some(texture_set);
|
||||
}
|
||||
|
||||
self.bake_preview_refresh();
|
||||
}
|
||||
|
||||
/// Install one finished map of set `texture_set`. Returns false when no preview shows.
|
||||
pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool {
|
||||
let Some(preview) = &mut self.bake_preview else { return false };
|
||||
|
||||
let set = preview.sets.entry(texture_set).or_default();
|
||||
|
||||
// A new bake of the set starts from nothing (the baker never repeats a map)
|
||||
if streamed.index == 0 {
|
||||
set.baked = BakedMaps::default();
|
||||
}
|
||||
|
||||
set.baked.resolution = streamed.resolution;
|
||||
set.baked.maps.insert(streamed.map, streamed.data);
|
||||
preview.newest = Some(streamed.map);
|
||||
self.bake_preview_refresh();
|
||||
true
|
||||
}
|
||||
|
||||
/// Choose what the view shows (Follow, a pinned map or the material).
|
||||
pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> {
|
||||
let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) };
|
||||
|
||||
preview.show = show;
|
||||
self.bake_preview_refresh();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The user picked a view mode during a bake: a mesh map pins it, any other mode shows
|
||||
/// the material and is what comes back when the bake ends.
|
||||
pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) {
|
||||
let Some(preview) = &mut self.bake_preview else { return };
|
||||
|
||||
match view {
|
||||
ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map),
|
||||
other => {
|
||||
preview.show = PreviewShow::Material;
|
||||
preview.restore = other;
|
||||
}
|
||||
}
|
||||
|
||||
self.bake_preview_refresh();
|
||||
if !matches!(view, ViewMode::MeshMap(_)) {
|
||||
self.view = view;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the displayed maps and restore the previous view mode. This does not stop a
|
||||
/// worker or undo any applied results; the UI also uses it when leaving Bake mode.
|
||||
pub fn bake_preview_end(&mut self) {
|
||||
if let Some(preview) = self.bake_preview.take() {
|
||||
self.view = preview.restore;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bake_preview_active(&self) -> bool {
|
||||
self.bake_preview.is_some()
|
||||
}
|
||||
|
||||
/// The streamed maps of set `texture_set` while a preview shows (empty for a set not baked
|
||||
/// yet: neutral values), None when the document's baked maps are what shows.
|
||||
pub fn bake_preview_baked(&self, texture_set: usize) -> Option<&BakedMaps> {
|
||||
self.bake_preview.as_ref()?.sets.get(&texture_set).map(|set| &set.baked)
|
||||
}
|
||||
|
||||
/// Why painting is not possible now, when a bake preview shows.
|
||||
pub fn painting_blocked(&self) -> Option<&'static str> {
|
||||
self.bake_preview.as_ref().map(|_| PAINTING_PAUSED)
|
||||
}
|
||||
|
||||
fn bake_preview_refresh(&mut self) {
|
||||
let Some(preview) = &self.bake_preview else { return };
|
||||
|
||||
self.view = match preview.shown() {
|
||||
Some(map) => ViewMode::MeshMap(map),
|
||||
None => ViewMode::Material,
|
||||
};
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`.
|
||||
pub fn preview_json(session: &Session) -> Value {
|
||||
let Some(preview) = &session.bake_preview else { return json!({ "active": false }) };
|
||||
|
||||
let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total }));
|
||||
let sets: Vec<Value> = preview
|
||||
.sets
|
||||
.iter()
|
||||
.map(|(texture_set, set)| {
|
||||
json!({
|
||||
"set": texture_set,
|
||||
"order": set.order.iter().map(|map| map.id()).collect::<Vec<_>>(),
|
||||
"done": set.baked.maps.keys().map(|map| map.id()).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
json!({
|
||||
"active": true,
|
||||
"show": preview.show.id(),
|
||||
"shown": preview.shown().map(|map| map.id()),
|
||||
"newest": preview.newest.map(|map| map.id()),
|
||||
"restore": preview.restore.label(),
|
||||
"stage": stage,
|
||||
"sets": sets,
|
||||
})
|
||||
}
|
||||
|
||||
fn preview(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if let Some(show) = strp(params, "show") {
|
||||
let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:<id>")))?;
|
||||
session.bake_preview_show(show)?;
|
||||
}
|
||||
|
||||
Ok(preview_json(session))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// The maps of one texture set streamed so far.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PreviewSet {
|
||||
pub baked: BakedMaps,
|
||||
/// The maps this set's bake makes, in the order they arrive.
|
||||
pub order: Vec<BakedMap>,
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// What the 3D view shows while a bake runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PreviewShow {
|
||||
/// The newest finished map (the first one, still neutral, before any is done).
|
||||
Follow,
|
||||
/// One map, pinned: neutral until it is baked.
|
||||
Pin(BakedMap),
|
||||
/// The lit material.
|
||||
Material,
|
||||
}
|
||||
|
||||
impl PreviewShow {
|
||||
pub fn id(self) -> String {
|
||||
match self {
|
||||
PreviewShow::Follow => "follow".into(),
|
||||
PreviewShow::Pin(map) => format!("map:{}", map.id()),
|
||||
PreviewShow::Material => "material".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Option<PreviewShow> {
|
||||
match text {
|
||||
"follow" => Some(PreviewShow::Follow),
|
||||
"material" => Some(PreviewShow::Material),
|
||||
_ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// The map a bake is working on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Stage {
|
||||
pub texture_set: usize,
|
||||
pub map: BakedMap,
|
||||
/// 1-based position among the set's maps, and how many there are.
|
||||
pub position: usize,
|
||||
pub total: usize,
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Color selection effects: the ID colors they select, picked from the ID mesh map
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{BakedMap, EffectKind, LayerId};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::surface_at;
|
||||
|
||||
use crate::commands::{CommandSpec, bad, f32p, has_layer};
|
||||
use crate::mask_cmds::effect_id;
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Most colors one color selection holds; an ID map rarely has more distinct parts
|
||||
const MAX_SELECTED_COLORS: usize = 256;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"effect.colorSelection.pick",
|
||||
"Pick ID color",
|
||||
[],
|
||||
None,
|
||||
"{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point",
|
||||
has_layer,
|
||||
pick
|
||||
)]
|
||||
}
|
||||
|
||||
/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection
|
||||
pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> {
|
||||
if let Some(list) = params.get("colors") {
|
||||
*colors = colors_param(list)?;
|
||||
}
|
||||
if let Some(value) = f32p(params, "tolerance") {
|
||||
*tolerance = value.clamp(0.0, 1.0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1
|
||||
fn colors_param(list: &Value) -> Result<Vec<[f32; 3]>> {
|
||||
const CMD: &str = "effect.set";
|
||||
let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?;
|
||||
if items.is_empty() || items.len() > MAX_SELECTED_COLORS {
|
||||
return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors")));
|
||||
}
|
||||
|
||||
items
|
||||
.iter()
|
||||
.map(|item| match finite_numbers::<3>(item) {
|
||||
Some(color) => Ok(color.map(|value| value.clamp(0.0, 1.0) as f32)),
|
||||
_ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Samples the ID map under a viewport point or at a UV and adds the color to a color selection
|
||||
fn pick(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.colorSelection.pick";
|
||||
let effect = effect_id(session, params, CMD)?;
|
||||
let (owner, color_count) = match session.doc.project.effect(effect) {
|
||||
Some((owner, found)) => match &found.kind {
|
||||
EffectKind::ColorSelection { colors, .. } => (owner, colors.len()),
|
||||
other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))),
|
||||
},
|
||||
None => return Err(bad(CMD, format!("no effect {}", effect.0))),
|
||||
};
|
||||
|
||||
let index = params
|
||||
.get("index")
|
||||
.filter(|index| !index.is_null())
|
||||
.map(|index| index.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer")))
|
||||
.transpose()?;
|
||||
let index = match index {
|
||||
Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?),
|
||||
None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let color = id_color_at(session, params, owner)?;
|
||||
session.edit("Pick ID color", |session| {
|
||||
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind {
|
||||
match index.and_then(|index| colors.get_mut(index)) {
|
||||
Some(slot) => *slot = color,
|
||||
None => colors.push(color),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "color": color, "index": index.unwrap_or(color_count) }))
|
||||
}
|
||||
|
||||
/// The ID map color of the texel a color selection on `owner` reads at the picked point
|
||||
fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> {
|
||||
const CMD: &str = "effect.colorSelection.pick";
|
||||
let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?;
|
||||
let set = session.doc.project.texture_set(set_index)?;
|
||||
let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id));
|
||||
let Some(baked) = baked else {
|
||||
return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name)));
|
||||
};
|
||||
|
||||
let uv = match params.get("uv") {
|
||||
Some(uv) => uv_param(uv)?,
|
||||
None => {
|
||||
let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else {
|
||||
return Err(bad(CMD, "give `x` and `y` (viewport pixels) or `uv`"));
|
||||
};
|
||||
|
||||
let (uv, material) = visible_surface(session, Vec2::new(x, y), viewport_of(session, params))
|
||||
.ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?;
|
||||
if material != set.material {
|
||||
return Err(bad(CMD, "that surface belongs to another texture set"));
|
||||
}
|
||||
uv
|
||||
}
|
||||
};
|
||||
|
||||
// The same texel the mask evaluates, so a picked color always selects where it was picked
|
||||
let size = set.size();
|
||||
let texel = [uv.x * size.0 as f32, uv.y * size.1 as f32];
|
||||
if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) {
|
||||
return Err(bad(CMD, "that point is outside the texture set's UV space"));
|
||||
}
|
||||
baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there"))
|
||||
}
|
||||
|
||||
/// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray
|
||||
fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(Vec2, usize)> {
|
||||
let viewport = viewport.max(Vec2::ONE);
|
||||
let device = Vec2::new(screen.x / viewport.x * 2.0 - 1.0, 1.0 - screen.y / viewport.y * 2.0);
|
||||
let ray = session.camera.ray(device, viewport.x / viewport.y);
|
||||
let sets = &session.doc.project.texture_sets;
|
||||
let visible = |triangle: u32| {
|
||||
let material = session.mesh.material_of(triangle as usize).unwrap_or(0);
|
||||
sets.iter().find(|set| set.material == material).is_none_or(|set| set.visible)
|
||||
};
|
||||
|
||||
let hit = session.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, &visible)?;
|
||||
let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?;
|
||||
Some((surface.uv, session.mesh.material_of(hit.tri as usize).unwrap_or(0)))
|
||||
}
|
||||
|
||||
/// A `[u, v]` param of finite numbers
|
||||
fn uv_param(uv: &Value) -> Result<Vec2> {
|
||||
match finite_numbers::<2>(uv) {
|
||||
Some([u, v]) => Ok(Vec2::new(u as f32, v as f32)),
|
||||
_ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the shape before reading components, without allocating for oversized input
|
||||
fn finite_numbers<const N: usize>(list: &Value) -> Option<[f64; N]> {
|
||||
let items: &[Value; N] = list.as_array()?.as_slice().try_into().ok()?;
|
||||
let mut numbers = [0.0; N];
|
||||
for (number, item) in numbers.iter_mut().zip(items) {
|
||||
*number = item.as_f64().filter(|value| value.is_finite())?;
|
||||
}
|
||||
Some(numbers)
|
||||
}
|
||||
@@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::layer_ops::specs());
|
||||
v.extend(crate::instance_cmds::specs());
|
||||
v.extend(crate::mask_cmds::specs());
|
||||
v.extend(crate::color_selection_cmds::specs());
|
||||
v.extend(crate::effect_clipboard::specs());
|
||||
v.extend(crate::tool_cmds::specs());
|
||||
v.extend(crate::brush_preset_cmds::specs());
|
||||
@@ -65,10 +66,12 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::quick_mask::specs());
|
||||
v.extend(crate::set_cmds::specs());
|
||||
v.extend(crate::meshmap_cmds::specs());
|
||||
v.extend(crate::meshmap_import_cmds::specs());
|
||||
v.extend(crate::uv_tile_cmds::specs());
|
||||
v.extend(crate::template_cmds::specs());
|
||||
v.extend(crate::project_cmds::specs());
|
||||
v.extend(crate::bake::specs());
|
||||
v.extend(crate::bake_preview::specs());
|
||||
v.extend(crate::materialx_cmds::specs());
|
||||
v.extend(crate::file_cmds::specs());
|
||||
v.extend(crate::preset_cmds::specs());
|
||||
|
||||
@@ -331,6 +331,11 @@ mod native {
|
||||
strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required")))
|
||||
}
|
||||
|
||||
/// `path` made absolute (as given when that fails), for [`Project::mesh_path`].
|
||||
pub fn absolute(path: &str) -> String {
|
||||
std::path::absolute(Path::new(path)).map_or_else(|_| path.to_string(), |p| p.display().to_string())
|
||||
}
|
||||
|
||||
/// Mesh file `path` with the files it references next to it folded in (a `.gltf`'s buffers
|
||||
/// and images, a loose USD layer's textures), ready to import and store in the project.
|
||||
pub fn read_mesh(cmd: &str, path: &str) -> Result<texturecraft_formats::MeshFile> {
|
||||
@@ -349,6 +354,7 @@ mod native {
|
||||
} else {
|
||||
let f = read_mesh("file.open", path)?;
|
||||
let mut s = Session::from_mesh_bytes(&f.name, &f.bytes, 2048, &stem_of(path))?;
|
||||
s.doc.project.mesh_path = absolute(path);
|
||||
s.log.extend(f.warnings);
|
||||
Ok(s)
|
||||
}
|
||||
@@ -367,8 +373,10 @@ mod native {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{open_path, read_mesh};
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`,
|
||||
/// remembering its path for Reimport mesh.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "mesh", "file.new")?;
|
||||
@@ -377,6 +385,7 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048);
|
||||
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
|
||||
let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?;
|
||||
next.doc.project.mesh_path = native::absolute(path);
|
||||
next.log.extend(f.warnings);
|
||||
if let Some(t) = &template {
|
||||
next.apply_template(t);
|
||||
@@ -414,14 +423,28 @@ fn save_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
native::save_to(s, &path, false)
|
||||
}
|
||||
|
||||
/// `file.reimportMesh {path?, preserveStrokes?}`: reimport from `path`, or from the project's own
|
||||
/// copy of the mesh when there is none. A path given is remembered as the project's mesh path.
|
||||
/// The remembered path is never read implicitly (a project file could point it anywhere on the
|
||||
/// host); callers that may read host files pass [`Session::remembered_mesh_path`] as `path`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let file = strp(p, "path").map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
|
||||
s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))
|
||||
let path = strp(p, "path");
|
||||
let file = path.map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
|
||||
let reply = s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))?;
|
||||
if let Some(path) = path {
|
||||
s.doc.project.mesh_path = native::absolute(path);
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Session {
|
||||
/// The file the mesh was imported from, when it is still there: what Reimport mesh reads again.
|
||||
pub fn remembered_mesh_path(&self) -> Option<&str> {
|
||||
Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file())
|
||||
}
|
||||
|
||||
/// Replace the mesh with `file` (or re-read the project's own copy) and keep the project:
|
||||
/// texture sets map by material index. Nothing changes unless the new mesh fits the project.
|
||||
/// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies
|
||||
@@ -449,6 +472,7 @@ impl Session {
|
||||
next.log.extend(warnings);
|
||||
next.path = self.path.clone();
|
||||
next.modified = true;
|
||||
next.project_id = self.project_id;
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
self.switch_to(next);
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
@@ -611,14 +635,57 @@ fn close(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Reimport mesh reads the mesh file again from where it was imported, so a change saved to
|
||||
/// the file since shows up (it used to re-read the project's own copy and change nothing).
|
||||
#[test]
|
||||
fn reimport_picks_up_changes_saved_to_the_mesh_file() {
|
||||
let dir = std::env::temp_dir().join(format!("tc_reimport_disk_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("tri.obj");
|
||||
let obj = |z: f32| {
|
||||
format!(
|
||||
"v -1 -1 {z}
|
||||
v 1 -1 0
|
||||
v 1 1 0
|
||||
vt 0 0
|
||||
vt 1 0
|
||||
vt 1 1
|
||||
f 1/1 2/2 3/3
|
||||
"
|
||||
)
|
||||
};
|
||||
std::fs::write(&file, obj(0.0)).unwrap();
|
||||
let path = file.display().to_string();
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap();
|
||||
let low = |s: &Session| s.mesh.positions.iter().map(|p| p.z.abs()).fold(0.0_f32, f32::max);
|
||||
assert_eq!(low(&s), 0.0);
|
||||
// Edit the file, save the project, reopen it, then reimport with no path.
|
||||
std::fs::write(&file, obj(0.5)).unwrap();
|
||||
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(low(&reopened), 0.0, "the project still holds the old copy");
|
||||
// A command without a path never reads the remembered host path (automation allows it).
|
||||
crate::execute(&mut reopened, "file.reimportMesh", &Value::Null).unwrap();
|
||||
assert_eq!(low(&reopened), 0.0, "no path: the project's own copy");
|
||||
let remembered = reopened.remembered_mesh_path().map(str::to_string).expect("the imported file is remembered");
|
||||
crate::execute(&mut reopened, "file.reimportMesh", &json!({ "path": remembered })).unwrap();
|
||||
assert!(low(&reopened) > 0.0, "the edited file must be read again");
|
||||
// The file gone: nothing is remembered, so the UI asks for one.
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert!(reopened.remembered_mesh_path().is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reimporting_a_saved_project_marks_it_modified() {
|
||||
let obj = b"v -1 -1 0\nv 1 -1 0\nv 1 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 1/1 2/2 3/3\n";
|
||||
let original = Session::from_mesh_bytes("mesh.obj", obj, 128, "mesh").unwrap();
|
||||
let mut saved = Session::from_project_bytes(&original.to_project_bytes().unwrap()).unwrap();
|
||||
assert!(!saved.modified);
|
||||
let project = saved.project_id;
|
||||
crate::execute(&mut saved, "file.reimportMesh", &Value::Null).unwrap();
|
||||
assert!(saved.modified, "reimport must trigger the unsaved-changes prompt");
|
||||
assert_eq!(saved.project_id, project, "a reimport stays the same project");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -42,6 +42,10 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
|
||||
match &effect.kind {
|
||||
EffectKind::Generator(generator) => out["generator"] = generator_json(generator),
|
||||
EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]),
|
||||
EffectKind::ColorSelection { colors, tolerance } => {
|
||||
out["colors"] = json!(colors);
|
||||
out["tolerance"] = json!(tolerance);
|
||||
}
|
||||
EffectKind::Path(paths) => {
|
||||
out["paths"] = json!(
|
||||
paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::<Vec<_>>()
|
||||
@@ -183,6 +187,7 @@ pub fn session(s: &Session) -> Value {
|
||||
"layers": stack(s, ts),
|
||||
"tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) },
|
||||
"view": s.view.label(),
|
||||
"bakePreview": crate::bake_preview::preview_json(s),
|
||||
"camera": crate::view_cmds::camera_json(s),
|
||||
"display": s.doc.project.display,
|
||||
"history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() },
|
||||
|
||||
@@ -9,8 +9,10 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake;
|
||||
pub mod bake_preview;
|
||||
pub mod brush_preset_cmds;
|
||||
pub mod camera_cmds;
|
||||
pub mod color_selection_cmds;
|
||||
pub mod commands;
|
||||
pub mod decal_cmds;
|
||||
pub mod effect_clipboard;
|
||||
@@ -30,6 +32,8 @@ mod material_preview_pixel;
|
||||
pub mod materials;
|
||||
pub mod materialx_cmds;
|
||||
pub mod meshmap_cmds;
|
||||
mod meshmap_file_name;
|
||||
pub mod meshmap_import_cmds;
|
||||
mod orb_camera;
|
||||
pub mod orb_preview;
|
||||
pub mod painting;
|
||||
@@ -55,7 +59,8 @@ mod uv_stroke_state;
|
||||
pub mod uv_tile_cmds;
|
||||
pub mod view_cmds;
|
||||
|
||||
pub use bake::{BakeMesh, BakeMeshes, BakeTask};
|
||||
pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap};
|
||||
pub use bake_preview::{BakePreview, PreviewShow};
|
||||
pub use commands::{CommandSpec, command_specs, execute, find};
|
||||
pub use fill_hit_test::FillHitTest;
|
||||
pub use fill_mode::FillMode;
|
||||
|
||||
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}",
|
||||
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
@@ -519,7 +519,8 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
|
||||
}
|
||||
}
|
||||
EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => {
|
||||
EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?,
|
||||
EffectKind::Compare { tolerance, .. } => {
|
||||
if let Some(value) = f32p(params, "tolerance") {
|
||||
*tolerance = value.clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
@@ -38,55 +38,91 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?;
|
||||
let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let set = s.doc.project.texture_set(ts)?.clone();
|
||||
let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?;
|
||||
// Every mesh map of a set shares one size: the other maps', or what a bake would make (a
|
||||
// block of the bake resolution per tile of the atlas).
|
||||
let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows));
|
||||
let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) {
|
||||
Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))),
|
||||
None => {
|
||||
let (width, height) = set.bake.common.output_size();
|
||||
(width.saturating_mul(cols), height.saturating_mul(rows))
|
||||
}
|
||||
let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let images = match texture_set.tile_grid() {
|
||||
Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?,
|
||||
None => BTreeMap::from([(FIRST_TILE, image)]),
|
||||
};
|
||||
if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) {
|
||||
return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty")));
|
||||
}
|
||||
let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = match &tiles {
|
||||
None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)),
|
||||
// An atlas texel reads the image of the tile its mesh UV falls in.
|
||||
Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}),
|
||||
};
|
||||
s.edit("Use image as mesh map", |s| {
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = res;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "map": map.id(), "resolution": res }))
|
||||
|
||||
let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?;
|
||||
Ok(json!({ "map": map.id(), "resolution": resolution }))
|
||||
}
|
||||
|
||||
/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for
|
||||
/// each tile's.
|
||||
fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result<BTreeMap<u32, Arc<ImageRes>>> {
|
||||
const CMD: &str = "textureSet.meshMap.set";
|
||||
let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
|
||||
/// The tile number a set without UV tiles keys its one image by
|
||||
pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start();
|
||||
|
||||
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width
|
||||
pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let grid = texture_set.tile_grid();
|
||||
if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
|
||||
return Err(bad(cmd, format!("no image for UV tile {tile}")));
|
||||
}
|
||||
|
||||
let (width, height) = image_map_size(s, cmd, ts)?;
|
||||
|
||||
let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = match (grid, images.values().next()) {
|
||||
(_, None) => return Err(bad(cmd, "no image to use")),
|
||||
(None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)),
|
||||
// An atlas texel reads the image of the tile its mesh UV falls in
|
||||
(Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}),
|
||||
};
|
||||
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = width;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(width)
|
||||
}
|
||||
|
||||
/// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels
|
||||
pub(crate) fn image_map_size(s: &Session, cmd: &str, ts: usize) -> Result<(u32, u32)> {
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let grid = texture_set.tile_grid();
|
||||
|
||||
// Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile)
|
||||
let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
|
||||
let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) {
|
||||
Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))),
|
||||
None => {
|
||||
let (width, height) = texture_set.bake.common.output_size();
|
||||
(width.saturating_mul(columns), height.saturating_mul(rows))
|
||||
}
|
||||
};
|
||||
let empty = width == 0 || height == 0;
|
||||
let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS;
|
||||
let too_wide = grid.is_none() && width > MAX_RESOLUTION;
|
||||
if empty || too_many_texels || too_wide {
|
||||
return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty")));
|
||||
}
|
||||
|
||||
Ok((width, height))
|
||||
}
|
||||
|
||||
/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's
|
||||
fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result<BTreeMap<u32, Arc<ImageRes>>> {
|
||||
let tile_at =
|
||||
udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
|
||||
let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default());
|
||||
tiles
|
||||
.iter()
|
||||
.map(|&t| {
|
||||
let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default());
|
||||
images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}")))
|
||||
.map(|&tile| {
|
||||
let tile_name = format!("{before_tile}{tile}{after_tile}");
|
||||
images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The UV tile number in a file name (`Body_ao.1002.png` → 1002)
|
||||
pub(crate) fn tile_number(file_name: &str) -> Option<u32> {
|
||||
udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok())
|
||||
}
|
||||
|
||||
/// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts.
|
||||
fn udim_in(name: &str) -> Option<usize> {
|
||||
let b = name.as_bytes();
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion)
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use texturecraft_core::{BakedMap, UDIM_RANGE};
|
||||
|
||||
/// Mesh maps named by two words anywhere in the file name; they win over the one-word names
|
||||
const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[
|
||||
("world", &["normal", "normals"], BakedMap::WorldNormal),
|
||||
("bent", &["normal", "normals"], BakedMap::BentNormal),
|
||||
("ambient", &["occlusion"], BakedMap::AmbientOcclusion),
|
||||
];
|
||||
|
||||
/// Mesh maps named by one word, including the two-word names written as one
|
||||
const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[
|
||||
("worldnormal", BakedMap::WorldNormal),
|
||||
("worldnormals", BakedMap::WorldNormal),
|
||||
("bentnormal", BakedMap::BentNormal),
|
||||
("bentnormals", BakedMap::BentNormal),
|
||||
("ambientocclusion", BakedMap::AmbientOcclusion),
|
||||
("normal", BakedMap::Normal),
|
||||
("normals", BakedMap::Normal),
|
||||
("nrm", BakedMap::Normal),
|
||||
("occlusion", BakedMap::AmbientOcclusion),
|
||||
("ao", BakedMap::AmbientOcclusion),
|
||||
("curvature", BakedMap::Curvature),
|
||||
("curv", BakedMap::Curvature),
|
||||
("id", BakedMap::Id),
|
||||
("position", BakedMap::Position),
|
||||
("pos", BakedMap::Position),
|
||||
("thickness", BakedMap::Thickness),
|
||||
("height", BakedMap::Height),
|
||||
("displacement", BakedMap::Height),
|
||||
("opacity", BakedMap::Opacity),
|
||||
("alpha", BakedMap::Opacity),
|
||||
];
|
||||
|
||||
fn is_separator(c: char) -> bool {
|
||||
matches!(c, '_' | '-' | '.' | ' ')
|
||||
}
|
||||
|
||||
/// The lowercase file name without its folder and extension
|
||||
fn lowercase_stem(path: &str) -> String {
|
||||
Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase()
|
||||
}
|
||||
|
||||
/// What follows `set_name` at the start of a lowercase stem, when a separator follows it
|
||||
fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> {
|
||||
if set_name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator))
|
||||
}
|
||||
|
||||
/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins
|
||||
pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option<BakedMap> {
|
||||
let stem = lowercase_stem(path);
|
||||
let rest = after_set_name(&stem, set_name).unwrap_or(&stem);
|
||||
let is_tile_number = |word: &str| word.len() == 4 && word.parse::<u32>().is_ok_and(|number| UDIM_RANGE.contains(&number));
|
||||
let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect();
|
||||
|
||||
let has = |name: &str| words.contains(&name);
|
||||
TWO_WORD_NAMES
|
||||
.iter()
|
||||
.find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second)))
|
||||
.map(|(_, _, map)| *map)
|
||||
.or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map)))
|
||||
}
|
||||
|
||||
/// The set a file is for: the longest set name its name starts with before a separator (any name with one set)
|
||||
pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option<usize> {
|
||||
if set_names.len() == 1 {
|
||||
return Some(0);
|
||||
}
|
||||
|
||||
let stem = lowercase_stem(path);
|
||||
set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_word_names_its_map() {
|
||||
let cases = [
|
||||
("Body_normal.png", BakedMap::Normal),
|
||||
("Body_normals.png", BakedMap::Normal),
|
||||
("Body_nrm.png", BakedMap::Normal),
|
||||
("Body_world_normal.png", BakedMap::WorldNormal),
|
||||
("Body_normals_world.png", BakedMap::WorldNormal),
|
||||
("Body_WorldNormal.png", BakedMap::WorldNormal),
|
||||
("Body_bent_normals.png", BakedMap::BentNormal),
|
||||
("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body_occlusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body AO.png", BakedMap::AmbientOcclusion),
|
||||
("Body_curvature.png", BakedMap::Curvature),
|
||||
("Body_curv.png", BakedMap::Curvature),
|
||||
("Body_ID.png", BakedMap::Id),
|
||||
("Body_position.png", BakedMap::Position),
|
||||
("Body_pos.png", BakedMap::Position),
|
||||
("Body_thickness.png", BakedMap::Thickness),
|
||||
("Body_height.png", BakedMap::Height),
|
||||
("Body_displacement.png", BakedMap::Height),
|
||||
("Body_opacity.png", BakedMap::Opacity),
|
||||
("Body_alpha.png", BakedMap::Opacity),
|
||||
];
|
||||
for (file, map) in cases {
|
||||
assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_numbers_and_folders_are_ignored() {
|
||||
assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion));
|
||||
assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal));
|
||||
assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_words_match_no_map() {
|
||||
assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("", "Body"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_set_name_is_not_read_as_a_map() {
|
||||
assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal));
|
||||
assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None);
|
||||
assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_longest_set_name_wins() {
|
||||
let sets = ["Body", "Body_Upper", "Head"];
|
||||
assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1));
|
||||
assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_name_must_end_at_a_separator() {
|
||||
let sets = ["Body", "Head"];
|
||||
assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None);
|
||||
assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None);
|
||||
assert_eq!(texture_set_from_file_name("Body.png", &sets), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_set_takes_every_file() {
|
||||
assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("ao.png", &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images};
|
||||
use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name};
|
||||
use crate::resource_cmds::read_image_file;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
const CMD: &str = "textureSet.meshMap.import";
|
||||
|
||||
/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles
|
||||
const MAX_FILES: usize = 512;
|
||||
|
||||
/// Bound retained file bytes, decoded RGBA floats and resampled maps together, before allocating pixels
|
||||
const MAX_TOTAL_BYTES: u64 = 2 << 30;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"textureSet.meshMap.import",
|
||||
"Import baked maps",
|
||||
[],
|
||||
None,
|
||||
"{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); at most 512 files and 2 GiB of file bytes, decoded images and mesh maps; desktop only",
|
||||
always,
|
||||
import
|
||||
)]
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
import_with_budget(s, p, MAX_TOTAL_BYTES)
|
||||
}
|
||||
|
||||
fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Value> {
|
||||
let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?;
|
||||
if files.len() > MAX_FILES {
|
||||
return Err(bad(CMD, format!("at most {MAX_FILES} files at once")));
|
||||
}
|
||||
|
||||
let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect();
|
||||
let mut slots: BTreeMap<(usize, BakedMap), BTreeMap<u32, &str>> = BTreeMap::new();
|
||||
let mut unmatched = Vec::new();
|
||||
for file in files {
|
||||
let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?;
|
||||
let given_map = match file.get("map") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(id)) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?),
|
||||
Some(_) => return Err(bad(CMD, "`map` must be a mesh map id string")),
|
||||
};
|
||||
|
||||
match slot_of(s, &set_names, path, given_map) {
|
||||
Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => {
|
||||
slots.entry(slot).or_default().insert(tile, path);
|
||||
}
|
||||
_ => unmatched.push(path),
|
||||
}
|
||||
}
|
||||
|
||||
// A UV-tiled map needs a file for every tile of its set
|
||||
slots.retain(|(ts, _), tiles| {
|
||||
let complete =
|
||||
s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile)));
|
||||
if !complete {
|
||||
unmatched.extend(tiles.values());
|
||||
}
|
||||
complete
|
||||
});
|
||||
if slots.is_empty() {
|
||||
return Ok(json!({ "assigned": [], "unmatched": unmatched }));
|
||||
}
|
||||
|
||||
let result = s.edit("Import baked maps", |s| {
|
||||
let mut assigned = Vec::new();
|
||||
let mut remaining_bytes = max_bytes;
|
||||
for ((ts, map), tiles) in &slots {
|
||||
let (width, height) = image_map_size(s, CMD, *ts)?;
|
||||
let map_bytes = u64::from(width) * u64::from(height) * map.components() as u64 * size_of::<f32>() as u64;
|
||||
reserve_bytes(&mut remaining_bytes, map_bytes)?;
|
||||
|
||||
let mut images = BTreeMap::new();
|
||||
for (tile, path) in tiles {
|
||||
let bytes = read_image_file(CMD, path, remaining_bytes)?;
|
||||
reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?;
|
||||
|
||||
let bytes_per_texel = size_of::<[f32; 4]>() as u64;
|
||||
let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?;
|
||||
let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?;
|
||||
reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?;
|
||||
images.insert(*tile, image.clone());
|
||||
assigned.push(json!({"path": path, "ts": ts, "map": map.id()}));
|
||||
}
|
||||
use_images(s, CMD, *ts, *map, &images)?;
|
||||
}
|
||||
Ok(assigned)
|
||||
});
|
||||
// A failed edit leaves the document as it was; forget the images it decoded
|
||||
if result.is_err() {
|
||||
s.sync_images();
|
||||
}
|
||||
|
||||
Ok(json!({ "assigned": result?, "unmatched": unmatched }))
|
||||
}
|
||||
|
||||
fn reserve_bytes(remaining_bytes: &mut u64, bytes: u64) -> Result<()> {
|
||||
*remaining_bytes = remaining_bytes.checked_sub(bytes).ok_or_else(|| bad(CMD, "the files, decoded images and mesh maps exceed the import memory budget"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles)
|
||||
fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option<BakedMap>) -> Option<((usize, BakedMap), u32)> {
|
||||
let ts = texture_set_from_file_name(path, set_names)?;
|
||||
let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?;
|
||||
let texture_set = s.doc.project.texture_sets.get(ts)?;
|
||||
let tile = match texture_set.tile_grid() {
|
||||
Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?,
|
||||
None => FIRST_TILE,
|
||||
};
|
||||
Some(((ts, map), tile))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::BakeResolution;
|
||||
|
||||
#[test]
|
||||
fn import_budget_counts_decoded_images_and_resampled_maps() {
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-import-budget-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let paths = [dir.join("ao.png"), dir.join("height.png")];
|
||||
for path in &paths {
|
||||
image::RgbaImage::from_pixel(16, 16, image::Rgba([128, 128, 128, 255])).save(path).unwrap();
|
||||
}
|
||||
let file_bytes: u64 = paths.iter().map(|path| std::fs::metadata(path).unwrap().len()).sum();
|
||||
let decoded_bytes = 2 * 16 * 16 * 16;
|
||||
let map_bytes = 2 * 16 * 16 * 4;
|
||||
let required_bytes = file_bytes + decoded_bytes + map_bytes;
|
||||
let params = json!({"files": paths.map(|path| json!({"path": path}))});
|
||||
let mut session = Session::new_project("budget", texturecraft_geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R16;
|
||||
let revision = session.revision;
|
||||
|
||||
for budget in [file_bytes, file_bytes + decoded_bytes, required_bytes - 1] {
|
||||
let result = import_with_budget(&mut session, ¶ms, budget);
|
||||
assert!(result.is_err(), "budget {budget} must cover decoded pixels and mesh maps: {result:?}");
|
||||
assert!(session.doc.resources.is_empty() && session.images.is_empty());
|
||||
assert!(session.doc.baked.values().all(|baked| baked.maps.is_empty()));
|
||||
assert_eq!(session.revision, revision);
|
||||
assert!(!session.modified);
|
||||
assert!(session.undo_label().is_none());
|
||||
}
|
||||
|
||||
let result = import_with_budget(&mut session, ¶ms, required_bytes).unwrap();
|
||||
assert_eq!(result["assigned"].as_array().unwrap().len(), 2);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -155,6 +155,7 @@ impl Session {
|
||||
/// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh
|
||||
/// (the Clone tool's destination anchor).
|
||||
fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option<Vec2>) -> Result<()> {
|
||||
self.refuse_while_baking()?;
|
||||
let tool = self.tool.tool;
|
||||
let erase = tool == Tool::Eraser;
|
||||
let quick_mask = self.quick_mask.editing;
|
||||
@@ -296,9 +297,18 @@ impl Session {
|
||||
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile })
|
||||
}
|
||||
|
||||
/// Painting is paused while a bake preview shows the baked maps instead of the material.
|
||||
pub(crate) fn refuse_while_baking(&self) -> Result<()> {
|
||||
match self.painting_blocked() {
|
||||
Some(why) => Err(EngineError::Other(why.into())),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a stroke at `screen` (viewport pixels). Returns false when the cursor misses the
|
||||
/// mesh (the stroke starts anyway and resumes when the cursor enters the mesh).
|
||||
pub fn begin_stroke(&mut self, screen: Vec2, viewport: Vec2, pressure: f32) -> Result<bool> {
|
||||
self.refuse_while_baking()?;
|
||||
self.cancel_stroke();
|
||||
match self.tool.tool {
|
||||
Tool::PolygonFill => return self.polygon_fill(screen, viewport).map(|_| true),
|
||||
@@ -313,6 +323,7 @@ impl Session {
|
||||
|
||||
/// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there).
|
||||
pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> {
|
||||
self.refuse_while_baking()?;
|
||||
self.cancel_stroke();
|
||||
match self.tool.tool {
|
||||
Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()),
|
||||
|
||||
@@ -19,6 +19,7 @@ const CORNER_GRID_STEPS: f32 = 1e5;
|
||||
impl Session {
|
||||
/// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen`
|
||||
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
self.refuse_while_baking()?;
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
if hit.material != self.fill_material()? {
|
||||
return Err(EngineError::Other("that surface belongs to another texture set".into()));
|
||||
@@ -29,6 +30,7 @@ impl Session {
|
||||
|
||||
/// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked
|
||||
pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result<usize> {
|
||||
self.refuse_while_baking()?;
|
||||
let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let size = Vec2::new(gbuf.width as f32, gbuf.height as f32);
|
||||
let texel = (uv * size).floor();
|
||||
@@ -43,6 +45,8 @@ impl Session {
|
||||
|
||||
/// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step)
|
||||
pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
self.refuse_while_baking()?;
|
||||
|
||||
// A scripted box stands alone: it finishes any drag under way, and ends even when it fails
|
||||
self.end_polygon_fill_box();
|
||||
let shown = self.drag_polygon_fill_box(corner, opposite, viewport);
|
||||
@@ -52,6 +56,8 @@ impl Session {
|
||||
|
||||
/// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step)
|
||||
pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
|
||||
self.refuse_while_baking()?;
|
||||
|
||||
self.end_polygon_fill_box();
|
||||
let shown = self.drag_polygon_fill_box_uv(corner, opposite);
|
||||
let filled = self.end_polygon_fill_box();
|
||||
@@ -83,6 +89,7 @@ impl Session {
|
||||
|
||||
/// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None
|
||||
fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option<Vec2>) -> Result<usize> {
|
||||
self.refuse_while_baking()?;
|
||||
if !corner.is_finite() || !opposite.is_finite() {
|
||||
return Err(EngineError::Other("the box corners must be finite".into()));
|
||||
}
|
||||
|
||||
@@ -36,12 +36,18 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name.
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
|
||||
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX))
|
||||
}
|
||||
|
||||
/// Add an image within a decoded texel budget, inside the caller's edit
|
||||
pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec<u8>, max_texels: u64) -> Result<String> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
|
||||
}
|
||||
let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
|
||||
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image");
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let mut name = base.clone();
|
||||
@@ -50,11 +56,8 @@ impl Session {
|
||||
name = format!("{n}_{base}");
|
||||
n += 1;
|
||||
}
|
||||
let key = name.clone();
|
||||
self.edit("Import resource", |s| {
|
||||
s.doc.resources.insert(key, Arc::new(bytes));
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
self.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
Ok(name)
|
||||
}
|
||||
@@ -98,15 +101,44 @@ fn list(s: &Session) -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
|
||||
let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
|
||||
if meta.len() > MAX_BYTES as u64 {
|
||||
return Err(bad("resource.import", format!("{path} is too large")));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
|
||||
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
|
||||
let name = s.import_resource_bytes(path, bytes)?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Read a regular image file within both the per-file cap and the caller's remaining byte budget
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
|
||||
let max_bytes = max_bytes.min(MAX_BYTES as u64);
|
||||
let read_error = |error| bad(cmd, format!("cannot read {path}: {error}"));
|
||||
let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)"));
|
||||
let metadata = std::fs::metadata(path).map_err(read_error)?;
|
||||
// Pipes can block on open, and devices may never reach EOF
|
||||
if !metadata.is_file() {
|
||||
return Err(bad(cmd, format!("{path} is not a regular file")));
|
||||
}
|
||||
if metadata.len() > max_bytes {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
// Bound the read even if the file grows after the metadata check
|
||||
let file = std::fs::File::open(path).map_err(read_error)?;
|
||||
let mut bytes = Vec::with_capacity(metadata.len() as usize);
|
||||
file.take(max_bytes + 1).read_to_end(&mut bytes).map_err(read_error)?;
|
||||
if bytes.len() as u64 > max_bytes {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn read_image_file(cmd: &str, _: &str, _: u64) -> Result<Vec<u8>> {
|
||||
Err(bad(cmd, "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn import(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into()))
|
||||
@@ -165,3 +197,24 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn file_reads_obey_the_remaining_byte_budget() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
|
||||
std::fs::write(&path, b"1234").unwrap();
|
||||
let name = path.to_str().unwrap();
|
||||
assert!(read_image_file("test", name, 3).unwrap_err().to_string().contains("too large"));
|
||||
assert_eq!(read_image_file("test", name, 4).unwrap(), b"1234");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn devices_are_rejected_before_reading() {
|
||||
assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file"));
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,9 @@ pub struct Session {
|
||||
pub mesh: Arc<Mesh>,
|
||||
/// Unique per loaded mesh and UV layout (GPU caches compare it).
|
||||
pub mesh_id: u64,
|
||||
/// Unique per open project: a mesh reimport or UV layout change keeps it, and opening, closing
|
||||
/// or creating a project replaces it.
|
||||
pub project_id: u64,
|
||||
/// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas).
|
||||
pub(crate) source: Arc<Mesh>,
|
||||
pub bvh: Arc<Bvh>,
|
||||
@@ -338,6 +341,8 @@ pub struct Session {
|
||||
pub target: StackTarget,
|
||||
pub camera: OrbitCamera,
|
||||
pub view: ViewMode,
|
||||
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
|
||||
pub bake_preview: Option<crate::bake_preview::BakePreview>,
|
||||
/// Viewport size (pixels) used by scripted strokes.
|
||||
pub viewport: Vec2,
|
||||
pub(crate) stroke: Option<ActiveStroke>,
|
||||
@@ -384,6 +389,7 @@ impl Session {
|
||||
Ok(Session {
|
||||
doc,
|
||||
mesh_id: next_mesh_id(),
|
||||
project_id: next_mesh_id(),
|
||||
source,
|
||||
mesh,
|
||||
bvh: Arc::new(bvh),
|
||||
@@ -399,6 +405,7 @@ impl Session {
|
||||
target: StackTarget::Content,
|
||||
camera,
|
||||
view: ViewMode::Material,
|
||||
bake_preview: None,
|
||||
viewport: Vec2::new(1280.0, 800.0),
|
||||
stroke: None,
|
||||
clipboard: None,
|
||||
|
||||
@@ -88,7 +88,13 @@ fn frame(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn set_view(s: &mut Session, v: ViewMode) -> Result<Value> {
|
||||
s.view = v;
|
||||
if s.bake_preview.is_some() {
|
||||
// During a bake the view follows the preview: a mesh map pins it, another mode comes back afterwards
|
||||
s.bake_preview_user_view(v);
|
||||
} else {
|
||||
s.view = v;
|
||||
}
|
||||
let v = s.view;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "view": v.label() }))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back,
|
||||
//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it
|
||||
//! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the
|
||||
//! document share each map's buffer instead of holding two copies.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::bake::Progress;
|
||||
use texturecraft_engine::core::{BakeResolution, BakedMap, Channel};
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::{BakeTask, PreviewShow, Session, ViewMode, execute};
|
||||
|
||||
const MAPS: [BakedMap; 4] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Height];
|
||||
|
||||
fn session() -> Session {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
for texture_set in &mut session.doc.project.texture_sets {
|
||||
texture_set.bake = Default::default();
|
||||
texture_set.bake.common.resolution = BakeResolution::R64;
|
||||
texture_set.bake.maps.ao.parameters.rays.rays = 8;
|
||||
texture_set.bake.maps.select(MAPS);
|
||||
}
|
||||
|
||||
session
|
||||
}
|
||||
|
||||
fn task(session: &Session) -> BakeTask {
|
||||
let mut task = session.bake_task(0).unwrap();
|
||||
task.tracer = None;
|
||||
task
|
||||
}
|
||||
|
||||
fn order(session: &Session) -> Vec<BakedMap> {
|
||||
task(session).maps()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_maps_are_the_pixels_of_one_bake() {
|
||||
let session = session();
|
||||
let task = task(&session);
|
||||
let whole = task.run(&Progress::new()).unwrap();
|
||||
let mut streamed = Vec::new();
|
||||
|
||||
let combined = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap();
|
||||
|
||||
assert_eq!(streamed.iter().map(|map| map.map).collect::<Vec<_>>(), order(&session));
|
||||
assert_eq!(streamed.iter().map(|map| (map.index, map.total)).collect::<Vec<_>>(), (0..MAPS.len()).map(|index| (index, MAPS.len())).collect::<Vec<_>>());
|
||||
assert_eq!((combined.resolution, combined.height), (whole.resolution, whole.height));
|
||||
assert_eq!(combined.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
|
||||
for (map, pixels) in &whole.maps {
|
||||
assert!(*combined.maps[map] == *pixels, "{map:?} differs between a streamed and a single bake");
|
||||
}
|
||||
for map in &streamed {
|
||||
assert!(*map.data == whole.maps[&map.map], "{:?} handed over differs from the bake", map.map);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_view_follows_each_map_and_the_previous_mode_comes_back() {
|
||||
let mut session = session();
|
||||
session.view = ViewMode::Channel(Channel::Roughness);
|
||||
let before = session.view;
|
||||
let baked_before = session.doc.baked.get(&0).cloned();
|
||||
let maps = order(&session);
|
||||
|
||||
session.bake_preview_begin(vec![(0, maps.clone())]);
|
||||
session.bake_preview_set_current(0);
|
||||
|
||||
// Nothing is baked yet: the first map shows, neutral
|
||||
assert_eq!(session.view, ViewMode::MeshMap(maps[0]));
|
||||
assert!(session.bake_preview_baked(0).is_some_and(|baked| baked.maps.is_empty()));
|
||||
|
||||
let task = task(&session);
|
||||
let mut shown = Vec::new();
|
||||
let mut stages = Vec::new();
|
||||
let output = task
|
||||
.run_streaming(&Progress::new(), &mut |map| {
|
||||
session.bake_preview_map(0, map);
|
||||
shown.push(session.view);
|
||||
stages.push(session.bake_preview.as_ref().and_then(|preview| preview.stage()).map(|stage| (stage.position, stage.total)));
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(shown, maps.iter().map(|map| ViewMode::MeshMap(*map)).collect::<Vec<_>>(), "the view follows the newest map");
|
||||
assert_eq!(stages, [Some((2, 4)), Some((3, 4)), Some((4, 4)), None], "the stage names the next map");
|
||||
assert_eq!(session.doc.baked.get(&0).cloned(), baked_before, "the document is untouched until the bake is applied");
|
||||
let undo_before = session.undo_label().map(str::to_owned);
|
||||
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
assert_ne!(session.undo_label().map(str::to_owned), undo_before, "applying the bake is one undo step");
|
||||
session.bake_preview_end();
|
||||
|
||||
assert_eq!(session.view, before, "the previous view mode is restored");
|
||||
assert!(!session.bake_preview_active());
|
||||
assert!(maps.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinning_material_and_follow() {
|
||||
let mut session = session();
|
||||
let maps = order(&session);
|
||||
|
||||
session.bake_preview_begin(vec![(0, maps.clone())]);
|
||||
session.bake_preview_set_current(0);
|
||||
let task = task(&session);
|
||||
let mut count = 0;
|
||||
|
||||
task.run_streaming(&Progress::new(), &mut |map| {
|
||||
session.bake_preview_map(0, map);
|
||||
count += 1;
|
||||
match count {
|
||||
// Pin the finished map: later maps do not take the view
|
||||
1 => session.bake_preview_show(PreviewShow::Pin(maps[0])).unwrap(),
|
||||
2 => {
|
||||
assert_eq!(session.view, ViewMode::MeshMap(maps[0]));
|
||||
session.bake_preview_show(PreviewShow::Material).unwrap();
|
||||
}
|
||||
3 => {
|
||||
assert_eq!(session.view, ViewMode::Material);
|
||||
session.bake_preview_show(PreviewShow::Follow).unwrap();
|
||||
assert_eq!(session.view, ViewMode::MeshMap(maps[2]));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// A mesh map picked in the viewport pins it; another mode is what comes back at the end
|
||||
execute(&mut session, "viewport.view", &json!({ "mode": "map:height" })).unwrap();
|
||||
assert_eq!(session.bake_preview.as_ref().map(|preview| preview.show), Some(PreviewShow::Pin(BakedMap::Height)));
|
||||
execute(&mut session, "viewport.view", &json!({ "mode": "uvChecker" })).unwrap();
|
||||
assert_eq!(session.view, ViewMode::UvChecker);
|
||||
session.bake_preview_end();
|
||||
|
||||
assert_eq!(session.view, ViewMode::UvChecker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbaked_sets_show_neutral_and_the_control_command_reports() {
|
||||
let mut session = session();
|
||||
assert_eq!(execute(&mut session, "bake.preview", &Value::Null).unwrap()["active"], false);
|
||||
assert!(execute(&mut session, "bake.preview", &json!({ "show": "material" })).is_err(), "nothing to show when no bake runs");
|
||||
|
||||
session.bake_preview_begin(vec![(0, order(&session)), (1, order(&session))]);
|
||||
session.bake_preview_set_current(0);
|
||||
|
||||
assert!(session.bake_preview_baked(1).is_some_and(|baked| baked.maps.is_empty()), "a queued set has nothing yet");
|
||||
assert!(session.bake_preview_baked(7).is_none(), "a set outside the bake shows its document maps");
|
||||
let reply = execute(&mut session, "bake.preview", &json!({ "show": "map:ambientOcclusion" })).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
(reply["active"].clone(), reply["show"].clone(), reply["shown"].clone()),
|
||||
(json!(true), json!("map:ambientOcclusion"), json!("ambientOcclusion"))
|
||||
);
|
||||
assert!(execute(&mut session, "bake.preview", &json!({ "show": "nonsense" })).is_err());
|
||||
assert_eq!(texturecraft_engine::inspect::session(&session)["bakePreview"]["active"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painting_is_refused_while_a_bake_shows() {
|
||||
let mut session = session();
|
||||
session.bake_preview_begin(vec![(0, order(&session))]);
|
||||
|
||||
let error = session.begin_stroke(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0), 1.0).unwrap_err().to_string();
|
||||
|
||||
assert_eq!(error, texturecraft_engine::bake_preview::PAINTING_PAUSED);
|
||||
assert!(session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).is_err());
|
||||
assert!(session.polygon_fill(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0)).is_err());
|
||||
assert!(!session.stroke_active());
|
||||
session.bake_preview_end();
|
||||
assert!(session.painting_blocked().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() {
|
||||
let mut session = session();
|
||||
let before = session.doc.baked.get(&0).cloned();
|
||||
let maps = order(&session);
|
||||
let full = task(&session).run(&Progress::new()).unwrap();
|
||||
session.bake_preview_begin(vec![(0, maps.clone())]);
|
||||
session.bake_preview_set_current(0);
|
||||
let progress = Progress::new();
|
||||
let task = task(&session);
|
||||
|
||||
let result = task.run_streaming(&progress, &mut |map| {
|
||||
if map.index == 1 {
|
||||
progress.cancel();
|
||||
}
|
||||
session.bake_preview_map(0, map);
|
||||
});
|
||||
|
||||
assert!(result.is_err(), "a cancelled bake fails");
|
||||
|
||||
// The two maps that landed are whole and equal to a full bake's; the others are still neutral
|
||||
let shown = session.bake_preview_baked(0).unwrap();
|
||||
assert_eq!(shown.maps.len(), 2);
|
||||
for (map, data) in &shown.maps {
|
||||
assert!(**data == full.maps[map], "{map:?}");
|
||||
}
|
||||
|
||||
// What the app does on cancel: end the preview; the document keeps what it had
|
||||
session.bake_preview_end();
|
||||
|
||||
assert_eq!(session.doc.baked.get(&0).cloned(), before);
|
||||
assert!(session.bake_preview_baked(0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_and_the_applied_document_share_each_map_buffer() {
|
||||
let mut session = session();
|
||||
let maps = order(&session);
|
||||
|
||||
session.bake_preview_begin(vec![(0, maps)]);
|
||||
session.bake_preview_set_current(0);
|
||||
let mut handed_over = Vec::new();
|
||||
|
||||
let output = task(&session)
|
||||
.run_streaming(&Progress::new(), &mut |map| {
|
||||
handed_over.push((map.map, map.data.clone()));
|
||||
session.bake_preview_map(0, map);
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Sharing the streamed buffers keeps preview memory independent of document ownership
|
||||
for (map, data) in &handed_over {
|
||||
assert!(std::sync::Arc::ptr_eq(data, &output.maps[map]), "{map:?} was copied on the way out of the bake");
|
||||
let shown = &session.bake_preview_baked(0).unwrap().maps[map];
|
||||
assert!(std::sync::Arc::ptr_eq(data, shown), "{map:?} is held twice by the preview");
|
||||
}
|
||||
|
||||
// Applying the result must preserve sharing with the preview
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
for (map, data) in &handed_over {
|
||||
assert!(std::sync::Arc::ptr_eq(data, &session.doc.baked[&0].maps[map]), "{map:?} was copied into the document");
|
||||
}
|
||||
session.bake_preview_end();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_keeps_a_set_that_was_already_applied_as_one_undo_step() {
|
||||
let mut session = session();
|
||||
let before = session.doc.baked.get(&0).cloned();
|
||||
let maps = order(&session);
|
||||
|
||||
// A multi-set bake applies each set when it finishes; a later cancel does not undo it
|
||||
session.bake_preview_begin(vec![(0, maps)]);
|
||||
session.bake_preview_set_current(0);
|
||||
let output = task(&session)
|
||||
.run_streaming(&Progress::new(), &mut |map| {
|
||||
session.bake_preview_map(0, map);
|
||||
})
|
||||
.unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
session.bake_preview_end();
|
||||
|
||||
assert!(MAPS.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)), "the finished set stays baked after the cancel");
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.baked.get(&0).cloned(), before, "applying the set was one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resized_partial_streamed_bake_keeps_unchecked_maps() {
|
||||
use std::sync::Arc;
|
||||
use texturecraft_engine::compose::BakedMaps;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
|
||||
let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
session.doc.baked.insert(
|
||||
0,
|
||||
BakedMaps {
|
||||
resolution: 64,
|
||||
maps: [
|
||||
(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])),
|
||||
(BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3])),
|
||||
(BakedMap::Height, Arc::new(vec![0.75; 64 * 32])),
|
||||
]
|
||||
.into(),
|
||||
},
|
||||
);
|
||||
execute(&mut session, "bake.settings", &json!({"resolution": 64, "maps": ["ambientOcclusion", "height"], "rays": 2})).unwrap();
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
let before = session.doc.baked.clone();
|
||||
let task = task(&session);
|
||||
let whole = task.run(&Progress::new()).unwrap();
|
||||
let mut streamed = Vec::new();
|
||||
|
||||
let output = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap();
|
||||
|
||||
assert_eq!((output.resolution, output.height), (128, 64));
|
||||
assert_eq!(output.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
|
||||
for (map, pixels) in &whole.maps {
|
||||
assert_eq!(*output.maps[map], *pixels, "{map:?} must match a whole bake, including retained pixels");
|
||||
}
|
||||
assert_eq!(streamed.iter().map(|map| map.map).collect::<Vec<_>>(), [BakedMap::AmbientOcclusion, BakedMap::Height]);
|
||||
for map in &streamed {
|
||||
assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]));
|
||||
}
|
||||
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
for (map, pixels) in &whole.maps {
|
||||
assert_eq!(*session.doc.baked[&0].maps[map], *pixels);
|
||||
}
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.baked, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_fills_are_refused_while_a_bake_shows() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
|
||||
execute(&mut session, "tool.polygonFill", &Value::Null).unwrap();
|
||||
session.bake_preview_begin(vec![(0, order(&session))]);
|
||||
let before = texturecraft_engine::inspect::session(&session);
|
||||
let viewport = Vec2::new(100.0, 100.0);
|
||||
|
||||
for result in [
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE),
|
||||
session.drag_polygon_fill_box(Vec2::ZERO, viewport, viewport),
|
||||
session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE),
|
||||
session.polygon_fill_box(Vec2::ZERO, viewport, viewport),
|
||||
execute(&mut session, "tool.click", &json!({"uv0": [0, 0], "uv1": [1, 1]})).map(|_| 0),
|
||||
execute(&mut session, "tool.click", &json!({"x0": 0, "y0": 0, "x1": 100, "y1": 100})).map(|_| 0),
|
||||
] {
|
||||
assert_eq!(result.unwrap_err().to_string(), texturecraft_engine::bake_preview::PAINTING_PAUSED);
|
||||
}
|
||||
|
||||
assert_eq!(session.end_polygon_fill_box(), 0);
|
||||
assert_eq!(texturecraft_engine::inspect::session(&session), before);
|
||||
session.bake_preview_end();
|
||||
assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_order_matches_each_sets_bake_task() {
|
||||
let mut session = session();
|
||||
session.doc.project.texture_sets[1].bake.maps.select([BakedMap::WorldNormal, BakedMap::Height]);
|
||||
let expected: Vec<_> = [0, 1].into_iter().map(|texture_set| session.bake_task(texture_set).unwrap().maps()).collect();
|
||||
|
||||
session.bake_preview_begin_for(&[0, 1]).unwrap();
|
||||
|
||||
let preview = session.bake_preview.as_ref().unwrap();
|
||||
for (texture_set, maps) in expected.iter().enumerate() {
|
||||
assert_eq!(&preview.sets[&texture_set].order, maps);
|
||||
assert!(preview.sets[&texture_set].baked.maps.is_empty());
|
||||
}
|
||||
assert_eq!(session.view, ViewMode::MeshMap(expected[0][0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_preview_sets_preserve_the_existing_preview_and_view() {
|
||||
let mut session = session();
|
||||
session.bake_preview_begin_for(&[0]).unwrap();
|
||||
session.bake_preview_set_current(0);
|
||||
session.bake_preview_show(PreviewShow::Material).unwrap();
|
||||
let before = texturecraft_engine::bake_preview::preview_json(&session);
|
||||
let view = session.view;
|
||||
let revision = session.revision;
|
||||
let invalid_set = session.set_count();
|
||||
let expected_error = session.doc.project.texture_set(invalid_set).unwrap_err().to_string();
|
||||
|
||||
let error = session.bake_preview_begin_for(&[1, invalid_set]).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains(&expected_error));
|
||||
assert_eq!(texturecraft_engine::bake_preview::preview_json(&session), before);
|
||||
assert_eq!(session.view, view);
|
||||
assert_eq!(session.revision, revision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_a_bake_preview_discards_an_active_stroke() {
|
||||
for (from_settings, paint_mask) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let mut session = session();
|
||||
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
|
||||
if paint_mask {
|
||||
session.target = texturecraft_engine::StackTarget::Mask;
|
||||
}
|
||||
|
||||
let before = session.doc.clone();
|
||||
let history = session.history_labels();
|
||||
let view = session.view;
|
||||
session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
|
||||
assert!(session.stroke_tiles() > 0, "the stroke must contain paint before the preview starts");
|
||||
|
||||
if from_settings {
|
||||
session.bake_preview_begin_for(&[0]).unwrap();
|
||||
} else {
|
||||
session.bake_preview_begin(vec![(0, order(&session))]);
|
||||
}
|
||||
let stroke_survived = session.stroke_active();
|
||||
session.continue_stroke_uv(Vec2::splat(0.6), 1.0);
|
||||
session.end_stroke().unwrap();
|
||||
|
||||
assert_eq!(session.history_labels(), history, "releasing the pointer during a preview must not commit paint");
|
||||
assert!(!stroke_survived, "activation must cancel the stroke immediately");
|
||||
assert_eq!(session.doc.project, before.project);
|
||||
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
|
||||
assert_eq!(session.doc.pixels.masks, before.pixels.masks);
|
||||
assert!(session.bake_preview_active());
|
||||
session.bake_preview_end();
|
||||
|
||||
assert_eq!(session.view, view);
|
||||
session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
|
||||
session.end_stroke().unwrap();
|
||||
assert_eq!(session.history_labels().len(), history.len() + 1, "painting resumes after the preview ends");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_bake_preview_preserves_the_active_stroke() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
|
||||
let history_steps = session.history_labels().len();
|
||||
let view = session.view;
|
||||
session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
|
||||
let painted_tiles = session.stroke_tiles();
|
||||
assert!(painted_tiles > 0);
|
||||
|
||||
let result = session.bake_preview_begin_for(&[0, session.set_count()]);
|
||||
|
||||
assert!(result.is_err());
|
||||
assert!(!session.bake_preview_active());
|
||||
assert!(session.stroke_active());
|
||||
assert_eq!(session.stroke_tiles(), painted_tiles);
|
||||
assert_eq!(session.view, view);
|
||||
session.end_stroke().unwrap();
|
||||
|
||||
assert_eq!(session.history_labels().len(), history_steps + 1, "a rejected preview must not discard painting");
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Color selection effects: editing their ID colors and picking them from the ID mesh map
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{EffectKind, LayerId};
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
const TOP_LEFT_ID: [u8; 3] = [200, 30, 10];
|
||||
const TOP_RIGHT_ID: [u8; 3] = [10, 200, 30];
|
||||
const BOTTOM_ID: [u8; 3] = [30, 10, 200];
|
||||
const NO_PART: [f32; 3] = [0.0, 0.0, 0.0];
|
||||
|
||||
fn session() -> Session {
|
||||
let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
|
||||
session.viewport = Vec2::new(400.0, 400.0);
|
||||
session.camera.yaw = 0.0;
|
||||
session.camera.pitch = 0.0;
|
||||
session.update();
|
||||
session
|
||||
}
|
||||
|
||||
/// An 8×8 ID map: two parts on the top half, one on the bottom half
|
||||
fn id_map_png() -> Vec<u8> {
|
||||
let image = image::RgbaImage::from_fn(8, 8, |x, y| {
|
||||
let [red, green, blue] = match (x < 4, y < 4) {
|
||||
(true, true) => TOP_LEFT_ID,
|
||||
(false, true) => TOP_RIGHT_ID,
|
||||
_ => BOTTOM_ID,
|
||||
};
|
||||
image::Rgba([red, green, blue, 255])
|
||||
});
|
||||
let mut bytes = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
bytes
|
||||
}
|
||||
|
||||
fn stored(id: [u8; 3]) -> [f32; 3] {
|
||||
id.map(|channel| channel as f32 / 255.0)
|
||||
}
|
||||
|
||||
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
|
||||
assert!(actual.iter().zip(expected).all(|(channel, wanted)| (channel - wanted).abs() < 1e-3), "{actual:?} vs {expected:?}");
|
||||
}
|
||||
|
||||
/// A fill layer masked by a color selection that selects no part yet: (layer, effect)
|
||||
fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) {
|
||||
if with_id_map {
|
||||
let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
|
||||
execute(session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
|
||||
}
|
||||
|
||||
let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap());
|
||||
execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap();
|
||||
let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id;
|
||||
(layer, effect)
|
||||
}
|
||||
|
||||
fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> {
|
||||
match &session.doc.project.effect(effect).unwrap().1.kind {
|
||||
EffectKind::ColorSelection { colors, .. } => colors.clone(),
|
||||
other => panic!("not a color selection: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_picked_on_the_mesh_is_selected_where_it_was_picked() {
|
||||
let mut session = session();
|
||||
let (layer, effect) = masked_layer(&mut session, true);
|
||||
let center = Vec2::new(200.0, 200.0);
|
||||
let hit = session.pick(center, session.viewport).unwrap();
|
||||
let (width, height) = session.caches[0].size;
|
||||
let texel = ((hit.uv.x * width as f32) as u32, (hit.uv.y * height as f32) as u32);
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0], "nothing selected before the pick");
|
||||
|
||||
let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": center.x, "y": center.y})).unwrap();
|
||||
|
||||
assert_eq!(picked["index"], json!(1));
|
||||
assert_eq!(colors(&session, effect).len(), 2);
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART], "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uv_pick_adds_the_color_there_or_replaces_one() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
|
||||
assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID));
|
||||
|
||||
let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap();
|
||||
assert_eq!(replaced["index"], json!(0));
|
||||
let picked = colors(&session, effect);
|
||||
assert_eq!(picked.len(), 2);
|
||||
assert_close(picked[0], stored(BOTTOM_ID));
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_colors_param_replaces_the_list_in_one_undo_step() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, false);
|
||||
let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)];
|
||||
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap();
|
||||
assert_eq!(colors(&session, effect), edited.to_vec());
|
||||
let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") };
|
||||
assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2));
|
||||
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_colors_are_refused_and_change_nothing() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, false);
|
||||
let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")];
|
||||
|
||||
for colors_param in &refused {
|
||||
assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}");
|
||||
}
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap();
|
||||
assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_explains_what_is_missing() {
|
||||
let mut session = session();
|
||||
let (layer, effect) = masked_layer(&mut session, false);
|
||||
let pick = |session: &mut Session, params: Value| execute(session, "effect.colorSelection.pick", ¶ms).unwrap_err().to_string();
|
||||
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5]})).contains("no ID map"));
|
||||
let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
|
||||
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "x": 1, "y": 1})).contains("nothing under that point"));
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [1.5, 0.5]})).contains("outside"));
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5], "index": 7})).contains("no color 7"));
|
||||
assert!(pick(&mut session, json!({"effect": effect.0})).contains("`x` and `y`"));
|
||||
|
||||
let fill = execute(&mut session, "effect.add.fill", &json!({"layer": layer.0})).unwrap()["effect"].as_u64().unwrap();
|
||||
assert!(pick(&mut session, json!({"effect": fill, "uv": [0.5, 0.5]})).contains("not a color selection"));
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_params_never_crash_the_color_selection_commands() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let hostile = [
|
||||
json!({"effect": effect.0, "x": f32::MAX, "y": -1e30, "viewport": [0, 0]}),
|
||||
json!({"effect": effect.0, "uv": [f64::MAX, -1e300], "index": u64::MAX}),
|
||||
json!({"effect": effect.0, "uv": [0.5], "colors": [[f64::MAX, -f64::MAX, 0.0]]}),
|
||||
json!({"effect": effect.0, "uv": "x", "colors": {"r": 1}}),
|
||||
json!({"effect": u64::MAX, "uv": [0.5, 0.5]}),
|
||||
];
|
||||
|
||||
for params in &hostile {
|
||||
let _ = execute(&mut session, "effect.colorSelection.pick", params);
|
||||
let _ = execute(&mut session, "effect.set", params);
|
||||
session.update();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_texture_set_does_not_block_a_pick_behind_it() {
|
||||
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
|
||||
session.viewport = Vec2::new(400.0, 400.0);
|
||||
session.update();
|
||||
let set_named = |name: &str| session.doc.project.texture_sets.iter().position(|set| set.name == name).unwrap();
|
||||
let (base, ball) = (set_named("Base"), set_named("Ball"));
|
||||
execute(&mut session, "textureSet.select", &json!({"ts": base})).unwrap();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let pick_at = |session: &mut Session, y: f32| execute(session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": 200, "y": y}));
|
||||
let ball_in_front = |session: &Session, y: f32| {
|
||||
session.pick(Vec2::new(200.0, y), session.viewport).is_some_and(|hit| session.texture_set_of_material(hit.material) == Some(ball))
|
||||
};
|
||||
|
||||
// Down the middle until a pixel where the hidden ball covers the base: the pick reads the base
|
||||
execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": false})).unwrap();
|
||||
let mut covered = None;
|
||||
for y in (200..400).map(|y| y as f32) {
|
||||
if ball_in_front(&session, y) && pick_at(&mut session, y).is_ok() {
|
||||
covered = Some(y);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let y = covered.expect("a pixel where the ball covers the base");
|
||||
assert_eq!(colors(&session, effect).len(), 2);
|
||||
|
||||
execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap();
|
||||
assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_replacement_indices_are_rejected_without_editing() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let history = session.history_labels();
|
||||
|
||||
for index in [json!(-1), json!(0.4), json!("0"), json!(true), json!([])] {
|
||||
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": index}));
|
||||
assert!(result.is_err(), "invalid index {index} was accepted: {result:?}");
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_limit_rejects_additions_but_allows_replacement() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let full = vec![NO_PART; 256];
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": full})).unwrap();
|
||||
let history = session.history_labels();
|
||||
let project = session.doc.project.clone();
|
||||
|
||||
for params in [json!({"effect": effect.0, "uv": [0.25, 0.25]}), json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 256})] {
|
||||
assert!(execute(&mut session, "effect.colorSelection.pick", ¶ms).is_err());
|
||||
assert_eq!(colors(&session, effect), full);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; 257], "name": "Invalid edit"})).is_err());
|
||||
assert_eq!(session.history_labels(), history);
|
||||
assert_eq!(session.doc.project, project, "invalid colors also roll back edits to other fields");
|
||||
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 255})).unwrap();
|
||||
assert_eq!(colors(&session, effect).len(), 256);
|
||||
assert_close(colors(&session, effect)[255], stored(TOP_LEFT_ID));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_exposes_the_selected_colors_and_tolerance() {
|
||||
let mut session = session();
|
||||
let (layer, effect) = masked_layer(&mut session, true);
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.25})).unwrap();
|
||||
|
||||
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
|
||||
let layer = inspected["layers"].as_array().unwrap().iter().find(|found| found["id"] == layer.0).unwrap();
|
||||
let found = &layer["mask"]["effects"][0];
|
||||
assert_eq!(found["colors"], json!(colors(&session, effect)));
|
||||
assert_eq!(found["tolerance"], json!(0.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_use_the_working_texel_on_a_smaller_uv_tile() {
|
||||
let mut session = Session::new_project("UV tiles", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
|
||||
for tile in [1001, 1002] {
|
||||
session.import_resource_bytes(&format!("id.{tile}.png"), id_map_png()).unwrap();
|
||||
}
|
||||
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": "id.1001.png"})).unwrap();
|
||||
let (layer, effect) = masked_layer(&mut session, false);
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.0})).unwrap();
|
||||
let size = session.doc.project.texture_sets[0].size();
|
||||
let uv = [0.625, 0.25];
|
||||
let texel = ((uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32);
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0]);
|
||||
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": uv})).unwrap();
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
|
||||
let before = colors(&session, effect);
|
||||
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.9, 0.8]}));
|
||||
assert!(result.unwrap_err().to_string().contains("no ID color"), "unused tile space has no sample");
|
||||
assert_eq!(colors(&session, effect), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"]
|
||||
fn benchmark_color_selection_edits() {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const SAMPLES: u32 = 10;
|
||||
for resolution in [256, 1024] {
|
||||
let started = Instant::now();
|
||||
let mut session = Session::new_project("benchmark", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, resolution).unwrap();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
session.update();
|
||||
let construction = started.elapsed();
|
||||
|
||||
for count in [1, 256] {
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; count]})).unwrap();
|
||||
session.update();
|
||||
let params = json!({"effect": effect.0, "uv": [0.25, 0.25], "index": count - 1});
|
||||
let (mut command_time, mut composite_time) = (Duration::ZERO, Duration::ZERO);
|
||||
for _ in 0..SAMPLES {
|
||||
let started = Instant::now();
|
||||
execute(&mut session, "effect.colorSelection.pick", ¶ms).unwrap();
|
||||
command_time += started.elapsed();
|
||||
let started = Instant::now();
|
||||
session.update();
|
||||
composite_time += started.elapsed();
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
session.update();
|
||||
}
|
||||
println!(
|
||||
"{resolution}x{resolution}, {count} colors, {SAMPLES} samples: construction {construction:.3?}; pick {:.3?}; composite {:.3?}; session memory {} bytes",
|
||||
command_time / SAMPLES,
|
||||
composite_time / SAMPLES,
|
||||
session.memory().total()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
|
||||
fn vertex(height: f32) -> Option<VertexReach> {
|
||||
Some(VertexReach {
|
||||
low_position: Vec3::ZERO,
|
||||
start: RayStart::Distance { up: Vec3::Y, scale: 1.0 },
|
||||
high_position: Vec3::new(0.0, height, 0.0),
|
||||
high_facing: Vec3::Y,
|
||||
name_matches: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn reach(vertices: Vec<Option<VertexReach>>) -> Option<HighPolyReach> {
|
||||
Some(HighPolyReach { vertices, cage_units: 1.0, ignore_backface: false })
|
||||
}
|
||||
|
||||
fn sets() -> Vec<Option<HighPolyReach>> {
|
||||
vec![None, reach(vec![vertex(0.5), vertex(-0.25), None, None, None]), reach(vec![None, None, vertex(0.5), vertex(-0.25), None])]
|
||||
}
|
||||
|
||||
const DISTANCES: [(f32, f32); 3] = [(9.0, 9.0), (0.25, 0.25), (0.5, 0.125)];
|
||||
|
||||
#[test]
|
||||
fn each_owning_set_uses_its_own_frontal_and_rear_distances() {
|
||||
let reaches = sets();
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, None, 6), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
let expanded = [(9.0, 9.0), (0.5, 0.25), (0.5, 0.25)];
|
||||
assert_eq!(high_poly_missed(&reaches, &expanded, None, 6), vec![0.0; 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_set_filter_leaves_other_sets_unmarked() {
|
||||
let reaches = sets();
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
for only_set in [0, reaches.len(), usize::MAX] {
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_reach_or_distances_leave_vertices_unmarked() {
|
||||
assert_eq!(high_poly_missed(&[], &DISTANCES, None, 6), vec![0.0; 6]);
|
||||
assert_eq!(high_poly_missed(&sets(), &[], None, 6), vec![0.0; 6]);
|
||||
assert_eq!(high_poly_missed(&sets(), &DISTANCES[..2], None, 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&sets(), &DISTANCES, None, 1), vec![1.0]);
|
||||
assert!(high_poly_missed(&sets(), &DISTANCES, None, 0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reached_vertex_is_not_overridden_by_a_later_set() {
|
||||
let reaches = [reach(vec![vertex(0.5)]), reach(vec![vertex(0.5)])];
|
||||
let distances = [(0.5, 0.0), (0.25, 0.0)];
|
||||
assert_eq!(high_poly_missed(&reaches, &distances, None, 1), vec![0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &distances, Some(1), 1), vec![1.0]);
|
||||
}
|
||||
@@ -5,14 +5,17 @@ mod bake;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_tiles;
|
||||
mod color_selection;
|
||||
mod content_effects;
|
||||
mod export_colour_space;
|
||||
mod filter_swap;
|
||||
mod filters;
|
||||
mod high_poly_missed;
|
||||
mod instances;
|
||||
mod materialcraft_link;
|
||||
mod materialx;
|
||||
mod materialx_import;
|
||||
mod meshmap_import;
|
||||
mod painter_gaps;
|
||||
mod path_tool;
|
||||
mod perf;
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Importing baked map files at once: each lands in the texture set and mesh map its name names
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
/// The material ball: texture sets "Ball" and "Base"
|
||||
fn session() -> Session {
|
||||
Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap()
|
||||
}
|
||||
|
||||
/// A folder of 4×4 gray PNGs named `files`, each with its own gray level
|
||||
fn bake_folder(test: &str, files: &[&str]) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (index, file) in files.iter().enumerate() {
|
||||
let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX);
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, dir: &Path, files: &[(&str, Option<&str>)]) -> Value {
|
||||
let files: Vec<Value> = files
|
||||
.iter()
|
||||
.map(|(file, map)| {
|
||||
let path = dir.join(file).display().to_string();
|
||||
match map {
|
||||
Some(map) => json!({"path": path, "map": map}),
|
||||
None => json!({"path": path}),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap()
|
||||
}
|
||||
|
||||
fn file_names(list: &Value) -> Vec<String> {
|
||||
list.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap()))
|
||||
.map(|path| path.rsplit(['/', '\\']).next().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool {
|
||||
s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_go_to_the_set_and_map_their_names_name() {
|
||||
let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"];
|
||||
let dir = bake_folder("sets", &files);
|
||||
let mut s = session();
|
||||
let label_before = s.undo_label().map(str::to_string);
|
||||
|
||||
let result = import(&mut s, &dir, &files.map(|file| (file, None)));
|
||||
|
||||
let assigned = &result["assigned"];
|
||||
assert_eq!(file_names(assigned).len(), 5, "{result}");
|
||||
for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] {
|
||||
assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id());
|
||||
assert!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["map"] == map.id()), "{result}");
|
||||
}
|
||||
assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]);
|
||||
assert_eq!(s.undo_label(), Some("Import baked maps"));
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step");
|
||||
assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map");
|
||||
assert!(s.doc.resources.is_empty(), "undo removes the imported image resources");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_map_overrides_the_name() {
|
||||
let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]);
|
||||
let mut s = session();
|
||||
|
||||
let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]);
|
||||
|
||||
assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}");
|
||||
assert!(has_map(&s, 0, BakedMap::Thickness));
|
||||
assert!(has_map(&s, 1, BakedMap::Height));
|
||||
assert!(!has_map(&s, 1, BakedMap::Normal));
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_file_for_one_slot_is_left_out() {
|
||||
let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]);
|
||||
let mut s = session();
|
||||
|
||||
let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]);
|
||||
|
||||
assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]);
|
||||
assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]);
|
||||
assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undecodable_file_imports_nothing() {
|
||||
let dir = bake_folder("undecodable", &["Ball_ao.png"]);
|
||||
std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap();
|
||||
let mut s = session();
|
||||
let label_before = s.undo_label().map(str::to_string);
|
||||
let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]});
|
||||
|
||||
let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string();
|
||||
|
||||
assert!(error.contains("Base_ao.png"), "{error}");
|
||||
assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()));
|
||||
assert!(s.doc.resources.is_empty() && s.images.is_empty());
|
||||
assert_eq!(s.undo_label().map(str::to_string), label_before);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002
|
||||
fn tiled_session() -> Session {
|
||||
Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() {
|
||||
let files = ["Plane_ao.1001.png", "plane-AO-1002.png"];
|
||||
let dir = bake_folder("tiles", &files);
|
||||
let mut s = tiled_session();
|
||||
|
||||
let result = import(&mut s, &dir, &files.map(|file| (file, None)));
|
||||
|
||||
assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}");
|
||||
let baked = &s.doc.baked[&0];
|
||||
let ao = &baked.maps[&BakedMap::AmbientOcclusion];
|
||||
let width = baked.resolution as usize;
|
||||
let middle_row = ao.len() / width / 2 * width;
|
||||
assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiled_files_without_their_tiles_are_left_out_alone() {
|
||||
let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"];
|
||||
let dir = bake_folder("partial-tiles", &files);
|
||||
let mut s = tiled_session();
|
||||
|
||||
let result = import(&mut s, &dir, &files.map(|file| (file, None)));
|
||||
|
||||
assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]);
|
||||
assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]);
|
||||
assert!(has_map(&s, 0, BakedMap::AmbientOcclusion));
|
||||
assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_matched_makes_no_undo_step() {
|
||||
let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]);
|
||||
let mut s = session();
|
||||
let label_before = s.undo_label().map(str::to_string);
|
||||
|
||||
let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]);
|
||||
|
||||
assert_eq!(file_names(&result["assigned"]), Vec::<String>::new());
|
||||
assert_eq!(file_names(&result["unmatched"]).len(), 2);
|
||||
assert_eq!(s.undo_label().map(str::to_string), label_before);
|
||||
assert!(!s.modified);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_map_override_does_not_fall_back_to_the_file_name() {
|
||||
let dir = bake_folder("invalid-map", &["Ball_ao.png"]);
|
||||
let mut session = session();
|
||||
for map in [json!(true), json!(42), json!([]), json!({}), json!("unknown")] {
|
||||
let params = json!({"files": [{"path": dir.join("Ball_ao.png"), "map": map}]});
|
||||
let result = execute(&mut session, "textureSet.meshMap.import", ¶ms);
|
||||
assert!(result.is_err(), "invalid map {map} must be rejected: {result:?}");
|
||||
assert!(session.doc.resources.is_empty());
|
||||
assert!(!session.modified);
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"]
|
||||
fn benchmark_baked_map_import() {
|
||||
use std::time::Instant;
|
||||
use texturecraft_engine::core::BakeResolution;
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-import-benchmark-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (size, tiled) in [(1024, false), (2048, false), (1024, true)] {
|
||||
let mut files = Vec::new();
|
||||
let mut encoded_bytes = 0;
|
||||
for map in ["normal", "ao", "curvature"] {
|
||||
for tile in 1001..=if tiled { 1002 } else { 1001 } {
|
||||
let path = dir.join(format!("mesh_{map}.{tile}.png"));
|
||||
image::RgbaImage::from_fn(size, size, |x, y| {
|
||||
let value = (x.wrapping_mul(73) ^ y.wrapping_mul(151) ^ tile) as u8;
|
||||
image::Rgba([value, value.wrapping_add(37), 255, 255])
|
||||
})
|
||||
.save(&path)
|
||||
.unwrap();
|
||||
encoded_bytes += std::fs::metadata(&path).unwrap().len();
|
||||
files.push(json!({"path": path}));
|
||||
}
|
||||
}
|
||||
let params = json!({"files": files});
|
||||
let mut milliseconds = Vec::new();
|
||||
for iteration in 0..6 {
|
||||
let mesh = if tiled { primitives::udim_plane() } else { primitives::cube(2.0) };
|
||||
let mut session = Session::new_project("benchmark", mesh, "builtin:cube", None, 128).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::from_pixels(size).unwrap();
|
||||
let started = Instant::now();
|
||||
let result = execute(&mut session, "textureSet.meshMap.import", ¶ms).unwrap();
|
||||
let elapsed = started.elapsed().as_secs_f64() * 1000.0;
|
||||
assert_eq!(result["assigned"].as_array().unwrap().len(), files.len());
|
||||
assert_eq!(session.doc.baked[&0].maps.len(), 3);
|
||||
if iteration > 0 {
|
||||
milliseconds.push(elapsed);
|
||||
}
|
||||
}
|
||||
milliseconds.sort_by(f64::total_cmp);
|
||||
eprintln!(
|
||||
"import size={size} tiles={} files={} encoded_bytes={encoded_bytes} median_ms={:.3} min_ms={:.3} max_ms={:.3}",
|
||||
if tiled { 2 } else { 1 },
|
||||
files.len(),
|
||||
milliseconds[2],
|
||||
milliseconds[0],
|
||||
milliseconds[4]
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiled_import_uses_new_images_when_resource_names_collide() {
|
||||
let files = ["Plane_ao.1001.png", "Plane_ao.1002.png"];
|
||||
let dir = bake_folder("collisions", &files);
|
||||
let mut session = tiled_session();
|
||||
let old_bytes = std::fs::read(dir.join(files[0])).unwrap();
|
||||
for name in files {
|
||||
session.import_resource_bytes(name, old_bytes.clone()).unwrap();
|
||||
}
|
||||
let revision_before = session.revision;
|
||||
|
||||
import(&mut session, &dir, &files.map(|file| (file, None)));
|
||||
|
||||
let baked = &session.doc.baked[&0];
|
||||
let ao = &baked.maps[&BakedMap::AmbientOcclusion];
|
||||
let width = baked.resolution as usize;
|
||||
let row = ao.len() / width / 2 * width;
|
||||
assert!((ao[row + width / 4] - 20.0 / 255.0).abs() < 1e-5);
|
||||
assert!((ao[row + 3 * width / 4] - 40.0 / 255.0).abs() < 1e-5);
|
||||
assert_eq!(session.revision, revision_before + 1);
|
||||
assert_eq!(session.doc.resources.len(), 4);
|
||||
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.resources.len(), 2);
|
||||
assert_eq!(session.images.len(), 2);
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.images.len(), 4);
|
||||
assert!(has_map(&session, 0, BakedMap::AmbientOcclusion));
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_files_are_rejected_before_reading_any() {
|
||||
let mut session = session();
|
||||
let files = vec![json!({"path": "Ball_ao.png"}); 513];
|
||||
let error = execute(&mut session, "textureSet.meshMap.import", &json!({"files": files})).unwrap_err().to_string();
|
||||
assert!(error.contains("at most 512 files"), "{error}");
|
||||
assert!(session.doc.resources.is_empty());
|
||||
assert!(!session.modified);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tga_maps_survive_undo_redo_and_project_reload() {
|
||||
let dir = bake_folder("tga", &["Ball_normal.tga", "Base_ao.png"]);
|
||||
let mut session = session();
|
||||
let result = import(&mut session, &dir, &[("Ball_normal.tga", None), ("Base_ao.png", None)]);
|
||||
assert_eq!(result["assigned"].as_array().unwrap().len(), 2);
|
||||
assert!(has_map(&session, 0, BakedMap::Normal));
|
||||
let image = session.images["Ball_normal.tga"].clone();
|
||||
|
||||
session.undo().unwrap();
|
||||
assert!(session.images.is_empty());
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.images["Ball_normal.tga"].rgba, image.rgba);
|
||||
let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(reloaded.images["Ball_normal.tga"].rgba, image.rgba);
|
||||
assert_eq!(reloaded.doc.baked, session.doc.baked);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -128,6 +128,19 @@ fn polygon_fill_boxes_survive_hostile_params() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A small project still gets the production bake defaults; only panic_hunt overrides them.
|
||||
#[test]
|
||||
fn new_project_keeps_full_resolution_bake_defaults() {
|
||||
let s = session();
|
||||
assert!(!s.doc.project.texture_sets.is_empty());
|
||||
for texture_set in &s.doc.project.texture_sets {
|
||||
assert_eq!(texture_set.resolution, 256);
|
||||
assert_eq!(texture_set.bake, texturecraft_engine::core::BakeSettings::default());
|
||||
assert_eq!(texture_set.bake.common.output_size(), (2048, 2048));
|
||||
assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 64);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command must return Ok or Err — never panic — for hostile params.
|
||||
#[test]
|
||||
fn panic_hunt() {
|
||||
@@ -145,6 +158,11 @@ fn panic_hunt() {
|
||||
}
|
||||
for p in &hostile {
|
||||
let mut s = session();
|
||||
// Match the 256px fixture: otherwise empty/irrelevant bake.run params perform
|
||||
// repeated 2048px default bakes. Keep every input, ray count and fresh session.
|
||||
for texture_set in &mut s.doc.project.texture_sets {
|
||||
texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256;
|
||||
}
|
||||
let _ = execute(&mut s, spec.id, p);
|
||||
s.update();
|
||||
}
|
||||
|
||||
@@ -21,20 +21,27 @@ pub fn decode_image(bytes: &[u8]) -> Result<DecodedImage> {
|
||||
/// [`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<DecodedImage> {
|
||||
let reader =
|
||||
let mut reader =
|
||||
image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
|
||||
let (w, h) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
|
||||
if w == 0 || h == 0 || w > MAX_IMAGE_SIZE || h > MAX_IMAGE_SIZE {
|
||||
return Err(FormatError::TooLarge(format!("image is {w}x{h} (limit {MAX_IMAGE_SIZE})")));
|
||||
|
||||
// TGA has no magic signature; its decoder validates the header when no format was recognized
|
||||
let format = reader.format().unwrap_or(image::ImageFormat::Tga);
|
||||
reader.set_format(format);
|
||||
|
||||
let (width, height) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
|
||||
if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE {
|
||||
return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})")));
|
||||
}
|
||||
if u64::from(w) * u64::from(h) > max_texels {
|
||||
return Err(FormatError::TooLarge(format!("image is {w}x{h}, more than {max_texels} texels")));
|
||||
if u64::from(width) * u64::from(height) > max_texels {
|
||||
return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels")));
|
||||
}
|
||||
let img = crate::guard("image", || image::load_from_memory(bytes).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?;
|
||||
let srgb = !matches!(img, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_));
|
||||
let f = img.into_rgba32f();
|
||||
let (width, height) = f.dimensions();
|
||||
let rgba = f.pixels().map(|p| p.0).collect();
|
||||
|
||||
let image =
|
||||
crate::guard("image", || image::load_from_memory_with_format(bytes, format).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?;
|
||||
let srgb = !matches!(image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_));
|
||||
let float_image = image.into_rgba32f();
|
||||
let (width, height) = float_image.dimensions();
|
||||
let rgba = float_image.pixels().map(|pixel| pixel.0).collect();
|
||||
Ok(DecodedImage { width, height, rgba, srgb })
|
||||
}
|
||||
|
||||
@@ -69,6 +76,19 @@ mod tests {
|
||||
assert!(coverage_png(2, 2, &[0], [255; 3]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tga_without_a_magic_signature_decodes_within_the_texel_budget() {
|
||||
let mut bytes = Vec::new();
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Tga).unwrap();
|
||||
let image = decode_image_within(&bytes, 16).unwrap();
|
||||
assert_eq!((image.width, image.height), (4, 4));
|
||||
assert!((image.rgba[0][1] - 0.2).abs() < 1e-6);
|
||||
assert!(image.srgb);
|
||||
let header = &bytes[..18];
|
||||
assert!(matches!(decode_image_within(header, 15), Err(FormatError::TooLarge(_))));
|
||||
assert!(decode_image(header).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoding_within_a_texel_limit_refuses_big_images_from_the_header() {
|
||||
let png = {
|
||||
|
||||
@@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4};
|
||||
|
||||
use crate::{GeomError, Result};
|
||||
|
||||
/// An edge by the bits of its two end positions, the lower one first
|
||||
type EdgePositions = ([u32; 3], [u32; 3]);
|
||||
|
||||
/// A contiguous index range drawn with one material.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SubMesh {
|
||||
@@ -107,6 +110,47 @@ impl Mesh {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
|
||||
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
// 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<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
|
||||
for material in 0..seams.len() {
|
||||
for triangle in self.triangles_of(material) {
|
||||
let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
|
||||
|
||||
for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] {
|
||||
let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue };
|
||||
|
||||
let (from_bits, to_bits) = (bits(*from_position), bits(*to_position));
|
||||
let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) };
|
||||
sides.entry(edge).or_default().push((pair.0, pair.1, material));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let uv = |index: u32| self.uvs.get(index as usize).copied();
|
||||
for pairs in sides.into_values() {
|
||||
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
|
||||
|
||||
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
|
||||
for (from, to, material) in pairs {
|
||||
if let Some(edges) = seams.get_mut(material) {
|
||||
edges.push((from.min(to), from.max(to)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for edges in &mut seams {
|
||||
edges.sort_unstable();
|
||||
edges.dedup();
|
||||
}
|
||||
|
||||
seams
|
||||
}
|
||||
|
||||
/// Material of triangle `t`.
|
||||
pub fn material_of(&self, t: usize) -> Option<usize> {
|
||||
let idx = (t * 3) as u32;
|
||||
@@ -433,6 +477,55 @@ mod tests {
|
||||
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_are_where_the_uv_layout_splits() {
|
||||
let mesh = quad();
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam");
|
||||
|
||||
// Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut
|
||||
let mut seam = mesh.clone();
|
||||
seam.positions.push(seam.positions[0]);
|
||||
seam.normals.push(seam.normals[0]);
|
||||
seam.tangents.push(seam.tangents[0]);
|
||||
seam.uvs.push(Vec2::new(0.9, 0.9));
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
|
||||
// The same split with the same UV is a hard edge, not a seam
|
||||
let mut hard = seam.clone();
|
||||
hard.uvs[4] = hard.uvs[0];
|
||||
assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_join_positions_with_opposite_signed_zero() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0));
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
assert_eq!(mesh.positions[0], mesh.positions[4]);
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_between_materials_belong_to_both_materials() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(mesh.positions[0]);
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
mesh.materials.push("second".into());
|
||||
mesh.submeshes[0].count = 3;
|
||||
mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 });
|
||||
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
|
||||
mesh.uvs[4] = mesh.uvs[0];
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_catches_bad_indices() {
|
||||
let mut m = quad();
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly
|
||||
|
||||
/// Which parts of the bake setup the 3D view draws
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct BakeVisualization {
|
||||
pub high_poly: bool,
|
||||
pub cage: bool,
|
||||
pub uv_seams: bool,
|
||||
pub low_poly: bool,
|
||||
/// Draw the cage, seams and low poly of only this texture set
|
||||
pub only_set: Option<usize>,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs
|
||||
pub(crate) struct CageGpu {
|
||||
/// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners`
|
||||
pub(crate) topology: u64,
|
||||
pub(crate) corners: wgpu::Buffer,
|
||||
pub(crate) corner_count: u32,
|
||||
pub(crate) edges: wgpu::Buffer,
|
||||
pub(crate) edge_index_count: u32,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/// The high poly bake mode draws over the low poly
|
||||
pub(crate) struct HighPolyGpu {
|
||||
/// Which mesh the buffers hold
|
||||
pub(crate) id: u64,
|
||||
pub(crate) vertices: wgpu::Buffer,
|
||||
pub(crate) vertex_count: usize,
|
||||
pub(crate) indices: wgpu::Buffer,
|
||||
pub(crate) index_count: u32,
|
||||
/// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it
|
||||
pub(crate) missed: wgpu::Buffer,
|
||||
}
|
||||
@@ -13,12 +13,15 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake_visualization;
|
||||
mod cage_gpu;
|
||||
pub mod displace;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod gpu_bake;
|
||||
pub mod gpu_trace;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod headless;
|
||||
mod high_poly_gpu;
|
||||
pub mod ibl;
|
||||
pub mod mesh_maps;
|
||||
pub mod readback;
|
||||
@@ -26,7 +29,9 @@ pub mod renderer;
|
||||
pub mod set_highlight;
|
||||
mod subdivide;
|
||||
pub mod trace;
|
||||
mod uv_seam_gpu;
|
||||
|
||||
pub use bake_visualization::BakeVisualization;
|
||||
pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale};
|
||||
pub use set_highlight::SetHighlight;
|
||||
pub use wgpu;
|
||||
@@ -26,6 +26,19 @@ pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_
|
||||
out
|
||||
}
|
||||
|
||||
/// RGBA8 of the neutral value of map `m` (what a map not baked yet shows during a bake: flat
|
||||
/// normals, white occlusion, mid-gray height ...), `size × size`, encoded like [`mesh_map_rgba`].
|
||||
pub fn neutral_rgba(m: BakedMap, size: u32) -> Vec<u8> {
|
||||
let value = m.neutral();
|
||||
let pixel = [0, 1, 2].map(|k| (value[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
|
||||
let size = size.max(1);
|
||||
let mut out = Vec::with_capacity((size * size * 4) as usize);
|
||||
for _ in 0..size * size {
|
||||
out.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 255]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+348
-91
@@ -30,10 +30,14 @@ use texturecraft_geom::glam::{Mat4, Vec3};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_texel::TILE;
|
||||
|
||||
use crate::bake_visualization::BakeVisualization;
|
||||
use crate::cage_gpu::CageGpu;
|
||||
use crate::gpu_trace::{Checked, checked};
|
||||
use crate::high_poly_gpu::HighPolyGpu;
|
||||
use crate::ibl;
|
||||
use crate::set_highlight::SetHighlight;
|
||||
use crate::subdivide::{self, Vertex};
|
||||
use crate::uv_seam_gpu::UvSeamGpu;
|
||||
|
||||
pub const MSAA: u32 = 4;
|
||||
pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
@@ -173,6 +177,8 @@ pub struct Shade {
|
||||
/// Move the surface by the height channel (3D view): a dense copy of the mesh, displaced in
|
||||
/// the vertex shader at the height-to-normal strength.
|
||||
pub displacement: bool,
|
||||
/// Bake mode's high poly, cage and UV seams over the 3D view
|
||||
pub bake: Option<BakeVisualization>,
|
||||
}
|
||||
|
||||
/// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the
|
||||
@@ -259,6 +265,7 @@ impl Default for Shade {
|
||||
sss_blur: None,
|
||||
refraction: false,
|
||||
displacement: false,
|
||||
bake: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -530,6 +537,11 @@ pub struct Renderer {
|
||||
wire3d_pipeline: wgpu::RenderPipeline,
|
||||
/// The highlighted set's mesh edges, wider and in the highlight color
|
||||
highlight_pipeline: wgpu::RenderPipeline,
|
||||
/// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams
|
||||
bake_high_pipeline: wgpu::RenderPipeline,
|
||||
cage_pipeline: wgpu::RenderPipeline,
|
||||
cage_wire_pipeline: wgpu::RenderPipeline,
|
||||
uv_seam_pipeline: wgpu::RenderPipeline,
|
||||
bg_pipeline: wgpu::RenderPipeline,
|
||||
blit_pipeline: wgpu::RenderPipeline,
|
||||
post_pipeline: wgpu::RenderPipeline,
|
||||
@@ -563,6 +575,10 @@ pub struct Renderer {
|
||||
/// accumulation.
|
||||
content_rev: u64,
|
||||
mesh: Option<MeshGpu>,
|
||||
bake_high: Option<HighPolyGpu>,
|
||||
/// Each texture set's cage, by set index
|
||||
cages: Vec<Option<CageGpu>>,
|
||||
uv_seams: Option<UvSeamGpu>,
|
||||
sets: Vec<SetGpu>,
|
||||
/// 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).
|
||||
@@ -808,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 {
|
||||
|
||||
const CLEAR: wgpu::LoadOp<wgpu::Color> = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT);
|
||||
|
||||
/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves
|
||||
const SHADOW_SLOPE_BIAS: f32 = 1.5;
|
||||
|
||||
/// Anisotropic filtering of the texture sets' sampler
|
||||
const MAX_ANISOTROPY: u16 = 8;
|
||||
|
||||
/// Size of the environment texture before the first environment loads
|
||||
const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256];
|
||||
|
||||
impl Renderer {
|
||||
/// `target_format`: the format of the pass [`Renderer::blit`] draws into.
|
||||
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer {
|
||||
let shader = |label: &str, source: &str| {
|
||||
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) })
|
||||
};
|
||||
let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl")));
|
||||
let module =
|
||||
shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl")));
|
||||
let util_module = shader("tc_util", include_str!("shaders/util.wgsl"));
|
||||
let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl")));
|
||||
let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl")));
|
||||
let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
|
||||
|
||||
let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries })
|
||||
};
|
||||
let globals_bgl = bgl(
|
||||
let globals_bind_group_layout = bind_group_layout(
|
||||
"tc_globals",
|
||||
&[
|
||||
uniform_entry(0),
|
||||
@@ -838,44 +865,47 @@ impl Renderer {
|
||||
fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)),
|
||||
],
|
||||
);
|
||||
// The display textures, the aux texture, the sampler.
|
||||
// The display textures, the aux texture, the sampler
|
||||
let textures = DisplayKind::ALL.len() as u32 + 1;
|
||||
// Displacement reads the height (and the sampler) in the vertex shader.
|
||||
let height = DisplayKind::ALL.iter().position(|k| *k == DisplayKind::Height).unwrap_or(0) as u32;
|
||||
// Displacement reads the height (and the sampler) in the vertex shader
|
||||
let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32;
|
||||
let set_entries: Vec<_> = (0..textures)
|
||||
.map(tex_entry)
|
||||
.chain(std::iter::once(sampler_entry(textures)))
|
||||
.map(|mut e| {
|
||||
if e.binding == height || e.binding == textures {
|
||||
e.visibility |= wgpu::ShaderStages::VERTEX;
|
||||
.map(|mut entry| {
|
||||
if entry.binding == height || entry.binding == textures {
|
||||
entry.visibility |= wgpu::ShaderStages::VERTEX;
|
||||
}
|
||||
e
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
let set_bgl = bgl("tc_set", &set_entries);
|
||||
let refr_bgl = bgl("tc_refr", &[tex_entry(0)]);
|
||||
let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]);
|
||||
let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]);
|
||||
let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]);
|
||||
let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]);
|
||||
let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| {
|
||||
let set_bind_group_layout = bind_group_layout("tc_set", &set_entries);
|
||||
let refraction_bind_group_layout = bind_group_layout("tc_refr", &[tex_entry(0)]);
|
||||
let blit_bind_group_layout = bind_group_layout("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]);
|
||||
let mip_bind_group_layout = bind_group_layout("tc_mip", &[tex_entry(0), sampler_entry(1)]);
|
||||
let effect_bind_group_layout =
|
||||
bind_group_layout("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]);
|
||||
let shadow_bind_group_layout = bind_group_layout("tc_shadow", &[uniform_entry(0)]);
|
||||
|
||||
let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| {
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 })
|
||||
};
|
||||
let layout = pl("tc_uv", &[Some(&globals_bgl), Some(&set_bgl)]);
|
||||
let mesh_layout = pl("tc_mesh", &[Some(&globals_bgl), Some(&set_bgl), Some(&refr_bgl)]);
|
||||
let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]);
|
||||
let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]);
|
||||
let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]);
|
||||
let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]);
|
||||
let vb = [Some(wgpu::VertexBufferLayout {
|
||||
let layout = pipeline_layout("tc_uv", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout)]);
|
||||
let mesh_layout = pipeline_layout("tc_mesh", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout), Some(&refraction_bind_group_layout)]);
|
||||
let background_layout = pipeline_layout("tc_bg", &[Some(&globals_bind_group_layout)]);
|
||||
let blit_layout = pipeline_layout("tc_blit", &[Some(&blit_bind_group_layout)]);
|
||||
let effect_layout = pipeline_layout("tc_fx", &[Some(&effect_bind_group_layout)]);
|
||||
let shadow_layout = pipeline_layout("tc_shadow", &[Some(&shadow_bind_group_layout), Some(&set_bind_group_layout)]);
|
||||
|
||||
let vertex_layout = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2],
|
||||
})];
|
||||
// shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode
|
||||
// (e.g. RGBM) if WebGL2 without float color buffers turns out to matter.
|
||||
|
||||
// shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter
|
||||
let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT };
|
||||
let hdr = |fs, blend| Some((fs, hdr_format, blend));
|
||||
let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend));
|
||||
let always = || Some(depth_state(false, wgpu::CompareFunction::Always));
|
||||
let mesh_pipeline = pipeline(
|
||||
device,
|
||||
@@ -883,8 +913,8 @@ impl Renderer {
|
||||
&mesh_layout,
|
||||
&module,
|
||||
"vs_mesh",
|
||||
&vb,
|
||||
hdr("fs_mesh", None),
|
||||
&vertex_layout,
|
||||
hdr_target("fs_mesh", None),
|
||||
MSAA,
|
||||
Some(depth_state(true, wgpu::CompareFunction::Less)),
|
||||
);
|
||||
@@ -894,31 +924,103 @@ impl Renderer {
|
||||
&mesh_layout,
|
||||
&module,
|
||||
"vs_mesh",
|
||||
&vb,
|
||||
hdr("fs_opaque", None),
|
||||
&vertex_layout,
|
||||
hdr_target("fs_opaque", None),
|
||||
MSAA,
|
||||
Some(depth_state(true, wgpu::CompareFunction::Less)),
|
||||
);
|
||||
let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always());
|
||||
let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_uv", None), MSAA, always());
|
||||
let blend = Some(wgpu::BlendState::ALPHA_BLENDING);
|
||||
let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always());
|
||||
let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire", blend), MSAA, always());
|
||||
let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual));
|
||||
let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone());
|
||||
let highlight_pipeline =
|
||||
pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth);
|
||||
let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always());
|
||||
let wire3d_pipeline =
|
||||
pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire3d", blend), MSAA, wire3d_depth.clone());
|
||||
let highlight_pipeline = pipeline(
|
||||
device,
|
||||
"tc_highlight",
|
||||
&layout,
|
||||
&module,
|
||||
"vs_wire_highlight",
|
||||
&vertex_layout,
|
||||
hdr_target("fs_wire_highlight", blend),
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
|
||||
let [mesh_vertex_layout] = vertex_layout.clone();
|
||||
let high_layout = [
|
||||
mesh_vertex_layout,
|
||||
Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<f32>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &wgpu::vertex_attr_array![4 => Float32],
|
||||
}),
|
||||
];
|
||||
let bake_high_pipeline = pipeline(
|
||||
device,
|
||||
"tc_bake_high",
|
||||
&background_layout,
|
||||
&module,
|
||||
"vs_bake_high",
|
||||
&high_layout,
|
||||
hdr_target("fs_bake_high", None),
|
||||
MSAA,
|
||||
Some(depth_state(true, wgpu::CompareFunction::Less)),
|
||||
);
|
||||
let corner_layout = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<[f32; 3]>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x3],
|
||||
})];
|
||||
let cage_pipeline = pipeline(
|
||||
device,
|
||||
"tc_cage",
|
||||
&background_layout,
|
||||
&module,
|
||||
"vs_bake_cage",
|
||||
&corner_layout,
|
||||
hdr_target("fs_bake_cage", blend),
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
let cage_wire_pipeline = pipeline(
|
||||
device,
|
||||
"tc_cage_wire",
|
||||
&background_layout,
|
||||
&module,
|
||||
"vs_bake_cage_wire",
|
||||
&corner_layout,
|
||||
hdr_target("fs_wire_bake_cage", blend),
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
let uv_seam_pipeline =
|
||||
pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone());
|
||||
let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always());
|
||||
let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None);
|
||||
let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None);
|
||||
let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))]
|
||||
.map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None));
|
||||
let gbuf_pipeline =
|
||||
pipeline(device, "tc_gbuf", &mesh_layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less)));
|
||||
let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None));
|
||||
let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None);
|
||||
let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None);
|
||||
let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| {
|
||||
pipeline(device, "tc_bloom", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, blend), 1, None)
|
||||
});
|
||||
let gbuffer_pipeline = pipeline(
|
||||
device,
|
||||
"tc_gbuf",
|
||||
&mesh_layout,
|
||||
&module,
|
||||
"vs_mesh",
|
||||
&vertex_layout,
|
||||
hdr_target("fs_gbuf", None),
|
||||
1,
|
||||
Some(depth_state(true, wgpu::CompareFunction::Less)),
|
||||
);
|
||||
let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fragment_entry_point| {
|
||||
pipeline(device, "tc_sss", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, None), 1, None)
|
||||
});
|
||||
let dof_pipeline = pipeline(device, "tc_dof", &effect_layout, &post_module, "vs_full", &[], hdr_target("fs_dof", None), 1, None);
|
||||
let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL });
|
||||
let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("tc_dof_gather"),
|
||||
layout: Some(&fx_layout),
|
||||
layout: Some(&effect_layout),
|
||||
vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() },
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
@@ -932,20 +1034,23 @@ impl Renderer {
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let shadow_depth = wgpu::DepthStencilState {
|
||||
bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 },
|
||||
bias: wgpu::DepthBiasState { constant: 0, slope_scale: SHADOW_SLOPE_BIAS, clamp: 0.0 },
|
||||
..depth_state(true, wgpu::CompareFunction::Less)
|
||||
};
|
||||
let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth));
|
||||
// accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average.
|
||||
let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vertex_layout, None, 1, Some(shadow_depth));
|
||||
|
||||
// accum = hdr_target * k + accum * (1 - k) with k = 1 / (sample + 1): a running average
|
||||
let average = wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::Constant,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusConstant,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
};
|
||||
let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]);
|
||||
let accum_layout = pipeline_layout("tc_accum", &[Some(&mip_bind_group_layout)]);
|
||||
let accum_blend = Some(wgpu::BlendState { color: average, alpha: average });
|
||||
let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_copy", accum_blend), 1, None);
|
||||
let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr_target("fs_copy", accum_blend), 1, None);
|
||||
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("tc_tex"),
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
@@ -953,7 +1058,7 @@ impl Renderer {
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::MipmapFilterMode::Linear,
|
||||
anisotropy_clamp: 8,
|
||||
anisotropy_clamp: MAX_ANISOTROPY,
|
||||
..Default::default()
|
||||
});
|
||||
let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
@@ -972,7 +1077,8 @@ impl Renderer {
|
||||
compare: Some(wgpu::CompareFunction::LessEqual),
|
||||
..Default::default()
|
||||
});
|
||||
let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
|
||||
let shadow_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("tc_shadow"),
|
||||
size: std::mem::size_of::<[[f32; 4]; 5]>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
@@ -986,39 +1092,45 @@ impl Renderer {
|
||||
vp: Mat4::IDENTITY,
|
||||
bg: device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("tc_shadow"),
|
||||
layout: &shadow_bgl,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buf.as_entire_binding() }],
|
||||
layout: &shadow_bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buffer.as_entire_binding() }],
|
||||
}),
|
||||
buf: shadow_buf,
|
||||
buf: shadow_buffer,
|
||||
};
|
||||
|
||||
let black = Tex::new(device, "tc_black", 1, 1, COLOR_FORMAT, 1).view;
|
||||
let refr_black = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
let refraction_black = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("tc_refr_black"),
|
||||
layout: &refr_bgl,
|
||||
layout: &refraction_bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }],
|
||||
});
|
||||
let env = Tex::new(device, "tc_env", 512, 256, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS);
|
||||
let mut r = Renderer {
|
||||
let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS);
|
||||
|
||||
let mut renderer = Renderer {
|
||||
target_format,
|
||||
hdr_format,
|
||||
globals_bgl,
|
||||
set_bgl,
|
||||
blit_bgl,
|
||||
mip_bgl,
|
||||
fx_bgl,
|
||||
refr_bgl,
|
||||
refr_black,
|
||||
globals_bgl: globals_bind_group_layout,
|
||||
set_bgl: set_bind_group_layout,
|
||||
blit_bgl: blit_bind_group_layout,
|
||||
mip_bgl: mip_bind_group_layout,
|
||||
fx_bgl: effect_bind_group_layout,
|
||||
refr_bgl: refraction_bind_group_layout,
|
||||
refr_black: refraction_black,
|
||||
mesh_pipeline,
|
||||
opaque_pipeline,
|
||||
uv_pipeline,
|
||||
wire_pipeline,
|
||||
wire3d_pipeline,
|
||||
highlight_pipeline,
|
||||
bake_high_pipeline,
|
||||
cage_pipeline,
|
||||
cage_wire_pipeline,
|
||||
uv_seam_pipeline,
|
||||
bg_pipeline,
|
||||
blit_pipeline,
|
||||
post_pipeline,
|
||||
bloom_pipelines,
|
||||
gbuf_pipeline,
|
||||
gbuf_pipeline: gbuffer_pipeline,
|
||||
sss_pipelines,
|
||||
dof_gather_pipeline,
|
||||
dof_pipeline,
|
||||
@@ -1038,13 +1150,16 @@ impl Renderer {
|
||||
sh: [[0.0; 4]; 9],
|
||||
content_rev: 0,
|
||||
mesh: None,
|
||||
bake_high: None,
|
||||
cages: Vec::new(),
|
||||
uv_seams: None,
|
||||
sets: Vec::new(),
|
||||
display_shift: 0,
|
||||
material_sets: Vec::new(),
|
||||
views: HashMap::new(),
|
||||
};
|
||||
r.set_environment(device, queue, "Studio Soft", None);
|
||||
r
|
||||
renderer.set_environment(device, queue, "Studio Soft", None);
|
||||
renderer
|
||||
}
|
||||
|
||||
pub fn environment_name(&self) -> &str {
|
||||
@@ -1124,6 +1239,94 @@ impl Renderer {
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
/// Upload the high poly when `id` changes; remove it on `None` or when its buffers exceed the device limit
|
||||
pub fn set_bake_high(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh: Option<&Mesh>, id: u64) -> Result<(), String> {
|
||||
if self.bake_high.as_ref().map(|high| high.id) == mesh.map(|_| id) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.bake_high = None;
|
||||
self.content_rev += 1;
|
||||
let Some(mesh) = mesh else { return Ok(()) };
|
||||
|
||||
// Imported high polys can outgrow a viewport buffer even when the CPU baker accepts them
|
||||
let limit = device.limits().max_buffer_size;
|
||||
let buffers = [
|
||||
(mesh.positions.len(), std::mem::size_of::<Vertex>()),
|
||||
(mesh.indices.len(), std::mem::size_of::<u32>()),
|
||||
(mesh.positions.len(), std::mem::size_of::<f32>()),
|
||||
];
|
||||
if mesh.indices.len() > u32::MAX as usize || buffers.iter().any(|&(count, stride)| count.checked_mul(stride).is_none_or(|bytes| bytes as u64 > limit)) {
|
||||
return Err(format!("High-poly visualization exceeds the GPU buffer limit ({limit} bytes). Use a smaller preview mesh or hide the high poly."));
|
||||
}
|
||||
|
||||
self.bake_high = Some(HighPolyGpu {
|
||||
id,
|
||||
vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX),
|
||||
vertex_count: mesh.positions.len(),
|
||||
indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX),
|
||||
index_count: mesh.indices.len() as u32,
|
||||
missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count
|
||||
pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) {
|
||||
let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return };
|
||||
|
||||
queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed));
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners
|
||||
pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) {
|
||||
if self.cages.len() <= texture_set {
|
||||
self.cages.resize_with(texture_set + 1, || None);
|
||||
}
|
||||
let Some(slot) = self.cages.get_mut(texture_set) else { return };
|
||||
|
||||
match (cage, slot.as_mut()) {
|
||||
(None, _) => *slot = None,
|
||||
(Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => {
|
||||
queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners));
|
||||
}
|
||||
(Some((corners, edges)), _) => {
|
||||
*slot = Some(CageGpu {
|
||||
topology,
|
||||
corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX),
|
||||
corner_count: corners.len() as u32,
|
||||
edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX),
|
||||
edge_index_count: (edges.len() * 2) as u32,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
/// Forget the cages of texture sets from `count` on (sets that were removed)
|
||||
pub fn truncate_bake_cages(&mut self, count: usize) {
|
||||
if self.cages.len() > count {
|
||||
self.cages.truncate(count);
|
||||
self.content_rev += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id`
|
||||
pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) {
|
||||
let mut line_indices: Vec<u32> = Vec::new();
|
||||
let mut line_draws = Vec::new();
|
||||
for (material, edges) in seams.iter().enumerate() {
|
||||
let start = line_indices.len() as u32;
|
||||
line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to]));
|
||||
line_draws.push((start, line_indices.len() as u32 - start, material));
|
||||
}
|
||||
|
||||
let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX);
|
||||
self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws });
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
/// Build the mesh's dense copy for displacement (once per mesh).
|
||||
fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
|
||||
let Some(m) = self.mesh.as_mut() else { return };
|
||||
@@ -1889,30 +2092,30 @@ impl Renderer {
|
||||
self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr);
|
||||
}
|
||||
|
||||
/// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight`
|
||||
/// One scene pass: background, then the mesh with `mesh_pipeline`, the wireframe with `wire` and one set's highlighted edges with `highlight`
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_scene(
|
||||
&self,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
v: &ViewTargets,
|
||||
targets: &ViewTargets,
|
||||
resolve: &wgpu::TextureView,
|
||||
globals_bg: &wgpu::BindGroup,
|
||||
globals_bind_group: &wgpu::BindGroup,
|
||||
frame: &Frame,
|
||||
pipe: &wgpu::RenderPipeline,
|
||||
mesh_pipeline: &wgpu::RenderPipeline,
|
||||
wire: Option<&wgpu::RenderPipeline>,
|
||||
highlight: Option<(&wgpu::RenderPipeline, usize)>,
|
||||
refr: &wgpu::BindGroup,
|
||||
refraction_source: &wgpu::BindGroup,
|
||||
) {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("tc_view"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &v.msaa,
|
||||
view: &targets.msaa,
|
||||
resolve_target: Some(resolve),
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Discard },
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &v.depth,
|
||||
view: &targets.depth,
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
@@ -1920,33 +2123,87 @@ impl Renderer {
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_bind_group(0, globals_bg, &[]);
|
||||
pass.set_bind_group(0, globals_bind_group, &[]);
|
||||
pass.set_pipeline(&self.bg_pipeline);
|
||||
pass.draw(0..3, 0..1);
|
||||
let Some(m) = &self.mesh else { return };
|
||||
let uv_ts = match frame.kind {
|
||||
let Some(mesh) = &self.mesh else { return };
|
||||
|
||||
let uv_set = match frame.kind {
|
||||
ViewKind::Scene => None,
|
||||
ViewKind::Uv { ts, .. } => Some(ts),
|
||||
};
|
||||
pass.set_bind_group(2, refr, &[]);
|
||||
let geo = self.geometry(m, frame);
|
||||
pass.set_bind_group(2, refraction_source, &[]);
|
||||
let geometry = self.geometry(mesh, frame);
|
||||
let bake = frame.shade.bake.filter(|_| uv_set.is_none());
|
||||
let low_poly_shown = bake.is_none_or(|bake| bake.low_poly);
|
||||
let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set);
|
||||
let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip();
|
||||
|
||||
// The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too)
|
||||
let (highlight, highlight_set) = highlight.unzip();
|
||||
let passes = [
|
||||
(Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1),
|
||||
(wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1),
|
||||
(highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
|
||||
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1),
|
||||
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1),
|
||||
(highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
|
||||
];
|
||||
for (pipe, vb, ib, ranges, only, instances) in passes {
|
||||
let Some(pipe) = pipe else { continue };
|
||||
pass.set_pipeline(pipe);
|
||||
pass.set_vertex_buffer(0, vb.slice(..));
|
||||
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(ranges, &frame.visible, only) {
|
||||
for (pipeline, vertices, indices, ranges, only_set, instances) in passes {
|
||||
let Some(pipeline) = pipeline else { continue };
|
||||
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_vertex_buffer(0, vertices.slice(..));
|
||||
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(ranges, &frame.visible, only_set) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..instances);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(bake) = bake {
|
||||
self.draw_bake(&mut pass, mesh, frame, bake);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bake mode's high poly, UV seams and cages over the low poly `low_poly`
|
||||
fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) {
|
||||
if bake.high_poly
|
||||
&& let Some(high) = &self.bake_high
|
||||
{
|
||||
pass.set_pipeline(&self.bake_high_pipeline);
|
||||
pass.set_vertex_buffer(0, high.vertices.slice(..));
|
||||
pass.set_vertex_buffer(1, high.missed.slice(..));
|
||||
pass.set_index_buffer(high.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..high.index_count, 0, 0..1);
|
||||
}
|
||||
|
||||
if bake.uv_seams
|
||||
&& let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id)
|
||||
{
|
||||
pass.set_pipeline(&self.uv_seam_pipeline);
|
||||
pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..));
|
||||
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
if !bake.cage {
|
||||
return;
|
||||
}
|
||||
|
||||
let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true);
|
||||
let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref());
|
||||
// The translucent faces first, then the wireframe over them
|
||||
pass.set_pipeline(&self.cage_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.draw(0..cage.corner_count, 0..1);
|
||||
}
|
||||
pass.set_pipeline(&self.cage_wire_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..cage.edge_index_count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h).
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams
|
||||
|
||||
struct BakeViewOut {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) world_position: vec3<f32>,
|
||||
@location(1) normal: vec3<f32>,
|
||||
// 1 where the bake's rays miss the high poly, 0 where they reach it
|
||||
@location(2) missed: f32,
|
||||
};
|
||||
|
||||
const HIGH_POLY_COLOR: vec3<f32> = vec3<f32>(0.10, 0.36, 0.56);
|
||||
const MISSED_COLOR: vec3<f32> = vec3<f32>(0.80, 0.01, 0.01);
|
||||
const CAGE_COLOR: vec3<f32> = vec3<f32>(0.55, 0.42, 0.26);
|
||||
const CAGE_OPACITY: f32 = 0.16;
|
||||
const CAGE_WIRE_COLOR: vec4<f32> = vec4<f32>(0.75, 0.62, 0.42, 0.7);
|
||||
const UV_SEAM_COLOR: vec4<f32> = vec4<f32>(0.20, 0.85, 0.30, 1.0);
|
||||
|
||||
// Brightness of surfaces seen edge-on; facing the camera adds the rest
|
||||
const HEADLIGHT_AMBIENT: f32 = 0.3;
|
||||
|
||||
// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order
|
||||
const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001;
|
||||
const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002;
|
||||
|
||||
// Lit from the camera: surfaces facing it are brightest
|
||||
fn headlight(color: vec3<f32>, normal: vec3<f32>, world_position: vec3<f32>) -> vec3<f32> {
|
||||
let facing = abs(dot(normal, normalize(g.eye.xyz - world_position)));
|
||||
return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing);
|
||||
}
|
||||
|
||||
fn pulled_toward_eye(world_position: vec3<f32>, fraction: f32) -> vec4<f32> {
|
||||
return g.view_proj * vec4<f32>(world_position + (g.eye.xyz - world_position) * fraction, 1.0);
|
||||
}
|
||||
|
||||
// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it
|
||||
@vertex
|
||||
fn vs_bake_high(@location(0) position: vec3<f32>, @location(1) normal: vec3<f32>, @location(4) missed: f32) -> BakeViewOut {
|
||||
var out: BakeViewOut;
|
||||
out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE);
|
||||
out.world_position = position;
|
||||
out.normal = normal;
|
||||
out.missed = missed;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed);
|
||||
return vec4<f32>(headlight(color, normalize(surface.normal), surface.world_position), 1.0);
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_bake_cage(@location(0) position: vec3<f32>) -> BakeViewOut {
|
||||
var out: BakeViewOut;
|
||||
out.clip = g.view_proj * vec4<f32>(position, 1.0);
|
||||
out.world_position = position;
|
||||
out.normal = vec3<f32>(0.0, 1.0, 0.0);
|
||||
out.missed = 0.0;
|
||||
return out;
|
||||
}
|
||||
|
||||
// The cage's own faces: their normal comes from the screen-space change of the position
|
||||
@fragment
|
||||
fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position)));
|
||||
return vec4<f32>(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY);
|
||||
}
|
||||
|
||||
// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces
|
||||
@vertex
|
||||
fn vs_bake_cage_wire(@location(0) position: vec3<f32>) -> BakeViewOut {
|
||||
var out: BakeViewOut;
|
||||
out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE);
|
||||
out.world_position = position;
|
||||
out.normal = vec3<f32>(0.0, 1.0, 0.0);
|
||||
out.missed = 0.0;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
return CAGE_WIRE_COLOR;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4<f32> {
|
||||
return UV_SEAM_COLOR;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/// The low poly's UV seams as a line list over its vertex buffer
|
||||
pub(crate) struct UvSeamGpu {
|
||||
/// The low-poly mesh the lines belong to
|
||||
pub(crate) mesh_id: u64,
|
||||
pub(crate) lines: wgpu::Buffer,
|
||||
/// (first index, count, material) per material
|
||||
pub(crate) line_draws: Vec<(u32, u32, usize)>,
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
use texturecraft_compose::{DisplayKind, ImageRes};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{OrbitCamera, primitives};
|
||||
use texturecraft_render::headless::Headless;
|
||||
use texturecraft_render::renderer::TAA_SAMPLES;
|
||||
use texturecraft_render::{Frame, Shade, ViewKind};
|
||||
use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind};
|
||||
|
||||
/// The UI's key light (`viewport::shade`).
|
||||
const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5];
|
||||
@@ -42,14 +43,18 @@ impl Img {
|
||||
}
|
||||
}
|
||||
|
||||
/// The id `setup` uploads the material ball under
|
||||
const MESH_ID: u64 = 1;
|
||||
|
||||
/// A headless renderer with the material ball framed in a 480×360 view (None without a GPU).
|
||||
fn setup() -> Option<(Headless, Frame)> {
|
||||
let Ok(mut h) = Headless::new() else {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
return None;
|
||||
};
|
||||
eprintln!("headless adapter: {:?}", h.device.adapter_info());
|
||||
let mesh = primitives::material_ball();
|
||||
h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1);
|
||||
h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID);
|
||||
h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2);
|
||||
let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
|
||||
let (lo, hi) = mesh.bounds();
|
||||
@@ -220,6 +225,122 @@ fn wireframe_3d_overlays_the_mesh() {
|
||||
assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_visualization_draws_the_high_poly_and_the_cage() {
|
||||
// A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color
|
||||
const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3;
|
||||
const CAGE_SCALE: f32 = 2.5;
|
||||
const HIGH_POLY_ID: u64 = 7;
|
||||
const CAGE_TOPOLOGY: u64 = 1;
|
||||
const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]];
|
||||
const COLOR_LEAD: i32 = 30;
|
||||
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
let ball = primitives::material_ball();
|
||||
let (low_min, low_max) = ball.bounds();
|
||||
let ball_center = (low_min + low_max) * 0.5;
|
||||
let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16);
|
||||
for position in &mut high.positions {
|
||||
*position += ball_center;
|
||||
}
|
||||
h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap();
|
||||
let corners: Vec<Vec3> = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect();
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY);
|
||||
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None };
|
||||
let center = (frame.size[0] / 2, frame.size[1] / 2);
|
||||
|
||||
let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name);
|
||||
let low_only = only(&mut h, bake, "bake_low_only");
|
||||
let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden");
|
||||
let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly");
|
||||
let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage");
|
||||
assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly");
|
||||
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background");
|
||||
assert_same(&hidden, &background, "without the low poly only the background is left");
|
||||
let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from);
|
||||
assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]);
|
||||
let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1));
|
||||
assert!(
|
||||
caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue,
|
||||
"the cage tints the ball tan: {:?} → {:?}",
|
||||
[low_red, low_green, low_blue],
|
||||
[caged_red, caged_green, caged_blue]
|
||||
);
|
||||
|
||||
// Vertices the bake's rays miss turn red
|
||||
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]);
|
||||
let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed");
|
||||
let [red, green, blue] = missed.at(center.0, center.1).map(i32::from);
|
||||
assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]);
|
||||
|
||||
// Show for selected texture set only: the other set's low poly and the cage of set 0 drop out
|
||||
let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set");
|
||||
let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set");
|
||||
assert_ne!(first_set.px, caged.px, "the second set's low poly is left out");
|
||||
assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out");
|
||||
assert_ne!(first_set.px, second_set.px);
|
||||
|
||||
// UV seams draw over the low poly
|
||||
h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges());
|
||||
let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams");
|
||||
assert_ne!(seams.px, low_only.px, "the seams show");
|
||||
|
||||
// A new distance with the same topology only moves the corners
|
||||
let grown: Vec<Vec3> = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect();
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY);
|
||||
let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown");
|
||||
assert_ne!(caged.px, bigger.px, "the cage grew");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_bake_high_poly_leaves_the_view_renderable() {
|
||||
let Some((mut headless, frame)) = setup() else { return };
|
||||
|
||||
let high = primitives::sphere(0.5, 16, 8);
|
||||
headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap();
|
||||
let limit = headless.device.limits().max_buffer_size;
|
||||
// The viewport vertex contains position, normal, tangent and UV: twelve f32 values
|
||||
let vertex_count = limit as usize / (12 * std::mem::size_of::<f32>()) + 1;
|
||||
let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() };
|
||||
let error = headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&oversized), 2).unwrap_err();
|
||||
assert!(error.contains("GPU buffer limit"), "{error}");
|
||||
|
||||
headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]);
|
||||
let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None };
|
||||
let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared");
|
||||
let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background");
|
||||
assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible");
|
||||
headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 3).unwrap();
|
||||
let recovered = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_recovered");
|
||||
assert_ne!(recovered.px, background.px, "a later valid high poly still draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_low_poly_visibility_also_filters_its_wireframe() {
|
||||
let Some((mut headless, frame)) = setup() else { return };
|
||||
|
||||
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None };
|
||||
let hidden = shaded(&frame, |shade| {
|
||||
shade.bake = Some(bake);
|
||||
shade.wireframe_3d = true;
|
||||
shade.highlight = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] });
|
||||
});
|
||||
let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_wire_background");
|
||||
let hidden_wire = render(&mut headless, &hidden, "bake_wire_hidden");
|
||||
assert_same(&hidden_wire, &background, "hiding the project mesh also hides its wireframe and highlight");
|
||||
|
||||
for texture_set in [0, 1] {
|
||||
let selected = shaded(&hidden, |shade| {
|
||||
shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake });
|
||||
shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] });
|
||||
});
|
||||
let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() };
|
||||
let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}"));
|
||||
let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}"));
|
||||
assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ortho_background_matches_perspective() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
@@ -15,6 +15,8 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"]
|
||||
egui = { workspace = true }
|
||||
craft-ui = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
craft-keymap = { workspace = true }
|
||||
craft-quit = { workspace = true }
|
||||
egui-phosphor = { version = "0.14", features = ["regular", "fill"] }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -22,7 +24,6 @@ rayon = { workspace = true }
|
||||
log = { workspace = true }
|
||||
base64 = "0.22"
|
||||
image = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
# The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`).
|
||||
@@ -30,6 +31,10 @@ zip = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
# Floating panels open as OS windows.
|
||||
craft-ui = { workspace = true, features = ["native-windows"] }
|
||||
# Help > Check for Updates and the check at start (updates_ui.rs).
|
||||
craft-update = { workspace = true }
|
||||
# Native file dialogs (file_dialogs.rs); the browser build has none.
|
||||
craft-dialogs = { workspace = true }
|
||||
|
||||
# build.rs: the interface faces lose their Private Use Area, where the icon font draws (the
|
||||
# versions craft-libs' craft-fonts-build subsets with).
|
||||
@@ -39,6 +44,7 @@ skrifa = { version = "0.48", default-features = false, features = ["std"] }
|
||||
|
||||
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use crate::RunningBake;
|
||||
|
||||
/// A background bake of one or more texture sets.
|
||||
pub struct BakeJob {
|
||||
pub queue: Vec<usize>,
|
||||
pub current: Option<RunningBake>,
|
||||
pub total: usize,
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use egui::collapsing_header::CollapsingState;
|
||||
use egui::{Rect, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{icon_button_without_tooltip, section_chevron};
|
||||
|
||||
/// The panel's width and its gap from the 3D view's top-left corner
|
||||
const PANEL_WIDTH: f32 = 280.0;
|
||||
const PANEL_MARGIN: f32 = 12.0;
|
||||
|
||||
/// Size of the panel's eye buttons
|
||||
const EYE_BUTTON_SIZE: f32 = 22.0;
|
||||
|
||||
/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view`
|
||||
pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) {
|
||||
let toggles = &mut app.ui.bake_visualization;
|
||||
egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show(
|
||||
ui.ctx(),
|
||||
|ui| {
|
||||
ui.set_width(PANEL_WIDTH);
|
||||
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true);
|
||||
let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open()));
|
||||
if header.clicked() {
|
||||
collapsing_state.toggle(ui);
|
||||
}
|
||||
|
||||
collapsing_state.show_body_unindented(ui, |ui| {
|
||||
ui.add_enabled_ui(toggles.on, |ui| {
|
||||
ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
|
||||
eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None);
|
||||
eye_row(ui, &mut toggles.cage, tr("Cage"), None);
|
||||
eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None);
|
||||
eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response
|
||||
fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option<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()));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() {
|
||||
*shown = !*shown;
|
||||
}
|
||||
});
|
||||
response
|
||||
})
|
||||
.inner
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use texturecraft_render::BakeVisualization;
|
||||
|
||||
/// The Baking Visualization panel's switches in bake mode's 3D view
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct BakeVisualizationToggles {
|
||||
/// The panel's eye: the whole visualization on or off
|
||||
pub on: bool,
|
||||
pub selected_set_only: bool,
|
||||
pub high_poly: bool,
|
||||
pub cage: bool,
|
||||
pub uv_seams: bool,
|
||||
pub low_poly: bool,
|
||||
}
|
||||
|
||||
impl Default for BakeVisualizationToggles {
|
||||
fn default() -> Self {
|
||||
Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl BakeVisualizationToggles {
|
||||
/// What the renderer draws with these switches while texture set `selected_set` is selected
|
||||
pub fn visualization(&self, selected_set: usize) -> Option<BakeVisualization> {
|
||||
self.on.then_some(BakeVisualization {
|
||||
high_poly: self.high_poly,
|
||||
cage: self.cage,
|
||||
uv_seams: self.uv_seams,
|
||||
low_poly: self.low_poly,
|
||||
only_set: self.selected_set_only.then_some(selected_set),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
//! Bake Mode presentation; persisted settings live in core and edits use engine commands
|
||||
|
||||
mod bake_paint_brush;
|
||||
mod bake_visualization_panel;
|
||||
mod bake_visualization_toggles;
|
||||
mod breadcrumb;
|
||||
mod common_settings;
|
||||
pub use bake_paint_brush::BakePaintBrush;
|
||||
pub(crate) use bake_visualization_panel::bake_visualization_panel;
|
||||
pub use bake_visualization_toggles::BakeVisualizationToggles;
|
||||
mod controls;
|
||||
mod map_settings;
|
||||
mod mesh_map_bakers;
|
||||
@@ -180,16 +184,64 @@ fn edit_settings(
|
||||
app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch }));
|
||||
}
|
||||
|
||||
/// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material
|
||||
fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
use texturecraft_engine::PreviewShow;
|
||||
|
||||
let Some(preview) = app.session.bake_preview.as_ref() else { return };
|
||||
|
||||
let show = preview.show;
|
||||
|
||||
// Finished maps of the set baking now can be pinned; the others are still neutral
|
||||
let rows: Vec<(BakedMap, bool)> =
|
||||
preview.current_set().map(|set| set.order.iter().map(|&map| (map, set.baked.maps.contains_key(&map))).collect()).unwrap_or_default();
|
||||
let text = match show {
|
||||
PreviewShow::Follow => tr("Follow Newest Map").to_owned(),
|
||||
PreviewShow::Material => tr("Material").to_owned(),
|
||||
PreviewShow::Pin(map) => trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]),
|
||||
};
|
||||
|
||||
let mut choice = None;
|
||||
egui::ComboBox::from_id_salt("bake_preview_show")
|
||||
.selected_text(text)
|
||||
.show_ui(ui, |ui| {
|
||||
if ui.selectable_label(show == PreviewShow::Follow, tr("Follow Newest Map")).clicked() {
|
||||
choice = Some(PreviewShow::Follow);
|
||||
}
|
||||
for (map, done) in rows {
|
||||
let label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]);
|
||||
if ui.add_enabled(done, egui::Button::selectable(show == PreviewShow::Pin(map), label)).clicked() {
|
||||
choice = Some(PreviewShow::Pin(map));
|
||||
}
|
||||
}
|
||||
if ui.selectable_label(show == PreviewShow::Material, tr("Material")).clicked() {
|
||||
choice = Some(PreviewShow::Material);
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
));
|
||||
|
||||
if let Some(show) = choice {
|
||||
app.run("bake.preview", json!({ "show": show.id() }));
|
||||
}
|
||||
}
|
||||
|
||||
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| {
|
||||
if let Some(status) = app.bake_status() {
|
||||
ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong()));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(progress) = app.bake_progress() {
|
||||
ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage());
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
app.cancel_bake();
|
||||
}
|
||||
preview_control(app, ui);
|
||||
} else {
|
||||
let texture_sets: Vec<usize> = app
|
||||
.session
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session
|
||||
|
||||
mod bake_scene_link;
|
||||
mod cage_link;
|
||||
mod cage_shell_key;
|
||||
mod cage_upload;
|
||||
mod reach_link;
|
||||
mod shared_handle;
|
||||
|
||||
pub use bake_scene_link::BakeSceneLink;
|
||||
pub use cage_upload::CageUpload;
|
||||
@@ -0,0 +1,239 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::geom::Mesh;
|
||||
use texturecraft_render::BakeVisualization;
|
||||
|
||||
use super::CageUpload;
|
||||
use super::cage_link::CageLink;
|
||||
use super::cage_shell_key::CageShellKey;
|
||||
use super::reach_link::ReachLink;
|
||||
use super::shared_handle::SharedHandle;
|
||||
use crate::gpu::SceneSync;
|
||||
|
||||
/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams
|
||||
#[derive(Default)]
|
||||
pub struct BakeSceneLink {
|
||||
/// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one)
|
||||
high: SharedHandle<Mesh>,
|
||||
high_id: u64,
|
||||
/// Whether the GPU has the high poly (a lost frame sends it again under the same id)
|
||||
high_sent: bool,
|
||||
cages: Vec<Option<CageLink>>,
|
||||
/// How many texture sets' cages the GPU was last told to keep
|
||||
sent_cage_count: Option<usize>,
|
||||
/// The low-poly mesh whose seams are uploaded
|
||||
seams_mesh_id: Option<u64>,
|
||||
next_topology: u64,
|
||||
reach: ReachLink,
|
||||
}
|
||||
|
||||
impl BakeSceneLink {
|
||||
/// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay
|
||||
pub fn resend(&mut self) {
|
||||
self.high_sent = false;
|
||||
self.sent_cage_count = None;
|
||||
self.seams_mesh_id = None;
|
||||
for link in self.cages.iter_mut().flatten() {
|
||||
link.max_frontal = f32::NAN;
|
||||
}
|
||||
self.reach.resend();
|
||||
}
|
||||
|
||||
/// Whether something is still being worked out off the UI thread
|
||||
pub fn busy(&self) -> bool {
|
||||
self.reach.busy()
|
||||
}
|
||||
|
||||
/// Add to `out` what the GPU needs to draw `visualization` this frame
|
||||
pub fn sync(&mut self, session: &Session, visualization: Option<BakeVisualization>, out: &mut SceneSync) {
|
||||
self.reach.poll();
|
||||
|
||||
let Some(visualization) = visualization else { return };
|
||||
|
||||
if visualization.high_poly {
|
||||
let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone());
|
||||
let handle = SharedHandle::of(high.as_ref());
|
||||
if handle != self.high {
|
||||
self.high = handle;
|
||||
self.high_id += 1;
|
||||
self.high_sent = false;
|
||||
}
|
||||
if !self.high_sent {
|
||||
out.bake_high = Some((high, self.high_id));
|
||||
self.high_sent = true;
|
||||
}
|
||||
self.reach.sync(session, self.high_id, visualization.only_set, out);
|
||||
}
|
||||
|
||||
if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) {
|
||||
self.seams_mesh_id = Some(session.mesh_id);
|
||||
out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges()));
|
||||
}
|
||||
|
||||
if visualization.cage {
|
||||
self.sync_cages(session, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the cages whose inputs changed and move the corners of those whose distance changed
|
||||
fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) {
|
||||
let set_count = session.doc.project.texture_sets.len();
|
||||
if self.sent_cage_count != Some(set_count) {
|
||||
out.bake_cage_count = Some(set_count);
|
||||
self.sent_cage_count = Some(set_count);
|
||||
}
|
||||
self.cages.truncate(set_count);
|
||||
self.cages.resize_with(set_count, || None);
|
||||
|
||||
for (texture_set, link) in self.cages.iter_mut().enumerate() {
|
||||
let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue };
|
||||
|
||||
let max_frontal = set.bake.cage.max_frontal;
|
||||
match link {
|
||||
Some(link) if link.key == key => {
|
||||
if link.max_frontal == max_frontal {
|
||||
continue;
|
||||
}
|
||||
link.max_frontal = max_frontal;
|
||||
}
|
||||
_ => {
|
||||
self.next_topology += 1;
|
||||
let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new);
|
||||
*link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal });
|
||||
}
|
||||
}
|
||||
|
||||
let Some(link) = link.as_ref() else { continue };
|
||||
|
||||
let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() });
|
||||
out.bake_cages.push((texture_set, upload, link.topology));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None };
|
||||
|
||||
/// How long a test waits for the reach worker: frames, and the pause between them
|
||||
const WAIT_FRAMES: usize = 2000;
|
||||
const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5);
|
||||
|
||||
/// The sample project with a high poly a little outside its low poly
|
||||
fn session() -> Session {
|
||||
const HIGH_POLY_OFFSET: f32 = 0.02;
|
||||
|
||||
let mut session = texturecraft_engine::sample_session(128, 128).unwrap();
|
||||
let low = session.mesh.clone();
|
||||
let mut obj = String::new();
|
||||
for (position, normal) in low.positions.iter().zip(&low.normals) {
|
||||
let raised = *position + *normal * HIGH_POLY_OFFSET;
|
||||
obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z);
|
||||
}
|
||||
for corners in low.indices.chunks(3) {
|
||||
obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1);
|
||||
}
|
||||
session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap();
|
||||
session
|
||||
}
|
||||
|
||||
fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync {
|
||||
let mut out = SceneSync::default();
|
||||
link.sync(session, Some(visualization), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red
|
||||
fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 {
|
||||
for _ in 0..WAIT_FRAMES {
|
||||
if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed {
|
||||
return missed.iter().sum::<f32>() / missed.len().max(1) as f32;
|
||||
}
|
||||
std::thread::sleep(WAIT_FRAME_PAUSE);
|
||||
}
|
||||
panic!("the reach never arrived");
|
||||
}
|
||||
|
||||
fn set_distances(session: &mut Session, max_frontal: f32) {
|
||||
texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() {
|
||||
let (mut session, mut link) = (session(), BakeSceneLink::default());
|
||||
let first = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len()));
|
||||
let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
|
||||
|
||||
let unchanged = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent");
|
||||
|
||||
set_distances(&mut session, 0.03);
|
||||
let moved = sync(&mut link, &session, EVERYTHING);
|
||||
let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
|
||||
assert_eq!(moved_topology, topology, "a distance only moves the corners");
|
||||
assert_ne!(moved_cage.corners, cage.corners);
|
||||
|
||||
texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap();
|
||||
let rebuilt = sync(&mut link, &session, EVERYTHING);
|
||||
assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage");
|
||||
// The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts
|
||||
red_share(&mut link, &session, EVERYTHING);
|
||||
|
||||
link.resend();
|
||||
let resent = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again");
|
||||
assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len());
|
||||
assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame");
|
||||
assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id");
|
||||
assert!(!link.busy(), "a lost frame doesn't work out the reach again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reach_finishes_while_nothing_is_drawn() {
|
||||
let session = session();
|
||||
let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING };
|
||||
for hidden in [None, Some(no_high_poly)] {
|
||||
let mut link = BakeSceneLink::default();
|
||||
sync(&mut link, &session, EVERYTHING);
|
||||
assert!(link.busy(), "the first frame starts working out the reach");
|
||||
|
||||
let finished = (0..WAIT_FRAMES).any(|_| {
|
||||
std::thread::sleep(WAIT_FRAME_PAUSE);
|
||||
link.sync(&session, hidden, &mut SceneSync::default());
|
||||
!link.busy()
|
||||
});
|
||||
assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_red_follows_the_distances_and_the_selected_set() {
|
||||
let (mut session, mut link) = (session(), BakeSceneLink::default());
|
||||
set_distances(&mut session, 0.0);
|
||||
let at_zero = red_share(&mut link, &session, EVERYTHING);
|
||||
assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}");
|
||||
|
||||
set_distances(&mut session, 0.05);
|
||||
let covered = red_share(&mut link, &session, EVERYTHING);
|
||||
assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}");
|
||||
|
||||
set_distances(&mut session, 0.0);
|
||||
let by_name = |session: &mut Session, low_suffix: &str| {
|
||||
for set in &mut session.doc.project.texture_sets {
|
||||
set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName;
|
||||
set.bake.high_poly.low_suffix = low_suffix.into();
|
||||
}
|
||||
};
|
||||
by_name(&mut session, "_no_such_suffix");
|
||||
let by_name_red = red_share(&mut link, &session, EVERYTHING);
|
||||
assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}");
|
||||
|
||||
let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING };
|
||||
assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_engine::bake::CageShell;
|
||||
|
||||
use super::cage_shell_key::CageShellKey;
|
||||
|
||||
/// A texture set's cage as the GPU has it
|
||||
pub(super) struct CageLink {
|
||||
pub(super) key: CageShellKey,
|
||||
/// `None`: the set bakes without a high poly or its cage can't be built
|
||||
pub(super) shell: Option<Arc<CageShell>>,
|
||||
/// The renderer's name for the shell's corner order and edges
|
||||
pub(super) topology: u64,
|
||||
/// The max frontal distance the GPU's corners are at
|
||||
pub(super) max_frontal: f32,
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::bake::BakePaintMap;
|
||||
use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings};
|
||||
use texturecraft_engine::geom::Mesh;
|
||||
|
||||
use super::shared_handle::SharedHandle;
|
||||
|
||||
/// Everything a texture set's cage shell is built from except the distances, which only move its corners
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct CageShellKey {
|
||||
mesh_id: u64,
|
||||
high: SharedHandle<Mesh>,
|
||||
cage_file: SharedHandle<Mesh>,
|
||||
material: usize,
|
||||
uv_tiles: Vec<u32>,
|
||||
tile_resolutions: BTreeMap<u32, u32>,
|
||||
cage_kind: CageType,
|
||||
relative_to_bounding_box: bool,
|
||||
average_normals: bool,
|
||||
use_low_as_high: bool,
|
||||
skew: SkewSettings,
|
||||
/// The painted skew and cage maps
|
||||
paint: [SharedHandle<BakePaintMap>; 2],
|
||||
}
|
||||
|
||||
impl CageShellKey {
|
||||
pub(super) fn of(session: &Session, texture_set: usize) -> Option<CageShellKey> {
|
||||
let set = session.doc.project.texture_sets.get(texture_set)?;
|
||||
let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target)));
|
||||
Some(CageShellKey {
|
||||
mesh_id: session.mesh_id,
|
||||
high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)),
|
||||
cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)),
|
||||
material: set.material,
|
||||
uv_tiles: set.uv_tiles.clone(),
|
||||
tile_resolutions: set.tile_resolutions.clone(),
|
||||
cage_kind: set.bake.cage.kind,
|
||||
relative_to_bounding_box: set.bake.cage.relative_to_bounding_box,
|
||||
average_normals: set.bake.cage.average_normals,
|
||||
use_low_as_high: set.bake.high_poly.use_low_as_high,
|
||||
skew: set.bake.skew,
|
||||
paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)],
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_engine::bake::CageShell;
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
|
||||
/// A texture set's cage for the GPU: its corners at the current distance and the shell they come from
|
||||
pub struct CageUpload {
|
||||
pub corners: Vec<Vec3>,
|
||||
pub shell: Arc<CageShell>,
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::bake::{HighPolyReach, high_poly_missed};
|
||||
use texturecraft_engine::core::HighPolySettings;
|
||||
|
||||
use super::cage_shell_key::CageShellKey;
|
||||
use crate::gpu::SceneSync;
|
||||
|
||||
/// Each set's (max frontal, max rear) and the selected-set filter
|
||||
type ShownDistances = (Vec<(f32, f32)>, Option<usize>);
|
||||
|
||||
/// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show
|
||||
#[derive(Default)]
|
||||
pub(super) struct ReachLink {
|
||||
/// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for
|
||||
keys: Vec<Option<(CageShellKey, HighPolySettings)>>,
|
||||
high_id: u64,
|
||||
job: Option<Receiver<Vec<Option<HighPolyReach>>>>,
|
||||
reach: Vec<Option<HighPolyReach>>,
|
||||
/// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for
|
||||
shown: Option<ShownDistances>,
|
||||
}
|
||||
|
||||
impl ReachLink {
|
||||
/// Whether a reach is being worked out (the view must keep drawing to pick it up)
|
||||
pub(super) fn busy(&self) -> bool {
|
||||
self.job.is_some()
|
||||
}
|
||||
|
||||
/// Send the colors again (the GPU lost what it was sent); the reach itself stays
|
||||
pub(super) fn resend(&mut self) {
|
||||
self.shown = None;
|
||||
}
|
||||
|
||||
/// Pick up the reach once the worker finishes; runs every frame, even when nothing is drawn, so `busy` clears
|
||||
pub(super) fn poll(&mut self) {
|
||||
let Some(job) = &self.job else { return };
|
||||
|
||||
match job.try_recv() {
|
||||
Ok(reach) => {
|
||||
self.reach = reach;
|
||||
self.shown = None;
|
||||
self.job = None;
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => self.job = None,
|
||||
Err(TryRecvError::Empty) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed
|
||||
pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option<usize>, out: &mut SceneSync) {
|
||||
// Coalesce paint edits while a worker runs; after polling it, the next job captures the latest inputs
|
||||
if self.job.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let set_count = session.doc.project.texture_sets.len();
|
||||
let keys: Vec<Option<(CageShellKey, HighPolySettings)>> = session
|
||||
.doc
|
||||
.project
|
||||
.texture_sets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone())))
|
||||
.collect();
|
||||
if keys != self.keys || high_id != self.high_id {
|
||||
let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect();
|
||||
self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || {
|
||||
inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect()
|
||||
}));
|
||||
(self.keys, self.high_id) = (keys, high_id);
|
||||
}
|
||||
|
||||
// Colors wait for the reach being worked out: the old ones stay until it arrives
|
||||
if self.job.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let distances: Vec<(f32, f32)> = session.doc.project.texture_sets.iter().map(|set| (set.bake.cage.max_frontal, set.bake.cage.max_rear)).collect();
|
||||
let shown = (distances, only_set);
|
||||
if self.shown.as_ref() == Some(&shown) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return };
|
||||
|
||||
out.bake_high_missed = Some((self.high_id, high_poly_missed(&self.reach, &shown.0, only_set, vertex_count)));
|
||||
self.shown = Some(shown);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
use texturecraft_engine::bake::BakePaintMap;
|
||||
use texturecraft_engine::core::BakePaintTarget;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
|
||||
#[test]
|
||||
fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() {
|
||||
let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap();
|
||||
session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let mut link = ReachLink { job: Some(receiver), ..Default::default() };
|
||||
|
||||
// Hold the original job open while paint and mesh inputs change
|
||||
for amount in [0.25, 0.5, 0.75] {
|
||||
session.doc.bake_paint.insert((0, BakePaintTarget::Cage), Arc::new(BakePaintMap::constant(amount)));
|
||||
let mut out = SceneSync::default();
|
||||
link.sync(&session, 2, None, &mut out);
|
||||
assert!(out.bake_high_missed.is_none());
|
||||
}
|
||||
assert!(sender.send(Vec::new()).is_ok(), "input changes must keep the running job's receiver");
|
||||
link.poll();
|
||||
|
||||
// The finished job is stale: a new job must capture the latest settings before sending colors
|
||||
session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true;
|
||||
let mut out = SceneSync::default();
|
||||
link.sync(&session, 2, None, &mut out);
|
||||
assert!(link.busy());
|
||||
assert!(out.bake_high_missed.is_none());
|
||||
|
||||
for _ in 0..2000 {
|
||||
link.poll();
|
||||
if !link.busy() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(!link.busy(), "the latest reach must finish");
|
||||
link.sync(&session, 2, None, &mut out);
|
||||
let (high_id, missed) = out.bake_high_missed.unwrap();
|
||||
assert_eq!(high_id, 2);
|
||||
assert_eq!(missed, vec![0.0; session.bake_meshes.merged_high().unwrap().mesh.positions.len()]);
|
||||
assert!(link.reach[0].is_none(), "the latest setting bakes without a high poly");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
/// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it
|
||||
#[derive(Debug)]
|
||||
pub(super) struct SharedHandle<T>(Option<Weak<T>>);
|
||||
|
||||
impl<T> SharedHandle<T> {
|
||||
pub(super) fn of(value: Option<&Arc<T>>) -> SharedHandle<T> {
|
||||
SharedHandle(value.map(Arc::downgrade))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for SharedHandle<T> {
|
||||
fn clone(&self) -> Self {
|
||||
SharedHandle(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for SharedHandle<T> {
|
||||
fn default() -> Self {
|
||||
SharedHandle(None)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq for SharedHandle<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (&self.0, &other.0) {
|
||||
(Some(this), Some(other)) => Weak::ptr_eq(this, other),
|
||||
(this, other) => this.is_none() && other.is_none(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Properties of a color selection effect: tolerance and the ID colors it selects
|
||||
|
||||
use egui::{Color32, RichText, Sense, Stroke, Ui, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::{BakedMap, LayerId};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::id_color_pick::IdColorPick;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{icon_button, slider_edit};
|
||||
|
||||
/// Width of one R, G or B readout, so the columns line up from row to row (fits "G: 255")
|
||||
const READOUT_WIDTH: f32 = 50.0;
|
||||
|
||||
/// Height of a color row's swatch and readouts, as tall as the app's other swatches
|
||||
const ROW_HEIGHT: f32 = 18.0;
|
||||
|
||||
const SWATCH_WIDTH: f32 = 36.0;
|
||||
|
||||
const ROW_BUTTON_SIZE: f32 = 20.0;
|
||||
|
||||
/// Tolerance, a Colors list with a pick mode, and one row per ID color (swatch, re-pick, R/G/B, remove)
|
||||
pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, colors: &[[f32; 3]], tolerance: f32) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let mut edited_tolerance = tolerance;
|
||||
if let Some(merge) = slider_edit(ui, tr("Tolerance"), &mut edited_tolerance, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": effect.0, "tolerance": edited_tolerance, "merge": merge}));
|
||||
}
|
||||
|
||||
let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index);
|
||||
let has_id_map = app.session.baked(set_index).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Id));
|
||||
if !has_id_map {
|
||||
ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (F8) to pick colors from the mesh."))).color(tokens.warning));
|
||||
}
|
||||
|
||||
let picking = app.picking_id_color.filter(|pick| pick.effect == effect);
|
||||
ui.group(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Colors"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let adding = picking.is_some_and(|pick| pick.index.is_none());
|
||||
let button = egui::Button::new(format!("{} {}", ic::EYEDROPPER, tr("Pick color"))).selected(adding);
|
||||
if ui.add_enabled(has_id_map, button).clicked() {
|
||||
toggle_pick(app, effect, None, adding);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
for (index, color) in colors.iter().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
id_swatch(ui, *color);
|
||||
let repicking = picking.is_some_and(|pick| pick.index == Some(index));
|
||||
let repick = ui.add_enabled_ui(has_id_map, |ui| icon_button(ui, ic::EYEDROPPER, tr("Pick color"), repicking, ROW_BUTTON_SIZE)).inner;
|
||||
if repick.clicked() {
|
||||
toggle_pick(app, effect, Some(index), repicking);
|
||||
}
|
||||
|
||||
for (channel, value) in ["R", "G", "B"].iter().zip(display_bytes(*color)) {
|
||||
ui.allocate_ui_with_layout(vec2(READOUT_WIDTH, ROW_HEIGHT), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_min_width(READOUT_WIDTH);
|
||||
ui.label(format!("{channel}: {value}"));
|
||||
});
|
||||
}
|
||||
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let remove = ui.add_enabled_ui(colors.len() > 1, |ui| icon_button(ui, ic::MINUS, tr("Remove"), false, ROW_BUTTON_SIZE)).inner;
|
||||
if remove.clicked() {
|
||||
// Removing a row changes the indices of pending replacements
|
||||
IdColorPick::end(app);
|
||||
let remaining: Vec<[f32; 3]> = colors.iter().enumerate().filter(|(kept, _)| *kept != index).map(|(_, kept)| *kept).collect();
|
||||
app.run("effect.set", json!({"effect": effect.0, "colors": remaining}));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The layer whose mask holds `effect`
|
||||
fn effect_owner(app: &TextureCraftApp, effect: LayerId) -> LayerId {
|
||||
app.session.doc.project.effect(effect).map_or(effect, |(owner, _)| owner)
|
||||
}
|
||||
|
||||
fn toggle_pick(app: &mut TextureCraftApp, effect: LayerId, index: Option<usize>, running: bool) {
|
||||
if running {
|
||||
IdColorPick::end(app);
|
||||
} else {
|
||||
IdColorPick::start(app, effect, index);
|
||||
}
|
||||
}
|
||||
|
||||
/// An ID color as the ID map view draws it: the stored value, unconverted, in 0–255
|
||||
fn display_bytes(color: [f32; 3]) -> [u8; 3] {
|
||||
color.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8)
|
||||
}
|
||||
|
||||
fn id_swatch(ui: &mut Ui, color: [f32; 3]) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let [red, green, blue] = display_bytes(color);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(SWATCH_WIDTH, ROW_HEIGHT), Sense::hover());
|
||||
ui.painter().rect(rect, f32::from(tokens.radius), Color32::from_rgb(red, green, blue), Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside);
|
||||
}
|
||||
@@ -110,9 +110,46 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &
|
||||
"uiMs": app.ui_ms,
|
||||
"titleBar": app.title_bar.name(),
|
||||
"baking": app.bake_progress(),
|
||||
"bakeStatus": app.bake_status(),
|
||||
"bakePreview": texturecraft_engine::bake_preview::preview_json(&app.session),
|
||||
"toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
"ui.bake.start" => {
|
||||
// Bake in the background like the Bake button: the 3D view shows the maps as they finish
|
||||
let count = app.session.doc.project.texture_sets.len();
|
||||
let sets: Vec<usize> = match p.get("ts") {
|
||||
Some(value) => match serde_json::from_value::<Vec<usize>>(if value.is_array() { value.clone() } else { json!([value]) }) {
|
||||
Ok(list) if list.iter().all(|&index| index < count) => list,
|
||||
_ => return err(format!("`ts` must be texture set indices below {count}")),
|
||||
},
|
||||
None => app
|
||||
.session
|
||||
.doc
|
||||
.project
|
||||
.texture_sets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, texture_set)| texture_set.bake.common.is_enabled)
|
||||
.map(|(index, _)| index)
|
||||
.collect(),
|
||||
};
|
||||
if app.bake.is_some() {
|
||||
return err("a bake is already running");
|
||||
}
|
||||
|
||||
if sets.is_empty() {
|
||||
return err("no texture set to bake: tick one in Bake mode or pass `ts`");
|
||||
}
|
||||
|
||||
app.ui.mode = crate::state::Mode::Baking;
|
||||
app.start_bake(sets);
|
||||
ok(texturecraft_engine::bake_preview::preview_json(&app.session))
|
||||
}
|
||||
"ui.bake.cancel" => {
|
||||
app.cancel_bake();
|
||||
ok(Value::Null)
|
||||
}
|
||||
"ui.menu.list" => ok(json!(
|
||||
crate::menus::CATALOG
|
||||
.iter()
|
||||
|
||||
@@ -2112,6 +2112,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
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),
|
||||
other => {
|
||||
ui.label(RichText::new(tr(other.name())).color(tk.text_dim));
|
||||
}
|
||||
|
||||
@@ -388,6 +388,17 @@ fn style(ui: &Ui, t: &Tokens) -> DockStyle {
|
||||
s
|
||||
}
|
||||
|
||||
/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included,
|
||||
/// do not take it.
|
||||
pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> bool {
|
||||
let modal = context.memory(|memory| memory.top_modal_layer()).is_some();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let modal = modal || crate::updates_ui::blocks_input(app);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = app;
|
||||
modal
|
||||
}
|
||||
|
||||
/// Draw the dock (viewport and panels) into `ui`.
|
||||
pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
for panel in Panel::ALL {
|
||||
@@ -400,7 +411,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tokens = Tokens::get(&context);
|
||||
let style = style(ui, &tokens);
|
||||
let layout = app.ui.dock.workspace.layout.clone();
|
||||
let mut area = DockArea::new(area_id()).input_blocked(context.memory(|memory| memory.top_modal_layer()).is_some());
|
||||
let mut area = DockArea::new(area_id()).input_blocked(input_blocked(app, &context));
|
||||
if let Some(panel) = app.ui.dock.raise.take() {
|
||||
area = area.raise_panel(panel);
|
||||
}
|
||||
|
||||
@@ -341,11 +341,14 @@ pub fn import(app: &mut TextureCraftApp, preset: &ExportPreset) {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import_file(app: &mut TextureCraftApp, _ctx: &egui::Context) {
|
||||
let Some(path) = rfd::FileDialog::new().add_filter(tr("Export template"), &["json"]).pick_file() else { return };
|
||||
match texturecraft_engine::formats::load_preset(&path) {
|
||||
Ok(p) => import(app, &p),
|
||||
Err(e) => app.toast(trf("Couldn't import {name}: {error}", &[("name", &path.display()), ("error", &e)]), true),
|
||||
}
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
app.ask_file(FileDialog::open().filter(tr("Export template"), &["json"]), Bound::App, |app, paths| {
|
||||
let Some(path) = paths.first() else { return };
|
||||
match texturecraft_engine::formats::load_preset(path) {
|
||||
Ok(p) => import(app, &p),
|
||||
Err(e) => app.toast(trf("Couldn't import {name}: {error}", &[("name", &path.display()), ("error", &e)]), true),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -356,26 +359,43 @@ fn import_file(_app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
fn export_file(app: &mut TextureCraftApp) {
|
||||
let Some(p) = selected(app) else { return };
|
||||
let name = format!("{}.json", sanitize_file_stem(&p.name));
|
||||
let saved = texturecraft_engine::formats::preset_to_json(&p).map_err(|e| e.to_string()).and_then(|json| write_json(&name, &json));
|
||||
match saved {
|
||||
Ok(Some(to)) => app.toast(trf("Exported template \"{name}\" to {path}", &[("name", &p.name), ("path", &to)]), false),
|
||||
Ok(None) => {}
|
||||
Err(e) => app.toast(trf("Couldn't export the template: {error}", &[("error", &e)]), true),
|
||||
}
|
||||
let json = match texturecraft_engine::formats::preset_to_json(&p) {
|
||||
Ok(json) => json,
|
||||
Err(e) => {
|
||||
export_failed(app, &e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
write_json(app, p.name, name, json);
|
||||
}
|
||||
|
||||
/// Save `json` with the native dialog (Ok(None): cancelled).
|
||||
fn export_failed(app: &mut TextureCraftApp, error: &dyn std::fmt::Display) {
|
||||
app.toast(trf("Couldn't export the template: {error}", &[("error", error)]), true);
|
||||
}
|
||||
|
||||
fn exported(app: &mut TextureCraftApp, name: &str, to: &str) {
|
||||
app.toast(trf("Exported template \"{name}\" to {path}", &[("name", &name), ("path", &to)]), false);
|
||||
}
|
||||
|
||||
/// Asks where to save `json` with the native dialog.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_json(name: &str, json: &str) -> Result<Option<String>, String> {
|
||||
let Some(path) = rfd::FileDialog::new().add_filter(tr("Export template"), &["json"]).set_file_name(name).save_file() else { return Ok(None) };
|
||||
std::fs::write(&path, json).map_err(|e| e.to_string())?;
|
||||
Ok(Some(path.display().to_string()))
|
||||
fn write_json(app: &mut TextureCraftApp, preset: String, name: String, json: String) {
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
app.ask_file(FileDialog::save().filter(tr("Export template"), &["json"]).file_name(name), Bound::App, move |app, paths| {
|
||||
let Some(path) = paths.first() else { return };
|
||||
match std::fs::write(path, &json) {
|
||||
Ok(()) => exported(app, &preset, &path.display().to_string()),
|
||||
Err(e) => export_failed(app, &e),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_json(name: &str, json: &str) -> Result<Option<String>, String> {
|
||||
crate::web_files::download(name, json.as_bytes())?;
|
||||
Ok(Some(name.to_string()))
|
||||
fn write_json(app: &mut TextureCraftApp, preset: String, name: String, json: String) {
|
||||
match crate::web_files::download(&name, json.as_bytes()) {
|
||||
Ok(()) => exported(app, &preset, &name),
|
||||
Err(e) => export_failed(app, &e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the user's templates: the library folder on the desktop, the app storage on the web.
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Native file dialogs that never block the frame (craft-dialogs).
|
||||
//!
|
||||
//! An action that needs a path calls [`TextureCraftApp::ask_file`] and returns. The dialog shows at
|
||||
//! the end of the frame, and the continuation runs with the answer on a later frame. The browser
|
||||
//! build has no native dialogs (`web_files.rs`).
|
||||
|
||||
use std::panic::Location;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use craft_dialogs::{Answer, FileDialog, Override, Request};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// Whether an answer still needs the project that was open when the dialog was asked for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Bound {
|
||||
/// The continuation reads or changes the open project, and does not run on another one.
|
||||
Project,
|
||||
/// The continuation does not depend on the open project.
|
||||
App,
|
||||
}
|
||||
|
||||
/// What runs with the answer. The list is empty when nothing was chosen.
|
||||
type Then = Box<dyn FnOnce(&mut TextureCraftApp, Vec<PathBuf>)>;
|
||||
|
||||
/// Which dialog was asked for, for which project and by which code. Asking again with all three
|
||||
/// the same brings the open panel to the front instead of queuing a second one.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct AskKey {
|
||||
request: Request,
|
||||
project: Option<u64>,
|
||||
origin: &'static Location<'static>,
|
||||
}
|
||||
|
||||
/// A dialog's continuation.
|
||||
pub struct Asked {
|
||||
key: AskKey,
|
||||
then: Then,
|
||||
}
|
||||
|
||||
/// The app's dialogs and the requests not yet answered.
|
||||
pub struct FileDialogs {
|
||||
dialogs: craft_dialogs::Dialogs<Asked>,
|
||||
asked: Vec<AskKey>,
|
||||
}
|
||||
|
||||
impl FileDialogs {
|
||||
/// The dialogs of the app whose context is `ctx`: an answer wakes its event loop.
|
||||
pub fn new(ctx: egui::Context) -> FileDialogs {
|
||||
FileDialogs { dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())), asked: Vec::new() }
|
||||
}
|
||||
|
||||
/// Answers every request with `answer_with` instead of a native dialog (tests).
|
||||
pub fn set_override(&mut self, answer_with: Option<Override>) {
|
||||
self.dialogs.set_override(answer_with);
|
||||
}
|
||||
|
||||
/// Requests that have not been answered yet.
|
||||
pub fn pending(&self) -> usize {
|
||||
self.asked.len()
|
||||
}
|
||||
|
||||
/// Shows the next dialog asked for. Call at the end of every frame with the window.
|
||||
pub fn show_pending(&mut self, frame: &eframe::Frame) {
|
||||
self.dialogs.show_pending(Some(frame));
|
||||
}
|
||||
}
|
||||
|
||||
impl TextureCraftApp {
|
||||
/// Queues `dialog`. `then` runs on a later frame with the chosen paths, or with none after
|
||||
/// Cancel, after a dialog that could not be shown, and when `bound` is [`Bound::Project`] and
|
||||
/// another project has been opened since. Returns false, and drops `then`, when the same dialog
|
||||
/// is already showing or waiting.
|
||||
#[track_caller]
|
||||
pub(crate) fn ask_file(&mut self, dialog: FileDialog, bound: Bound, then: impl FnOnce(&mut TextureCraftApp, Vec<PathBuf>) + 'static) -> bool {
|
||||
let project = (bound == Bound::Project).then_some(self.session.project_id);
|
||||
let key = AskKey { request: Request::File(dialog.clone()), project, origin: Location::caller() };
|
||||
if self.file_dialogs.asked.contains(&key) {
|
||||
self.file_dialogs.dialogs.raise();
|
||||
return false;
|
||||
}
|
||||
self.file_dialogs.asked.push(key.clone());
|
||||
self.file_dialogs.dialogs.ask(dialog, Asked { key, then: Box::new(then) });
|
||||
true
|
||||
}
|
||||
|
||||
/// Runs the continuations of the dialogs that have answered.
|
||||
pub(crate) fn run_file_dialog_answers(&mut self) {
|
||||
for (asked, answer) in self.file_dialogs.dialogs.take_answers() {
|
||||
let Asked { key, then } = asked;
|
||||
if let Some(i) = self.file_dialogs.asked.iter().position(|k| *k == key) {
|
||||
self.file_dialogs.asked.remove(i);
|
||||
}
|
||||
let paths = match answer {
|
||||
Answer::Paths(paths) => paths,
|
||||
Answer::Unavailable(why) => {
|
||||
self.toast(trf("The file dialog couldn't be shown: {error}", &[("error", &why)]), true);
|
||||
Vec::new()
|
||||
}
|
||||
Answer::Cancelled | Answer::Message(_) => Vec::new(),
|
||||
};
|
||||
let moved_on = key.project.is_some_and(|project| project != self.session.project_id);
|
||||
if moved_on && !paths.is_empty() {
|
||||
self.toast(tr("The project changed while the dialog was open, so nothing was done"), true);
|
||||
}
|
||||
then(self, if moved_on { Vec::new() } else { paths });
|
||||
}
|
||||
}
|
||||
}
|
||||
+141
-74
@@ -11,7 +11,9 @@ use texturecraft_engine::Session;
|
||||
use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes};
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::Mesh;
|
||||
use texturecraft_render::{Frame, Renderer, wgpu};
|
||||
use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu};
|
||||
|
||||
use crate::bake_scene::{BakeSceneLink, CageUpload};
|
||||
|
||||
/// Content shown through the aux texture.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -25,6 +27,9 @@ pub enum AuxView {
|
||||
/// A texture set's texels across and down, and its mesh material.
|
||||
pub type SetLayout = ((u32, u32), usize);
|
||||
|
||||
/// The low poly's UV seam edges (vertex pairs) per material
|
||||
pub type UvSeamEdges = Vec<Vec<(u32, u32)>>;
|
||||
|
||||
/// What the renderer must catch up with before drawing.
|
||||
#[derive(Default)]
|
||||
pub struct SceneSync {
|
||||
@@ -36,6 +41,16 @@ pub struct SceneSync {
|
||||
pub env: Option<(String, Option<Arc<ImageRes>>)>,
|
||||
pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec<u8>)>,
|
||||
pub aux: Vec<(usize, u32, Vec<u8>)>,
|
||||
/// Bake mode's high poly (`None` removes it) and the id it is sent under
|
||||
pub bake_high: Option<(Option<Arc<Mesh>>, u64)>,
|
||||
/// Which vertices of the high poly (by its id) the bake's rays miss (1) or reach (0)
|
||||
pub bake_high_missed: Option<(u64, Vec<f32>)>,
|
||||
/// Changed cages: texture set, the cage or `None` to remove it, its topology
|
||||
pub bake_cages: Vec<(usize, Option<CageUpload>, u64)>,
|
||||
/// Texture sets left after some were removed: their cages go too
|
||||
pub bake_cage_count: Option<usize>,
|
||||
/// The low poly's UV seams per material, for mesh id
|
||||
pub uv_seams: Option<(u64, UvSeamEdges)>,
|
||||
}
|
||||
|
||||
/// Lives in egui's callback resources.
|
||||
@@ -78,6 +93,7 @@ pub struct GpuLink {
|
||||
pub adapter: String,
|
||||
/// Most tiles waiting to be composited since compositing last caught up (progress).
|
||||
composite_total: usize,
|
||||
bake_scene: BakeSceneLink,
|
||||
}
|
||||
|
||||
/// Compositing time per frame: a full recomposite of a large texture set spreads over frames.
|
||||
@@ -124,6 +140,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink {
|
||||
aux: BTreeMap::new(),
|
||||
adapter: format!("{} ({:?})", info.name, info.backend),
|
||||
composite_total: 0,
|
||||
bake_scene: BakeSceneLink::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,132 +150,157 @@ impl GpuLink {
|
||||
std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner))
|
||||
}
|
||||
|
||||
/// Collect everything the GPU needs this frame (runs the compositor first).
|
||||
/// Whether bake mode's visualization is still being worked out off the UI thread
|
||||
pub fn bake_busy(&self) -> bool {
|
||||
self.bake_scene.busy()
|
||||
}
|
||||
|
||||
/// Compositing progress (0..1) while tiles wait to be composited.
|
||||
pub fn composite_progress(&self, s: &Session) -> Option<f32> {
|
||||
let pending = s.pending_tiles();
|
||||
(pending > 0 && self.composite_total > 0).then(|| 1.0 - pending as f32 / self.composite_total as f32)
|
||||
}
|
||||
|
||||
/// `spent_ms`: time this frame already took before the sync.
|
||||
pub fn sync(&mut self, s: &mut Session, aux_map: Option<AuxView>, shift: u32, spent_ms: f64) -> SceneSync {
|
||||
let start = crate::now_ms();
|
||||
/// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took
|
||||
pub fn sync(&mut self, session: &mut Session, aux_map: Option<AuxView>, bake: Option<BakeVisualization>, shift: u32, spent_ms: f64) -> SceneSync {
|
||||
let start_ms = crate::now_ms();
|
||||
let mut queued = 0usize;
|
||||
let left = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start) - queued as f64 * UPLOAD_MS_PER_TILE;
|
||||
let pending = s.pending_tiles();
|
||||
let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE;
|
||||
let pending = session.pending_tiles();
|
||||
self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) };
|
||||
s.update_for(COMPOSITE_BUDGET_MS.min(left(0)).max(MIN_SLICE_MS), crate::now_ms);
|
||||
session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms);
|
||||
|
||||
let mut out = SceneSync::default();
|
||||
if self.lost.swap(false, Ordering::AcqRel) {
|
||||
self.mesh_id = 0;
|
||||
self.sets.clear();
|
||||
self.env = Default::default();
|
||||
self.bake_scene.resend();
|
||||
self.reset.store(true, Ordering::Release);
|
||||
}
|
||||
if self.mesh_id != s.mesh_id {
|
||||
out.mesh = Some((s.mesh.clone(), s.mesh_id));
|
||||
self.mesh_id = s.mesh_id;
|
||||
|
||||
if self.mesh_id != session.mesh_id {
|
||||
out.mesh = Some((session.mesh.clone(), session.mesh_id));
|
||||
self.mesh_id = session.mesh_id;
|
||||
self.aux.clear();
|
||||
}
|
||||
let sets: Vec<SetLayout> = s.doc.project.texture_sets.iter().map(|t| (t.size(), t.material)).collect();
|
||||
|
||||
let sets: Vec<SetLayout> = session.doc.project.texture_sets.iter().map(|texture_set| (texture_set.size(), texture_set.material)).collect();
|
||||
if sets != self.sets || shift != self.shift || out.mesh.is_some() {
|
||||
out.sets = Some((sets.clone(), s.mesh.materials.len().max(1), shift));
|
||||
out.sets = Some((sets.clone(), session.mesh.materials.len().max(1), shift));
|
||||
self.sets = sets;
|
||||
self.shift = shift;
|
||||
}
|
||||
let d = &s.doc.project.display;
|
||||
let image = d.environment_resource().and_then(|n| s.images.get(n));
|
||||
let ptr = image.map_or(0, |i| Arc::as_ptr(i) as usize);
|
||||
if self.env.0 != d.environment || self.env.1 != ptr {
|
||||
self.env = (d.environment.clone(), ptr);
|
||||
out.env = Some((d.environment.clone(), image.cloned()));
|
||||
|
||||
let display = &session.doc.project.display;
|
||||
let image = display.environment_resource().and_then(|name| session.images.get(name));
|
||||
let image_identity = image.map_or(0, |image| Arc::as_ptr(image) as usize);
|
||||
if self.env.0 != display.environment || self.env.1 != image_identity {
|
||||
self.env = (display.environment.clone(), image_identity);
|
||||
out.env = Some((display.environment.clone(), image.cloned()));
|
||||
}
|
||||
|
||||
if self.reset.swap(false, Ordering::AcqRel) {
|
||||
for c in &mut s.caches {
|
||||
c.upload.extend(texturecraft_engine::compose::all_tiles(c.size.0, c.size.1));
|
||||
for cache in &mut session.caches {
|
||||
cache.upload.extend(texturecraft_engine::compose::all_tiles(cache.size.0, cache.size.1));
|
||||
}
|
||||
self.aux.clear();
|
||||
}
|
||||
for ts in 0..s.caches.len() {
|
||||
let tiles = s.take_uploads(ts);
|
||||
|
||||
for texture_set in 0..session.caches.len() {
|
||||
let tiles = session.take_uploads(texture_set);
|
||||
if tiles.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut done = 0;
|
||||
if let Some(cache) = s.caches.get(ts) {
|
||||
if let Some(cache) = session.caches.get(texture_set) {
|
||||
let empty = Default::default();
|
||||
let baked = s.doc.baked.get(&ts).unwrap_or(&empty);
|
||||
let comp = &cache.composite;
|
||||
// In chunks while the frame has time (at least one chunk); the rest waits.
|
||||
let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty);
|
||||
let composite = &cache.composite;
|
||||
// In chunks while the frame has time (at least one chunk); the rest waits
|
||||
for chunk in tiles.chunks(UPLOAD_CHUNK) {
|
||||
let bytes: Vec<_> = chunk
|
||||
.par_iter()
|
||||
.flat_map_iter(|&(tx, ty)| DisplayKind::ALL.into_iter().map(move |k| (k, tx, ty)))
|
||||
.map(|(k, tx, ty)| (ts, k, tx, ty, tile_bytes(comp, baked, k, tx, ty)))
|
||||
.flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y)))
|
||||
.map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y)))
|
||||
.collect();
|
||||
queued += bytes.len();
|
||||
out.tiles.extend(bytes);
|
||||
done += chunk.len();
|
||||
if left(queued) < MIN_SLICE_MS {
|
||||
if time_left_ms(queued) < MIN_SLICE_MS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(rest), Some(cache)) = (tiles.get(done..), s.caches.get_mut(ts)) {
|
||||
if let (Some(rest), Some(cache)) = (tiles.get(done..), session.caches.get_mut(texture_set)) {
|
||||
cache.upload.extend(rest.iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
match aux_map {
|
||||
Some(AuxView::MeshMap(m)) => {
|
||||
for ts in 0..s.caches.len() {
|
||||
let rev = s.doc.baked.get(&ts).and_then(|b| b.maps.get(&m)).map(|d| Arc::as_ptr(d) as u64).unwrap_or(0);
|
||||
let key = (format!("{m:?}"), rev);
|
||||
if self.aux.get(&ts) == Some(&key) {
|
||||
Some(AuxView::MeshMap(map)) => {
|
||||
for texture_set in 0..session.caches.len() {
|
||||
// While a bake shows, its streamed maps (neutral where not baked yet) replace the document's
|
||||
let preview = session.bake_preview_baked(texture_set);
|
||||
let baked = preview.or_else(|| session.doc.baked.get(&texture_set));
|
||||
let have = baked.and_then(|baked| baked.maps.get(&map));
|
||||
let revision = have.map(|data| Arc::as_ptr(data) as u64).unwrap_or(0);
|
||||
let key = (format!("{map:?}{}", if preview.is_some() { "~" } else { "" }), revision);
|
||||
if self.aux.get(&texture_set) == Some(&key) {
|
||||
continue;
|
||||
}
|
||||
let Some(cache) = s.caches.get(ts) else { continue };
|
||||
let Some(cache) = session.caches.get(texture_set) else { continue };
|
||||
|
||||
let res = texturecraft_render::aux_size(cache.size);
|
||||
out.aux.push((
|
||||
ts,
|
||||
res,
|
||||
texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales),
|
||||
));
|
||||
self.aux.insert(ts, key);
|
||||
let resolution = texturecraft_render::aux_size(cache.size);
|
||||
let rgba = if preview.is_some() && have.is_none() {
|
||||
texturecraft_render::mesh_maps::neutral_rgba(map, resolution)
|
||||
} else {
|
||||
texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, resolution, cache.size, &cache.composite.block_scales)
|
||||
};
|
||||
out.aux.push((texture_set, resolution, rgba));
|
||||
self.aux.insert(texture_set, key);
|
||||
}
|
||||
}
|
||||
Some(AuxView::Mask(id)) => {
|
||||
if let Some((ts, _, _)) = s.doc.project.locate(id) {
|
||||
let key = (format!("mask{}", id.0), s.revision);
|
||||
if self.aux.get(&ts) != Some(&key) && !s.stroke_active() {
|
||||
let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size));
|
||||
if let Some(rgba) = s.mask_view_rgba(id, res) {
|
||||
out.aux.push((ts, res, rgba));
|
||||
if let Some((texture_set, _, _)) = session.doc.project.locate(id) {
|
||||
let key = (format!("mask{}", id.0), session.revision);
|
||||
if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() {
|
||||
let resolution =
|
||||
session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size));
|
||||
if let Some(rgba) = session.mask_view_rgba(id, resolution) {
|
||||
out.aux.push((texture_set, resolution, rgba));
|
||||
}
|
||||
self.aux.insert(ts, key);
|
||||
self.aux.insert(texture_set, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(AuxView::QuickMask) => {
|
||||
for ts in 0..s.caches.len() {
|
||||
let Some(cache) = s.caches.get(ts) else { continue };
|
||||
let key = (format!("quickmask{}", s.quick_mask.revision), cache.revision);
|
||||
if self.aux.get(&ts) == Some(&key) {
|
||||
for texture_set in 0..session.caches.len() {
|
||||
let Some(cache) = session.caches.get(texture_set) else { continue };
|
||||
|
||||
let key = (format!("quickmask{}", session.quick_mask.revision), cache.revision);
|
||||
if self.aux.get(&texture_set) == Some(&key) {
|
||||
continue;
|
||||
}
|
||||
let res = texturecraft_render::aux_size(cache.size);
|
||||
if let Some(rgba) = s.quick_mask_rgba(ts, res) {
|
||||
out.aux.push((ts, res, rgba));
|
||||
let resolution = texturecraft_render::aux_size(cache.size);
|
||||
if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) {
|
||||
out.aux.push((texture_set, resolution, rgba));
|
||||
}
|
||||
self.aux.insert(ts, key);
|
||||
self.aux.insert(texture_set, key);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
self.bake_scene.sync(session, bake, &mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Mask view resolution for a texture set without a composite cache
|
||||
const MASK_VIEW_FALLBACK_RESOLUTION: u32 = 1024;
|
||||
|
||||
/// Paint callback for one view.
|
||||
pub struct ViewCallback {
|
||||
pub frame: Frame,
|
||||
@@ -295,39 +337,64 @@ impl CallbackTrait for ViewCallback {
|
||||
if let Some((mesh, id)) = &sync.mesh {
|
||||
gpu.renderer.set_mesh(device, queue, mesh, *id);
|
||||
}
|
||||
if let Some((sets, mats, shift)) = &sync.sets {
|
||||
if let Some((sets, material_count, shift)) = &sync.sets {
|
||||
gpu.renderer.set_display_shift(*shift);
|
||||
let reset = gpu.renderer.set_texture_sets(device, queue, sets, *mats);
|
||||
let reset = gpu.renderer.set_texture_sets(device, queue, sets, *material_count);
|
||||
if !reset.is_empty() {
|
||||
gpu.reset.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
for (ts, k, tx, ty, bytes) in &sync.tiles {
|
||||
gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes);
|
||||
for (texture_set, kind, tile_x, tile_y, bytes) in &sync.tiles {
|
||||
gpu.renderer.upload_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes);
|
||||
}
|
||||
for (ts, size, bytes) in &sync.aux {
|
||||
gpu.renderer.upload_aux(device, queue, *ts, *size, bytes);
|
||||
for (texture_set, size, bytes) in &sync.aux {
|
||||
gpu.renderer.upload_aux(device, queue, *texture_set, *size, bytes);
|
||||
}
|
||||
if let Some((high, id)) = &sync.bake_high
|
||||
&& let Err(error) = gpu.renderer.set_bake_high(device, queue, high.as_deref(), *id)
|
||||
{
|
||||
let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if reports.errors.len() < MAX_GPU_ERRORS && !reports.errors.contains(&error) {
|
||||
reports.errors.push(error);
|
||||
}
|
||||
gpu.ctx.request_repaint();
|
||||
}
|
||||
if let Some((id, missed)) = &sync.bake_high_missed {
|
||||
gpu.renderer.set_bake_high_missed(queue, *id, missed);
|
||||
}
|
||||
if let Some(count) = sync.bake_cage_count {
|
||||
gpu.renderer.truncate_bake_cages(count);
|
||||
}
|
||||
for (texture_set, cage, topology) in &sync.bake_cages {
|
||||
let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice()));
|
||||
gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology);
|
||||
}
|
||||
if let Some((mesh_id, seams)) = &sync.uv_seams {
|
||||
gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams);
|
||||
}
|
||||
}
|
||||
// Also installs (or rejects) full-size textures WebGPU answered for since last frame.
|
||||
|
||||
// Also installs (or rejects) full-size textures WebGPU answered for since last frame
|
||||
gpu.renderer.prepare(device, queue, encoder, &self.frame);
|
||||
let failed = gpu.renderer.take_memory_failures();
|
||||
if !failed.is_empty() {
|
||||
let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for ts in failed {
|
||||
if !r.memory.contains(&ts) {
|
||||
r.memory.push(ts);
|
||||
let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for texture_set in failed {
|
||||
if !reports.memory.contains(&texture_set) {
|
||||
reports.memory.push(texture_set);
|
||||
}
|
||||
}
|
||||
// This frame's report drain already ran: the next frame shows the toast.
|
||||
// This frame's report drain already ran: the next frame shows the toast
|
||||
gpu.ctx.request_repaint();
|
||||
}
|
||||
if gpu.renderer.awaiting_gpu() {
|
||||
gpu.ctx.request_repaint();
|
||||
}
|
||||
let ppp = screen.pixels_per_point;
|
||||
let r = self.rect;
|
||||
gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels);
|
||||
|
||||
let pixels_per_point = screen.pixels_per_point;
|
||||
let rect = self.rect;
|
||||
let blit_rect = [rect.min.x * pixels_per_point, rect.min.y * pixels_per_point, rect.width() * pixels_per_point, rect.height() * pixels_per_point];
|
||||
gpu.renderer.set_blit_rect(queue, self.frame.view_id, blit_rect, screen.size_in_pixels);
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
|
||||
@@ -134,13 +134,15 @@ pub fn os_language() -> &'static str {
|
||||
locale.map_or("en", |l| language_for_locale(&l))
|
||||
}
|
||||
|
||||
/// Tests that switch the global UI language, or draw the UI under it, run one at a time.
|
||||
#[cfg(test)]
|
||||
pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::TEST_LANGUAGE as LANGUAGE;
|
||||
use super::*;
|
||||
|
||||
/// Tests that switch the global UI language run one at a time.
|
||||
static LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Every key the UI looks up: `tr("…")` / `trf("…"` literals in the sources, plus the
|
||||
/// static catalogs whose labels are translated where they are shown.
|
||||
fn keys() -> Vec<String> {
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
//! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "جارٍ خبز {map} ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "جارٍ خبز {map} ({n}/{total})، مجموعة الخامات {set} من {sets}"),
|
||||
("Follow Newest Map", "تتبّع أحدث خريطة"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"الرسم متوقف مؤقتًا أثناء عرض عملية الخبز. ألغِ الخبز أو انتظر حتى ينتهي.",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"ما يعرضه العرض ثلاثي الأبعاد أثناء الخبز: أحدث خريطة مكتملة، أو أي خريطة مكتملة تختارها، أو الخامة. الخرائط التي لم تُخبز بعد تعرض قيمة محايدة.",
|
||||
),
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"),
|
||||
("2D view only", "عرض ثنائي الأبعاد فقط"),
|
||||
@@ -60,7 +71,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "دائماً"),
|
||||
("Ambient Occlusion", "الانسداد المحيطي (AO)"),
|
||||
("Ambient occlusion", "الانسداد المحيطي (AO)"),
|
||||
("Ambient occlusion intensity", "شدة الانسداد المحيطي"),
|
||||
("Amount", "المقدار"),
|
||||
("Anchor point", "نقطة ارتكاز"),
|
||||
("Anchor: {name}", "نقطة ارتكاز: {name}"),
|
||||
@@ -86,6 +96,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "المحور"),
|
||||
("Back to painting", "العودة إلى الرسم"),
|
||||
("Backface culling", "استبعاد الوجوه الخلفية"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "اخبز خريطة المعرّفات ID (F8) لالتقاط الألوان من الشبكة."),
|
||||
("Bake Mesh Maps", "خبز خرائط المجسم"),
|
||||
("Bake mesh maps", "خبز خرائط المجسم"),
|
||||
(
|
||||
@@ -121,6 +132,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "مدمج: {mesh}"),
|
||||
("Cage: {name}", "القفص (Cage): {name}"),
|
||||
("Camera", "الكاميرا"),
|
||||
("Colors", "الألوان"),
|
||||
("Go to camera 1", "الانتقال إلى الكاميرا 1"),
|
||||
("Go to camera 2", "الانتقال إلى الكاميرا 2"),
|
||||
("Go to camera 3", "الانتقال إلى الكاميرا 3"),
|
||||
@@ -138,6 +150,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "القناة"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "مصدر القناة: قيمة موحدة، إجرائي، صورة أو نقطة ارتكاز"),
|
||||
("Channels", "القنوات"),
|
||||
("Check for Updates...", "التحقق من وجود تحديثات..."),
|
||||
("Checker", "رقعة شطرنج"),
|
||||
("Clamp", "تقييد القيم"),
|
||||
("Clear", "مسح"),
|
||||
@@ -553,6 +566,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "تراكب (Overlay)"),
|
||||
("Overlay opacity", "عتامة التراكب"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - خشونة ومعدنية (TextureCraft)"),
|
||||
("Pick color", "التقاط لون"),
|
||||
("PNG image", "صورة PNG"),
|
||||
("Padding", "الحشو (Padding)"),
|
||||
("Paint", "رسم"),
|
||||
@@ -1037,6 +1051,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "إزالة تجاوز الدقة"),
|
||||
("Texture set resolution", "دقة مجموعة الخامات"),
|
||||
("UV tile {tile} resolution", "دقة بلاطة UV {tile}"),
|
||||
("Advanced settings", "إعدادات متقدمة"),
|
||||
("Import baked maps", "استيراد خرائط مخبوزة"),
|
||||
("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"),
|
||||
("Add...", "إضافة..."),
|
||||
("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"),
|
||||
("Not imported: {files}", "لم يتم استيرادها: {files}"),
|
||||
("Baking Visualization", "تصور الخبز"),
|
||||
("Show for Selected Texture Set Only", "العرض لمجموعة الخامات المحددة فقط"),
|
||||
("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"),
|
||||
("UV Seams", "فواصل UV"),
|
||||
("Project Mesh (LP)", "مجسم الإسقاط (LP)"),
|
||||
("Edges", "الحواف"),
|
||||
("Cavities", "التجاويف"),
|
||||
("Edges and cavities", "الحواف والتجاويف"),
|
||||
@@ -1066,4 +1091,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("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", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"),
|
||||
];
|
||||
@@ -1,6 +1,17 @@
|
||||
//! German UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "{map} wird gebacken ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} wird gebacken ({n}/{total}), Texturset {set} von {sets}"),
|
||||
("Follow Newest Map", "Neueste Map verfolgen"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"Das Malen ist pausiert, solange ein Bake angezeigt wird. Brich den Bake ab oder warte, bis er fertig ist.",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"Was die 3D-Ansicht während des Backens zeigt: die zuletzt fertige Map, eine fertige Map deiner Wahl oder das Material. Noch nicht gebackene Maps zeigen einen neutralen Wert.",
|
||||
),
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"),
|
||||
("2D view only", "Nur 2D-Ansicht"),
|
||||
@@ -63,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "Immer"),
|
||||
("Ambient Occlusion", "Ambient Occlusion"),
|
||||
("Ambient occlusion", "Ambient occlusion"),
|
||||
("Ambient occlusion intensity", "Ambient-Occlusion-Intensität"),
|
||||
("Amount", "Stärke"),
|
||||
("Anchor point", "Ankerpunkt"),
|
||||
("Anchor: {name}", "Anker: {name}"),
|
||||
@@ -89,6 +99,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "Achse"),
|
||||
("Back to painting", "Zurück zum Malen"),
|
||||
("Backface culling", "Rückseiten-Culling"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "Backe eine ID-Map (F8), um Farben vom Mesh aufzunehmen."),
|
||||
("Bake Mesh Maps", "Mesh-Maps backen"),
|
||||
("Bake mesh maps", "Mesh-Maps backen"),
|
||||
("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Mesh-Maps backen (F8) für Generatoren auf Basis von Krümmung, AO und Dicke."),
|
||||
@@ -121,6 +132,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "Integriert: {mesh}"),
|
||||
("Cage: {name}", "Cage: {name}"),
|
||||
("Camera", "Kamera"),
|
||||
("Colors", "Farben"),
|
||||
("Go to camera 1", "Zu Kamera 1 wechseln"),
|
||||
("Go to camera 2", "Zu Kamera 2 wechseln"),
|
||||
("Go to camera 3", "Zu Kamera 3 wechseln"),
|
||||
@@ -138,6 +150,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "Kanal"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "Kanalquelle: einheitlicher Wert, prozedural, Bild oder Anker"),
|
||||
("Channels", "Kanäle"),
|
||||
("Check for Updates...", "Nach Updates suchen..."),
|
||||
("Checker", "Schachbrett"),
|
||||
("Clamp", "Begrenzen"),
|
||||
("Clear", "Leeren"),
|
||||
@@ -586,6 +599,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "Ineinanderkopieren"),
|
||||
("Overlay opacity", "Überlagerungsdeckkraft"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallisch/Rauheit (TextureCraft)"),
|
||||
("Pick color", "Farbe aufnehmen"),
|
||||
("PNG image", "PNG-Bild"),
|
||||
("Padding", "Padding"),
|
||||
("Paint", "Malen"),
|
||||
@@ -1080,6 +1094,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "Auflösungsüberschreibung entfernen"),
|
||||
("Texture set resolution", "Auflösung des Textursets"),
|
||||
("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"),
|
||||
("Advanced settings", "Erweiterte Einstellungen"),
|
||||
("Import baked maps", "Gebackene Maps importieren"),
|
||||
("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"),
|
||||
("Add...", "Hinzufügen..."),
|
||||
("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"),
|
||||
("Not imported: {files}", "Nicht importiert: {files}"),
|
||||
("Baking Visualization", "Bake-Visualisierung"),
|
||||
("Show for Selected Texture Set Only", "Nur für das ausgewählte Texturset anzeigen"),
|
||||
("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"),
|
||||
("UV Seams", "UV-Nähte"),
|
||||
("Project Mesh (LP)", "Projektions-Mesh (LP)"),
|
||||
("Edges", "Kanten"),
|
||||
("Cavities", "Vertiefungen"),
|
||||
("Edges and cavities", "Kanten und Vertiefungen"),
|
||||
@@ -1112,4 +1137,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("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",
|
||||
),
|
||||
];
|
||||
@@ -1,6 +1,17 @@
|
||||
//! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "Horneando {map} ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Horneando {map} ({n}/{total}), conjunto de texturas {set} de {sets}"),
|
||||
("Follow Newest Map", "Seguir el mapa más reciente"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"La pintura está en pausa mientras se muestra un horneado. Cancela el horneado o espera a que termine.",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"Lo que muestra la vista 3D mientras se hornea: el último mapa terminado, un mapa terminado a elección o el material. Los mapas aún sin hornear muestran un valor neutro.",
|
||||
),
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"),
|
||||
("2D view only", "Solo vista 2D"),
|
||||
@@ -60,7 +71,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "Siempre"),
|
||||
("Ambient Occlusion", "Oclusión ambiental"),
|
||||
("Ambient occlusion", "Oclusión ambiental"),
|
||||
("Ambient occlusion intensity", "Intensidad de la oclusión ambiental"),
|
||||
("Amount", "Cantidad"),
|
||||
("Anchor point", "Punto de anclaje"),
|
||||
("Anchor: {name}", "Anclaje: {name}"),
|
||||
@@ -86,6 +96,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "Eje"),
|
||||
("Back to painting", "Volver a pintar"),
|
||||
("Backface culling", "Descarte de caras traseras"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "Hornea un mapa de ID (F8) para tomar colores de la malla."),
|
||||
("Bake Mesh Maps", "Hornear mapas de malla"),
|
||||
("Bake mesh maps", "Hornear mapas de malla"),
|
||||
(
|
||||
@@ -121,6 +132,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "Integrada: {mesh}"),
|
||||
("Cage: {name}", "Jaula: {name}"),
|
||||
("Camera", "Cámara"),
|
||||
("Colors", "Colores"),
|
||||
("Go to camera 1", "Ir a la cámara 1"),
|
||||
("Go to camera 2", "Ir a la cámara 2"),
|
||||
("Go to camera 3", "Ir a la cámara 3"),
|
||||
@@ -138,6 +150,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "Canal"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "Origen del canal: valor uniforme, procedural, imagen o anclaje"),
|
||||
("Channels", "Canales"),
|
||||
("Check for Updates...", "Buscar actualizaciones..."),
|
||||
("Checker", "Damero"),
|
||||
("Clamp", "Limitar"),
|
||||
("Clear", "Borrar"),
|
||||
@@ -577,6 +590,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "Superponer"),
|
||||
("Overlay opacity", "Opacidad de superposición"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidad (TextureCraft)"),
|
||||
("Pick color", "Tomar color"),
|
||||
("PNG image", "Imagen PNG"),
|
||||
("Padding", "Margen"),
|
||||
("Paint", "Pintar"),
|
||||
@@ -1065,6 +1079,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "Quitar resolución personalizada"),
|
||||
("Texture set resolution", "Resolución del conjunto de texturas"),
|
||||
("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"),
|
||||
("Advanced settings", "Ajustes avanzados"),
|
||||
("Import baked maps", "Importar mapas horneados"),
|
||||
("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"),
|
||||
("Add...", "Añadir..."),
|
||||
("Baked maps imported: {count}", "Mapas horneados importados: {count}"),
|
||||
("Not imported: {files}", "Sin importar: {files}"),
|
||||
("Baking Visualization", "Visualización del horneado"),
|
||||
("Show for Selected Texture Set Only", "Mostrar solo para el conjunto de texturas seleccionado"),
|
||||
("High Definition Mesh (HP)", "Malla de alta resolución (HP)"),
|
||||
("UV Seams", "Costuras UV"),
|
||||
("Project Mesh (LP)", "Malla de proyección (LP)"),
|
||||
("Edges", "Bordes"),
|
||||
("Cavities", "Cavidades"),
|
||||
("Edges and cavities", "Bordes y cavidades"),
|
||||
@@ -1100,4 +1125,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"\"{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",
|
||||
),
|
||||
];
|
||||
@@ -1,6 +1,17 @@
|
||||
//! French UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "Cuisson de {map} ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Cuisson de {map} ({n}/{total}), jeu de textures {set} sur {sets}"),
|
||||
("Follow Newest Map", "Suivre la dernière carte"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"La peinture est suspendue tant qu'une cuisson est affichée. Annulez la cuisson ou attendez qu'elle se termine.",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"Ce que la vue 3D affiche pendant la cuisson : la dernière carte terminée, une carte terminée au choix ou le matériau. Les cartes pas encore cuites affichent une valeur neutre.",
|
||||
),
|
||||
(
|
||||
"\"{layer}\" has no paint yet: the filter changes what you paint on it.",
|
||||
"\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.",
|
||||
@@ -66,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "Toujours"),
|
||||
("Ambient Occlusion", "Occlusion ambiante"),
|
||||
("Ambient occlusion", "Occlusion ambiante"),
|
||||
("Ambient occlusion intensity", "Intensité de l'occlusion ambiante"),
|
||||
("Amount", "Quantité"),
|
||||
("Anchor point", "Point d'ancrage"),
|
||||
("Anchor: {name}", "Ancrage : {name}"),
|
||||
@@ -92,6 +102,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "Axe"),
|
||||
("Back to painting", "Retour à la peinture"),
|
||||
("Backface culling", "Élimination des faces arrière"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "Précalculez une carte d'ID (F8) pour prélever des couleurs sur le maillage."),
|
||||
("Bake Mesh Maps", "Précalculer les cartes de maillage"),
|
||||
("Bake mesh maps", "Précalculer les cartes de maillage"),
|
||||
(
|
||||
@@ -127,6 +138,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "Intégré : {mesh}"),
|
||||
("Cage: {name}", "Cage : {name}"),
|
||||
("Camera", "Caméra"),
|
||||
("Colors", "Couleurs"),
|
||||
("Go to camera 1", "Aller à la caméra 1"),
|
||||
("Go to camera 2", "Aller à la caméra 2"),
|
||||
("Go to camera 3", "Aller à la caméra 3"),
|
||||
@@ -144,6 +156,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "Canal"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "Source du canal : valeur uniforme, procédural, image ou ancrage"),
|
||||
("Channels", "Canaux"),
|
||||
("Check for Updates...", "Rechercher des mises à jour..."),
|
||||
("Checker", "Damier"),
|
||||
("Clamp", "Limiter"),
|
||||
("Clear", "Effacer"),
|
||||
@@ -592,6 +605,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "Incrustation"),
|
||||
("Overlay opacity", "Opacité de superposition"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - Métallique Rugosité (TextureCraft)"),
|
||||
("Pick color", "Prélever une couleur"),
|
||||
("PNG image", "Image PNG"),
|
||||
("Padding", "Marge"),
|
||||
("Paint", "Peinture"),
|
||||
@@ -1089,6 +1103,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "Supprimer la résolution personnalisée"),
|
||||
("Texture set resolution", "Résolution de l'ensemble de textures"),
|
||||
("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"),
|
||||
("Advanced settings", "Paramètres avancés"),
|
||||
("Import baked maps", "Importer des cartes précalculées"),
|
||||
("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"),
|
||||
("Add...", "Ajouter..."),
|
||||
("Baked maps imported: {count}", "Cartes précalculées importées : {count}"),
|
||||
("Not imported: {files}", "Non importés : {files}"),
|
||||
("Baking Visualization", "Visualisation du baking"),
|
||||
("Show for Selected Texture Set Only", "Afficher uniquement pour l'ensemble de textures sélectionné"),
|
||||
("High Definition Mesh (HP)", "Maillage haute définition (HP)"),
|
||||
("UV Seams", "Coutures UV"),
|
||||
("Project Mesh (LP)", "Maillage de projection (LP)"),
|
||||
("Edges", "Arêtes"),
|
||||
("Cavities", "Cavités"),
|
||||
("Edges and cavities", "Arêtes et cavités"),
|
||||
@@ -1124,4 +1149,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"\"{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",
|
||||
),
|
||||
];
|
||||
@@ -1,6 +1,17 @@
|
||||
//! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "Bake di {map} in corso ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Bake di {map} in corso ({n}/{total}), set di texture {set} di {sets}"),
|
||||
("Follow Newest Map", "Segui la mappa più recente"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"La pittura è in pausa finché viene mostrato un bake. Annulla il bake o attendi che finisca.",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"Cosa mostra la vista 3D durante il bake: l'ultima mappa completata, una mappa completata a scelta o il materiale. Le mappe non ancora create mostrano un valore neutro.",
|
||||
),
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"),
|
||||
("2D view only", "Solo vista 2D"),
|
||||
@@ -63,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "Sempre"),
|
||||
("Ambient Occlusion", "Occlusione ambientale"),
|
||||
("Ambient occlusion", "Occlusione ambientale"),
|
||||
("Ambient occlusion intensity", "Intensità occlusione ambientale"),
|
||||
("Amount", "Quantità"),
|
||||
("Anchor point", "Punto di ancoraggio"),
|
||||
("Anchor: {name}", "Ancoraggio: {name}"),
|
||||
@@ -89,6 +99,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "Asse"),
|
||||
("Back to painting", "Torna alla pittura"),
|
||||
("Backface culling", "Culling facce posteriori"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "Esegui il bake di una mappa ID (F8) per prelevare i colori dalla mesh."),
|
||||
("Bake Mesh Maps", "Bake mappe mesh"),
|
||||
("Bake mesh maps", "Bake mappe mesh"),
|
||||
(
|
||||
@@ -124,6 +135,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "Integrata: {mesh}"),
|
||||
("Cage: {name}", "Gabbia: {name}"),
|
||||
("Camera", "Camera"),
|
||||
("Colors", "Colori"),
|
||||
("Go to camera 1", "Vai alla camera 1"),
|
||||
("Go to camera 2", "Vai alla camera 2"),
|
||||
("Go to camera 3", "Vai alla camera 3"),
|
||||
@@ -141,6 +153,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "Canale"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "Sorgente del canale: valore uniforme, procedurale, immagine o ancoraggio"),
|
||||
("Channels", "Canali"),
|
||||
("Check for Updates...", "Controlla aggiornamenti..."),
|
||||
("Checker", "Scacchiera"),
|
||||
("Clamp", "Limita"),
|
||||
("Clear", "Cancella"),
|
||||
@@ -583,6 +596,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "Sovrapponi"),
|
||||
("Overlay opacity", "Opacità sovrapposizione"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallico Rugosità (TextureCraft)"),
|
||||
("Pick color", "Preleva colore"),
|
||||
("PNG image", "Immagine PNG"),
|
||||
("Padding", "Padding"),
|
||||
("Paint", "Pittura"),
|
||||
@@ -1074,6 +1088,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "Rimuovi risoluzione personalizzata"),
|
||||
("Texture set resolution", "Risoluzione del set di texture"),
|
||||
("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"),
|
||||
("Advanced settings", "Impostazioni avanzate"),
|
||||
("Import baked maps", "Importa mappe bake"),
|
||||
("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"),
|
||||
("Add...", "Aggiungi..."),
|
||||
("Baked maps imported: {count}", "Mappe bake importate: {count}"),
|
||||
("Not imported: {files}", "Non importati: {files}"),
|
||||
("Baking Visualization", "Visualizzazione del baking"),
|
||||
("Show for Selected Texture Set Only", "Mostra solo per il set di texture selezionato"),
|
||||
("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"),
|
||||
("UV Seams", "Cuciture UV"),
|
||||
("Project Mesh (LP)", "Mesh di proiezione (LP)"),
|
||||
("Edges", "Bordi"),
|
||||
("Cavities", "Cavità"),
|
||||
("Edges and cavities", "Bordi e cavità"),
|
||||
@@ -1109,4 +1134,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"\"{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",
|
||||
),
|
||||
];
|
||||
@@ -1,6 +1,17 @@
|
||||
//! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "{map} をベイク中 ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} をベイク中 ({n}/{total})、テクスチャセット {set}/{sets}"),
|
||||
("Follow Newest Map", "最新のマップを追う"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"ベイクの表示中はペイントを一時停止しています。ベイクをキャンセルするか、終わるまでお待ちください。",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"ベイク中に3Dビューが表示するもの:最後に完成したマップ、完成済みの好きなマップ、またはマテリアル。まだベイクされていないマップは中立値で表示されます。",
|
||||
),
|
||||
(
|
||||
"\"{layer}\" has no paint yet: the filter changes what you paint on it.",
|
||||
"「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。",
|
||||
@@ -66,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "常に"),
|
||||
("Ambient Occlusion", "アンビエントオクルージョン"),
|
||||
("Ambient occlusion", "アンビエントオクルージョン"),
|
||||
("Ambient occlusion intensity", "アンビエントオクルージョンの強度"),
|
||||
("Amount", "量"),
|
||||
("Anchor point", "アンカーポイント"),
|
||||
("Anchor: {name}", "アンカー: {name}"),
|
||||
@@ -92,6 +102,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "軸"),
|
||||
("Back to painting", "ペイントに戻る"),
|
||||
("Backface culling", "背面カリング"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "メッシュから色を拾うには ID マップをベイクしてください (F8)。"),
|
||||
("Bake Mesh Maps", "メッシュマップのベイク"),
|
||||
("Bake mesh maps", "メッシュマップをベイク"),
|
||||
(
|
||||
@@ -127,6 +138,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "組み込み: {mesh}"),
|
||||
("Cage: {name}", "ケージ: {name}"),
|
||||
("Camera", "カメラ"),
|
||||
("Colors", "カラー"),
|
||||
("Go to camera 1", "カメラ 1 に移動"),
|
||||
("Go to camera 2", "カメラ 2 に移動"),
|
||||
("Go to camera 3", "カメラ 3 に移動"),
|
||||
@@ -144,6 +156,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "チャンネル"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "チャンネルのソース: 均一値、プロシージャル、画像、アンカー"),
|
||||
("Channels", "チャンネル"),
|
||||
("Check for Updates...", "アップデートを確認..."),
|
||||
("Checker", "チェッカー"),
|
||||
("Clamp", "クランプ"),
|
||||
("Clear", "クリア"),
|
||||
@@ -571,6 +584,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "オーバーレイ"),
|
||||
("Overlay opacity", "オーバーレイの不透明度"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - メタリック/ラフネス (TextureCraft)"),
|
||||
("Pick color", "色を拾う"),
|
||||
("PNG image", "PNG画像"),
|
||||
("Padding", "パディング"),
|
||||
("Paint", "ペイント"),
|
||||
@@ -1059,6 +1073,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "解像度の上書きを解除"),
|
||||
("Texture set resolution", "テクスチャセットの解像度"),
|
||||
("UV tile {tile} resolution", "UVタイル {tile} の解像度"),
|
||||
("Advanced settings", "詳細設定"),
|
||||
("Import baked maps", "ベイク済みマップを読み込む"),
|
||||
("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"),
|
||||
("Add...", "追加..."),
|
||||
("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"),
|
||||
("Not imported: {files}", "読み込まれなかったファイル: {files}"),
|
||||
("Baking Visualization", "ベイクの可視化"),
|
||||
("Show for Selected Texture Set Only", "選択したテクスチャセットのみ表示"),
|
||||
("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"),
|
||||
("UV Seams", "UVシーム"),
|
||||
("Project Mesh (LP)", "投影メッシュ (LP)"),
|
||||
("Edges", "エッジ"),
|
||||
("Cavities", "くぼみ"),
|
||||
("Edges and cavities", "エッジとくぼみ"),
|
||||
@@ -1094,4 +1119,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"\"{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", "ダイアログを開いている間にプロジェクトが変更されたため、何も実行されませんでした"),
|
||||
];
|
||||
@@ -1,6 +1,17 @@
|
||||
//! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "{map} 베이크 중 ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} 베이크 중 ({n}/{total}), 텍스처 세트 {set}/{sets}"),
|
||||
("Follow Newest Map", "최신 맵 따라가기"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"베이크를 표시하는 동안에는 페인팅이 일시 중지됩니다. 베이크를 취소하거나 끝날 때까지 기다리세요.",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"베이크하는 동안 3D 뷰가 보여 주는 것: 가장 최근에 완료된 맵, 완료된 맵 중 선택한 하나, 또는 머티리얼. 아직 베이크되지 않은 맵은 중립 값으로 표시됩니다.",
|
||||
),
|
||||
(
|
||||
"\"{layer}\" has no paint yet: the filter changes what you paint on it.",
|
||||
"\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.",
|
||||
@@ -63,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "항상"),
|
||||
("Ambient Occlusion", "앰비언트 오클루전"),
|
||||
("Ambient occlusion", "앰비언트 오클루전"),
|
||||
("Ambient occlusion intensity", "앰비언트 오클루전 강도"),
|
||||
("Amount", "양"),
|
||||
("Anchor point", "앵커 포인트"),
|
||||
("Anchor: {name}", "앵커: {name}"),
|
||||
@@ -89,6 +99,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "축"),
|
||||
("Back to painting", "페인팅으로 돌아가기"),
|
||||
("Backface culling", "후면 컬링"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "메시에서 색을 고르려면 ID 맵을 베이크하세요 (F8)."),
|
||||
("Bake Mesh Maps", "메시 맵 베이크"),
|
||||
("Bake mesh maps", "메시 맵 베이크"),
|
||||
("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "곡률, AO, 두께 기반 제너레이터를 사용하려면 메시 맵을 베이크하세요 (F8)."),
|
||||
@@ -121,6 +132,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "기본 제공: {mesh}"),
|
||||
("Cage: {name}", "케이지: {name}"),
|
||||
("Camera", "카메라"),
|
||||
("Colors", "색상"),
|
||||
("Go to camera 1", "카메라 1 보기"),
|
||||
("Go to camera 2", "카메라 2 보기"),
|
||||
("Go to camera 3", "카메라 3 보기"),
|
||||
@@ -138,6 +150,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "채널"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "채널 소스: 균일 값, 프로시저럴, 이미지 또는 앵커"),
|
||||
("Channels", "채널"),
|
||||
("Check for Updates...", "업데이트 확인..."),
|
||||
("Checker", "체커"),
|
||||
("Clamp", "클램프"),
|
||||
("Clear", "지우기"),
|
||||
@@ -562,6 +575,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "오버레이"),
|
||||
("Overlay opacity", "오버레이 불투명도"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - 메탈릭 러프니스 (TextureCraft)"),
|
||||
("Pick color", "색 고르기"),
|
||||
("PNG image", "PNG 이미지"),
|
||||
("Padding", "패딩"),
|
||||
("Paint", "페인트"),
|
||||
@@ -1047,6 +1061,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "해상도 재정의 제거"),
|
||||
("Texture set resolution", "텍스처 세트 해상도"),
|
||||
("UV tile {tile} resolution", "UV 타일 {tile} 해상도"),
|
||||
("Advanced settings", "고급 설정"),
|
||||
("Import baked maps", "베이크된 맵 가져오기"),
|
||||
("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"),
|
||||
("Add...", "추가..."),
|
||||
("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"),
|
||||
("Not imported: {files}", "가져오지 않음: {files}"),
|
||||
("Baking Visualization", "베이크 시각화"),
|
||||
("Show for Selected Texture Set Only", "선택한 텍스처 세트만 표시"),
|
||||
("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"),
|
||||
("UV Seams", "UV 심"),
|
||||
("Project Mesh (LP)", "투영 메시 (LP)"),
|
||||
("Edges", "가장자리"),
|
||||
("Cavities", "오목한 부분"),
|
||||
("Edges and cavities", "가장자리와 오목한 부분"),
|
||||
@@ -1079,4 +1104,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("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", "대화 상자가 열려 있는 동안 프로젝트가 변경되어 아무 작업도 수행하지 않았습니다"),
|
||||
];
|
||||
@@ -1,6 +1,17 @@
|
||||
//! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "Fazendo o bake de {map} ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Fazendo o bake de {map} ({n}/{total}), conjunto de texturas {set} de {sets}"),
|
||||
("Follow Newest Map", "Seguir o mapa mais recente"),
|
||||
(
|
||||
"Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.",
|
||||
"A pintura fica em pausa enquanto um bake é exibido. Cancele o bake ou espere ele terminar.",
|
||||
),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"O que a vista 3D mostra durante o bake: o último mapa concluído, um mapa concluído à escolha ou o material. Mapas ainda não gerados mostram um valor neutro.",
|
||||
),
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"),
|
||||
("2D view only", "Apenas vista 2D"),
|
||||
@@ -63,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "Sempre"),
|
||||
("Ambient Occlusion", "Oclusão de ambiente"),
|
||||
("Ambient occlusion", "Oclusão de ambiente"),
|
||||
("Ambient occlusion intensity", "Intensidade da oclusão de ambiente"),
|
||||
("Amount", "Quantidade"),
|
||||
("Anchor point", "Ponto de ancoragem"),
|
||||
("Anchor: {name}", "Âncora: {name}"),
|
||||
@@ -89,6 +99,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "Eixo"),
|
||||
("Back to painting", "Voltar à pintura"),
|
||||
("Backface culling", "Descarte de faces traseiras"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "Faça o bake de um mapa de ID (F8) para coletar cores da malha."),
|
||||
("Bake Mesh Maps", "Bake de mapas de malha"),
|
||||
("Bake mesh maps", "Fazer bake dos mapas de malha"),
|
||||
(
|
||||
@@ -124,6 +135,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "Embutida: {mesh}"),
|
||||
("Cage: {name}", "Cage: {name}"),
|
||||
("Camera", "Câmera"),
|
||||
("Colors", "Cores"),
|
||||
("Go to camera 1", "Ir para a câmera 1"),
|
||||
("Go to camera 2", "Ir para a câmera 2"),
|
||||
("Go to camera 3", "Ir para a câmera 3"),
|
||||
@@ -141,6 +153,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "Canal"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "Origem do canal: valor uniforme, procedural, imagem ou âncora"),
|
||||
("Channels", "Canais"),
|
||||
("Check for Updates...", "Verificar atualizações..."),
|
||||
("Checker", "Xadrez"),
|
||||
("Clamp", "Limitar"),
|
||||
("Clear", "Limpar"),
|
||||
@@ -574,6 +587,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "Sobrepor"),
|
||||
("Overlay opacity", "Opacidade da sobreposição"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidade (TextureCraft)"),
|
||||
("Pick color", "Coletar cor"),
|
||||
("PNG image", "Imagem PNG"),
|
||||
("Padding", "Margem"),
|
||||
("Paint", "Pintura"),
|
||||
@@ -1062,6 +1076,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "Remover resolução personalizada"),
|
||||
("Texture set resolution", "Resolução do conjunto de texturas"),
|
||||
("UV tile {tile} resolution", "Resolução do tile UV {tile}"),
|
||||
("Advanced settings", "Configurações avançadas"),
|
||||
("Import baked maps", "Importar mapas com bake"),
|
||||
("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"),
|
||||
("Add...", "Adicionar..."),
|
||||
("Baked maps imported: {count}", "Mapas com bake importados: {count}"),
|
||||
("Not imported: {files}", "Não importados: {files}"),
|
||||
("Baking Visualization", "Visualização do bake"),
|
||||
("Show for Selected Texture Set Only", "Mostrar apenas para o conjunto de texturas selecionado"),
|
||||
("High Definition Mesh (HP)", "Malha de alta resolução (HP)"),
|
||||
("UV Seams", "Costuras UV"),
|
||||
("Project Mesh (LP)", "Malha de projeção (LP)"),
|
||||
("Edges", "Bordas"),
|
||||
("Cavities", "Cavidades"),
|
||||
("Edges and cavities", "Bordas e cavidades"),
|
||||
@@ -1097,4 +1122,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"\"{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"),
|
||||
];
|
||||
@@ -1,6 +1,14 @@
|
||||
//! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("Baking {map} ({n}/{total})", "正在烘焙{map} ({n}/{total})"),
|
||||
("Baking {map} ({n}/{total}), texture set {set} of {sets}", "正在烘焙{map} ({n}/{total}),纹理集 {set}/{sets}"),
|
||||
("Follow Newest Map", "跟随最新贴图"),
|
||||
("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", "显示烘焙时已暂停绘制。请取消烘焙,或等待其完成。"),
|
||||
(
|
||||
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
|
||||
"烘焙过程中 3D 视图显示的内容:最新完成的贴图、任意已完成的贴图,或材质。尚未烘焙的贴图显示中性值。",
|
||||
),
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"),
|
||||
("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"),
|
||||
("2D view only", "仅 2D 视图"),
|
||||
@@ -54,7 +62,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Always", "始终"),
|
||||
("Ambient Occlusion", "环境光遮蔽"),
|
||||
("Ambient occlusion", "环境光遮蔽"),
|
||||
("Ambient occlusion intensity", "环境光遮蔽强度"),
|
||||
("Amount", "数量"),
|
||||
("Anchor point", "锚点"),
|
||||
("Anchor: {name}", "锚点:{name}"),
|
||||
@@ -80,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Axis", "轴"),
|
||||
("Back to painting", "返回绘画"),
|
||||
("Backface culling", "背面剔除"),
|
||||
("Bake an ID map (F8) to pick colors from the mesh.", "烘焙 ID 贴图(F8)以从网格上拾取颜色。"),
|
||||
("Bake Mesh Maps", "烘焙网格贴图"),
|
||||
("Bake mesh maps", "烘焙网格贴图"),
|
||||
("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "烘焙网格贴图(F8)以用于基于曲率、AO 和厚度的生成器。"),
|
||||
@@ -112,6 +120,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Built-in: {mesh}", "内置:{mesh}"),
|
||||
("Cage: {name}", "笼体:{name}"),
|
||||
("Camera", "相机"),
|
||||
("Colors", "颜色"),
|
||||
("Go to camera 1", "转到相机 1"),
|
||||
("Go to camera 2", "转到相机 2"),
|
||||
("Go to camera 3", "转到相机 3"),
|
||||
@@ -129,6 +138,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Channel", "通道"),
|
||||
("Channel source: uniform value, procedural, image or anchor", "通道来源:统一值、程序纹理、图像或锚点"),
|
||||
("Channels", "通道"),
|
||||
("Check for Updates...", "检查更新..."),
|
||||
("Checker", "棋盘格"),
|
||||
("Clamp", "钳制"),
|
||||
("Clear", "清除"),
|
||||
@@ -526,6 +536,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Overlay", "叠加"),
|
||||
("Overlay opacity", "叠加层不透明度"),
|
||||
("PBR - Metallic Roughness (TextureCraft)", "PBR - 金属度/粗糙度(TextureCraft)"),
|
||||
("Pick color", "拾取颜色"),
|
||||
("PNG image", "PNG 图像"),
|
||||
("Padding", "扩边"),
|
||||
("Paint", "绘画"),
|
||||
@@ -1005,6 +1016,17 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove resolution override", "移除分辨率覆盖"),
|
||||
("Texture set resolution", "纹理集分辨率"),
|
||||
("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"),
|
||||
("Advanced settings", "高级设置"),
|
||||
("Import baked maps", "导入已烘焙贴图"),
|
||||
("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"),
|
||||
("Add...", "添加..."),
|
||||
("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"),
|
||||
("Not imported: {files}", "未导入:{files}"),
|
||||
("Baking Visualization", "烘焙可视化"),
|
||||
("Show for Selected Texture Set Only", "仅显示所选纹理集"),
|
||||
("High Definition Mesh (HP)", "高模网格 (HP)"),
|
||||
("UV Seams", "UV 接缝"),
|
||||
("Project Mesh (LP)", "投射网格 (LP)"),
|
||||
("Edges", "边缘"),
|
||||
("Cavities", "凹陷"),
|
||||
("Edges and cavities", "边缘和凹陷"),
|
||||
@@ -1028,4 +1050,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("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", "对话框打开期间项目已更改,因此未执行任何操作"),
|
||||
];
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Pick mode of a color selection: the next click in the 3D or 2D view adds the ID color under it
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{BakedMap, LayerId};
|
||||
use texturecraft_engine::{StackTarget, ViewMode};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::state::Mode;
|
||||
|
||||
/// Height in points of the eyedropper drawn as the pointer while picking
|
||||
const EYEDROPPER_SIZE: f32 = 20.0;
|
||||
|
||||
/// A color selection waiting for a click, and the view to return to once it comes
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct IdColorPick {
|
||||
pub effect: LayerId,
|
||||
/// The color the click replaces; None adds one
|
||||
pub index: Option<usize>,
|
||||
previous_view: ViewMode,
|
||||
}
|
||||
|
||||
impl IdColorPick {
|
||||
/// Waits for a click that picks into `effect`, showing the ID map meanwhile
|
||||
pub fn start(app: &mut TextureCraftApp, effect: LayerId, index: Option<usize>) {
|
||||
let previous_view = match app.picking_id_color.take() {
|
||||
Some(running) => running.previous_view,
|
||||
None => app.session.view,
|
||||
};
|
||||
|
||||
app.properties_popup = None;
|
||||
app.picking_id_color = Some(IdColorPick { effect, index, previous_view });
|
||||
app.run("viewport.view", json!({"mode": format!("map:{}", BakedMap::Id.id())}));
|
||||
}
|
||||
|
||||
/// Leaves pick mode, returning to the earlier view unless the user chose another meanwhile
|
||||
pub fn end(app: &mut TextureCraftApp) {
|
||||
let Some(pick) = app.picking_id_color.take() else { return };
|
||||
|
||||
if app.session.view == ViewMode::MeshMap(BakedMap::Id) {
|
||||
app.run("viewport.view", view_params(pick.previous_view));
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks at `point` (`x`/`y`/`viewport` or `uv` params) and leaves pick mode
|
||||
pub fn pick_at(app: &mut TextureCraftApp, point: Value) {
|
||||
let Some(pick) = app.picking_id_color else { return };
|
||||
|
||||
let mut params = json!({"effect": pick.effect.0, "index": pick.index});
|
||||
if let (Some(target), Some(source)) = (params.as_object_mut(), point.as_object()) {
|
||||
target.extend(source.clone());
|
||||
}
|
||||
|
||||
app.run("effect.colorSelection.pick", params);
|
||||
IdColorPick::end(app);
|
||||
}
|
||||
|
||||
/// An eyedropper in place of the pointer while it is over `rect`, its tip on the hotspot
|
||||
pub fn draw_cursor(ui: &egui::Ui, rect: egui::Rect) {
|
||||
let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|pointer| rect.contains(*pointer)) else { return };
|
||||
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
|
||||
|
||||
// The glyph's tip is its bottom-left corner; a dark outline keeps it readable on any ID color
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("id_color_pick_cursor")));
|
||||
let font = egui::FontId::proportional(EYEDROPPER_SIZE);
|
||||
let glyph = egui_phosphor::regular::EYEDROPPER;
|
||||
for offset in [egui::vec2(-1.0, 0.0), egui::vec2(1.0, 0.0), egui::vec2(0.0, -1.0), egui::vec2(0.0, 1.0)] {
|
||||
painter.text(pointer + offset, egui::Align2::LEFT_BOTTOM, glyph, font.clone(), egui::Color32::from_black_alpha(220));
|
||||
}
|
||||
painter.text(pointer, egui::Align2::LEFT_BOTTOM, glyph, font, egui::Color32::WHITE);
|
||||
}
|
||||
|
||||
/// Ends pick mode once its effect is no longer selected or painting mode is left
|
||||
pub fn end_when_stale(app: &mut TextureCraftApp) {
|
||||
let Some(pick) = app.picking_id_color else { return };
|
||||
|
||||
if app.session.target != StackTarget::Effect(pick.effect) || app.ui.mode != Mode::Painting {
|
||||
IdColorPick::end(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `viewport.view` params that show `view`
|
||||
fn view_params(view: ViewMode) -> Value {
|
||||
match view {
|
||||
ViewMode::Material => json!({"mode": "material"}),
|
||||
ViewMode::Channel(channel) => json!({"mode": channel.id()}),
|
||||
ViewMode::MeshMap(map) => json!({"mode": format!("map:{}", map.id())}),
|
||||
ViewMode::UvChecker => json!({"mode": "uvChecker"}),
|
||||
ViewMode::Mask(layer) => json!({"mode": "mask", "layer": layer.0}),
|
||||
}
|
||||
}
|
||||
+256
-46
@@ -4,12 +4,14 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use craft_keymap::egui::Dispatcher;
|
||||
use craft_keymap::{Active, Bindable, Chord, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes};
|
||||
use egui::{Event, Id, Key, KeyboardShortcut, Modifiers, RichText, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::menus::{CATALOG, parse_shortcut};
|
||||
use crate::menus::CATALOG;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{icon_button, section};
|
||||
|
||||
@@ -64,7 +66,18 @@ pub fn tip(keymap: &Keymap, label: &str, id: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// "Ctrl+Shift+E" notation (the inverse of `menus::parse_shortcut`).
|
||||
/// craft-keymap's text of a shortcut: "Ctrl" here is the command modifier (Cmd on macOS), which the
|
||||
/// crate writes "Cmd".
|
||||
fn crate_text(text: &str) -> String {
|
||||
text.split('+').map(|part| if part == "Ctrl" { "Cmd" } else { part }).collect::<Vec<_>>().join("+")
|
||||
}
|
||||
|
||||
/// Read "Ctrl+Shift+E" notation.
|
||||
pub fn parse(text: &str) -> Option<Chord> {
|
||||
Chord::parse(&crate_text(text)).ok()
|
||||
}
|
||||
|
||||
/// "Ctrl+Shift+E" notation (the inverse of [`parse`]).
|
||||
pub fn format_shortcut(sc: &KeyboardShortcut) -> String {
|
||||
let m = sc.modifiers;
|
||||
let mut s = String::new();
|
||||
@@ -81,27 +94,118 @@ pub fn format_shortcut(sc: &KeyboardShortcut) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
fn modifier_count(m: Modifiers) -> u8 {
|
||||
u8::from(m.command || m.ctrl || m.mac_cmd) + u8::from(m.shift) + u8::from(m.alt)
|
||||
/// Every bound shortcut as egui's shortcut type.
|
||||
fn active(keymap: &Keymap) -> Vec<KeyboardShortcut> {
|
||||
bindings().iter().filter_map(|b| Some(parse(shortcut(keymap, b)?)?.to_egui_shortcut())).collect()
|
||||
}
|
||||
|
||||
/// Every bound shortcut with its item id, most modifiers first: egui ignores extra Shift and
|
||||
/// Alt when matching, so Shift+C has to be tried before C.
|
||||
pub fn active(keymap: &Keymap) -> Vec<(&'static str, KeyboardShortcut)> {
|
||||
let mut v: Vec<(&'static str, KeyboardShortcut)> = bindings().iter().filter_map(|b| Some((b.id, parse_shortcut(shortcut(keymap, b)?)?))).collect();
|
||||
v.sort_by_key(|(_, sc)| std::cmp::Reverse(modifier_count(sc.modifiers)));
|
||||
v
|
||||
/// The catalog as craft-keymap sees it, in `bindings()` order: the first one listed wins a shared
|
||||
/// shortcut.
|
||||
fn catalog() -> Vec<Bindable> {
|
||||
bindings()
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let item = Bindable::new(b.id, b.label, Scope::app());
|
||||
match b.default.and_then(parse) {
|
||||
Some(chord) => item.with_default(craft_keymap::Binding::new(chord)),
|
||||
None => item,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each binding's parsed shortcut, in `bindings()` order.
|
||||
pub fn resolve(keymap: &Keymap) -> Vec<Option<KeyboardShortcut>> {
|
||||
bindings().iter().map(|b| shortcut(keymap, b).and_then(parse_shortcut)).collect()
|
||||
/// craft-keymap's text of a stored shortcut. A symbol that needs Shift is looked up without it, so
|
||||
/// "Shift+Colon" is ":".
|
||||
fn override_text(text: &str) -> String {
|
||||
match parse(text) {
|
||||
Some(chord) => Layout::new().resolve(&KeyInput::new(chord.mods).with_typed(chord.key)).unwrap_or(chord).to_string(),
|
||||
None => crate_text(text),
|
||||
}
|
||||
}
|
||||
|
||||
/// Another binding with the same shortcut as binding `i`.
|
||||
pub fn conflict(resolved: &[Option<KeyboardShortcut>], i: usize) -> Option<usize> {
|
||||
let sc = resolved.get(i).copied().flatten()?;
|
||||
resolved.iter().enumerate().position(|(j, o)| j != i && *o == Some(sc))
|
||||
/// The stored shortcuts as craft-keymap overrides ("" = no shortcut).
|
||||
fn overrides(keymap: &Keymap) -> Overrides {
|
||||
let mut out = Overrides::new();
|
||||
for (id, text) in keymap {
|
||||
let texts = if text.is_empty() { Vec::new() } else { vec![override_text(text)] };
|
||||
// Only an overlong id or text is refused, and neither can be a shortcut.
|
||||
let _ = out.insert(id.clone(), texts);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The keymap with `keymap`'s shortcuts for `platform`.
|
||||
fn resolved(keymap: &Keymap, platform: Platform) -> craft_keymap::Keymap {
|
||||
craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap))
|
||||
}
|
||||
|
||||
/// The resolved keymap and the dispatcher that runs it against each frame's keys.
|
||||
pub struct Bindings {
|
||||
stored: Keymap,
|
||||
map: craft_keymap::Keymap,
|
||||
dispatcher: Dispatcher,
|
||||
}
|
||||
|
||||
impl Default for Bindings {
|
||||
fn default() -> Bindings {
|
||||
let stored = Keymap::new();
|
||||
let map = resolved(&stored, Platform::current());
|
||||
// Held keys repeat their command. Copy, Cut and Paste events count as Ctrl+C, X and V.
|
||||
Bindings { stored, map, dispatcher: Dispatcher::new().with_repeat(true).with_clipboard_events(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Bindings {
|
||||
/// Follows the stored shortcuts and the platform; a no-op while neither changed.
|
||||
pub(crate) fn sync(&mut self, keymap: &Keymap, platform: Platform) {
|
||||
if self.stored != *keymap || self.map.platform() != platform {
|
||||
self.stored = keymap.clone();
|
||||
self.map = resolved(keymap, platform);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the commands this frame's key presses run, in press order. The presses are
|
||||
/// removed from the input.
|
||||
pub(crate) fn dispatch(&mut self, input: &mut egui::InputState) -> Vec<String> {
|
||||
self.dispatcher.dispatch(input, &self.map, &Active::NONE).into_iter().map(|hit| hit.command.id).collect()
|
||||
}
|
||||
|
||||
/// The id of the command a key press outside the main window runs. The press is matched as
|
||||
/// the main window's presses are.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn command_of(&self, press: &Event) -> Option<String> {
|
||||
let input = KeyInput::from_egui(press, self.map.platform())?;
|
||||
self.dispatcher.layout().candidates(&input).into_iter().find_map(|chord| match self.map.lookup(&chord, false, &Active::NONE) {
|
||||
Lookup::Run(command) => Some(command.id),
|
||||
Lookup::Cycle(commands) => commands.into_iter().next().map(|command| command.id),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The shortcut a press records: the chord it runs, keeping the held Ctrl and Cmd as they are.
|
||||
fn recorded(&self, press: &Event, key: Key, modifiers: Modifiers, platform: Platform) -> KeyboardShortcut {
|
||||
let chord = KeyInput::from_egui(press, platform).and_then(|input| self.dispatcher.layout().resolve(&input));
|
||||
match chord {
|
||||
Some(chord) => KeyboardShortcut::new(Modifiers { shift: chord.mods.shift, ..modifiers }, chord.to_egui_shortcut().logical_key),
|
||||
None => KeyboardShortcut::new(modifiers, key),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a Shift-only Cut or Paste, read as Shift+Delete or Shift+Insert, runs nothing.
|
||||
pub(crate) fn shift_clipboard_is_free(&self, event: &Event) -> bool {
|
||||
let key = match event {
|
||||
Event::Cut => craft_keymap::Key::Delete,
|
||||
Event::Paste(_) => craft_keymap::Key::Insert,
|
||||
_ => return false,
|
||||
};
|
||||
matches!(self.map.lookup(&Chord::new(Mods::SHIFT, key), false, &Active::NONE), Lookup::None)
|
||||
}
|
||||
|
||||
/// Another binding on the same shortcut as `b`.
|
||||
fn conflict(&self, b: &Binding) -> Option<&'static Binding> {
|
||||
let clash = self.map.conflicts_with(&CommandRef::new(b.id)).into_iter().find(|c| c.kind == ConflictKind::Clash)?;
|
||||
bindings().iter().find(|x| x.id == clash.b.0.id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind `b` to `value` ("" = no shortcut); the default is stored as no override.
|
||||
@@ -127,7 +231,6 @@ pub fn sync_captured(keymap: &Keymap) {
|
||||
let clipboard = [Key::C, Key::V, Key::X];
|
||||
let keys: Vec<KeyboardShortcut> = active(keymap)
|
||||
.into_iter()
|
||||
.map(|(_, sc)| sc)
|
||||
.filter(|sc| {
|
||||
let fkey = sc.logical_key.name().strip_prefix('F').is_some_and(|n| n.parse::<u8>().is_ok());
|
||||
(sc.modifiers.command || sc.modifiers.alt || fkey) && !(sc.modifiers.command && !sc.modifiers.shift && clipboard.contains(&sc.logical_key))
|
||||
@@ -151,10 +254,11 @@ pub fn capturing(ctx: &egui::Context) -> bool {
|
||||
}
|
||||
|
||||
/// The first key press this frame as a shortcut.
|
||||
fn pressed(ctx: &egui::Context) -> Option<KeyboardShortcut> {
|
||||
fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option<KeyboardShortcut> {
|
||||
let platform = craft_keymap::egui::platform(ctx);
|
||||
ctx.input(|i| {
|
||||
i.events.iter().find_map(|e| match e {
|
||||
Event::Key { key, pressed: true, modifiers, .. } => Some(KeyboardShortcut::new(*modifiers, *key)),
|
||||
Event::Key { key, pressed: true, modifiers, .. } => Some(bindings.recorded(e, *key, *modifiers, platform)),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
@@ -169,7 +273,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let capture_id = Id::unique(CAPTURE);
|
||||
let filter_id = Id::unique("keymap_filter");
|
||||
let mut capture: Option<usize> = ctx.data(|d| d.get_temp(capture_id));
|
||||
if let (Some(i), Some(sc)) = (capture, pressed(ctx)) {
|
||||
if let (Some(i), Some(sc)) = (capture, pressed(ctx, &app.bindings)) {
|
||||
if (sc.logical_key != Key::Escape || !sc.modifiers.is_none())
|
||||
&& let Some(b) = bindings().get(i)
|
||||
{
|
||||
@@ -177,10 +281,10 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
capture = None;
|
||||
}
|
||||
app.bindings.sync(&app.ui.keymap, craft_keymap::egui::platform(ctx));
|
||||
let mut filter: String = ctx.data(|d| d.get_temp(filter_id)).unwrap_or_default();
|
||||
let mut open = true;
|
||||
crate::windows::window("keyboard_shortcuts", tr("Keyboard shortcuts"), &mut open).default_width(480.0).show(ctx, |ui| {
|
||||
let resolved = resolve(&app.ui.keymap);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim));
|
||||
ui.add(egui::TextEdit::singleline(&mut filter).hint_text(tr("Search commands or keys")).desired_width(300.0));
|
||||
@@ -190,7 +294,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
});
|
||||
let clashes = (0..resolved.len()).filter(|i| conflict(&resolved, *i).is_some()).count();
|
||||
let clashes = bindings().iter().filter(|b| app.bindings.conflict(b).is_some()).count();
|
||||
if clashes > 0 {
|
||||
ui.label(
|
||||
RichText::new(format!("{} {}", ic::WARNING, trf("{n} items share a shortcut; the first one listed wins.", &[("n", &clashes)])))
|
||||
@@ -220,7 +324,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
let bound = current.is_some();
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(other) = conflict(&resolved, i).and_then(|j| bindings().get(j)) {
|
||||
if let Some(other) = app.bindings.conflict(b) {
|
||||
ui.label(RichText::new(ic::WARNING).color(tk.danger))
|
||||
.on_hover_text(trf("Also bound to {item} ({menu})", &[("item", &tr(other.label)), ("menu", &tr(other.group))]));
|
||||
}
|
||||
@@ -300,48 +404,154 @@ mod tests {
|
||||
fn shortcuts_round_trip_through_parse_and_format() {
|
||||
for b in bindings() {
|
||||
if let Some(s) = b.default {
|
||||
let sc = parse_shortcut(s).unwrap_or_else(|| panic!("{} has an unparsable shortcut {s}", b.id));
|
||||
assert_eq!(format_shortcut(&sc), s);
|
||||
let chord = parse(s).unwrap_or_else(|| panic!("{} has an unparsable shortcut {s}", b.id));
|
||||
assert_eq!(format_shortcut(&chord.to_egui_shortcut()), s);
|
||||
}
|
||||
}
|
||||
for s in ["Ctrl+Shift+Alt+F12", "Alt+OpenBracket", "Shift+Delete", "Ctrl+9"] {
|
||||
assert_eq!(parse_shortcut(s).map(|sc| format_shortcut(&sc)).as_deref(), Some(s));
|
||||
assert_eq!(parse(s).map(|chord| format_shortcut(&chord.to_egui_shortcut())).as_deref(), Some(s));
|
||||
}
|
||||
assert!(parse_shortcut("Ctrl+").is_none() && parse_shortcut("Ctrl+NoSuchKey").is_none());
|
||||
assert!(parse("Ctrl+").is_none() && parse("Ctrl+NoSuchKey").is_none());
|
||||
}
|
||||
|
||||
fn bindings_for(keymap: &Keymap) -> Bindings {
|
||||
let mut out = Bindings::default();
|
||||
out.sync(keymap, Platform::Windows);
|
||||
out
|
||||
}
|
||||
|
||||
fn binding(id: &str) -> &'static Binding {
|
||||
bindings().iter().find(|b| b.id == id).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_shortcuts_do_not_conflict() {
|
||||
let resolved = resolve(&Keymap::new());
|
||||
for (i, b) in bindings().iter().enumerate() {
|
||||
assert!(conflict(&resolved, i).is_none(), "{} shares its default shortcut", b.id);
|
||||
let resolved = bindings_for(&Keymap::new());
|
||||
for b in bindings() {
|
||||
assert!(resolved.conflict(b).is_none(), "{} shares its default shortcut", b.id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebinding_detects_conflicts_and_resets() {
|
||||
let all = bindings();
|
||||
let save = all.iter().position(|b| b.id == "file.save").unwrap();
|
||||
let undo = all.iter().position(|b| b.id == "edit.undo").unwrap();
|
||||
let (save, undo) = (binding("file.save"), binding("edit.undo"));
|
||||
let mut keymap = Keymap::new();
|
||||
rebind(&mut keymap, &all[save], "Ctrl+Z");
|
||||
let resolved = resolve(&keymap);
|
||||
assert_eq!(conflict(&resolved, save), Some(undo));
|
||||
assert_eq!(conflict(&resolved, undo), Some(save));
|
||||
rebind(&mut keymap, save, "Ctrl+Z");
|
||||
let resolved = bindings_for(&keymap);
|
||||
assert_eq!(resolved.conflict(save).map(|b| b.id), Some("edit.undo"));
|
||||
assert_eq!(resolved.conflict(undo).map(|b| b.id), Some("file.save"));
|
||||
assert_eq!(shortcut_of(&keymap, "file.save"), Some("Ctrl+Z"));
|
||||
// Unbinding clears the conflict; binding back to the default drops the override.
|
||||
rebind(&mut keymap, &all[save], "");
|
||||
rebind(&mut keymap, save, "");
|
||||
assert_eq!(shortcut_of(&keymap, "file.save"), None);
|
||||
assert!(conflict(&resolve(&keymap), undo).is_none());
|
||||
rebind(&mut keymap, &all[save], "Ctrl+S");
|
||||
assert!(bindings_for(&keymap).conflict(undo).is_none());
|
||||
rebind(&mut keymap, save, "Ctrl+S");
|
||||
assert!(keymap.is_empty());
|
||||
}
|
||||
|
||||
fn press(key: Key, modifiers: Modifiers) -> Event {
|
||||
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
fn press_at(key: Key, physical: Key, modifiers: Modifiers) -> Event {
|
||||
Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
fn dispatched(bindings: &mut Bindings, events: Vec<Event>, modifiers: Modifiers) -> Vec<String> {
|
||||
let mut input = egui::InputState::default();
|
||||
input.modifiers = modifiers;
|
||||
input.events = events;
|
||||
bindings.dispatch(&mut input)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn specific_shortcuts_are_tried_first() {
|
||||
let active = active(&Keymap::new());
|
||||
let pos = |id: &str| active.iter().position(|(x, _)| *x == id).unwrap();
|
||||
assert!(pos("viewport.previousChannel") < pos("viewport.nextChannel"));
|
||||
assert!(pos("file.saveAs") < pos("file.save"));
|
||||
fn a_stored_shortcut_on_a_shifted_symbol_runs_on_that_press() {
|
||||
for (stored, key, physical, modifiers) in [
|
||||
("Shift+Colon", Key::Colon, Key::Semicolon, Modifiers::SHIFT),
|
||||
("Shift+Exclamationmark", Key::Exclamationmark, Key::Num1, Modifiers::SHIFT),
|
||||
("Shift+Questionmark", Key::Questionmark, Key::Slash, Modifiers::SHIFT),
|
||||
("Ctrl+Shift+Plus", Key::Plus, Key::Equals, Modifiers::COMMAND | Modifiers::SHIFT),
|
||||
] {
|
||||
let mut keymap = Keymap::new();
|
||||
keymap.insert("file.save".into(), stored.into());
|
||||
let mut resolved = bindings_for(&keymap);
|
||||
assert_eq!(dispatched(&mut resolved, vec![press_at(key, physical, modifiers)], modifiers), ["file.save"], "{stored}");
|
||||
assert_eq!(resolved.command_of(&press_at(key, physical, modifiers)).as_deref(), Some("file.save"), "{stored} in a floating panel");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recorded_shifted_symbol_is_the_chord_it_runs() {
|
||||
let resolved = bindings_for(&Keymap::new());
|
||||
let recorded = |key, physical, modifiers| format_shortcut(&resolved.recorded(&press_at(key, physical, modifiers), key, modifiers, Platform::Windows));
|
||||
assert_eq!(recorded(Key::Colon, Key::Semicolon, Modifiers::SHIFT), "Colon");
|
||||
// The layout needs Shift for this slash; the key at that position is not a symbol.
|
||||
assert_eq!(recorded(Key::Slash, Key::Num7, Modifiers::SHIFT), "Slash");
|
||||
assert_eq!(recorded(Key::E, Key::E, Modifiers::COMMAND | Modifiers::SHIFT), "Ctrl+Shift+E");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_floating_panel_matches_presses_as_the_main_window_does() {
|
||||
let mut keymap = Keymap::new();
|
||||
keymap.insert("file.save".into(), "Equals".into());
|
||||
let resolved = bindings_for(&keymap);
|
||||
assert_eq!(resolved.command_of(&press(Key::Plus, Modifiers::NONE)).as_deref(), Some("file.save"), "+ stands for =");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_floating_panel_leaves_a_bound_shift_insert_to_its_binding() {
|
||||
let paste = || Event::Paste("text".into());
|
||||
let free = bindings_for(&Keymap::new());
|
||||
let event = crate::menus::forwarded_press(&free, paste(), Modifiers::SHIFT);
|
||||
assert_eq!(free.command_of(&event).as_deref(), Some("layer.paste"));
|
||||
let mut keymap = Keymap::new();
|
||||
keymap.insert("file.save".into(), "Shift+Insert".into());
|
||||
keymap.insert("file.saveAs".into(), "Shift+Delete".into());
|
||||
let bound = bindings_for(&keymap);
|
||||
let event = crate::menus::forwarded_press(&bound, paste(), Modifiers::SHIFT);
|
||||
assert_eq!(bound.command_of(&event).as_deref(), Some("file.save"));
|
||||
let event = crate::menus::forwarded_press(&bound, Event::Cut, Modifiers::SHIFT);
|
||||
assert_eq!(bound.command_of(&event).as_deref(), Some("file.saveAs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_press_runs_the_command_bound_to_exactly_that_chord() {
|
||||
let resolved = bindings_for(&Keymap::new());
|
||||
let run = |mods: Modifiers, key: Key| resolved.command_of(&press(key, mods));
|
||||
assert_eq!(run(Modifiers::COMMAND, Key::S).as_deref(), Some("file.save"));
|
||||
assert_eq!(run(Modifiers::COMMAND | Modifiers::SHIFT, Key::S).as_deref(), Some("file.saveAs"));
|
||||
assert_eq!(run(Modifiers::SHIFT, Key::C).as_deref(), Some("viewport.previousChannel"));
|
||||
assert_eq!(run(Modifiers::NONE, Key::C).as_deref(), Some("viewport.nextChannel"));
|
||||
assert_eq!(run(Modifiers::ALT, Key::C), None, "Alt+C is not bound");
|
||||
assert_eq!(run(Modifiers::SHIFT, Key::M), None, "Shift+M is not bound");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() {
|
||||
let mut keymap = Keymap::new();
|
||||
keymap.insert("file.save".into(), "F5".into());
|
||||
keymap.insert("edit.undo".into(), String::new());
|
||||
let resolved = bindings_for(&keymap);
|
||||
assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save"));
|
||||
assert_eq!(resolved.command_of(&press(Key::S, Modifiers::COMMAND)), None);
|
||||
assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_in_the_notation_is_the_command_key_on_macos() {
|
||||
let mut resolved = Bindings::default();
|
||||
resolved.sync(&Keymap::new(), Platform::Mac);
|
||||
let cmd = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE };
|
||||
assert_eq!(resolved.command_of(&press(Key::S, cmd)).as_deref(), Some("file.save"));
|
||||
assert_eq!(resolved.command_of(&press(Key::S, Modifiers::CTRL)), None, "the Control key is another key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_item_listed_wins_a_shared_shortcut() {
|
||||
let mut keymap = Keymap::new();
|
||||
keymap.insert("file.save".into(), "Ctrl+Z".into());
|
||||
let resolved = bindings_for(&keymap);
|
||||
let first = bindings().iter().find(|b| matches!(b.id, "file.save" | "edit.undo")).unwrap().id;
|
||||
assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)).as_deref(), Some(first));
|
||||
}
|
||||
}
|
||||
+167
-25
@@ -7,19 +7,26 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod bake_job;
|
||||
pub mod bake_mode;
|
||||
mod bake_scene;
|
||||
mod color_selection_editor;
|
||||
pub mod control;
|
||||
pub mod dock;
|
||||
pub mod docking;
|
||||
pub mod export_templates;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod file_dialogs;
|
||||
mod filter_slot;
|
||||
pub mod fonts;
|
||||
pub mod gpu;
|
||||
pub mod i18n;
|
||||
pub mod id_color_pick;
|
||||
pub mod keymap;
|
||||
mod mask_preview_image;
|
||||
mod material_preview_image;
|
||||
pub mod menus;
|
||||
pub mod new_project_advanced;
|
||||
mod orb_shape;
|
||||
pub mod parity;
|
||||
mod preview_image;
|
||||
@@ -30,6 +37,7 @@ pub mod properties_popup;
|
||||
pub mod render_mode;
|
||||
mod resource_picker;
|
||||
mod resource_picker_item;
|
||||
mod running_bake;
|
||||
pub mod shelf;
|
||||
pub mod shelf_preview;
|
||||
mod soft_box;
|
||||
@@ -38,6 +46,9 @@ pub mod theme;
|
||||
pub mod thumbs;
|
||||
pub mod titlebar;
|
||||
pub mod toolbar;
|
||||
pub mod ui_state_store;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) mod updates_ui;
|
||||
pub mod uv_paint_point;
|
||||
pub mod viewport;
|
||||
pub mod web_files;
|
||||
@@ -52,22 +63,25 @@ use serde_json::Value;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::bake::Progress;
|
||||
|
||||
pub use bake_job::BakeJob;
|
||||
pub use control::ControlRequest;
|
||||
pub use running_bake::RunningBake;
|
||||
pub use state::UiState;
|
||||
|
||||
/// The app as the updater knows it: its releases, and the icon and color of its update prompt.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const UPDATE_APP: craft_update::App = craft_update::App {
|
||||
icon_png: Some(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png")),
|
||||
accent: Some([0xc2, 0x67, 0x2b]),
|
||||
..craft_update::App::new("texturecraft", "TextureCraft", "3D texture painting", "storytold/texturecraft")
|
||||
};
|
||||
|
||||
/// A texture set resize running on a worker thread (`Session::resize_task`).
|
||||
pub struct ResizeJob {
|
||||
pub progress: Arc<Progress>,
|
||||
pub rx: std::sync::mpsc::Receiver<texturecraft_engine::Result<texturecraft_engine::ResizeOutput>>,
|
||||
}
|
||||
|
||||
/// A background bake of one or more texture sets.
|
||||
pub struct BakeJob {
|
||||
pub queue: Vec<usize>,
|
||||
pub current: Option<(usize, Arc<Progress>, std::sync::mpsc::Receiver<texturecraft_engine::Result<texturecraft_engine::bake::BakeOutput>>)>,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
/// A MaterialCraft material re-cooking on a worker thread (one per layer at a time).
|
||||
pub struct LinkCook {
|
||||
pub layer: texturecraft_engine::core::LayerId,
|
||||
@@ -76,6 +90,9 @@ pub struct LinkCook {
|
||||
pub rx: std::sync::mpsc::Receiver<texturecraft_engine::Result<Vec<u8>>>,
|
||||
}
|
||||
|
||||
/// The engine's refusal to paint while a bake shows (translated where it is toasted).
|
||||
pub const PAINTING_PAUSED: &str = i18n::n_("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.");
|
||||
|
||||
/// The browser build's notice when WebGPU is unavailable and wgpu fell back to WebGL2.
|
||||
pub const WEBGL_NOTICE: &str = i18n::n_(
|
||||
"WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.",
|
||||
@@ -92,6 +109,8 @@ pub struct TextureCraftApp {
|
||||
/// A smooth move to a saved camera in progress.
|
||||
camera_glide: Option<CameraGlide>,
|
||||
pub ui: UiState,
|
||||
/// Where `ui` is saved between runs
|
||||
ui_store: ui_state_store::UiStateStore,
|
||||
pub gpu: Option<gpu::GpuLink>,
|
||||
pub control: Option<std::sync::mpsc::Receiver<ControlRequest>>,
|
||||
pub toasts: Vec<Toast>,
|
||||
@@ -122,6 +141,8 @@ pub struct TextureCraftApp {
|
||||
pub placing_decal: Option<texturecraft_engine::core::LayerId>,
|
||||
/// The Properties popup a right click in a view opens.
|
||||
pub properties_popup: Option<properties_popup::PropertiesPopup>,
|
||||
/// The color selection the next click in the 3D or 2D view picks an ID color for
|
||||
pub picking_id_color: Option<id_color_pick::IdColorPick>,
|
||||
/// The wgpu state (screenshots read the renderer's targets).
|
||||
pub render_state: Option<eframe::egui_wgpu::RenderState>,
|
||||
/// CJK fallback fonts for the UI language.
|
||||
@@ -138,6 +159,20 @@ pub struct TextureCraftApp {
|
||||
styled: Option<(theme::Brightness, theme::Accent)>,
|
||||
/// Whether the window had focus last frame.
|
||||
focused: bool,
|
||||
/// The update check and prompt (desktop only).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) updates_rt: updates_ui::Runtime,
|
||||
/// Native file dialogs and their continuations (desktop only).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub file_dialogs: file_dialogs::FileDialogs,
|
||||
/// The unsaved-changes dialog's Save is waiting on the Save dialog's answer.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) saving_for_prompt: bool,
|
||||
/// That Save dialog saved the project; the prompt goes on at its next frame.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) prompt_saved: bool,
|
||||
/// The resolved keymap and its key dispatcher.
|
||||
pub(crate) bindings: keymap::Bindings,
|
||||
}
|
||||
|
||||
impl TextureCraftApp {
|
||||
@@ -151,7 +186,8 @@ impl TextureCraftApp {
|
||||
let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx));
|
||||
|
||||
// The first run speaks the OS (or browser) language
|
||||
let ui = cc.storage.and_then(|storage| eframe::get_value::<UiState>(storage, "ui")).unwrap_or_else(|| {
|
||||
let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned());
|
||||
let ui = ui_store.load(cc.storage).unwrap_or_else(|| {
|
||||
let mut ui = UiState::default();
|
||||
ui.prefs.language = i18n::os_language().into();
|
||||
ui
|
||||
@@ -162,6 +198,7 @@ impl TextureCraftApp {
|
||||
camera_glide: None,
|
||||
session,
|
||||
ui,
|
||||
ui_store,
|
||||
gpu,
|
||||
control: None,
|
||||
toasts: Vec::new(),
|
||||
@@ -181,6 +218,7 @@ impl TextureCraftApp {
|
||||
last_paint_uv: None,
|
||||
placing_decal: None,
|
||||
properties_popup: None,
|
||||
picking_id_color: None,
|
||||
render_state: cc.wgpu_render_state.clone(),
|
||||
fonts: fonts::UiFonts::default(),
|
||||
banner: None,
|
||||
@@ -189,10 +227,20 @@ impl TextureCraftApp {
|
||||
next_autosave,
|
||||
styled: None,
|
||||
focused: true,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: updates_ui::Runtime::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
saving_for_prompt: false,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
prompt_saved: false,
|
||||
bindings: keymap::Bindings::default(),
|
||||
};
|
||||
app.ui.rename = None;
|
||||
app.ui.windows.new_project = false;
|
||||
i18n::set_language(&app.ui.prefs.language);
|
||||
app.report_ui_storage_warning();
|
||||
export_templates::load_library(&mut app, cc.storage);
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -231,6 +279,13 @@ impl TextureCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
fn report_ui_storage_warning(&mut self) {
|
||||
if let Some(warning) = self.ui_store.take_warning() {
|
||||
self.session.log.push(warning.clone());
|
||||
self.toast_sticky(warning);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toast(&mut self, text: impl Into<String>, error: bool) {
|
||||
self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 } });
|
||||
}
|
||||
@@ -241,11 +296,21 @@ impl TextureCraftApp {
|
||||
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY });
|
||||
}
|
||||
|
||||
/// Start baking texture sets in the background (one after another).
|
||||
/// Start baking texture sets in the background, one after another. Invalid set indices
|
||||
/// show an error without starting a preview or queuing any work.
|
||||
pub fn start_bake(&mut self, sets: Vec<usize>) {
|
||||
if self.bake.is_some() || sets.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Restore the picker's view before the preview starts following baked maps
|
||||
id_color_pick::IdColorPick::end(self);
|
||||
|
||||
if let Err(error) = self.session.bake_preview_begin_for(&sets) {
|
||||
self.toast(error.to_string(), true);
|
||||
return;
|
||||
}
|
||||
|
||||
let total = sets.len();
|
||||
self.bake = Some(BakeJob { queue: sets, current: None, total });
|
||||
}
|
||||
@@ -299,16 +364,39 @@ impl TextureCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Show at most one streamed map per frame, then apply the set as one undo step after
|
||||
/// its map channel closes. Closing the preview alone does not stop the background bake.
|
||||
fn poll_bake(&mut self, ctx: &egui::Context) {
|
||||
let Some(job) = self.bake.as_mut() else { return };
|
||||
// Leaving Bake mode puts the view mode back; the bake goes on
|
||||
if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking {
|
||||
self.session.bake_preview_end();
|
||||
}
|
||||
|
||||
let Some(job) = self.bake.as_mut() else {
|
||||
// A preview whose bake is gone must not keep the view
|
||||
self.session.bake_preview_end();
|
||||
return;
|
||||
};
|
||||
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
if let Some((set_index, _, receiver)) = &job.current {
|
||||
match receiver.try_recv() {
|
||||
if let Some(running) = &job.current {
|
||||
let set_index = running.set_index;
|
||||
|
||||
// Show one map per poll so each reaches its own frame
|
||||
// An empty channel can gain a map before the result arrives: wait for the sender to close
|
||||
match running.maps.try_recv() {
|
||||
Ok(map) => {
|
||||
self.session.bake_preview_map(set_index, map);
|
||||
return;
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => return,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {}
|
||||
}
|
||||
|
||||
match running.receiver.try_recv() {
|
||||
Ok(Ok(output)) => {
|
||||
let set_index = *set_index;
|
||||
job.current = None;
|
||||
if let Err(error) = self.session.apply_bake(set_index, output) {
|
||||
if let Err(error) = self.session.apply_streamed_bake(set_index, output) {
|
||||
self.toast(error.to_string(), true);
|
||||
}
|
||||
}
|
||||
@@ -325,34 +413,52 @@ impl TextureCraftApp {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(job) = self.bake.as_mut() else { return };
|
||||
|
||||
if job.queue.is_empty() {
|
||||
self.bake = None;
|
||||
self.session.bake_preview_end();
|
||||
self.toast(i18n::tr("Mesh maps baked"), false);
|
||||
return;
|
||||
}
|
||||
|
||||
let set_index = job.queue.remove(0);
|
||||
self.session.bake_preview_set_current(set_index);
|
||||
match self.session.bake_task(set_index) {
|
||||
Ok(task) => {
|
||||
let progress = Arc::new(Progress::new());
|
||||
let worker_progress = progress.clone();
|
||||
let receiver = spawn_worker("texturecraft-bake", move || task.run(&worker_progress));
|
||||
let maps_total = task.maps().len();
|
||||
let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let worker_done = maps_done.clone();
|
||||
let (sender, maps) = std::sync::mpsc::channel();
|
||||
let receiver = spawn_worker("texturecraft-bake", move || {
|
||||
task.run_streaming(&worker_progress, &mut |map| {
|
||||
worker_done.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = sender.send(map);
|
||||
})
|
||||
});
|
||||
|
||||
if let Some(job) = self.bake.as_mut() {
|
||||
job.current = Some((set_index, progress, receiver));
|
||||
job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total });
|
||||
}
|
||||
}
|
||||
Err(error) => self.toast(error.to_string(), true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel the active bake and discard queued sets
|
||||
/// Cancel the active worker, discard queued sets and restore the view. The current set's
|
||||
/// preview maps are discarded; previously applied sets keep their results and undo steps.
|
||||
pub fn cancel_bake(&mut self) {
|
||||
let Some(job) = self.bake.take() else { return };
|
||||
|
||||
if let Some((_, progress, _)) = job.current {
|
||||
progress.cancel.store(true, Ordering::Relaxed);
|
||||
if let Some(running) = job.current {
|
||||
running.progress.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
// Only the current set is uncommitted; completed sets remain applied
|
||||
self.session.bake_preview_end();
|
||||
}
|
||||
|
||||
/// Resize texture set `ts` to `resolution` on a worker thread (the document changes when
|
||||
@@ -389,12 +495,35 @@ impl TextureCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The map being baked and its position among the queued maps and texture sets.
|
||||
pub fn bake_status(&self) -> Option<String> {
|
||||
let job = self.bake.as_ref()?;
|
||||
let stage = self.session.bake_preview.as_ref()?.stage()?;
|
||||
let map = i18n::tr(i18n::baked_map_label(stage.map));
|
||||
let (n, total) = (stage.position, stage.total);
|
||||
if job.total > 1 {
|
||||
let set = job.total - job.queue.len();
|
||||
return Some(i18n::trf(
|
||||
"Baking {map} ({n}/{total}), texture set {set} of {sets}",
|
||||
&[("map", &map), ("n", &n), ("total", &total), ("set", &set.max(1)), ("sets", &job.total)],
|
||||
));
|
||||
}
|
||||
|
||||
Some(i18n::trf("Baking {map} ({n}/{total})", &[("map", &map), ("n", &n), ("total", &total)]))
|
||||
}
|
||||
|
||||
/// Bake progress 0..1 across all queued sets.
|
||||
pub fn bake_progress(&self) -> Option<f32> {
|
||||
let job = self.bake.as_ref()?;
|
||||
let done = job.total - job.queue.len() - usize::from(job.current.is_some());
|
||||
let cur = job.current.as_ref().map(|(_, p, _)| p.fraction()).unwrap_or(0.0);
|
||||
Some(((done as f32 + cur) / job.total.max(1) as f32).clamp(0.0, 1.0))
|
||||
|
||||
// Each map is a bake of its own: its progress runs from 0 to 1 within the set's share
|
||||
let current = job
|
||||
.current
|
||||
.as_ref()
|
||||
.map(|running| (running.maps_done.load(Ordering::Relaxed) as f32 + running.progress.fraction()) / running.maps_total.max(1) as f32)
|
||||
.unwrap_or(0.0);
|
||||
Some(((done as f32 + current) / job.total.max(1) as f32).clamp(0.0, 1.0))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -498,7 +627,8 @@ impl eframe::App for TextureCraftApp {
|
||||
}
|
||||
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
eframe::set_value(storage, "ui", &self.ui);
|
||||
self.ui_store.save(&self.ui, storage);
|
||||
self.report_ui_storage_warning();
|
||||
export_templates::save_library(self, storage);
|
||||
}
|
||||
|
||||
@@ -517,6 +647,8 @@ impl eframe::App for TextureCraftApp {
|
||||
}
|
||||
self.step_camera_glide(ctx);
|
||||
control::poll(self, ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.run_file_dialog_answers();
|
||||
web_files::poll(self);
|
||||
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
|
||||
for f in &dropped {
|
||||
@@ -544,6 +676,9 @@ impl eframe::App for TextureCraftApp {
|
||||
web_files::sync_unsaved(self);
|
||||
}
|
||||
self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::tick(self, ctx);
|
||||
self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx));
|
||||
menus::shortcuts(self, ctx);
|
||||
// A stored path being edited repaints its sublayer as its points, brush or material change.
|
||||
if let Err(e) = self.session.path_live() {
|
||||
@@ -553,9 +688,12 @@ impl eframe::App for TextureCraftApp {
|
||||
profile::drive(self, ctx);
|
||||
self.toasts.retain(|t| t.until > now);
|
||||
self.profiler.logic_ms = (now_ms() - t0) as f32;
|
||||
// Last, so it sees every close request this frame's work made.
|
||||
windows::close_request(self, ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let t0 = now_ms();
|
||||
if !self.ui.hide_ui {
|
||||
@@ -571,10 +709,14 @@ impl eframe::App for TextureCraftApp {
|
||||
let hide = self.ui.hide_ui;
|
||||
let tk = theme::Tokens::get(&ctx);
|
||||
// The dock keeps the cards' gutter from the bars and rails around it.
|
||||
let frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) };
|
||||
egui::CentralPanel::default().frame(frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) });
|
||||
let panel_frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) };
|
||||
egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) });
|
||||
windows::show(self, &ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::show(self, &ctx);
|
||||
toasts(self, &ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.file_dialogs.show_pending(frame);
|
||||
let end = now_ms();
|
||||
let dt = (end - t0) as f32;
|
||||
self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 };
|
||||
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user