diff --git a/Cargo.lock b/Cargo.lock
index 7a9453c3..384c4457 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -412,6 +412,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -448,6 +454,15 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block2"
version = "0.5.1"
@@ -691,6 +706,16 @@ dependencies = [
"libc",
]
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@@ -704,7 +729,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
dependencies = [
"bitflags 1.3.2",
- "core-foundation",
+ "core-foundation 0.9.4",
"core-graphics-types",
"foreign-types",
"libc",
@@ -717,19 +742,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
dependencies = [
"bitflags 1.3.2",
- "core-foundation",
+ "core-foundation 0.9.4",
"libc",
]
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "craft-dialogs"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
+dependencies = [
+ "block2 0.6.2",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
+ "raw-window-handle",
+ "rfd",
+]
+
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
[[package]]
name = "craft-i18n"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -749,10 +796,44 @@ dependencies = [
"writeable",
]
+[[package]]
+name = "craft-keymap"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
+dependencies = [
+ "egui",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "craft-menu"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
+dependencies = [
+ "craft-keymap",
+ "craft-quit",
+ "egui",
+ "muda",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+]
+
+[[package]]
+name = "craft-quit"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
+dependencies = [
+ "dispatch2",
+ "egui",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+]
+
[[package]]
name = "craft-ui"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -770,10 +851,36 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "craft-update"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
+dependencies = [
+ "chrono",
+ "dunce",
+ "egui",
+ "flate2",
+ "getrandom 0.3.4",
+ "image",
+ "log",
+ "plist",
+ "semver",
+ "serde",
+ "serde_json",
+ "sha2",
+ "tar",
+ "tempfile",
+ "ureq",
+ "verifysign",
+ "winreg",
+ "winsafe",
+ "zip",
+]
+
[[package]]
name = "craft-window"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -790,6 +897,15 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
+dependencies = [
+ "crossbeam-utils",
+]
+
[[package]]
name = "crossbeam-deque"
version = "0.8.8"
@@ -821,6 +937,16 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
[[package]]
name = "cursor-icon"
version = "1.2.0"
@@ -861,6 +987,22 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "deranged"
+version = "0.5.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -920,6 +1062,12 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
+[[package]]
+name = "dunce"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
[[package]]
name = "dyn-clone"
version = "1.0.20"
@@ -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"
diff --git a/Cargo.toml b/Cargo.toml
index 02b5a6dc..73a090c8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -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]
diff --git a/README.md b/README.md
index 80f807b6..69cd720c 100644
--- a/README.md
+++ b/README.md
@@ -32,6 +32,7 @@
+
diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml
index 2f80d416..b4a1d57c 100644
--- a/apps/texturecraft/Cargo.toml
+++ b/apps/texturecraft/Cargo.toml
@@ -30,6 +30,12 @@ ron = "0.12"
[target.'cfg(windows)'.dependencies]
winit = { version = "0.30", default-features = false }
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
+# The update helper is a copy of this program (`main`).
+craft-update = { workspace = true }
+
+# Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not.
+[target.'cfg(target_os = "macos")'.dependencies]
+craft-menu = { workspace = true }
[build-dependencies]
winresource = "0.1"
diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs
index 377b2e52..4965c438 100644
--- a/apps/texturecraft/src/main.rs
+++ b/apps/texturecraft/src/main.rs
@@ -11,11 +11,17 @@ mod window_frame;
use texturecraft_engine::Session;
use texturecraft_ui_egui::titlebar::TitleBar;
+use texturecraft_ui_egui::ui_state_store;
use texturecraft_ui_egui::{TextureCraftApp, UiState};
/// The app name eframe keeps the settings under (`eframe::storage_dir`).
const APP_NAME: &str = "TextureCraft";
+/// The window's size when it opens, in points.
+const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0];
+/// The smallest size the window can be resized to, in points.
+const MIN_SIZE: [f32; 2] = [960.0, 600.0];
+
const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png");
fn version() -> String {
@@ -115,13 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) {
}
}
-/// Settings › Interface › System title bar, read from the saved settings before the window opens
-/// (eframe hands the app its storage only afterwards). Missing or unreadable: off.
-fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool {
- let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron")));
- let saved = file.and_then(|f| std::fs::read_to_string(f).ok());
- let kv = saved.and_then(|s| ron::from_str::>(&s).ok());
- kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
+/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off
+fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool {
+ if let Some(ui) = ui_file.and_then(ui_state_store::read) {
+ return ui.prefs.system_title_bar;
+ }
+
+ let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
+ let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
+ let entries = saved.and_then(|text| ron::from_str::>(&text).ok());
+ entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
}
/// The app with the window chrome that needs the native window: the Windows borderless guard, and
@@ -161,7 +170,17 @@ impl eframe::App for Shell {
}
}
+/// A script driving the app gets no network check and no update prompt over its window.
+fn checks_for_updates_at_start(control: Option) -> bool {
+ control.is_none()
+}
+
fn main() {
+ // Windows: the update helper is a copy of this program started with `--finish-update`.
+ #[cfg(windows)]
+ if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) {
+ std::process::exit(i32::from(result.is_err()));
+ }
let args = match parse_args() {
Ok(Some(a)) => a,
Ok(None) => return,
@@ -170,21 +189,25 @@ fn main() {
std::process::exit(2);
}
};
- // Errors before the window opens speak the system's language; the app then applies the saved one.
+ // Errors before the window opens speak the system's language; the app then applies the saved one
texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language());
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
- // A message box needs the main thread on macOS; other threads' panics are only logged.
+ // A message box needs the main thread on macOS; other threads' panics are only logged
fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main"));
prev(info);
}));
let session = initial_session(&args);
- // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor
- // overwrite the user's saved UI layout and settings: state goes to a throwaway folder.
+ // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files
let persistence_path =
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
- let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref()));
- let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]);
+ let ui_file =
+ persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json")));
+ if let Some(file) = &ui_file {
+ let _ = ui_state_store::FILE.set(file.clone());
+ }
+ let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref()));
+ let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
@@ -195,7 +218,7 @@ fn main() {
std::process::exit(2);
}
let control = args.control;
- // The start window offers new, open and recent projects, unless a file was given or a script drives the app.
+ // The start window offers new, open and recent projects, unless a file was given or a script drives the app
let start = args.file.is_none() && control.is_none();
let r = eframe::run_native(
APP_NAME,
@@ -205,10 +228,16 @@ fn main() {
if let Some(w) = cc.winit_window() {
set_taskbar_icon(w);
}
+ // winit's Quit ends the process without asking; this menu's asks like the close button.
+ #[cfg(target_os = "macos")]
+ if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) {
+ log::warn!("the app menu could not be installed: {e}");
+ }
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
let mut app = TextureCraftApp::new(cc, session);
app.title_bar = title_bar;
app.ui.windows.start = start && app.ui.prefs.start_window;
+ app.set_startup_update_check(checks_for_updates_at_start(control));
if let Some(port) = control {
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
}
@@ -274,6 +303,12 @@ mod tests {
assert_eq!(args.gpu.as_deref(), Some("3080"));
}
+ #[test]
+ fn only_a_run_without_a_control_port_checks_for_updates_at_start() {
+ assert!(checks_for_updates_at_start(None));
+ assert!(!checks_for_updates_at_start(Some(9000)));
+ }
+
#[test]
fn rejects_missing_or_invalid_gpu_args() {
assert!(parse_args_from(["--gpu".to_string()]).is_err());
@@ -296,19 +331,27 @@ mod tests {
}
#[test]
- fn the_system_title_bar_setting_is_read_from_eframes_settings_file() {
- let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
+ fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() {
+ let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
+ let json_path = ron_path.with_extension("json");
for on in [false, true] {
let mut ui = UiState::default();
ui.prefs.system_title_bar = on;
- // Written as eframe writes it: a pretty RON map of RON strings.
+ // Written as eframe writes it: a pretty RON map of RON strings
let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]);
- std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
- assert_eq!(saved_system_title_bar(Some(&path)), on);
+ std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
+ assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on);
+
+ ui.prefs.system_title_bar = !on;
+ std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap();
+ assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first");
}
- std::fs::write(&path, "not ron").unwrap();
- assert!(!saved_system_title_bar(Some(&path)));
- std::fs::remove_file(&path).unwrap();
- assert!(!saved_system_title_bar(Some(&path)));
+
+ std::fs::write(&json_path, "not json").unwrap();
+ std::fs::write(&ron_path, "not ron").unwrap();
+ assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
+ std::fs::remove_file(&json_path).unwrap();
+ std::fs::remove_file(&ron_path).unwrap();
+ assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
}
}
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index 2015c090..1061db2d 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError {
AutomationError::Io(format!("{op} `{path}` failed: {e}"))
}
-/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`,
-/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped
-/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command
-/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is
-/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the
-/// embedded mesh).
+/// Host keys a command reads or writes a file through, at the top level or in each `files` entry
+const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"];
+
+/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
- let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null()));
- let ok = match id {
+ let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path));
+
+ // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path
+ let allowed = match id {
"file.close" | "file.removeUnused" => true,
"file.reimportMesh" => !has_path,
_ => !id.starts_with("file.") && !has_path,
};
- if ok {
+ if allowed {
Ok(())
} else {
Err(bad(format!(
@@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError
}
}
+/// Whether `params` names a host path or folder at its own top level
+fn names_host_path(params: &Value) -> bool {
+ HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null()))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -243,6 +248,18 @@ mod tests {
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
}
+ #[test]
+ fn nested_file_paths_are_denied() {
+ let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]});
+ assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err());
+
+ let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]});
+ assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err());
+
+ let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]});
+ assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok());
+ }
+
/// Every registry command documenting a host path must be classified (fails when a new
/// path-taking command is added without an automation policy).
#[test]
diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs
new file mode 100644
index 00000000..d2c7d7f3
--- /dev/null
+++ b/crates/bake/src/cage.rs
@@ -0,0 +1,15 @@
+//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws
+
+mod cage_shell;
+mod high_poly_reach;
+mod ray_frame;
+mod ray_start;
+mod vertex_reach;
+
+#[cfg(test)]
+pub(crate) use cage_shell::CORNERS;
+pub use cage_shell::CageShell;
+pub use high_poly_reach::HighPolyReach;
+pub(crate) use ray_frame::RayFrame;
+pub use ray_start::RayStart;
+pub use vertex_reach::VertexReach;
diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs
new file mode 100644
index 00000000..e1664219
--- /dev/null
+++ b/crates/bake/src/cage/cage_shell.rs
@@ -0,0 +1,65 @@
+use super::{RayFrame, RayStart};
+use crate::{BakeError, BakeRequest, MeshExtent};
+use rayon::prelude::*;
+use std::collections::{HashMap, HashSet};
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::surface_at;
+
+/// Barycentric coordinates of a triangle's three corners
+pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
+
+/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles
+#[derive(Clone, Debug, Default)]
+pub struct CageShell {
+ /// Low-poly position of each triangle corner, three per triangle
+ pub positions: Vec,
+ pub starts: Vec,
+ /// Corner pairs along the low poly's polygon edges, for the wireframe
+ pub edges: Vec<[u32; 2]>,
+ /// World units per unit of the max frontal distance setting
+ pub cage_units: f32,
+}
+
+impl CageShell {
+ /// The cage of `request`'s texture set, from the same ray starts the bake uses
+ pub fn new(request: &BakeRequest) -> Result {
+ let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
+ let (frame, mesh) = (&ray_frame, request.mesh);
+ let triangles: Vec = mesh.triangles_of(request.material).collect();
+ let (positions, starts): (Vec, Vec) = triangles
+ .par_iter()
+ .flat_map_iter(|&triangle| {
+ CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) {
+ Some(surface) => (surface.pos, frame.start(&surface, barycentric)),
+ None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }),
+ })
+ })
+ .unzip();
+
+ let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
+ let mut edge_corners = HashMap::new();
+ for (triangle_index, &triangle) in triangles.iter().enumerate() {
+ let Some(vertices) = mesh.tri(triangle) else { continue };
+
+ for corner in 0..3 {
+ let next = (corner + 1) % 3;
+ let (from, to) = (vertices[corner] as u32, vertices[next] as u32);
+ let key = (from.min(to), from.max(to));
+ if wire_edges.contains(&key) {
+ let first_corner = (triangle_index * 3) as u32;
+ edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]);
+ }
+ }
+ }
+ let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect();
+ edges.sort_unstable();
+
+ Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units })
+ }
+
+ /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling
+ pub fn corners(&self, max_frontal: f32) -> Vec {
+ let frontal = max_frontal * self.cage_units;
+ self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect()
+ }
+}
diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs
new file mode 100644
index 00000000..f957ce49
--- /dev/null
+++ b/crates/bake/src/cage/high_poly_reach.rs
@@ -0,0 +1,103 @@
+use super::{RayFrame, VertexReach};
+use crate::map::transfer_keys;
+use crate::tracing::ANY;
+use crate::{BakeError, BakeRequest, MeshExtent};
+use rayon::prelude::*;
+use texturecraft_core::MeshMatchMode;
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::{Mesh, surface_at};
+
+/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses
+#[derive(Clone, Debug, Default)]
+pub struct HighPolyReach {
+ /// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly
+ pub vertices: Vec>,
+ /// World units per unit of the cage distance settings
+ pub cage_units: f32,
+ pub ignore_backface: bool,
+}
+
+impl HighPolyReach {
+ /// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there
+ pub fn new(request: &BakeRequest) -> Result {
+ let Some(high) = request.high else { return Ok(HighPolyReach::default()) };
+
+ let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
+ let mut in_set = vec![false; request.mesh.triangle_count()];
+ for triangle in request.mesh.triangles_of(request.material) {
+ if let Some(flag) = in_set.get_mut(triangle) {
+ *flag = true;
+ }
+ }
+
+ let winding_normals = winding_normals(high.mesh);
+ let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode {
+ MeshMatchMode::Always => (Vec::new(), Vec::new()),
+ MeshMatchMode::ByMeshName => {
+ let (low_keys, high_keys) = transfer_keys(request);
+ (low_keys, vertex_keys(high.mesh, &high_keys))
+ }
+ };
+ let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY);
+ let frame = &frame;
+ let vertices = high
+ .mesh
+ .positions
+ .par_iter()
+ .zip(&winding_normals)
+ .enumerate()
+ .map(|(vertex, (&high_position, &high_facing))| {
+ let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?;
+ if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) {
+ return None;
+ }
+
+ let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?;
+ let ray_key = key(&low_keys, nearest.tri as usize);
+ Some(VertexReach {
+ low_position: surface.pos,
+ start: frame.start(&surface, [nearest.u, nearest.v]),
+ high_position,
+ high_facing,
+ name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key,
+ })
+ })
+ .collect();
+
+ Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface })
+ }
+
+ /// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's
+ pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option {
+ let reach = self.vertices.get(vertex).copied().flatten()?;
+ Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface))
+ }
+}
+
+/// Each vertex's mesh-name key, from the first triangle that uses it
+fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec {
+ let mut keys = vec![ANY; mesh.positions.len()];
+ for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) {
+ for &corner in corners {
+ if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) {
+ *key = triangle_key;
+ }
+ }
+ }
+ keys
+}
+
+/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front
+fn winding_normals(mesh: &Mesh) -> Vec {
+ let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
+ for corners in mesh.indices.chunks_exact(3) {
+ let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO);
+ let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0]));
+ for &corner in corners {
+ if let Some(normal) = normals.get_mut(corner as usize) {
+ *normal += winding_normal;
+ }
+ }
+ }
+ normals
+}
diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs
new file mode 100644
index 00000000..e8692cf2
--- /dev/null
+++ b/crates/bake/src/cage/ray_frame.rs
@@ -0,0 +1,63 @@
+use super::RayStart;
+use crate::MeshExtent;
+use crate::map::{interpolate, welded};
+use crate::skew::PreparedSkew;
+use crate::{BakeError, BakePaintMap, BakeRequest};
+use texturecraft_core::CageType;
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::{Mesh, Surface};
+
+/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount
+pub(crate) struct RayFrame<'a> {
+ mesh: &'a Mesh,
+ ray_normals: Vec,
+ cage: Option<&'a Mesh>,
+ skew: Option>,
+ cage_paint: Option<&'a BakePaintMap>,
+ /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead
+ ray_epsilon: f32,
+ /// World units per unit of the cage distance settings
+ pub(crate) cage_units: f32,
+}
+
+impl<'a> RayFrame<'a> {
+ pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> {
+ let settings = request.settings;
+ let ray_normals = match settings.cage.average_normals && request.high.is_some() {
+ true => {
+ let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal);
+ welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
+ }
+ false => Vec::new(),
+ };
+
+ Ok(RayFrame {
+ mesh: request.mesh,
+ ray_normals,
+ cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
+ skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?,
+ cage_paint: request.cage_paint,
+ ray_epsilon: extent.ray_epsilon(),
+ cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 },
+ })
+ }
+
+ /// Where the transfer ray of the low-poly point `surface` at `barycentric` starts
+ pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart {
+ let cage_offset = self
+ .cage
+ .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
+ .map(|cage_position| surface.pos - cage_position)
+ .filter(|offset| offset.length() > self.ray_epsilon);
+ if let Some(offset) = cage_offset {
+ return RayStart::CageMesh(offset);
+ }
+
+ let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
+ let up = match &self.skew {
+ Some(skew) => skew.correct(self.mesh, surface, averaged_normal),
+ None => averaged_normal,
+ };
+ RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) }
+ }
+}
diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs
new file mode 100644
index 00000000..c0c3923a
--- /dev/null
+++ b/crates/bake/src/cage/ray_start.rs
@@ -0,0 +1,20 @@
+use texturecraft_geom::glam::Vec3;
+
+/// Where the bake's transfer ray for one low-poly point starts
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum RayStart {
+ /// On the cage mesh: the offset from the cage to the low-poly point
+ CageMesh(Vec3),
+ /// Out along `up` by the frontal distance times `scale` (the painted cage amount)
+ Distance { up: Vec3, scale: f32 },
+}
+
+impl RayStart {
+ /// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance
+ pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 {
+ match *self {
+ RayStart::CageMesh(offset) => position - offset,
+ RayStart::Distance { up, scale } => position + up * frontal * scale,
+ }
+ }
+}
diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs
new file mode 100644
index 00000000..34adea92
--- /dev/null
+++ b/crates/bake/src/cage/vertex_reach.rs
@@ -0,0 +1,28 @@
+use super::RayStart;
+use texturecraft_geom::glam::Vec3;
+
+/// One high-poly vertex seen from the transfer ray through its nearest low-poly point
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct VertexReach {
+ pub low_position: Vec3,
+ pub start: RayStart,
+ pub high_position: Vec3,
+ /// The side the high poly's triangles face at the vertex, by their winding (not normalized)
+ pub high_facing: Vec3,
+ /// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name)
+ pub name_matches: bool,
+}
+
+impl VertexReach {
+ /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray
+ pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool {
+ let origin = self.start.origin(self.low_position, frontal);
+ let (direction, front) = match self.start {
+ RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()),
+ RayStart::Distance { up, scale } => (-up, frontal * scale),
+ };
+ let along_ray = (self.high_position - origin).dot(direction);
+
+ !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0)
+ }
+}
diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs
index a8b087bc..eb8a61de 100644
--- a/crates/bake/src/lib.rs
+++ b/crates/bake/src/lib.rs
@@ -6,13 +6,17 @@
mod bake_error;
mod bake_output;
mod bake_request;
+mod cage;
mod high_poly;
+mod mesh_extent;
mod progress;
pub use bake_error::BakeError;
pub use bake_output::BakeOutput;
pub use bake_request::BakeRequest;
+pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach};
pub use high_poly::HighPoly;
+pub(crate) use mesh_extent::MeshExtent;
pub use progress::Progress;
mod map;
diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs
index 384d9d02..c9c30fd6 100644
--- a/crates/bake/src/map.rs
+++ b/crates/bake/src/map.rs
@@ -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;
diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs
index 21fed094..f3e35df6 100644
--- a/crates/bake/src/map/bake_context.rs
+++ b/crates/bake/src/map/bake_context.rs
@@ -1,28 +1,22 @@
use super::curvature::Curvature;
-use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded};
+use super::sampling::{pack, splitmix64, tangent_normal};
use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer};
-use crate::skew::PreparedSkew;
+use crate::cage::{RayFrame, RayStart};
use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh};
-use crate::{BakeError, BakeRequest};
+use crate::{BakeError, BakeRequest, MeshExtent};
use rayon::prelude::*;
-use std::collections::HashMap;
use texturecraft_core::{
- AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
+ AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
};
-use texturecraft_geom::glam::Vec3;
-use texturecraft_geom::{Hit, Mesh, Surface, surface_at};
+use texturecraft_geom::{Hit, Surface, surface_at};
const CURVATURE_CHUNK: usize = 1 << 15;
pub(crate) struct BakeContext<'a> {
low: Source<'a>,
high: Option>,
- cage: Option<&'a Mesh>,
- skew: Option>,
- cage_paint: Option<&'a crate::BakePaintMap>,
- ray_normals: Vec,
+ ray_frame: RayFrame<'a>,
settings: &'a BakeSettings,
- eps: f32,
frontal: f32,
rear: f32,
position: PositionProjection,
@@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> {
impl<'a> BakeContext<'a> {
pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> {
let settings = request.settings;
- let (bounds_min, bounds_max) = request.mesh.bounds();
- let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6);
- if !mesh_diagonal.is_finite() {
- return Err(BakeError::Invalid("mesh bounds are too large".into()));
- }
-
- let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6);
- let mut name_keys = HashMap::new();
- let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys);
- let high = request.high.map(|high_mesh| {
- Source::new(
- high_mesh.mesh,
- high_mesh.bvh,
- high_mesh.base_color,
- high_mesh.file_ids,
- &settings.high_poly.high_suffix,
- &settings.high_poly,
- &mut name_keys,
- )
- });
- let ray_normals = match settings.cage.average_normals && high.is_some() {
- true => {
- let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal);
- welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
- }
- false => Vec::new(),
- };
-
- let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?;
- let ray_epsilon = 1e-6 * mesh_diagonal;
+ let extent = MeshExtent::of(request.mesh)?;
+ let (low, high) = Source::of_request(request);
+ let ray_frame = RayFrame::new(request, extent)?;
+ let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon());
let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| {
let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians();
let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 };
@@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> {
pass.ignore_backface = parameters.ignore_backface;
pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName;
pass.attenuation = parameters.attenuation;
- pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset);
+ pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset);
}
+
let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion);
if let Some(pass) = &mut bent {
pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface;
pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName;
}
+
let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness);
if let Some(pass) = &mut thickness {
pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName;
}
- let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 };
+
+ let cage_units = ray_frame.cage_units;
Ok(BakeContext {
low,
high,
- cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
- skew,
- cage_paint: request.cage_paint,
- ray_normals,
+ ray_frame,
settings,
- eps: ray_epsilon,
frontal: settings.cage.max_frontal * cage_units,
rear: settings.cage.max_rear * cage_units,
position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters),
@@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> {
}
pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) {
- let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
- let cage = self
- .cage
- .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
- .map(|cage_position| surface.pos - cage_position)
- .filter(|offset| offset.length() > self.eps);
- let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv));
- let (origin, direction, front) = match cage {
- Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()),
- None => {
- let up = match &self.skew {
- Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal),
- None => averaged_normal,
- };
- (surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale)
- }
+ let start = self.ray_frame.start(surface, barycentric);
+ let origin = start.origin(surface.pos, self.frontal);
+ let (direction, front) = match start {
+ RayStart::CageMesh(offset) => (offset.normalize(), offset.length()),
+ RayStart::Distance { up, scale } => (-up, self.frontal * scale),
};
let key = match self.settings.high_poly.match_mode {
MeshMatchMode::Always => ANY,
diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs
index d19e4afa..5f2d2677 100644
--- a/crates/bake/src/map/sampling.rs
+++ b/crates/bake/src/map/sampling.rs
@@ -3,34 +3,43 @@ use std::ops::{Add, Mul};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, Surface};
-pub(super) fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option {
- let [a, b, c] = mesh.tri(tri as usize)?;
- Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2)
+/// `values` (one per vertex) at `barycentric` in triangle `triangle`
+pub(crate) fn interpolate + Add>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option {
+ let [first, second, third] = mesh.tri(triangle as usize)?;
+ let [second_weight, third_weight] = barycentric;
+
+ Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight)
}
-pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) {
- let q = diag * 1e-5;
- let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
- let (mut pos, mut nrm) = (Vec::new(), Vec::::new());
- let weld: Vec = mesh
+/// Vertices closer than this fraction of the mesh diagonal count as one when welding
+const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5;
+
+/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals
+pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec, Vec, Vec) {
+ let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL;
+ let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new();
+ let (mut positions, mut normal_sums) = (Vec::new(), Vec::::new());
+
+ let welded_indices: Vec = mesh
.positions
.iter()
.zip(&mesh.normals)
- .map(|(p, n)| {
- let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64);
- let id = *ids.entry(key).or_insert_with(|| {
- pos.push(*p);
- nrm.push(Vec3::ZERO);
- (pos.len() - 1) as u32
+ .map(|(position, normal)| {
+ let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64);
+ let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| {
+ positions.push(*position);
+ normal_sums.push(Vec3::ZERO);
+ (positions.len() - 1) as u32
});
- if let Some(acc) = nrm.get_mut(id as usize) {
- *acc += *n;
+ if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) {
+ *normal_sum += *normal;
}
- id
+ welded_index
})
.collect();
- let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
- (weld, pos, nrm)
+
+ let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect();
+ (welded_indices, positions, normals)
}
pub(super) fn splitmix64(x: u64) -> u64 {
diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs
index 0e1f9164..ad057b11 100644
--- a/crates/bake/src/map/source.rs
+++ b/crates/bake/src/map/source.rs
@@ -1,4 +1,5 @@
use super::sampling::{generated_hue, interpolate, splitmix64};
+use crate::BakeRequest;
use crate::tracing::{ANY, TraceMesh};
use std::collections::HashMap;
use std::sync::Arc;
@@ -21,6 +22,18 @@ pub(super) struct Source<'a> {
}
impl<'a> Source<'a> {
+ /// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part
+ pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option>) {
+ let settings = &request.settings.high_poly;
+ let mut name_keys = HashMap::new();
+ let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys);
+ let high = request.high.map(|high_mesh| {
+ Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys)
+ });
+
+ (low, high)
+ }
+
pub(super) fn new(
mesh: &'a Mesh,
bvh: &'a Bvh,
diff --git a/crates/bake/src/map/transfer_keys.rs b/crates/bake/src/map/transfer_keys.rs
new file mode 100644
index 00000000..69e9b12a
--- /dev/null
+++ b/crates/bake/src/map/transfer_keys.rs
@@ -0,0 +1,8 @@
+use super::source::Source;
+use crate::BakeRequest;
+
+/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key
+pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec, Vec) {
+ let (low, high) = Source::of_request(request);
+ (low.key, high.map(|high| high.key).unwrap_or_default())
+}
diff --git a/crates/bake/src/mesh_extent.rs b/crates/bake/src/mesh_extent.rs
new file mode 100644
index 00000000..3c6fa48d
--- /dev/null
+++ b/crates/bake/src/mesh_extent.rs
@@ -0,0 +1,35 @@
+use crate::BakeError;
+use texturecraft_geom::Mesh;
+use texturecraft_geom::glam::Vec3;
+
+/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances
+const MIN_MESH_SIZE: f32 = 1e-6;
+
+/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal
+const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6;
+
+/// The low-poly mesh's size, which scales the bake's relative distances
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct MeshExtent {
+ pub(crate) bounds_min: Vec3,
+ pub(crate) diagonal: f32,
+ /// The bounding box's largest side
+ pub(crate) scale: f32,
+}
+
+impl MeshExtent {
+ pub(crate) fn of(mesh: &Mesh) -> Result {
+ let (bounds_min, bounds_max) = mesh.bounds();
+ let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE);
+ if !diagonal.is_finite() {
+ return Err(BakeError::Invalid("mesh bounds are too large".into()));
+ }
+
+ Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) })
+ }
+
+ /// How far a ray starts past the surface it leaves, in world units
+ pub(crate) fn ray_epsilon(&self) -> f32 {
+ RAY_EPSILON_PER_DIAGONAL * self.diagonal
+ }
+}
diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs
new file mode 100644
index 00000000..2d114b06
--- /dev/null
+++ b/crates/bake/src/test/cage_shell.rs
@@ -0,0 +1,103 @@
+use super::settings;
+use crate::cage::CORNERS;
+use crate::map::BakeContext;
+use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly};
+use texturecraft_core::{BakedMap, CageType};
+use texturecraft_geom::glam::{Vec2, Vec3};
+use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
+
+/// A painted map whose values vary over the UV square
+fn painted_map() -> BakePaintMap {
+ let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap();
+ map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap();
+ map
+}
+
+/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit
+fn assert_cage_matches_the_ray_origins(request: &BakeRequest) {
+ let shell = CageShell::new(request).unwrap();
+ let corners = shell.corners(request.settings.cage.max_frontal);
+ let context = BakeContext::new(request).unwrap();
+ let triangles: Vec = request.mesh.triangles_of(request.material).collect();
+ assert_eq!(corners.len(), triangles.len() * 3);
+
+ for (corner_index, corner) in corners.iter().enumerate() {
+ let barycentric = CORNERS[corner_index % 3];
+ let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap();
+ let (ray, _) = context.transfer_ray(&surface, barycentric);
+ assert_eq!(*corner, ray.origin, "corner {corner_index}");
+ }
+}
+
+#[test]
+fn the_cage_corners_are_the_bake_ray_origins() {
+ let low = primitives::cube(1.0);
+ let high_mesh = primitives::sphere(0.8, 16, 8);
+ let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
+ let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
+ let (skew, cage_paint) = (painted_map(), painted_map());
+ let mut bake_settings = settings(16, &[BakedMap::Normal]);
+ bake_settings.cage.max_frontal = 0.03;
+ bake_settings.skew.edge_protection = true;
+ let request = |settings| BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material: 0,
+ settings,
+ high: Some(high),
+ cage: None,
+ skew: Some(&skew),
+ cage_paint: Some(&cage_paint),
+ tiles: (1, 1),
+ };
+
+ assert_cage_matches_the_ray_origins(&request(&bake_settings));
+ let face_normals = {
+ let mut face_normals = bake_settings.clone();
+ face_normals.cage.average_normals = false;
+ face_normals.cage.relative_to_bounding_box = false;
+ face_normals
+ };
+ assert_cage_matches_the_ray_origins(&request(&face_normals));
+}
+
+#[test]
+fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() {
+ let low = primitives::cube(1.0);
+ let low_bvh = Bvh::new(&low);
+ let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] };
+ let mut bake_settings = settings(16, &[BakedMap::Normal]);
+ bake_settings.cage.relative_to_bounding_box = false;
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material: 0,
+ settings: &bake_settings,
+ high: Some(high),
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let shell = CageShell::new(&request).unwrap();
+ let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max);
+
+ assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly");
+ // Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis
+ assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance");
+ assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge");
+
+ let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() };
+ let custom_settings = {
+ let mut custom_settings = bake_settings.clone();
+ custom_settings.cage.kind = CageType::CustomFile;
+ custom_settings
+ };
+ let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request };
+ assert_cage_matches_the_ray_origins(&custom);
+ let corners = CageShell::new(&custom).unwrap().corners(0.0);
+ assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is");
+ assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO));
+}
diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs
new file mode 100644
index 00000000..e6d66d07
--- /dev/null
+++ b/crates/bake/src/test/high_poly_reach.rs
@@ -0,0 +1,222 @@
+use super::settings;
+use crate::map::{BakeContext, transfer_keys};
+use crate::tracing::ANY;
+use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart};
+use texturecraft_core::{BakedMap, MeshMatchMode};
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
+
+/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them
+const BOUNDARY: f32 = 1e-4;
+
+/// How close the ray's hit must be to the vertex to count as reaching it
+const HIT_TOLERANCE: f32 = 1e-4;
+
+/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way
+fn bumpy_high_poly() -> (Mesh, Vec) {
+ const FLIPPED_FROM_X: f32 = 0.2;
+
+ let mut mesh = primitives::plane(1.0, 40);
+ for position in &mut mesh.positions {
+ position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005;
+ }
+
+ let mut flipped = vec![false; mesh.positions.len()];
+ let mut unflipped = vec![false; mesh.positions.len()];
+ for corners in mesh.indices.chunks_exact_mut(3) {
+ let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0;
+ if center_x > FLIPPED_FROM_X {
+ corners.swap(1, 2);
+ }
+ for &corner in corners.iter() {
+ if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true }
+ }
+ }
+ // Vertices on the border face both ways: neither answer is right for them
+ let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect();
+ (mesh, mixed)
+}
+
+#[test]
+fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() {
+ let low = primitives::plane(1.0, 8);
+ let (high_mesh, mixed) = bumpy_high_poly();
+ let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
+ let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
+ let back_facing = |triangle: u32, direction: Vec3| {
+ let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]);
+ (b - a).cross(c - a).dot(direction) > 0.0
+ };
+ let mut checked = [0usize; 2];
+
+ for ignore_backface in [false, true] {
+ for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] {
+ let mut bake_settings = settings(16, &[BakedMap::Normal]);
+ bake_settings.cage.relative_to_bounding_box = false;
+ bake_settings.high_poly.ignore_backface = ignore_backface;
+ (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear);
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material: 0,
+ settings: &bake_settings,
+ high: Some(high),
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let reach = HighPolyReach::new(&request).unwrap();
+ let context = BakeContext::new(&request).unwrap();
+
+ for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
+ let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap());
+ let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") };
+ let height = vertex_reach.high_position.y - vertex_reach.low_position.y;
+ let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY);
+ if near_the_range_end || mixed[vertex] {
+ continue;
+ }
+
+ let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
+ let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
+ let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
+ let hit = high_bvh
+ .closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction)));
+ let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
+ assert_eq!(
+ missed, !reaches_the_vertex,
+ "vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}"
+ );
+ checked[usize::from(missed)] += 1;
+ }
+ }
+ }
+ assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}");
+}
+
+#[test]
+fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() {
+ let mut low = primitives::plane(1.0, 4);
+ let mut right = primitives::plane(1.0, 4);
+ for position in &mut right.positions {
+ position.x += 2.0;
+ }
+ low.append(&right);
+ assert_eq!(low.materials.len(), 2, "each plane is its own texture set");
+ let mut high_mesh = primitives::plane(3.0, 30);
+ for position in &mut high_mesh.positions {
+ position.x += 1.0;
+ position.y = 0.3;
+ }
+ let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
+ let bake_settings = settings(16, &[BakedMap::Normal]);
+ let request = |material| BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material,
+ settings: &bake_settings,
+ high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap());
+
+ for (vertex, position) in high_mesh.positions.iter().enumerate() {
+ let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some());
+ assert!(owners != (true, true), "vertex {vertex} belongs to one set at most");
+ if position.x < 0.9 {
+ assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set");
+ } else if position.x > 1.1 {
+ assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set");
+ }
+ }
+}
+
+#[test]
+fn matching_by_mesh_name_misses_the_parts_with_another_name() {
+ const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01;
+
+ let mut low = primitives::plane(1.0, 8);
+ low.submeshes[0].name = "part_low".into();
+ let mut high_mesh = primitives::plane(0.5, 10);
+ let mut other_part = primitives::plane(0.5, 10);
+ for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] {
+ for position in &mut mesh.positions {
+ position.x += center_x;
+ position.y = HEIGHT_INSIDE_THE_CAGE;
+ }
+ }
+ high_mesh.append(&other_part);
+ high_mesh.submeshes[0].name = "part_high".into();
+ high_mesh.submeshes[1].name = "other_high".into();
+ let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
+ let mut bake_settings = settings(16, &[BakedMap::Normal]);
+ bake_settings.cage.relative_to_bounding_box = false;
+ bake_settings.cage.max_frontal = 0.02;
+ bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName;
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material: 0,
+ settings: &bake_settings,
+ high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let reach = HighPolyReach::new(&request).unwrap();
+ let context = BakeContext::new(&request).unwrap();
+ let (_, high_keys) = transfer_keys(&request);
+
+ for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
+ let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap());
+ // On the line where the two parts meet, a ray reaches either part's triangles
+ if vertex_reach.high_position.x.abs() < BOUNDARY {
+ continue;
+ }
+
+ let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
+ let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
+ let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
+ let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key);
+ let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name);
+ let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
+ assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position);
+ assert_eq!(
+ missed,
+ vertex >= high_mesh.positions.len() - other_part.positions.len(),
+ "only the part named like the low poly is reached: vertex {vertex}"
+ );
+ }
+}
+
+#[test]
+fn without_a_high_poly_no_vertex_has_a_reach() {
+ let low = primitives::plane(1.0, 4);
+ let low_bvh = Bvh::new(&low);
+ let bake_settings = settings(16, &[BakedMap::Normal]);
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material: 0,
+ settings: &bake_settings,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+
+ let reach = HighPolyReach::new(&request).unwrap();
+ assert!(reach.vertices.is_empty());
+ // Any cage distances: there is no vertex to miss
+ assert_eq!(reach.missed(0, 0.02, 0.01), None);
+}
diff --git a/crates/bake/src/test/vertex_reach.rs b/crates/bake/src/test/vertex_reach.rs
new file mode 100644
index 00000000..7675e8dc
--- /dev/null
+++ b/crates/bake/src/test/vertex_reach.rs
@@ -0,0 +1,51 @@
+use crate::{RayStart, VertexReach};
+use texturecraft_geom::glam::Vec3;
+
+/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25
+const FRONTAL: f32 = 0.5;
+const REAR: f32 = 0.25;
+
+/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage
+const IGNORED_FRONTAL: f32 = 9.0;
+
+/// How far past an end of the ray's range a vertex counts as outside it
+const PAST_THE_END: f32 = 1e-3;
+
+/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing`
+fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach {
+ VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches }
+}
+
+#[test]
+fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() {
+ // A painted cage amount of 2 doubles the frontal distance
+ let starts = [
+ (RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL),
+ (RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0),
+ (RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL),
+ ];
+ let (top, bottom) = (FRONTAL, -REAR);
+ // Height, facing, name matches, ignore backface: missed
+ let cases = [
+ (top, Vec3::Y, true, false, false),
+ (bottom, Vec3::Y, true, false, false),
+ (0.0, Vec3::Y, true, false, false),
+ (top + PAST_THE_END, Vec3::Y, true, false, true),
+ (bottom - PAST_THE_END, Vec3::Y, true, false, true),
+ (0.0, Vec3::Y, false, false, true),
+ (0.0, Vec3::NEG_Y, true, false, false),
+ (0.0, Vec3::NEG_Y, true, true, true),
+ (0.0, Vec3::Y, true, true, false),
+ ];
+
+ for (start, frontal) in starts {
+ for (height, facing, name_matches, ignore_backface, missed) in cases {
+ let reach = vertex(start, height, facing, name_matches);
+ assert_eq!(
+ reach.missed(frontal, REAR, ignore_backface),
+ missed,
+ "{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}"
+ );
+ }
+ }
+}
diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs
index a3d80571..1bf7fa25 100644
--- a/crates/bake/src/tests.rs
+++ b/crates/bake/src/tests.rs
@@ -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(
{
diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs
index 36b5f856..3fe26e04 100644
--- a/crates/core/src/project.rs
+++ b/crates/core/src/project.rs
@@ -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,
pub layers: BTreeMap,
@@ -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(),
diff --git a/crates/engine/src/bake/bake_cage_inputs.rs b/crates/engine/src/bake/bake_cage_inputs.rs
new file mode 100644
index 00000000..ab559beb
--- /dev/null
+++ b/crates/engine/src/bake/bake_cage_inputs.rs
@@ -0,0 +1,45 @@
+use super::MergedHigh;
+use std::sync::Arc;
+use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach};
+use texturecraft_core::BakeSettings;
+use texturecraft_geom::{Bvh, Mesh};
+
+/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it
+#[derive(Clone, Debug)]
+pub struct BakeCageInputs {
+ pub(super) mesh: Arc,
+ pub(super) bvh: Arc,
+ pub(super) material: usize,
+ pub(super) settings: BakeSettings,
+ pub(super) high: MergedHigh,
+ pub(super) cage: Option>,
+ pub(super) skew: Option>,
+ pub(super) cage_paint: Option>,
+}
+
+impl BakeCageInputs {
+ /// The cage the 3D view draws: the bake's ray origins at each triangle corner
+ pub fn cage_shell(&self) -> Result {
+ CageShell::new(&self.request())
+ }
+
+ /// Where each high-poly vertex sits relative to the bake's transfer rays
+ pub fn high_poly_reach(&self) -> Result {
+ HighPolyReach::new(&self.request())
+ }
+
+ fn request(&self) -> BakeRequest<'_> {
+ BakeRequest {
+ low_base_color: &[],
+ mesh: &self.mesh,
+ bvh: &self.bvh,
+ material: self.material,
+ settings: &self.settings,
+ high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }),
+ cage: self.cage.as_deref(),
+ skew: self.skew.as_deref(),
+ cage_paint: self.cage_paint.as_deref(),
+ tiles: (1, 1),
+ }
+ }
+}
diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs
index 260002db..da0e4a97 100644
--- a/crates/engine/src/bake/bake_meshes.rs
+++ b/crates/engine/src/bake/bake_meshes.rs
@@ -14,6 +14,11 @@ pub struct BakeMeshes {
}
impl BakeMeshes {
+ /// Every high poly appended into one mesh, as bakes see it
+ pub fn merged_high(&self) -> Option<&MergedHigh> {
+ self.merged.as_ref()
+ }
+
pub(crate) fn rebuild(&mut self) {
self.merged = (!self.high.is_empty()).then(|| {
let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new());
diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs
index 8c942176..24629b56 100644
--- a/crates/engine/src/bake/bake_task.rs
+++ b/crates/engine/src/bake/bake_task.rs
@@ -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 {
+ self.settings.maps.enabled().collect()
+ }
+
+ /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
+ /// and return all of them together. Each map is a bake of its own, so with a high poly
+ /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
+ /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
+ /// The handed-over buffers are the returned ones too (no copy is made), so a preview that
+ /// keeps them costs no second set of maps. A cancel or an error leaves the maps already
+ /// handed over whole.
+ pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result {
+ let maps = self.maps();
+ let total = maps.len();
+ let mut combined: Option = None;
+
+ for (index, map) in maps.iter().copied().enumerate() {
+ let mut settings = self.settings.clone();
+ settings.maps.select([map]);
+ let mut output = self.run_with(&settings, progress)?;
+ let Some(data) = output.maps.remove(&map) else { continue };
+ if combined.is_none() {
+ // Retain unchecked maps once, using the full selection rather than this one-map pass.
+ super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?;
+ }
+
+ let data = Arc::new(data);
+ on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() });
+ match &mut combined {
+ Some(combined) => {
+ combined.maps.insert(map, data);
+ }
+ None => {
+ // A resized partial bake also returns unchecked maps that must survive application
+ let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
+ retained.insert(map, data);
+ combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer });
+ }
+ }
+ }
+
+ match combined {
+ Some(output) => Ok(output),
+ None => {
+ let output = self.run(progress)?;
+ Ok(StreamedBake {
+ resolution: output.resolution,
+ height: output.height,
+ maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
+ tracer: output.tracer,
+ })
+ }
+ }
+ }
+
pub fn run(&self, progress: &Progress) -> Result {
+ let mut output = self.run_with(&self.settings, progress)?;
+ super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
+ Ok(output)
+ }
+
+ fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result {
let high =
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
let request = BakeRequest {
@@ -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::>(), whole.maps.keys().collect::>());
+ for (map, pixels) in &whole.maps {
+ assert_eq!(*output.maps[map], *pixels, "{map:?} must preserve the ordinary bake's pixels");
+ }
+ for map in handed_over {
+ assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]), "streaming must keep sharing the baked buffer");
+ }
+ }
+ }
+
+ #[test]
+ fn cancelling_a_partial_stream_does_not_resample_future_maps() {
+ let task = partial_task(&SELECTED_MAPS, true, true);
+ let whole = task.run(&Progress::new()).unwrap();
+ super::super::preserve_tiles::take_retained_allocations();
+ let progress = Progress::new();
+ let mut handed_over = Vec::new();
+ let result = task.run_streaming(&progress, &mut |map| {
+ handed_over.push(map);
+ progress.cancel();
+ });
+ assert!(result.is_err());
+ assert_eq!(handed_over.len(), 1);
+ for map in handed_over {
+ assert_eq!(*map.data, whole.maps[&map.map], "cancellation leaves the handed-over map whole");
+ }
+ assert_eq!(super::super::preserve_tiles::take_retained_allocations(), [BakedMap::Normal]);
+ }
+
+ #[test]
+ fn an_empty_streaming_selection_keeps_the_ordinary_bake_behavior() {
+ let task = partial_task(&[], true, true);
+ super::super::preserve_tiles::take_retained_allocations();
+ let whole = task.run(&Progress::new());
+ let expected_allocations = super::super::preserve_tiles::take_retained_allocations();
+ let output = task.run_streaming(&Progress::new(), &mut |_| panic!("an empty selection must not stream a map"));
+ assert_eq!(super::super::preserve_tiles::take_retained_allocations(), expected_allocations);
+ match (whole, output) {
+ (Ok(whole), Ok(output)) => {
+ assert_eq!((output.resolution, output.height), (whole.resolution, whole.height));
+ assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>());
+ for (map, pixels) in whole.maps {
+ assert_eq!(*output.maps[&map], pixels);
+ }
+ }
+ (Err(whole), Err(output)) => assert_eq!(whole.to_string(), output.to_string()),
+ _ => panic!("empty streaming and ordinary bakes must agree"),
+ }
+ }
+}
diff --git a/crates/engine/src/bake/high_poly_missed.rs b/crates/engine/src/bake/high_poly_missed.rs
new file mode 100644
index 00000000..21de6c05
--- /dev/null
+++ b/crates/engine/src/bake/high_poly_missed.rs
@@ -0,0 +1,23 @@
+use rayon::prelude::*;
+use texturecraft_bake::HighPolyReach;
+
+/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0
+/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked
+/// `vertex_count` is the validated high-poly mesh's vertex count
+pub fn high_poly_missed(reach: &[Option], distances: &[(f32, f32)], only_set: Option, vertex_count: usize) -> Vec {
+ // Ownership is already assigned by HighPolyReach; other sets must not color the vertex
+ let sets: Vec<(&HighPolyReach, f32, f32)> = reach
+ .iter()
+ .zip(distances)
+ .enumerate()
+ .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set))
+ .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear)))
+ .collect();
+ (0..vertex_count)
+ .into_par_iter()
+ .map(|vertex| {
+ let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear));
+ f32::from(u8::from(missed.unwrap_or(false)))
+ })
+ .collect()
+}
diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs
index e5982f18..14248cc3 100644
--- a/crates/engine/src/bake/mesh_map_command.rs
+++ b/crates/engine/src/bake/mesh_map_command.rs
@@ -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) -> Result {
}
impl Session {
- pub fn bake_task(&self, ts: usize) -> Result {
- let set = self.doc.project.texture_set(ts)?;
+ pub fn bake_task(&self, texture_set: usize) -> Result {
+ let set = self.doc.project.texture_set(texture_set)?;
if !set.has_enabled_bake_tiles() {
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
}
@@ -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> {
+ let set = self.doc.project.texture_set(texture_set)?;
+ let Some(high) = self.bake_high(texture_set)? else { return Ok(None) };
+ let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) };
+
+ Ok(Some(BakeCageInputs {
+ mesh: self.bake_mesh(texture_set)?,
+ bvh: self.bvh.clone(),
+ material: set.material,
+ settings: set.bake.clone(),
+ high,
+ cage,
+ skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?,
+ cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?,
+ }))
+ }
+
+ /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly
+ fn bake_high(&self, texture_set: usize) -> Result > {
+ let set = self.doc.project.texture_set(texture_set)?;
+ Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() })
+ }
+
+ /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage
+ fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result >> {
+ let set = self.doc.project.texture_set(texture_set)?;
+ if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile {
+ return Ok(None);
+ }
+
+ let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?;
+ Ok(Some(cage.mesh.clone()))
+ }
+
+ /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly
+ fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result >> {
+ let set = self.doc.project.texture_set(texture_set)?;
+ let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high);
+ paint.map(|map| super::layout::paint_for_bake(map, set)).transpose()
+ }
+
+ /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas
+ fn bake_mesh(&self, texture_set: usize) -> Result> {
+ let set = self.doc.project.texture_set(texture_set)?;
+ Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) {
+ Some(grid) => {
+ let mut mesh = (*self.source).clone();
+ mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array())));
+ Arc::new(mesh)
+ }
+ None => self.mesh.clone(),
+ })
+ }
+
/// Store a finished bake as one undo step
pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
let tracer = output.tracer.clone();
@@ -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>>) -> 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(())
}
diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs
index 213e1ff6..f06ab265 100644
--- a/crates/engine/src/bake/mod.rs
+++ b/crates/engine/src/bake/mod.rs
@@ -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;
diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs
index 27c74ae8..f44a09a4 100644
--- a/crates/engine/src/bake/preserve_tiles.rs
+++ b/crates/engine/src/bake/preserve_tiles.rs
@@ -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> = const { std::cell::RefCell::new(Vec::new()) };
+}
+
+#[cfg(test)]
+pub(super) fn take_retained_allocations() -> Vec {
+ RETAINED_ALLOCATIONS.with(|allocations| std::mem::take(&mut *allocations.borrow_mut()))
+}
diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs
new file mode 100644
index 00000000..55aecbca
--- /dev/null
+++ b/crates/engine/src/bake/streamed_bake.rs
@@ -0,0 +1,14 @@
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use texturecraft_core::BakedMap;
+
+/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them,
+/// so the preview and the document hold one buffer per map, never two
+#[derive(Clone, Debug)]
+pub struct StreamedBake {
+ pub resolution: u32,
+ pub height: u32,
+ pub maps: BTreeMap>>,
+ pub tracer: String,
+}
diff --git a/crates/engine/src/bake/streamed_map.rs b/crates/engine/src/bake/streamed_map.rs
new file mode 100644
index 00000000..33781099
--- /dev/null
+++ b/crates/engine/src/bake/streamed_map.rs
@@ -0,0 +1,17 @@
+use std::sync::Arc;
+
+use texturecraft_core::BakedMap;
+
+/// One finished map of a streamed bake (see [`crate::BakeTask::run_streaming`]).
+#[derive(Clone, Debug)]
+pub struct StreamedMap {
+ pub map: BakedMap,
+ /// Position among the maps this bake makes, from 0, and how many there are.
+ pub index: usize,
+ pub total: usize,
+ /// Width and height in texels.
+ pub resolution: u32,
+ pub height: u32,
+ /// Row-major, `map.components()` floats per texel, padded.
+ pub data: Arc>,
+}
diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs
new file mode 100644
index 00000000..878fb276
--- /dev/null
+++ b/crates/engine/src/bake_preview.rs
@@ -0,0 +1,236 @@
+//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon
+//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in
+//! the document: nothing enters the undo history until a texture set's bake is applied
+//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already
+//! applied keep their results and undo steps. The preview shows one map at a time, raw on the
+//! model; maps and texture sets not baked yet show their neutral value.
+
+mod preview_set;
+mod preview_show;
+mod stage;
+
+pub use preview_set::PreviewSet;
+pub use preview_show::PreviewShow;
+pub use stage::Stage;
+
+use std::collections::BTreeMap;
+
+use serde_json::{Value, json};
+use texturecraft_compose::BakedMaps;
+use texturecraft_core::BakedMap;
+
+use crate::bake::StreamedMap;
+use crate::commands::{CommandSpec, always, bad, strp};
+use crate::session::ViewMode;
+use crate::{Result, Session, cmd};
+
+/// What painting says while a bake preview shows (the app translates it).
+pub const PAINTING_PAUSED: &str = "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.";
+
+pub fn specs() -> Vec {
+ vec![cmd!(
+ "bake.preview",
+ "Bake preview",
+ [],
+ None,
+ "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)",
+ always,
+ preview
+ )]
+}
+
+#[derive(Clone, Debug)]
+pub struct BakePreview {
+ /// The view mode to put back when the preview ends.
+ pub restore: ViewMode,
+ pub show: PreviewShow,
+ pub sets: BTreeMap,
+ /// The texture set being baked.
+ pub current: Option,
+ /// The last map that finished.
+ pub newest: Option,
+}
+
+impl BakePreview {
+ /// The map the view shows, None for the material.
+ pub fn shown(&self) -> Option {
+ match self.show {
+ PreviewShow::Material => None,
+ PreviewShow::Pin(map) => Some(map),
+ PreviewShow::Follow => self
+ .newest
+ .or_else(|| self.current_set().and_then(|set| set.order.first().copied()))
+ .or_else(|| self.sets.values().find_map(|set| set.order.first().copied())),
+ }
+ }
+
+ pub fn current_set(&self) -> Option<&PreviewSet> {
+ self.sets.get(&self.current?)
+ }
+
+ /// The map being baked now (None between sets and once the set's maps are all in).
+ pub fn stage(&self) -> Option {
+ let texture_set = self.current?;
+ let set = self.sets.get(&texture_set)?;
+ let done = set.baked.maps.len();
+ Some(Stage { texture_set, map: *set.order.get(done)?, position: done + 1, total: set.order.len() })
+ }
+}
+
+impl Session {
+ /// Start a preview from each selected texture set's enabled maps, in the same order as
+ /// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before
+ /// changing the preview or view mode. This reads settings without preparing bake geometry.
+ pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> {
+ let orders = sets
+ .iter()
+ .map(|&texture_set| {
+ let set = self.doc.project.texture_set(texture_set)?;
+ Ok((texture_set, set.bake.maps.enabled().collect()))
+ })
+ .collect::>>()?;
+
+ self.bake_preview_begin(orders);
+ Ok(())
+ }
+
+ /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view
+ /// follows the newest map and every set shows neutral values until its maps arrive. The
+ /// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is
+ /// discarded so a later pointer release cannot commit paint during the preview.
+ pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec)>) {
+ self.cancel_stroke();
+
+ let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore);
+ let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect();
+
+ self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None });
+ self.bake_preview_refresh();
+ }
+
+ /// The texture set whose maps stream in now.
+ pub fn bake_preview_set_current(&mut self, texture_set: usize) {
+ if let Some(preview) = &mut self.bake_preview {
+ preview.current = Some(texture_set);
+ }
+
+ self.bake_preview_refresh();
+ }
+
+ /// Install one finished map of set `texture_set`. Returns false when no preview shows.
+ pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool {
+ let Some(preview) = &mut self.bake_preview else { return false };
+
+ let set = preview.sets.entry(texture_set).or_default();
+
+ // A new bake of the set starts from nothing (the baker never repeats a map)
+ if streamed.index == 0 {
+ set.baked = BakedMaps::default();
+ }
+
+ set.baked.resolution = streamed.resolution;
+ set.baked.maps.insert(streamed.map, streamed.data);
+ preview.newest = Some(streamed.map);
+ self.bake_preview_refresh();
+ true
+ }
+
+ /// Choose what the view shows (Follow, a pinned map or the material).
+ pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> {
+ let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) };
+
+ preview.show = show;
+ self.bake_preview_refresh();
+ Ok(())
+ }
+
+ /// The user picked a view mode during a bake: a mesh map pins it, any other mode shows
+ /// the material and is what comes back when the bake ends.
+ pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) {
+ let Some(preview) = &mut self.bake_preview else { return };
+
+ match view {
+ ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map),
+ other => {
+ preview.show = PreviewShow::Material;
+ preview.restore = other;
+ }
+ }
+
+ self.bake_preview_refresh();
+ if !matches!(view, ViewMode::MeshMap(_)) {
+ self.view = view;
+ }
+ }
+
+ /// Drop the displayed maps and restore the previous view mode. This does not stop a
+ /// worker or undo any applied results; the UI also uses it when leaving Bake mode.
+ pub fn bake_preview_end(&mut self) {
+ if let Some(preview) = self.bake_preview.take() {
+ self.view = preview.restore;
+ self.revision = self.revision.wrapping_add(1);
+ }
+ }
+
+ pub fn bake_preview_active(&self) -> bool {
+ self.bake_preview.is_some()
+ }
+
+ /// The streamed maps of set `texture_set` while a preview shows (empty for a set not baked
+ /// yet: neutral values), None when the document's baked maps are what shows.
+ pub fn bake_preview_baked(&self, texture_set: usize) -> Option<&BakedMaps> {
+ self.bake_preview.as_ref()?.sets.get(&texture_set).map(|set| &set.baked)
+ }
+
+ /// Why painting is not possible now, when a bake preview shows.
+ pub fn painting_blocked(&self) -> Option<&'static str> {
+ self.bake_preview.as_ref().map(|_| PAINTING_PAUSED)
+ }
+
+ fn bake_preview_refresh(&mut self) {
+ let Some(preview) = &self.bake_preview else { return };
+
+ self.view = match preview.shown() {
+ Some(map) => ViewMode::MeshMap(map),
+ None => ViewMode::Material,
+ };
+ self.revision = self.revision.wrapping_add(1);
+ }
+}
+
+/// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`.
+pub fn preview_json(session: &Session) -> Value {
+ let Some(preview) = &session.bake_preview else { return json!({ "active": false }) };
+
+ let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total }));
+ let sets: Vec = preview
+ .sets
+ .iter()
+ .map(|(texture_set, set)| {
+ json!({
+ "set": texture_set,
+ "order": set.order.iter().map(|map| map.id()).collect::>(),
+ "done": set.baked.maps.keys().map(|map| map.id()).collect::>(),
+ })
+ })
+ .collect();
+
+ json!({
+ "active": true,
+ "show": preview.show.id(),
+ "shown": preview.shown().map(|map| map.id()),
+ "newest": preview.newest.map(|map| map.id()),
+ "restore": preview.restore.label(),
+ "stage": stage,
+ "sets": sets,
+ })
+}
+
+fn preview(session: &mut Session, params: &Value) -> Result {
+ if let Some(show) = strp(params, "show") {
+ let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:")))?;
+ session.bake_preview_show(show)?;
+ }
+
+ Ok(preview_json(session))
+}
diff --git a/crates/engine/src/bake_preview/preview_set.rs b/crates/engine/src/bake_preview/preview_set.rs
new file mode 100644
index 00000000..e1eabef8
--- /dev/null
+++ b/crates/engine/src/bake_preview/preview_set.rs
@@ -0,0 +1,10 @@
+use texturecraft_compose::BakedMaps;
+use texturecraft_core::BakedMap;
+
+/// The maps of one texture set streamed so far.
+#[derive(Clone, Debug, Default)]
+pub struct PreviewSet {
+ pub baked: BakedMaps,
+ /// The maps this set's bake makes, in the order they arrive.
+ pub order: Vec,
+}
diff --git a/crates/engine/src/bake_preview/preview_show.rs b/crates/engine/src/bake_preview/preview_show.rs
new file mode 100644
index 00000000..28a13614
--- /dev/null
+++ b/crates/engine/src/bake_preview/preview_show.rs
@@ -0,0 +1,30 @@
+use texturecraft_core::BakedMap;
+
+/// What the 3D view shows while a bake runs.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PreviewShow {
+ /// The newest finished map (the first one, still neutral, before any is done).
+ Follow,
+ /// One map, pinned: neutral until it is baked.
+ Pin(BakedMap),
+ /// The lit material.
+ Material,
+}
+
+impl PreviewShow {
+ pub fn id(self) -> String {
+ match self {
+ PreviewShow::Follow => "follow".into(),
+ PreviewShow::Pin(map) => format!("map:{}", map.id()),
+ PreviewShow::Material => "material".into(),
+ }
+ }
+
+ pub fn parse(text: &str) -> Option {
+ match text {
+ "follow" => Some(PreviewShow::Follow),
+ "material" => Some(PreviewShow::Material),
+ _ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin),
+ }
+ }
+}
diff --git a/crates/engine/src/bake_preview/stage.rs b/crates/engine/src/bake_preview/stage.rs
new file mode 100644
index 00000000..d1513ae2
--- /dev/null
+++ b/crates/engine/src/bake_preview/stage.rs
@@ -0,0 +1,11 @@
+use texturecraft_core::BakedMap;
+
+/// The map a bake is working on.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Stage {
+ pub texture_set: usize,
+ pub map: BakedMap,
+ /// 1-based position among the set's maps, and how many there are.
+ pub position: usize,
+ pub total: usize,
+}
diff --git a/crates/engine/src/color_selection_cmds.rs b/crates/engine/src/color_selection_cmds.rs
new file mode 100644
index 00000000..2b9f9eaf
--- /dev/null
+++ b/crates/engine/src/color_selection_cmds.rs
@@ -0,0 +1,160 @@
+//! Color selection effects: the ID colors they select, picked from the ID mesh map
+
+use serde_json::{Value, json};
+use texturecraft_core::{BakedMap, EffectKind, LayerId};
+use texturecraft_geom::glam::Vec2;
+use texturecraft_geom::surface_at;
+
+use crate::commands::{CommandSpec, bad, f32p, has_layer};
+use crate::mask_cmds::effect_id;
+use crate::tool_cmds::viewport_of;
+use crate::{Result, Session, cmd};
+
+/// Most colors one color selection holds; an ID map rarely has more distinct parts
+const MAX_SELECTED_COLORS: usize = 256;
+
+pub fn specs() -> Vec {
+ vec![cmd!(
+ "effect.colorSelection.pick",
+ "Pick ID color",
+ [],
+ None,
+ "{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point",
+ has_layer,
+ pick
+ )]
+}
+
+/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection
+pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> {
+ if let Some(list) = params.get("colors") {
+ *colors = colors_param(list)?;
+ }
+ if let Some(value) = f32p(params, "tolerance") {
+ *tolerance = value.clamp(0.0, 1.0);
+ }
+ Ok(())
+}
+
+/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1
+fn colors_param(list: &Value) -> Result> {
+ const CMD: &str = "effect.set";
+ let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?;
+ if items.is_empty() || items.len() > MAX_SELECTED_COLORS {
+ return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors")));
+ }
+
+ items
+ .iter()
+ .map(|item| match finite_numbers::<3>(item) {
+ Some(color) => Ok(color.map(|value| value.clamp(0.0, 1.0) as f32)),
+ _ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")),
+ })
+ .collect()
+}
+
+/// Samples the ID map under a viewport point or at a UV and adds the color to a color selection
+fn pick(session: &mut Session, params: &Value) -> Result {
+ const CMD: &str = "effect.colorSelection.pick";
+ let effect = effect_id(session, params, CMD)?;
+ let (owner, color_count) = match session.doc.project.effect(effect) {
+ Some((owner, found)) => match &found.kind {
+ EffectKind::ColorSelection { colors, .. } => (owner, colors.len()),
+ other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))),
+ },
+ None => return Err(bad(CMD, format!("no effect {}", effect.0))),
+ };
+
+ let index = params
+ .get("index")
+ .filter(|index| !index.is_null())
+ .map(|index| index.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer")))
+ .transpose()?;
+ let index = match index {
+ Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?),
+ None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))),
+ None => None,
+ };
+
+ let color = id_color_at(session, params, owner)?;
+ session.edit("Pick ID color", |session| {
+ let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
+ if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind {
+ match index.and_then(|index| colors.get_mut(index)) {
+ Some(slot) => *slot = color,
+ None => colors.push(color),
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({ "color": color, "index": index.unwrap_or(color_count) }))
+}
+
+/// The ID map color of the texel a color selection on `owner` reads at the picked point
+fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> {
+ const CMD: &str = "effect.colorSelection.pick";
+ let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?;
+ let set = session.doc.project.texture_set(set_index)?;
+ let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id));
+ let Some(baked) = baked else {
+ return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name)));
+ };
+
+ let uv = match params.get("uv") {
+ Some(uv) => uv_param(uv)?,
+ None => {
+ let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else {
+ return Err(bad(CMD, "give `x` and `y` (viewport pixels) or `uv`"));
+ };
+
+ let (uv, material) = visible_surface(session, Vec2::new(x, y), viewport_of(session, params))
+ .ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?;
+ if material != set.material {
+ return Err(bad(CMD, "that surface belongs to another texture set"));
+ }
+ uv
+ }
+ };
+
+ // The same texel the mask evaluates, so a picked color always selects where it was picked
+ let size = set.size();
+ let texel = [uv.x * size.0 as f32, uv.y * size.1 as f32];
+ if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) {
+ return Err(bad(CMD, "that point is outside the texture set's UV space"));
+ }
+ baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there"))
+}
+
+/// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray
+fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(Vec2, usize)> {
+ let viewport = viewport.max(Vec2::ONE);
+ let device = Vec2::new(screen.x / viewport.x * 2.0 - 1.0, 1.0 - screen.y / viewport.y * 2.0);
+ let ray = session.camera.ray(device, viewport.x / viewport.y);
+ let sets = &session.doc.project.texture_sets;
+ let visible = |triangle: u32| {
+ let material = session.mesh.material_of(triangle as usize).unwrap_or(0);
+ sets.iter().find(|set| set.material == material).is_none_or(|set| set.visible)
+ };
+
+ let hit = session.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, &visible)?;
+ let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?;
+ Some((surface.uv, session.mesh.material_of(hit.tri as usize).unwrap_or(0)))
+}
+
+/// A `[u, v]` param of finite numbers
+fn uv_param(uv: &Value) -> Result {
+ match finite_numbers::<2>(uv) {
+ Some([u, v]) => Ok(Vec2::new(u as f32, v as f32)),
+ _ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")),
+ }
+}
+
+/// Validate the shape before reading components, without allocating for oversized input
+fn finite_numbers(list: &Value) -> Option<[f64; N]> {
+ let items: &[Value; N] = list.as_array()?.as_slice().try_into().ok()?;
+ let mut numbers = [0.0; N];
+ for (number, item) in numbers.iter_mut().zip(items) {
+ *number = item.as_f64().filter(|value| value.is_finite())?;
+ }
+ Some(numbers)
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 9f0d126b..072f4071 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::layer_ops::specs());
v.extend(crate::instance_cmds::specs());
v.extend(crate::mask_cmds::specs());
+ v.extend(crate::color_selection_cmds::specs());
v.extend(crate::effect_clipboard::specs());
v.extend(crate::tool_cmds::specs());
v.extend(crate::brush_preset_cmds::specs());
@@ -65,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());
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index f2b95e03..ae2f00b5 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -331,6 +331,11 @@ mod native {
strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required")))
}
+ /// `path` made absolute (as given when that fails), for [`Project::mesh_path`].
+ pub fn absolute(path: &str) -> String {
+ std::path::absolute(Path::new(path)).map_or_else(|_| path.to_string(), |p| p.display().to_string())
+ }
+
/// Mesh file `path` with the files it references next to it folded in (a `.gltf`'s buffers
/// and images, a loose USD layer's textures), ready to import and store in the project.
pub fn read_mesh(cmd: &str, path: &str) -> Result {
@@ -349,6 +354,7 @@ mod native {
} else {
let f = read_mesh("file.open", path)?;
let mut s = Session::from_mesh_bytes(&f.name, &f.bytes, 2048, &stem_of(path))?;
+ s.doc.project.mesh_path = absolute(path);
s.log.extend(f.warnings);
Ok(s)
}
@@ -367,8 +373,10 @@ mod native {
}
#[cfg(not(target_arch = "wasm32"))]
-pub use native::{open_path, read_mesh};
+pub use native::{absolute, open_path, read_mesh};
+/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`,
+/// remembering its path for Reimport mesh.
#[cfg(not(target_arch = "wasm32"))]
fn new_from_mesh(s: &mut Session, p: &Value) -> Result {
let path = native::path_param(p, "mesh", "file.new")?;
@@ -377,6 +385,7 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result {
let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048);
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?;
+ next.doc.project.mesh_path = native::absolute(path);
next.log.extend(f.warnings);
if let Some(t) = &template {
next.apply_template(t);
@@ -414,14 +423,28 @@ fn save_copy(s: &mut Session, p: &Value) -> Result {
native::save_to(s, &path, false)
}
+/// `file.reimportMesh {path?, preserveStrokes?}`: reimport from `path`, or from the project's own
+/// copy of the mesh when there is none. A path given is remembered as the project's mesh path.
+/// The remembered path is never read implicitly (a project file could point it anywhere on the
+/// host); callers that may read host files pass [`Session::remembered_mesh_path`] as `path`.
#[cfg(not(target_arch = "wasm32"))]
fn reimport(s: &mut Session, p: &Value) -> Result {
- let file = strp(p, "path").map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
- s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))
+ let path = strp(p, "path");
+ let file = path.map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
+ let reply = s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))?;
+ if let Some(path) = path {
+ s.doc.project.mesh_path = native::absolute(path);
+ }
+ Ok(reply)
}
#[cfg(not(target_arch = "wasm32"))]
impl Session {
+ /// The file the mesh was imported from, when it is still there: what Reimport mesh reads again.
+ pub fn remembered_mesh_path(&self) -> Option<&str> {
+ Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file())
+ }
+
/// Replace the mesh with `file` (or re-read the project's own copy) and keep the project:
/// texture sets map by material index. Nothing changes unless the new mesh fits the project.
/// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies
@@ -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 {
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]
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index ae73a3a7..2db27946 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -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::>()
@@ -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() },
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index e0cfb3e4..9302fc3e 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -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;
diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs
index 27c18bca..b8aad872 100644
--- a/crates/engine/src/mask_cmds.rs
+++ b/crates/engine/src/mask_cmds.rs
@@ -94,7 +94,7 @@ pub fn specs() -> Vec {
"Edit effect",
[],
None,
- "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, 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 {
*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);
}
diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs
index 0fbe1f5b..4524b361 100644
--- a/crates/engine/src/meshmap_cmds.rs
+++ b/crates/engine/src/meshmap_cmds.rs
@@ -38,55 +38,91 @@ fn set(s: &mut Session, p: &Value) -> Result {
let ts = ts_param(s, p, CMD)?;
let map = map_param(p, CMD)?;
let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?;
- let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
- let set = s.doc.project.texture_set(ts)?.clone();
- let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?;
- // Every mesh map of a set shares one size: the other maps', or what a bake would make (a
- // block of the bake resolution per tile of the atlas).
- let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows));
- let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) {
- Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))),
- None => {
- let (width, height) = set.bake.common.output_size();
- (width.saturating_mul(cols), height.saturating_mul(rows))
- }
+ let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
+ let texture_set = s.doc.project.texture_set(ts)?;
+ let images = match texture_set.tile_grid() {
+ Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?,
+ None => BTreeMap::from([(FIRST_TILE, image)]),
};
- if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) {
- return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty")));
- }
- let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
- let data = match &tiles {
- None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)),
- // An atlas texel reads the image of the tile its mesh UV falls in.
- Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| {
- let uv = 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>> {
- const CMD: &str = "textureSet.meshMap.set";
- let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
+/// The tile number a set without UV tiles keys its one image by
+pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start();
+
+/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width
+pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result {
+ let texture_set = s.doc.project.texture_set(ts)?;
+ let grid = texture_set.tile_grid();
+ if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
+ return Err(bad(cmd, format!("no image for UV tile {tile}")));
+ }
+
+ let (width, height) = image_map_size(s, cmd, ts)?;
+
+ let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
+ let data = match (grid, images.values().next()) {
+ (_, None) => return Err(bad(cmd, "no image to use")),
+ (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)),
+ // An atlas texel reads the image of the tile its mesh UV falls in
+ (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| {
+ let uv = grid.from_atlas([u, v]);
+ udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
+ }),
+ };
+
+ let entry = s.doc.baked.entry(ts).or_default();
+ entry.resolution = width;
+ entry.maps.insert(map, Arc::new(data));
+ s.doc.project.texture_set_mut(ts)?.baked.insert(map);
+ Ok(width)
+}
+
+/// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels
+pub(crate) fn image_map_size(s: &Session, cmd: &str, ts: usize) -> Result<(u32, u32)> {
+ let texture_set = s.doc.project.texture_set(ts)?;
+ let grid = texture_set.tile_grid();
+
+ // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile)
+ let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
+ let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) {
+ Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))),
+ None => {
+ let (width, height) = texture_set.bake.common.output_size();
+ (width.saturating_mul(columns), height.saturating_mul(rows))
+ }
+ };
+ let empty = width == 0 || height == 0;
+ let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS;
+ let too_wide = grid.is_none() && width > MAX_RESOLUTION;
+ if empty || too_many_texels || too_wide {
+ return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty")));
+ }
+
+ Ok((width, height))
+}
+
+/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's
+fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> {
+ let tile_at =
+ udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
+ let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default());
tiles
.iter()
- .map(|&t| {
- let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default());
- images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}")))
+ .map(|&tile| {
+ let tile_name = format!("{before_tile}{tile}{after_tile}");
+ images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}")))
})
.collect()
}
+/// The UV tile number in a file name (`Body_ao.1002.png` → 1002)
+pub(crate) fn tile_number(file_name: &str) -> Option {
+ udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok())
+}
+
/// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts.
fn udim_in(name: &str) -> Option {
let b = name.as_bytes();
diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs
new file mode 100644
index 00000000..fde32d5e
--- /dev/null
+++ b/crates/engine/src/meshmap_file_name.rs
@@ -0,0 +1,159 @@
+//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion)
+
+use std::path::Path;
+
+use texturecraft_core::{BakedMap, UDIM_RANGE};
+
+/// Mesh maps named by two words anywhere in the file name; they win over the one-word names
+const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[
+ ("world", &["normal", "normals"], BakedMap::WorldNormal),
+ ("bent", &["normal", "normals"], BakedMap::BentNormal),
+ ("ambient", &["occlusion"], BakedMap::AmbientOcclusion),
+];
+
+/// Mesh maps named by one word, including the two-word names written as one
+const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[
+ ("worldnormal", BakedMap::WorldNormal),
+ ("worldnormals", BakedMap::WorldNormal),
+ ("bentnormal", BakedMap::BentNormal),
+ ("bentnormals", BakedMap::BentNormal),
+ ("ambientocclusion", BakedMap::AmbientOcclusion),
+ ("normal", BakedMap::Normal),
+ ("normals", BakedMap::Normal),
+ ("nrm", BakedMap::Normal),
+ ("occlusion", BakedMap::AmbientOcclusion),
+ ("ao", BakedMap::AmbientOcclusion),
+ ("curvature", BakedMap::Curvature),
+ ("curv", BakedMap::Curvature),
+ ("id", BakedMap::Id),
+ ("position", BakedMap::Position),
+ ("pos", BakedMap::Position),
+ ("thickness", BakedMap::Thickness),
+ ("height", BakedMap::Height),
+ ("displacement", BakedMap::Height),
+ ("opacity", BakedMap::Opacity),
+ ("alpha", BakedMap::Opacity),
+];
+
+fn is_separator(c: char) -> bool {
+ matches!(c, '_' | '-' | '.' | ' ')
+}
+
+/// The lowercase file name without its folder and extension
+fn lowercase_stem(path: &str) -> String {
+ Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase()
+}
+
+/// What follows `set_name` at the start of a lowercase stem, when a separator follows it
+fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> {
+ if set_name.is_empty() {
+ return None;
+ }
+
+ stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator))
+}
+
+/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins
+pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option {
+ let stem = lowercase_stem(path);
+ let rest = after_set_name(&stem, set_name).unwrap_or(&stem);
+ let is_tile_number = |word: &str| word.len() == 4 && word.parse::().is_ok_and(|number| UDIM_RANGE.contains(&number));
+ let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect();
+
+ let has = |name: &str| words.contains(&name);
+ TWO_WORD_NAMES
+ .iter()
+ .find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second)))
+ .map(|(_, _, map)| *map)
+ .or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map)))
+}
+
+/// The set a file is for: the longest set name its name starts with before a separator (any name with one set)
+pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option {
+ if set_names.len() == 1 {
+ return Some(0);
+ }
+
+ let stem = lowercase_stem(path);
+ set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn each_word_names_its_map() {
+ let cases = [
+ ("Body_normal.png", BakedMap::Normal),
+ ("Body_normals.png", BakedMap::Normal),
+ ("Body_nrm.png", BakedMap::Normal),
+ ("Body_world_normal.png", BakedMap::WorldNormal),
+ ("Body_normals_world.png", BakedMap::WorldNormal),
+ ("Body_WorldNormal.png", BakedMap::WorldNormal),
+ ("Body_bent_normals.png", BakedMap::BentNormal),
+ ("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion),
+ ("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion),
+ ("Body_occlusion.png", BakedMap::AmbientOcclusion),
+ ("Body AO.png", BakedMap::AmbientOcclusion),
+ ("Body_curvature.png", BakedMap::Curvature),
+ ("Body_curv.png", BakedMap::Curvature),
+ ("Body_ID.png", BakedMap::Id),
+ ("Body_position.png", BakedMap::Position),
+ ("Body_pos.png", BakedMap::Position),
+ ("Body_thickness.png", BakedMap::Thickness),
+ ("Body_height.png", BakedMap::Height),
+ ("Body_displacement.png", BakedMap::Height),
+ ("Body_opacity.png", BakedMap::Opacity),
+ ("Body_alpha.png", BakedMap::Opacity),
+ ];
+ for (file, map) in cases {
+ assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}");
+ }
+ }
+
+ #[test]
+ fn tile_numbers_and_folders_are_ignored() {
+ assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion));
+ assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal));
+ assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1));
+ }
+
+ #[test]
+ fn unknown_words_match_no_map() {
+ assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None);
+ assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None);
+ assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None);
+ assert_eq!(baked_map_from_file_name("", "Body"), None);
+ }
+
+ #[test]
+ fn the_set_name_is_not_read_as_a_map() {
+ assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal));
+ assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None);
+ assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion));
+ }
+
+ #[test]
+ fn the_longest_set_name_wins() {
+ let sets = ["Body", "Body_Upper", "Head"];
+ assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1));
+ assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0));
+ assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2));
+ }
+
+ #[test]
+ fn a_set_name_must_end_at_a_separator() {
+ let sets = ["Body", "Head"];
+ assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None);
+ assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None);
+ assert_eq!(texture_set_from_file_name("Body.png", &sets), None);
+ }
+
+ #[test]
+ fn one_set_takes_every_file() {
+ assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0));
+ assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0));
+ assert_eq!(texture_set_from_file_name("ao.png", &[]), None);
+ }
+}
diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs
new file mode 100644
index 00000000..20913de2
--- /dev/null
+++ b/crates/engine/src/meshmap_import_cmds.rs
@@ -0,0 +1,162 @@
+//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names
+
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use serde_json::{Value, json};
+use texturecraft_core::BakedMap;
+
+use crate::commands::{CommandSpec, always, bad, strp};
+use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images};
+use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name};
+use crate::resource_cmds::read_image_file;
+use crate::{Result, Session, cmd};
+
+const CMD: &str = "textureSet.meshMap.import";
+
+/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles
+const MAX_FILES: usize = 512;
+
+/// Bound retained file bytes, decoded RGBA floats and resampled maps together, before allocating pixels
+const MAX_TOTAL_BYTES: u64 = 2 << 30;
+
+pub fn specs() -> Vec {
+ vec![cmd!(
+ "textureSet.meshMap.import",
+ "Import baked maps",
+ [],
+ None,
+ "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); at most 512 files and 2 GiB of file bytes, decoded images and mesh maps; desktop only",
+ always,
+ import
+ )]
+}
+
+fn import(s: &mut Session, p: &Value) -> Result {
+ import_with_budget(s, p, MAX_TOTAL_BYTES)
+}
+
+fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result {
+ let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?;
+ if files.len() > MAX_FILES {
+ return Err(bad(CMD, format!("at most {MAX_FILES} files at once")));
+ }
+
+ let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect();
+ let mut slots: BTreeMap<(usize, BakedMap), BTreeMap> = BTreeMap::new();
+ let mut unmatched = Vec::new();
+ for file in files {
+ let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?;
+ let given_map = match file.get("map") {
+ None | Some(Value::Null) => None,
+ Some(Value::String(id)) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?),
+ Some(_) => return Err(bad(CMD, "`map` must be a mesh map id string")),
+ };
+
+ match slot_of(s, &set_names, path, given_map) {
+ Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => {
+ slots.entry(slot).or_default().insert(tile, path);
+ }
+ _ => unmatched.push(path),
+ }
+ }
+
+ // A UV-tiled map needs a file for every tile of its set
+ slots.retain(|(ts, _), tiles| {
+ let complete =
+ s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile)));
+ if !complete {
+ unmatched.extend(tiles.values());
+ }
+ complete
+ });
+ if slots.is_empty() {
+ return Ok(json!({ "assigned": [], "unmatched": unmatched }));
+ }
+
+ let result = s.edit("Import baked maps", |s| {
+ let mut assigned = Vec::new();
+ let mut remaining_bytes = max_bytes;
+ for ((ts, map), tiles) in &slots {
+ let (width, height) = image_map_size(s, CMD, *ts)?;
+ let map_bytes = u64::from(width) * u64::from(height) * map.components() as u64 * size_of::() as u64;
+ reserve_bytes(&mut remaining_bytes, map_bytes)?;
+
+ let mut images = BTreeMap::new();
+ for (tile, path) in tiles {
+ let bytes = read_image_file(CMD, path, remaining_bytes)?;
+ reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?;
+
+ let bytes_per_texel = size_of::<[f32; 4]>() as u64;
+ let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?;
+ let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?;
+ reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?;
+ images.insert(*tile, image.clone());
+ assigned.push(json!({"path": path, "ts": ts, "map": map.id()}));
+ }
+ use_images(s, CMD, *ts, *map, &images)?;
+ }
+ Ok(assigned)
+ });
+ // A failed edit leaves the document as it was; forget the images it decoded
+ if result.is_err() {
+ s.sync_images();
+ }
+
+ Ok(json!({ "assigned": result?, "unmatched": unmatched }))
+}
+
+fn reserve_bytes(remaining_bytes: &mut u64, bytes: u64) -> Result<()> {
+ *remaining_bytes = remaining_bytes.checked_sub(bytes).ok_or_else(|| bad(CMD, "the files, decoded images and mesh maps exceed the import memory budget"))?;
+ Ok(())
+}
+
+/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles)
+fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option) -> Option<((usize, BakedMap), u32)> {
+ let ts = texture_set_from_file_name(path, set_names)?;
+ let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?;
+ let texture_set = s.doc.project.texture_sets.get(ts)?;
+ let tile = match texture_set.tile_grid() {
+ Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?,
+ None => FIRST_TILE,
+ };
+ Some(((ts, map), tile))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use texturecraft_core::BakeResolution;
+
+ #[test]
+ fn import_budget_counts_decoded_images_and_resampled_maps() {
+ let dir = std::env::temp_dir().join(format!("texturecraft-import-budget-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let paths = [dir.join("ao.png"), dir.join("height.png")];
+ for path in &paths {
+ image::RgbaImage::from_pixel(16, 16, image::Rgba([128, 128, 128, 255])).save(path).unwrap();
+ }
+ let file_bytes: u64 = paths.iter().map(|path| std::fs::metadata(path).unwrap().len()).sum();
+ let decoded_bytes = 2 * 16 * 16 * 16;
+ let map_bytes = 2 * 16 * 16 * 4;
+ let required_bytes = file_bytes + decoded_bytes + map_bytes;
+ let params = json!({"files": paths.map(|path| json!({"path": path}))});
+ let mut session = Session::new_project("budget", texturecraft_geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
+ session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R16;
+ let revision = session.revision;
+
+ for budget in [file_bytes, file_bytes + decoded_bytes, required_bytes - 1] {
+ let result = import_with_budget(&mut session, ¶ms, budget);
+ assert!(result.is_err(), "budget {budget} must cover decoded pixels and mesh maps: {result:?}");
+ assert!(session.doc.resources.is_empty() && session.images.is_empty());
+ assert!(session.doc.baked.values().all(|baked| baked.maps.is_empty()));
+ assert_eq!(session.revision, revision);
+ assert!(!session.modified);
+ assert!(session.undo_label().is_none());
+ }
+
+ let result = import_with_budget(&mut session, ¶ms, required_bytes).unwrap();
+ assert_eq!(result["assigned"].as_array().unwrap().len(), 2);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+}
diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs
index 27377af1..6344311f 100644
--- a/crates/engine/src/painting.rs
+++ b/crates/engine/src/painting.rs
@@ -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) -> 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 {
+ 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(|_| ()),
diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs
index ea7270f5..af93f71c 100644
--- a/crates/engine/src/polygon_fill.rs
+++ b/crates/engine/src/polygon_fill.rs
@@ -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 {
+ 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 {
+ 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 {
+ 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 {
+ 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) -> Result {
+ self.refuse_while_baking()?;
if !corner.is_finite() || !opposite.is_finite() {
return Err(EngineError::Other("the box corners must be finite".into()));
}
diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs
index 87f6d50f..86e7c9b8 100644
--- a/crates/engine/src/resource_cmds.rs
+++ b/crates/engine/src/resource_cmds.rs
@@ -36,12 +36,18 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc {
}
impl Session {
- /// Add an image resource from bytes (one undo step); returns its unique, sanitized name.
+ /// Add an image resource from bytes (one undo step); returns its unique, sanitized name
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result {
+ self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX))
+ }
+
+ /// Add an image within a decoded texel budget, inside the caller's edit
+ pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec, max_texels: u64) -> Result {
if bytes.len() > MAX_BYTES {
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
}
- let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
+
+ let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image");
let base = texturecraft_formats::sanitize_resource_name(leaf);
let mut name = base.clone();
@@ -50,11 +56,8 @@ impl Session {
name = format!("{n}_{base}");
n += 1;
}
- let key = name.clone();
- self.edit("Import resource", |s| {
- s.doc.resources.insert(key, Arc::new(bytes));
- Ok(())
- })?;
+
+ self.doc.resources.insert(name.clone(), Arc::new(bytes));
self.images.insert(name.clone(), decoded(image));
Ok(name)
}
@@ -98,15 +101,44 @@ fn list(s: &Session) -> Value {
#[cfg(not(target_arch = "wasm32"))]
fn import(s: &mut Session, p: &Value) -> Result {
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
- let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
- if meta.len() > MAX_BYTES as u64 {
- return Err(bad("resource.import", format!("{path} is too large")));
- }
- let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
+ let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
let name = s.import_resource_bytes(path, bytes)?;
Ok(json!({ "name": name }))
}
+/// Read a regular image file within both the per-file cap and the caller's remaining byte budget
+#[cfg(not(target_arch = "wasm32"))]
+pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result> {
+ use std::io::Read;
+
+ let max_bytes = max_bytes.min(MAX_BYTES as u64);
+ let read_error = |error| bad(cmd, format!("cannot read {path}: {error}"));
+ let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)"));
+ let metadata = std::fs::metadata(path).map_err(read_error)?;
+ // Pipes can block on open, and devices may never reach EOF
+ if !metadata.is_file() {
+ return Err(bad(cmd, format!("{path} is not a regular file")));
+ }
+ if metadata.len() > max_bytes {
+ return Err(too_large());
+ }
+
+ // Bound the read even if the file grows after the metadata check
+ let file = std::fs::File::open(path).map_err(read_error)?;
+ let mut bytes = Vec::with_capacity(metadata.len() as usize);
+ file.take(max_bytes + 1).read_to_end(&mut bytes).map_err(read_error)?;
+ if bytes.len() as u64 > max_bytes {
+ return Err(too_large());
+ }
+
+ Ok(bytes)
+}
+
+#[cfg(target_arch = "wasm32")]
+pub(crate) fn read_image_file(cmd: &str, _: &str, _: u64) -> Result> {
+ Err(bad(cmd, "file paths are not available in the browser"))
+}
+
#[cfg(target_arch = "wasm32")]
fn import(_: &mut Session, _: &Value) -> Result {
Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into()))
@@ -165,3 +197,24 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result {
})?;
Ok(json!({ "layer": id.0 }))
}
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn file_reads_obey_the_remaining_byte_budget() {
+ let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
+ std::fs::write(&path, b"1234").unwrap();
+ let name = path.to_str().unwrap();
+ assert!(read_image_file("test", name, 3).unwrap_err().to_string().contains("too large"));
+ assert_eq!(read_image_file("test", name, 4).unwrap(), b"1234");
+ std::fs::remove_file(path).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn devices_are_rejected_before_reading() {
+ assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file"));
+ }
+}
diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs
index d2f55445..64ebec69 100644
--- a/crates/engine/src/session.rs
+++ b/crates/engine/src/session.rs
@@ -318,6 +318,9 @@ pub struct Session {
pub mesh: Arc,
/// Unique per loaded mesh and UV layout (GPU caches compare it).
pub mesh_id: u64,
+ /// Unique per open project: a mesh reimport or UV layout change keeps it, and opening, closing
+ /// or creating a project replaces it.
+ pub project_id: u64,
/// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas).
pub(crate) source: Arc,
pub bvh: Arc,
@@ -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,
/// Viewport size (pixels) used by scripted strokes.
pub viewport: Vec2,
pub(crate) stroke: Option,
@@ -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,
diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs
index b39c876d..9fb03ecf 100644
--- a/crates/engine/src/view_cmds.rs
+++ b/crates/engine/src/view_cmds.rs
@@ -88,7 +88,13 @@ fn frame(s: &mut Session, _: &Value) -> Result {
}
fn set_view(s: &mut Session, v: ViewMode) -> Result {
- s.view = v;
+ if s.bake_preview.is_some() {
+ // During a bake the view follows the preview: a mesh map pins it, another mode comes back afterwards
+ s.bake_preview_user_view(v);
+ } else {
+ s.view = v;
+ }
+ let v = s.view;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "view": v.label() }))
}
diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs
new file mode 100644
index 00000000..e8eb477b
--- /dev/null
+++ b/crates/engine/tests/bake_preview.rs
@@ -0,0 +1,428 @@
+//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back,
+//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it
+//! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the
+//! document share each map's buffer instead of holding two copies.
+
+use serde_json::{Value, json};
+use texturecraft_engine::bake::Progress;
+use texturecraft_engine::core::{BakeResolution, BakedMap, Channel};
+use texturecraft_engine::geom::glam::Vec2;
+use texturecraft_engine::{BakeTask, PreviewShow, Session, ViewMode, execute};
+
+const MAPS: [BakedMap; 4] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Height];
+
+fn session() -> Session {
+ let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
+ for texture_set in &mut session.doc.project.texture_sets {
+ texture_set.bake = Default::default();
+ texture_set.bake.common.resolution = BakeResolution::R64;
+ texture_set.bake.maps.ao.parameters.rays.rays = 8;
+ texture_set.bake.maps.select(MAPS);
+ }
+
+ session
+}
+
+fn task(session: &Session) -> BakeTask {
+ let mut task = session.bake_task(0).unwrap();
+ task.tracer = None;
+ task
+}
+
+fn order(session: &Session) -> Vec {
+ task(session).maps()
+}
+
+#[test]
+fn streamed_maps_are_the_pixels_of_one_bake() {
+ let session = session();
+ let task = task(&session);
+ let whole = task.run(&Progress::new()).unwrap();
+ let mut streamed = Vec::new();
+
+ let combined = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap();
+
+ assert_eq!(streamed.iter().map(|map| map.map).collect::>(), order(&session));
+ assert_eq!(streamed.iter().map(|map| (map.index, map.total)).collect::>(), (0..MAPS.len()).map(|index| (index, MAPS.len())).collect::>());
+ assert_eq!((combined.resolution, combined.height), (whole.resolution, whole.height));
+ assert_eq!(combined.maps.keys().collect::>(), whole.maps.keys().collect::>());
+ for (map, pixels) in &whole.maps {
+ assert!(*combined.maps[map] == *pixels, "{map:?} differs between a streamed and a single bake");
+ }
+ for map in &streamed {
+ assert!(*map.data == whole.maps[&map.map], "{:?} handed over differs from the bake", map.map);
+ }
+}
+
+#[test]
+fn the_view_follows_each_map_and_the_previous_mode_comes_back() {
+ let mut session = session();
+ session.view = ViewMode::Channel(Channel::Roughness);
+ let before = session.view;
+ let baked_before = session.doc.baked.get(&0).cloned();
+ let maps = order(&session);
+
+ session.bake_preview_begin(vec![(0, maps.clone())]);
+ session.bake_preview_set_current(0);
+
+ // Nothing is baked yet: the first map shows, neutral
+ assert_eq!(session.view, ViewMode::MeshMap(maps[0]));
+ assert!(session.bake_preview_baked(0).is_some_and(|baked| baked.maps.is_empty()));
+
+ let task = task(&session);
+ let mut shown = Vec::new();
+ let mut stages = Vec::new();
+ let output = task
+ .run_streaming(&Progress::new(), &mut |map| {
+ session.bake_preview_map(0, map);
+ shown.push(session.view);
+ stages.push(session.bake_preview.as_ref().and_then(|preview| preview.stage()).map(|stage| (stage.position, stage.total)));
+ })
+ .unwrap();
+
+ assert_eq!(shown, maps.iter().map(|map| ViewMode::MeshMap(*map)).collect::>(), "the view follows the newest map");
+ assert_eq!(stages, [Some((2, 4)), Some((3, 4)), Some((4, 4)), None], "the stage names the next map");
+ assert_eq!(session.doc.baked.get(&0).cloned(), baked_before, "the document is untouched until the bake is applied");
+ let undo_before = session.undo_label().map(str::to_owned);
+
+ session.apply_streamed_bake(0, output).unwrap();
+ assert_ne!(session.undo_label().map(str::to_owned), undo_before, "applying the bake is one undo step");
+ session.bake_preview_end();
+
+ assert_eq!(session.view, before, "the previous view mode is restored");
+ assert!(!session.bake_preview_active());
+ assert!(maps.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)));
+}
+
+#[test]
+fn pinning_material_and_follow() {
+ let mut session = session();
+ let maps = order(&session);
+
+ session.bake_preview_begin(vec![(0, maps.clone())]);
+ session.bake_preview_set_current(0);
+ let task = task(&session);
+ let mut count = 0;
+
+ task.run_streaming(&Progress::new(), &mut |map| {
+ session.bake_preview_map(0, map);
+ count += 1;
+ match count {
+ // Pin the finished map: later maps do not take the view
+ 1 => session.bake_preview_show(PreviewShow::Pin(maps[0])).unwrap(),
+ 2 => {
+ assert_eq!(session.view, ViewMode::MeshMap(maps[0]));
+ session.bake_preview_show(PreviewShow::Material).unwrap();
+ }
+ 3 => {
+ assert_eq!(session.view, ViewMode::Material);
+ session.bake_preview_show(PreviewShow::Follow).unwrap();
+ assert_eq!(session.view, ViewMode::MeshMap(maps[2]));
+ }
+ _ => {}
+ }
+ })
+ .unwrap();
+
+ // A mesh map picked in the viewport pins it; another mode is what comes back at the end
+ execute(&mut session, "viewport.view", &json!({ "mode": "map:height" })).unwrap();
+ assert_eq!(session.bake_preview.as_ref().map(|preview| preview.show), Some(PreviewShow::Pin(BakedMap::Height)));
+ execute(&mut session, "viewport.view", &json!({ "mode": "uvChecker" })).unwrap();
+ assert_eq!(session.view, ViewMode::UvChecker);
+ session.bake_preview_end();
+
+ assert_eq!(session.view, ViewMode::UvChecker);
+}
+
+#[test]
+fn unbaked_sets_show_neutral_and_the_control_command_reports() {
+ let mut session = session();
+ assert_eq!(execute(&mut session, "bake.preview", &Value::Null).unwrap()["active"], false);
+ assert!(execute(&mut session, "bake.preview", &json!({ "show": "material" })).is_err(), "nothing to show when no bake runs");
+
+ session.bake_preview_begin(vec![(0, order(&session)), (1, order(&session))]);
+ session.bake_preview_set_current(0);
+
+ assert!(session.bake_preview_baked(1).is_some_and(|baked| baked.maps.is_empty()), "a queued set has nothing yet");
+ assert!(session.bake_preview_baked(7).is_none(), "a set outside the bake shows its document maps");
+ let reply = execute(&mut session, "bake.preview", &json!({ "show": "map:ambientOcclusion" })).unwrap();
+
+ assert_eq!(
+ (reply["active"].clone(), reply["show"].clone(), reply["shown"].clone()),
+ (json!(true), json!("map:ambientOcclusion"), json!("ambientOcclusion"))
+ );
+ assert!(execute(&mut session, "bake.preview", &json!({ "show": "nonsense" })).is_err());
+ assert_eq!(texturecraft_engine::inspect::session(&session)["bakePreview"]["active"], true);
+}
+
+#[test]
+fn painting_is_refused_while_a_bake_shows() {
+ let mut session = session();
+ session.bake_preview_begin(vec![(0, order(&session))]);
+
+ let error = session.begin_stroke(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0), 1.0).unwrap_err().to_string();
+
+ assert_eq!(error, texturecraft_engine::bake_preview::PAINTING_PAUSED);
+ assert!(session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).is_err());
+ assert!(session.polygon_fill(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0)).is_err());
+ assert!(!session.stroke_active());
+ session.bake_preview_end();
+ assert!(session.painting_blocked().is_none());
+}
+
+#[test]
+fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() {
+ let mut session = session();
+ let before = session.doc.baked.get(&0).cloned();
+ let maps = order(&session);
+ let full = task(&session).run(&Progress::new()).unwrap();
+ session.bake_preview_begin(vec![(0, maps.clone())]);
+ session.bake_preview_set_current(0);
+ let progress = Progress::new();
+ let task = task(&session);
+
+ let result = task.run_streaming(&progress, &mut |map| {
+ if map.index == 1 {
+ progress.cancel();
+ }
+ session.bake_preview_map(0, map);
+ });
+
+ assert!(result.is_err(), "a cancelled bake fails");
+
+ // The two maps that landed are whole and equal to a full bake's; the others are still neutral
+ let shown = session.bake_preview_baked(0).unwrap();
+ assert_eq!(shown.maps.len(), 2);
+ for (map, data) in &shown.maps {
+ assert!(**data == full.maps[map], "{map:?}");
+ }
+
+ // What the app does on cancel: end the preview; the document keeps what it had
+ session.bake_preview_end();
+
+ assert_eq!(session.doc.baked.get(&0).cloned(), before);
+ assert!(session.bake_preview_baked(0).is_none());
+}
+
+#[test]
+fn the_preview_and_the_applied_document_share_each_map_buffer() {
+ let mut session = session();
+ let maps = order(&session);
+
+ session.bake_preview_begin(vec![(0, maps)]);
+ session.bake_preview_set_current(0);
+ let mut handed_over = Vec::new();
+
+ let output = task(&session)
+ .run_streaming(&Progress::new(), &mut |map| {
+ handed_over.push((map.map, map.data.clone()));
+ session.bake_preview_map(0, map);
+ })
+ .unwrap();
+
+ // Sharing the streamed buffers keeps preview memory independent of document ownership
+ for (map, data) in &handed_over {
+ assert!(std::sync::Arc::ptr_eq(data, &output.maps[map]), "{map:?} was copied on the way out of the bake");
+ let shown = &session.bake_preview_baked(0).unwrap().maps[map];
+ assert!(std::sync::Arc::ptr_eq(data, shown), "{map:?} is held twice by the preview");
+ }
+
+ // Applying the result must preserve sharing with the preview
+ session.apply_streamed_bake(0, output).unwrap();
+ for (map, data) in &handed_over {
+ assert!(std::sync::Arc::ptr_eq(data, &session.doc.baked[&0].maps[map]), "{map:?} was copied into the document");
+ }
+ session.bake_preview_end();
+}
+
+#[test]
+fn cancelling_keeps_a_set_that_was_already_applied_as_one_undo_step() {
+ let mut session = session();
+ let before = session.doc.baked.get(&0).cloned();
+ let maps = order(&session);
+
+ // A multi-set bake applies each set when it finishes; a later cancel does not undo it
+ session.bake_preview_begin(vec![(0, maps)]);
+ session.bake_preview_set_current(0);
+ let output = task(&session)
+ .run_streaming(&Progress::new(), &mut |map| {
+ session.bake_preview_map(0, map);
+ })
+ .unwrap();
+ session.apply_streamed_bake(0, output).unwrap();
+ session.bake_preview_end();
+
+ assert!(MAPS.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)), "the finished set stays baked after the cancel");
+ session.undo().unwrap();
+ assert_eq!(session.doc.baked.get(&0).cloned(), before, "applying the set was one undo step");
+}
+
+#[test]
+fn a_resized_partial_streamed_bake_keeps_unchecked_maps() {
+ use std::sync::Arc;
+ use texturecraft_engine::compose::BakedMaps;
+ use texturecraft_engine::geom::primitives;
+
+ let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
+ session.doc.baked.insert(
+ 0,
+ BakedMaps {
+ resolution: 64,
+ maps: [
+ (BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])),
+ (BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3])),
+ (BakedMap::Height, Arc::new(vec![0.75; 64 * 32])),
+ ]
+ .into(),
+ },
+ );
+ execute(&mut session, "bake.settings", &json!({"resolution": 64, "maps": ["ambientOcclusion", "height"], "rays": 2})).unwrap();
+ execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
+ let before = session.doc.baked.clone();
+ let task = task(&session);
+ let whole = task.run(&Progress::new()).unwrap();
+ let mut streamed = Vec::new();
+
+ let output = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap();
+
+ assert_eq!((output.resolution, output.height), (128, 64));
+ assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>());
+ for (map, pixels) in &whole.maps {
+ assert_eq!(*output.maps[map], *pixels, "{map:?} must match a whole bake, including retained pixels");
+ }
+ assert_eq!(streamed.iter().map(|map| map.map).collect::>(), [BakedMap::AmbientOcclusion, BakedMap::Height]);
+ for map in &streamed {
+ assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]));
+ }
+
+ session.apply_streamed_bake(0, output).unwrap();
+
+ for (map, pixels) in &whole.maps {
+ assert_eq!(*session.doc.baked[&0].maps[map], *pixels);
+ }
+ session.undo().unwrap();
+ assert_eq!(session.doc.baked, before);
+}
+
+#[test]
+fn box_fills_are_refused_while_a_bake_shows() {
+ let mut session = session();
+ execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
+ execute(&mut session, "tool.polygonFill", &Value::Null).unwrap();
+ session.bake_preview_begin(vec![(0, order(&session))]);
+ let before = texturecraft_engine::inspect::session(&session);
+ let viewport = Vec2::new(100.0, 100.0);
+
+ for result in [
+ session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE),
+ session.drag_polygon_fill_box(Vec2::ZERO, viewport, viewport),
+ session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE),
+ session.polygon_fill_box(Vec2::ZERO, viewport, viewport),
+ execute(&mut session, "tool.click", &json!({"uv0": [0, 0], "uv1": [1, 1]})).map(|_| 0),
+ execute(&mut session, "tool.click", &json!({"x0": 0, "y0": 0, "x1": 100, "y1": 100})).map(|_| 0),
+ ] {
+ assert_eq!(result.unwrap_err().to_string(), texturecraft_engine::bake_preview::PAINTING_PAUSED);
+ }
+
+ assert_eq!(session.end_polygon_fill_box(), 0);
+ assert_eq!(texturecraft_engine::inspect::session(&session), before);
+ session.bake_preview_end();
+ assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0);
+}
+
+#[test]
+fn preview_order_matches_each_sets_bake_task() {
+ let mut session = session();
+ session.doc.project.texture_sets[1].bake.maps.select([BakedMap::WorldNormal, BakedMap::Height]);
+ let expected: Vec<_> = [0, 1].into_iter().map(|texture_set| session.bake_task(texture_set).unwrap().maps()).collect();
+
+ session.bake_preview_begin_for(&[0, 1]).unwrap();
+
+ let preview = session.bake_preview.as_ref().unwrap();
+ for (texture_set, maps) in expected.iter().enumerate() {
+ assert_eq!(&preview.sets[&texture_set].order, maps);
+ assert!(preview.sets[&texture_set].baked.maps.is_empty());
+ }
+ assert_eq!(session.view, ViewMode::MeshMap(expected[0][0]));
+}
+
+#[test]
+fn invalid_preview_sets_preserve_the_existing_preview_and_view() {
+ let mut session = session();
+ session.bake_preview_begin_for(&[0]).unwrap();
+ session.bake_preview_set_current(0);
+ session.bake_preview_show(PreviewShow::Material).unwrap();
+ let before = texturecraft_engine::bake_preview::preview_json(&session);
+ let view = session.view;
+ let revision = session.revision;
+ let invalid_set = session.set_count();
+ let expected_error = session.doc.project.texture_set(invalid_set).unwrap_err().to_string();
+
+ let error = session.bake_preview_begin_for(&[1, invalid_set]).unwrap_err();
+
+ assert!(error.to_string().contains(&expected_error));
+ assert_eq!(texturecraft_engine::bake_preview::preview_json(&session), before);
+ assert_eq!(session.view, view);
+ assert_eq!(session.revision, revision);
+}
+
+#[test]
+fn starting_a_bake_preview_discards_an_active_stroke() {
+ for (from_settings, paint_mask) in [(false, false), (true, false), (false, true), (true, true)] {
+ let mut session = session();
+ execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
+ if paint_mask {
+ session.target = texturecraft_engine::StackTarget::Mask;
+ }
+
+ let before = session.doc.clone();
+ let history = session.history_labels();
+ let view = session.view;
+ session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
+ assert!(session.stroke_tiles() > 0, "the stroke must contain paint before the preview starts");
+
+ if from_settings {
+ session.bake_preview_begin_for(&[0]).unwrap();
+ } else {
+ session.bake_preview_begin(vec![(0, order(&session))]);
+ }
+ let stroke_survived = session.stroke_active();
+ session.continue_stroke_uv(Vec2::splat(0.6), 1.0);
+ session.end_stroke().unwrap();
+
+ assert_eq!(session.history_labels(), history, "releasing the pointer during a preview must not commit paint");
+ assert!(!stroke_survived, "activation must cancel the stroke immediately");
+ assert_eq!(session.doc.project, before.project);
+ assert_eq!(session.doc.pixels.layers, before.pixels.layers);
+ assert_eq!(session.doc.pixels.masks, before.pixels.masks);
+ assert!(session.bake_preview_active());
+ session.bake_preview_end();
+
+ assert_eq!(session.view, view);
+ session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
+ session.end_stroke().unwrap();
+ assert_eq!(session.history_labels().len(), history.len() + 1, "painting resumes after the preview ends");
+ }
+}
+
+#[test]
+fn a_rejected_bake_preview_preserves_the_active_stroke() {
+ let mut session = session();
+ execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
+ let history_steps = session.history_labels().len();
+ let view = session.view;
+ session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
+ let painted_tiles = session.stroke_tiles();
+ assert!(painted_tiles > 0);
+
+ let result = session.bake_preview_begin_for(&[0, session.set_count()]);
+
+ assert!(result.is_err());
+ assert!(!session.bake_preview_active());
+ assert!(session.stroke_active());
+ assert_eq!(session.stroke_tiles(), painted_tiles);
+ assert_eq!(session.view, view);
+ session.end_stroke().unwrap();
+
+ assert_eq!(session.history_labels().len(), history_steps + 1, "a rejected preview must not discard painting");
+}
diff --git a/crates/engine/tests/it/color_selection.rs b/crates/engine/tests/it/color_selection.rs
new file mode 100644
index 00000000..bdb984b5
--- /dev/null
+++ b/crates/engine/tests/it/color_selection.rs
@@ -0,0 +1,309 @@
+//! Color selection effects: editing their ID colors and picking them from the ID mesh map
+
+use serde_json::{Value, json};
+use texturecraft_engine::core::{EffectKind, LayerId};
+use texturecraft_engine::geom::glam::Vec2;
+use texturecraft_engine::geom::primitives;
+use texturecraft_engine::{Session, execute};
+
+const TOP_LEFT_ID: [u8; 3] = [200, 30, 10];
+const TOP_RIGHT_ID: [u8; 3] = [10, 200, 30];
+const BOTTOM_ID: [u8; 3] = [30, 10, 200];
+const NO_PART: [f32; 3] = [0.0, 0.0, 0.0];
+
+fn session() -> Session {
+ let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
+ session.viewport = Vec2::new(400.0, 400.0);
+ session.camera.yaw = 0.0;
+ session.camera.pitch = 0.0;
+ session.update();
+ session
+}
+
+/// An 8×8 ID map: two parts on the top half, one on the bottom half
+fn id_map_png() -> Vec {
+ let image = image::RgbaImage::from_fn(8, 8, |x, y| {
+ let [red, green, blue] = match (x < 4, y < 4) {
+ (true, true) => TOP_LEFT_ID,
+ (false, true) => TOP_RIGHT_ID,
+ _ => BOTTOM_ID,
+ };
+ image::Rgba([red, green, blue, 255])
+ });
+ let mut bytes = Vec::new();
+ image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
+ bytes
+}
+
+fn stored(id: [u8; 3]) -> [f32; 3] {
+ id.map(|channel| channel as f32 / 255.0)
+}
+
+fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
+ assert!(actual.iter().zip(expected).all(|(channel, wanted)| (channel - wanted).abs() < 1e-3), "{actual:?} vs {expected:?}");
+}
+
+/// A fill layer masked by a color selection that selects no part yet: (layer, effect)
+fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) {
+ if with_id_map {
+ let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
+ execute(session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
+ }
+
+ let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap());
+ execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap();
+ let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id;
+ (layer, effect)
+}
+
+fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> {
+ match &session.doc.project.effect(effect).unwrap().1.kind {
+ EffectKind::ColorSelection { colors, .. } => colors.clone(),
+ other => panic!("not a color selection: {other:?}"),
+ }
+}
+
+#[test]
+fn a_color_picked_on_the_mesh_is_selected_where_it_was_picked() {
+ let mut session = session();
+ let (layer, effect) = masked_layer(&mut session, true);
+ let center = Vec2::new(200.0, 200.0);
+ let hit = session.pick(center, session.viewport).unwrap();
+ let (width, height) = session.caches[0].size;
+ let texel = ((hit.uv.x * width as f32) as u32, (hit.uv.y * height as f32) as u32);
+ assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0], "nothing selected before the pick");
+
+ let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": center.x, "y": center.y})).unwrap();
+
+ assert_eq!(picked["index"], json!(1));
+ assert_eq!(colors(&session, effect).len(), 2);
+ assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
+ execute(&mut session, "edit.undo", &Value::Null).unwrap();
+ assert_eq!(colors(&session, effect), vec![NO_PART], "one undo step");
+}
+
+#[test]
+fn a_uv_pick_adds_the_color_there_or_replaces_one() {
+ let mut session = session();
+ let (_, effect) = masked_layer(&mut session, true);
+
+ execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
+ assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID));
+
+ let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap();
+ assert_eq!(replaced["index"], json!(0));
+ let picked = colors(&session, effect);
+ assert_eq!(picked.len(), 2);
+ assert_close(picked[0], stored(BOTTOM_ID));
+ execute(&mut session, "edit.undo", &Value::Null).unwrap();
+ assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step");
+}
+
+#[test]
+fn the_colors_param_replaces_the_list_in_one_undo_step() {
+ let mut session = session();
+ let (_, effect) = masked_layer(&mut session, false);
+ let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)];
+
+ execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap();
+ assert_eq!(colors(&session, effect), edited.to_vec());
+ let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") };
+ assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2));
+
+ execute(&mut session, "edit.undo", &Value::Null).unwrap();
+ assert_eq!(colors(&session, effect), vec![NO_PART]);
+}
+
+#[test]
+fn bad_colors_are_refused_and_change_nothing() {
+ let mut session = session();
+ let (_, effect) = masked_layer(&mut session, false);
+ let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")];
+
+ for colors_param in &refused {
+ assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}");
+ }
+ assert_eq!(colors(&session, effect), vec![NO_PART]);
+ execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap();
+ assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1");
+}
+
+#[test]
+fn picking_explains_what_is_missing() {
+ let mut session = session();
+ let (layer, effect) = masked_layer(&mut session, false);
+ let pick = |session: &mut Session, params: Value| execute(session, "effect.colorSelection.pick", ¶ms).unwrap_err().to_string();
+
+ assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5]})).contains("no ID map"));
+ let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
+ execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
+ assert!(pick(&mut session, json!({"effect": effect.0, "x": 1, "y": 1})).contains("nothing under that point"));
+ assert!(pick(&mut session, json!({"effect": effect.0, "uv": [1.5, 0.5]})).contains("outside"));
+ assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5], "index": 7})).contains("no color 7"));
+ assert!(pick(&mut session, json!({"effect": effect.0})).contains("`x` and `y`"));
+
+ let fill = execute(&mut session, "effect.add.fill", &json!({"layer": layer.0})).unwrap()["effect"].as_u64().unwrap();
+ assert!(pick(&mut session, json!({"effect": fill, "uv": [0.5, 0.5]})).contains("not a color selection"));
+ assert_eq!(colors(&session, effect), vec![NO_PART]);
+}
+
+#[test]
+fn hostile_params_never_crash_the_color_selection_commands() {
+ let mut session = session();
+ let (_, effect) = masked_layer(&mut session, true);
+ let hostile = [
+ json!({"effect": effect.0, "x": f32::MAX, "y": -1e30, "viewport": [0, 0]}),
+ json!({"effect": effect.0, "uv": [f64::MAX, -1e300], "index": u64::MAX}),
+ json!({"effect": effect.0, "uv": [0.5], "colors": [[f64::MAX, -f64::MAX, 0.0]]}),
+ json!({"effect": effect.0, "uv": "x", "colors": {"r": 1}}),
+ json!({"effect": u64::MAX, "uv": [0.5, 0.5]}),
+ ];
+
+ for params in &hostile {
+ let _ = execute(&mut session, "effect.colorSelection.pick", params);
+ let _ = execute(&mut session, "effect.set", params);
+ session.update();
+ }
+}
+
+#[test]
+fn a_hidden_texture_set_does_not_block_a_pick_behind_it() {
+ let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
+ session.viewport = Vec2::new(400.0, 400.0);
+ session.update();
+ let set_named = |name: &str| session.doc.project.texture_sets.iter().position(|set| set.name == name).unwrap();
+ let (base, ball) = (set_named("Base"), set_named("Ball"));
+ execute(&mut session, "textureSet.select", &json!({"ts": base})).unwrap();
+ let (_, effect) = masked_layer(&mut session, true);
+ let pick_at = |session: &mut Session, y: f32| execute(session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": 200, "y": y}));
+ let ball_in_front = |session: &Session, y: f32| {
+ session.pick(Vec2::new(200.0, y), session.viewport).is_some_and(|hit| session.texture_set_of_material(hit.material) == Some(ball))
+ };
+
+ // Down the middle until a pixel where the hidden ball covers the base: the pick reads the base
+ execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": false})).unwrap();
+ let mut covered = None;
+ for y in (200..400).map(|y| y as f32) {
+ if ball_in_front(&session, y) && pick_at(&mut session, y).is_ok() {
+ covered = Some(y);
+ break;
+ }
+ }
+ let y = covered.expect("a pixel where the ball covers the base");
+ assert_eq!(colors(&session, effect).len(), 2);
+
+ execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap();
+ assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it");
+}
+
+#[test]
+fn malformed_replacement_indices_are_rejected_without_editing() {
+ let mut session = session();
+ let (_, effect) = masked_layer(&mut session, true);
+ let history = session.history_labels();
+
+ for index in [json!(-1), json!(0.4), json!("0"), json!(true), json!([])] {
+ let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": index}));
+ assert!(result.is_err(), "invalid index {index} was accepted: {result:?}");
+ assert_eq!(colors(&session, effect), vec![NO_PART]);
+ assert_eq!(session.history_labels(), history);
+ }
+}
+
+#[test]
+fn the_color_limit_rejects_additions_but_allows_replacement() {
+ let mut session = session();
+ let (_, effect) = masked_layer(&mut session, true);
+ let full = vec![NO_PART; 256];
+ execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": full})).unwrap();
+ let history = session.history_labels();
+ let project = session.doc.project.clone();
+
+ for params in [json!({"effect": effect.0, "uv": [0.25, 0.25]}), json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 256})] {
+ assert!(execute(&mut session, "effect.colorSelection.pick", ¶ms).is_err());
+ assert_eq!(colors(&session, effect), full);
+ assert_eq!(session.history_labels(), history);
+ }
+ assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; 257], "name": "Invalid edit"})).is_err());
+ assert_eq!(session.history_labels(), history);
+ assert_eq!(session.doc.project, project, "invalid colors also roll back edits to other fields");
+
+ execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 255})).unwrap();
+ assert_eq!(colors(&session, effect).len(), 256);
+ assert_close(colors(&session, effect)[255], stored(TOP_LEFT_ID));
+}
+
+#[test]
+fn inspect_exposes_the_selected_colors_and_tolerance() {
+ let mut session = session();
+ let (layer, effect) = masked_layer(&mut session, true);
+ execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
+ execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.25})).unwrap();
+
+ let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
+ let layer = inspected["layers"].as_array().unwrap().iter().find(|found| found["id"] == layer.0).unwrap();
+ let found = &layer["mask"]["effects"][0];
+ assert_eq!(found["colors"], json!(colors(&session, effect)));
+ assert_eq!(found["tolerance"], json!(0.25));
+}
+
+#[test]
+fn picks_use_the_working_texel_on_a_smaller_uv_tile() {
+ let mut session = Session::new_project("UV tiles", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
+ for tile in [1001, 1002] {
+ session.import_resource_bytes(&format!("id.{tile}.png"), id_map_png()).unwrap();
+ }
+ execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": "id.1001.png"})).unwrap();
+ let (layer, effect) = masked_layer(&mut session, false);
+ execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
+ execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.0})).unwrap();
+ let size = session.doc.project.texture_sets[0].size();
+ let uv = [0.625, 0.25];
+ let texel = ((uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32);
+ assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0]);
+
+ execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": uv})).unwrap();
+ assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
+ let before = colors(&session, effect);
+ let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.9, 0.8]}));
+ assert!(result.unwrap_err().to_string().contains("no ID color"), "unused tile space has no sample");
+ assert_eq!(colors(&session, effect), before);
+}
+
+#[test]
+#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"]
+fn benchmark_color_selection_edits() {
+ use std::time::{Duration, Instant};
+
+ const SAMPLES: u32 = 10;
+ for resolution in [256, 1024] {
+ let started = Instant::now();
+ let mut session = Session::new_project("benchmark", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, resolution).unwrap();
+ let (_, effect) = masked_layer(&mut session, true);
+ session.update();
+ let construction = started.elapsed();
+
+ for count in [1, 256] {
+ execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; count]})).unwrap();
+ session.update();
+ let params = json!({"effect": effect.0, "uv": [0.25, 0.25], "index": count - 1});
+ let (mut command_time, mut composite_time) = (Duration::ZERO, Duration::ZERO);
+ for _ in 0..SAMPLES {
+ let started = Instant::now();
+ execute(&mut session, "effect.colorSelection.pick", ¶ms).unwrap();
+ command_time += started.elapsed();
+ let started = Instant::now();
+ session.update();
+ composite_time += started.elapsed();
+ execute(&mut session, "edit.undo", &Value::Null).unwrap();
+ session.update();
+ }
+ println!(
+ "{resolution}x{resolution}, {count} colors, {SAMPLES} samples: construction {construction:.3?}; pick {:.3?}; composite {:.3?}; session memory {} bytes",
+ command_time / SAMPLES,
+ composite_time / SAMPLES,
+ session.memory().total()
+ );
+ }
+ }
+}
diff --git a/crates/engine/tests/it/high_poly_missed.rs b/crates/engine/tests/it/high_poly_missed.rs
new file mode 100644
index 00000000..c5b132fa
--- /dev/null
+++ b/crates/engine/tests/it/high_poly_missed.rs
@@ -0,0 +1,57 @@
+use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed};
+use texturecraft_engine::geom::glam::Vec3;
+
+fn vertex(height: f32) -> Option {
+ Some(VertexReach {
+ low_position: Vec3::ZERO,
+ start: RayStart::Distance { up: Vec3::Y, scale: 1.0 },
+ high_position: Vec3::new(0.0, height, 0.0),
+ high_facing: Vec3::Y,
+ name_matches: true,
+ })
+}
+
+fn reach(vertices: Vec>) -> Option {
+ Some(HighPolyReach { vertices, cage_units: 1.0, ignore_backface: false })
+}
+
+fn sets() -> Vec> {
+ vec![None, reach(vec![vertex(0.5), vertex(-0.25), None, None, None]), reach(vec![None, None, vertex(0.5), vertex(-0.25), None])]
+}
+
+const DISTANCES: [(f32, f32); 3] = [(9.0, 9.0), (0.25, 0.25), (0.5, 0.125)];
+
+#[test]
+fn each_owning_set_uses_its_own_frontal_and_rear_distances() {
+ let reaches = sets();
+ assert_eq!(high_poly_missed(&reaches, &DISTANCES, None, 6), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
+ let expanded = [(9.0, 9.0), (0.5, 0.25), (0.5, 0.25)];
+ assert_eq!(high_poly_missed(&reaches, &expanded, None, 6), vec![0.0; 6]);
+}
+
+#[test]
+fn selected_set_filter_leaves_other_sets_unmarked() {
+ let reaches = sets();
+ assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
+ assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
+ for only_set in [0, reaches.len(), usize::MAX] {
+ assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]);
+ }
+}
+
+#[test]
+fn missing_reach_or_distances_leave_vertices_unmarked() {
+ assert_eq!(high_poly_missed(&[], &DISTANCES, None, 6), vec![0.0; 6]);
+ assert_eq!(high_poly_missed(&sets(), &[], None, 6), vec![0.0; 6]);
+ assert_eq!(high_poly_missed(&sets(), &DISTANCES[..2], None, 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
+ assert_eq!(high_poly_missed(&sets(), &DISTANCES, None, 1), vec![1.0]);
+ assert!(high_poly_missed(&sets(), &DISTANCES, None, 0).is_empty());
+}
+
+#[test]
+fn a_reached_vertex_is_not_overridden_by_a_later_set() {
+ let reaches = [reach(vec![vertex(0.5)]), reach(vec![vertex(0.5)])];
+ let distances = [(0.5, 0.0), (0.25, 0.0)];
+ assert_eq!(high_poly_missed(&reaches, &distances, None, 1), vec![0.0]);
+ assert_eq!(high_poly_missed(&reaches, &distances, Some(1), 1), vec![1.0]);
+}
diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs
index 1200ab30..7f13db57 100644
--- a/crates/engine/tests/it/main.rs
+++ b/crates/engine/tests/it/main.rs
@@ -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;
diff --git a/crates/engine/tests/it/meshmap_import.rs b/crates/engine/tests/it/meshmap_import.rs
new file mode 100644
index 00000000..33dc2ec8
--- /dev/null
+++ b/crates/engine/tests/it/meshmap_import.rs
@@ -0,0 +1,298 @@
+//! Importing baked map files at once: each lands in the texture set and mesh map its name names
+
+use std::path::{Path, PathBuf};
+
+use serde_json::{Value, json};
+use texturecraft_engine::core::BakedMap;
+use texturecraft_engine::geom::primitives;
+use texturecraft_engine::{Session, execute};
+
+/// The material ball: texture sets "Ball" and "Base"
+fn session() -> Session {
+ Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap()
+}
+
+/// A folder of 4×4 gray PNGs named `files`, each with its own gray level
+fn bake_folder(test: &str, files: &[&str]) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ for (index, file) in files.iter().enumerate() {
+ let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX);
+ image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap();
+ }
+ dir
+}
+
+fn import(s: &mut Session, dir: &Path, files: &[(&str, Option<&str>)]) -> Value {
+ let files: Vec = files
+ .iter()
+ .map(|(file, map)| {
+ let path = dir.join(file).display().to_string();
+ match map {
+ Some(map) => json!({"path": path, "map": map}),
+ None => json!({"path": path}),
+ }
+ })
+ .collect();
+ execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap()
+}
+
+fn file_names(list: &Value) -> Vec {
+ list.as_array()
+ .unwrap()
+ .iter()
+ .map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap()))
+ .map(|path| path.rsplit(['/', '\\']).next().unwrap().to_string())
+ .collect()
+}
+
+fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool {
+ s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map)
+}
+
+#[test]
+fn files_go_to_the_set_and_map_their_names_name() {
+ let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"];
+ let dir = bake_folder("sets", &files);
+ let mut s = session();
+ let label_before = s.undo_label().map(str::to_string);
+
+ let result = import(&mut s, &dir, &files.map(|file| (file, None)));
+
+ let assigned = &result["assigned"];
+ assert_eq!(file_names(assigned).len(), 5, "{result}");
+ for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] {
+ assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id());
+ assert!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["map"] == map.id()), "{result}");
+ }
+ assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]);
+ assert_eq!(s.undo_label(), Some("Import baked maps"));
+
+ execute(&mut s, "edit.undo", &Value::Null).unwrap();
+ assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step");
+ assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map");
+ assert!(s.doc.resources.is_empty(), "undo removes the imported image resources");
+ std::fs::remove_dir_all(dir).ok();
+}
+
+#[test]
+fn a_given_map_overrides_the_name() {
+ let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]);
+ let mut s = session();
+
+ let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]);
+
+ assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}");
+ assert!(has_map(&s, 0, BakedMap::Thickness));
+ assert!(has_map(&s, 1, BakedMap::Height));
+ assert!(!has_map(&s, 1, BakedMap::Normal));
+ std::fs::remove_dir_all(dir).ok();
+}
+
+#[test]
+fn a_second_file_for_one_slot_is_left_out() {
+ let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]);
+ let mut s = session();
+
+ let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]);
+
+ assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]);
+ assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]);
+ assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported");
+ std::fs::remove_dir_all(dir).ok();
+}
+
+#[test]
+fn an_undecodable_file_imports_nothing() {
+ let dir = bake_folder("undecodable", &["Ball_ao.png"]);
+ std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap();
+ let mut s = session();
+ let label_before = s.undo_label().map(str::to_string);
+ let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]});
+
+ let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string();
+
+ assert!(error.contains("Base_ao.png"), "{error}");
+ assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()));
+ assert!(s.doc.resources.is_empty() && s.images.is_empty());
+ assert_eq!(s.undo_label().map(str::to_string), label_before);
+ std::fs::remove_dir_all(dir).ok();
+}
+
+/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002
+fn tiled_session() -> Session {
+ Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap()
+}
+
+#[test]
+fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() {
+ let files = ["Plane_ao.1001.png", "plane-AO-1002.png"];
+ let dir = bake_folder("tiles", &files);
+ let mut s = tiled_session();
+
+ let result = import(&mut s, &dir, &files.map(|file| (file, None)));
+
+ assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}");
+ let baked = &s.doc.baked[&0];
+ let ao = &baked.maps[&BakedMap::AmbientOcclusion];
+ let width = baked.resolution as usize;
+ let middle_row = ao.len() / width / 2 * width;
+ assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file");
+ std::fs::remove_dir_all(dir).ok();
+}
+
+#[test]
+fn tiled_files_without_their_tiles_are_left_out_alone() {
+ let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"];
+ let dir = bake_folder("partial-tiles", &files);
+ let mut s = tiled_session();
+
+ let result = import(&mut s, &dir, &files.map(|file| (file, None)));
+
+ assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]);
+ assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]);
+ assert!(has_map(&s, 0, BakedMap::AmbientOcclusion));
+ assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported");
+ std::fs::remove_dir_all(dir).ok();
+}
+
+#[test]
+fn nothing_matched_makes_no_undo_step() {
+ let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]);
+ let mut s = session();
+ let label_before = s.undo_label().map(str::to_string);
+
+ let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]);
+
+ assert_eq!(file_names(&result["assigned"]), Vec::::new());
+ assert_eq!(file_names(&result["unmatched"]).len(), 2);
+ assert_eq!(s.undo_label().map(str::to_string), label_before);
+ assert!(!s.modified);
+ std::fs::remove_dir_all(dir).ok();
+}
+
+#[test]
+fn an_invalid_map_override_does_not_fall_back_to_the_file_name() {
+ let dir = bake_folder("invalid-map", &["Ball_ao.png"]);
+ let mut session = session();
+ for map in [json!(true), json!(42), json!([]), json!({}), json!("unknown")] {
+ let params = json!({"files": [{"path": dir.join("Ball_ao.png"), "map": map}]});
+ let result = execute(&mut session, "textureSet.meshMap.import", ¶ms);
+ assert!(result.is_err(), "invalid map {map} must be rejected: {result:?}");
+ assert!(session.doc.resources.is_empty());
+ assert!(!session.modified);
+ }
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"]
+fn benchmark_baked_map_import() {
+ use std::time::Instant;
+ use texturecraft_engine::core::BakeResolution;
+
+ let dir = std::env::temp_dir().join(format!("texturecraft-import-benchmark-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ for (size, tiled) in [(1024, false), (2048, false), (1024, true)] {
+ let mut files = Vec::new();
+ let mut encoded_bytes = 0;
+ for map in ["normal", "ao", "curvature"] {
+ for tile in 1001..=if tiled { 1002 } else { 1001 } {
+ let path = dir.join(format!("mesh_{map}.{tile}.png"));
+ image::RgbaImage::from_fn(size, size, |x, y| {
+ let value = (x.wrapping_mul(73) ^ y.wrapping_mul(151) ^ tile) as u8;
+ image::Rgba([value, value.wrapping_add(37), 255, 255])
+ })
+ .save(&path)
+ .unwrap();
+ encoded_bytes += std::fs::metadata(&path).unwrap().len();
+ files.push(json!({"path": path}));
+ }
+ }
+ let params = json!({"files": files});
+ let mut milliseconds = Vec::new();
+ for iteration in 0..6 {
+ let mesh = if tiled { primitives::udim_plane() } else { primitives::cube(2.0) };
+ let mut session = Session::new_project("benchmark", mesh, "builtin:cube", None, 128).unwrap();
+ session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::from_pixels(size).unwrap();
+ let started = Instant::now();
+ let result = execute(&mut session, "textureSet.meshMap.import", ¶ms).unwrap();
+ let elapsed = started.elapsed().as_secs_f64() * 1000.0;
+ assert_eq!(result["assigned"].as_array().unwrap().len(), files.len());
+ assert_eq!(session.doc.baked[&0].maps.len(), 3);
+ if iteration > 0 {
+ milliseconds.push(elapsed);
+ }
+ }
+ milliseconds.sort_by(f64::total_cmp);
+ eprintln!(
+ "import size={size} tiles={} files={} encoded_bytes={encoded_bytes} median_ms={:.3} min_ms={:.3} max_ms={:.3}",
+ if tiled { 2 } else { 1 },
+ files.len(),
+ milliseconds[2],
+ milliseconds[0],
+ milliseconds[4]
+ );
+ }
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn tiled_import_uses_new_images_when_resource_names_collide() {
+ let files = ["Plane_ao.1001.png", "Plane_ao.1002.png"];
+ let dir = bake_folder("collisions", &files);
+ let mut session = tiled_session();
+ let old_bytes = std::fs::read(dir.join(files[0])).unwrap();
+ for name in files {
+ session.import_resource_bytes(name, old_bytes.clone()).unwrap();
+ }
+ let revision_before = session.revision;
+
+ import(&mut session, &dir, &files.map(|file| (file, None)));
+
+ let baked = &session.doc.baked[&0];
+ let ao = &baked.maps[&BakedMap::AmbientOcclusion];
+ let width = baked.resolution as usize;
+ let row = ao.len() / width / 2 * width;
+ assert!((ao[row + width / 4] - 20.0 / 255.0).abs() < 1e-5);
+ assert!((ao[row + 3 * width / 4] - 40.0 / 255.0).abs() < 1e-5);
+ assert_eq!(session.revision, revision_before + 1);
+ assert_eq!(session.doc.resources.len(), 4);
+
+ session.undo().unwrap();
+ assert_eq!(session.doc.resources.len(), 2);
+ assert_eq!(session.images.len(), 2);
+ session.redo().unwrap();
+ assert_eq!(session.images.len(), 4);
+ assert!(has_map(&session, 0, BakedMap::AmbientOcclusion));
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn too_many_files_are_rejected_before_reading_any() {
+ let mut session = session();
+ let files = vec![json!({"path": "Ball_ao.png"}); 513];
+ let error = execute(&mut session, "textureSet.meshMap.import", &json!({"files": files})).unwrap_err().to_string();
+ assert!(error.contains("at most 512 files"), "{error}");
+ assert!(session.doc.resources.is_empty());
+ assert!(!session.modified);
+}
+
+#[test]
+fn tga_maps_survive_undo_redo_and_project_reload() {
+ let dir = bake_folder("tga", &["Ball_normal.tga", "Base_ao.png"]);
+ let mut session = session();
+ let result = import(&mut session, &dir, &[("Ball_normal.tga", None), ("Base_ao.png", None)]);
+ assert_eq!(result["assigned"].as_array().unwrap().len(), 2);
+ assert!(has_map(&session, 0, BakedMap::Normal));
+ let image = session.images["Ball_normal.tga"].clone();
+
+ session.undo().unwrap();
+ assert!(session.images.is_empty());
+ session.redo().unwrap();
+ assert_eq!(session.images["Ball_normal.tga"].rgba, image.rgba);
+ let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
+ assert_eq!(reloaded.images["Ball_normal.tga"].rgba, image.rgba);
+ assert_eq!(reloaded.doc.baked, session.doc.baked);
+ std::fs::remove_dir_all(dir).unwrap();
+}
diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs
index c28cf34a..4dd04032 100644
--- a/crates/engine/tests/session.rs
+++ b/crates/engine/tests/session.rs
@@ -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();
}
diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs
index 49e1e014..85590d9d 100644
--- a/crates/formats/src/image_res.rs
+++ b/crates/formats/src/image_res.rs
@@ -21,20 +21,27 @@ pub fn decode_image(bytes: &[u8]) -> Result {
/// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the
/// header, before any pixel is decoded or allocated.
pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result {
- let reader =
+ let mut reader =
image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
- let (w, h) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
- if w == 0 || h == 0 || w > MAX_IMAGE_SIZE || h > MAX_IMAGE_SIZE {
- return Err(FormatError::TooLarge(format!("image is {w}x{h} (limit {MAX_IMAGE_SIZE})")));
+
+ // TGA has no magic signature; its decoder validates the header when no format was recognized
+ let format = reader.format().unwrap_or(image::ImageFormat::Tga);
+ reader.set_format(format);
+
+ let (width, height) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
+ if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE {
+ return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})")));
}
- if u64::from(w) * u64::from(h) > max_texels {
- return Err(FormatError::TooLarge(format!("image is {w}x{h}, more than {max_texels} texels")));
+ if u64::from(width) * u64::from(height) > max_texels {
+ return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels")));
}
- let img = crate::guard("image", || image::load_from_memory(bytes).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?;
- let srgb = !matches!(img, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_));
- let f = img.into_rgba32f();
- let (width, height) = f.dimensions();
- let rgba = f.pixels().map(|p| p.0).collect();
+
+ let image =
+ crate::guard("image", || image::load_from_memory_with_format(bytes, format).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?;
+ let srgb = !matches!(image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_));
+ let float_image = image.into_rgba32f();
+ let (width, height) = float_image.dimensions();
+ let rgba = float_image.pixels().map(|pixel| pixel.0).collect();
Ok(DecodedImage { width, height, rgba, srgb })
}
@@ -69,6 +76,19 @@ mod tests {
assert!(coverage_png(2, 2, &[0], [255; 3]).is_err());
}
+ #[test]
+ fn tga_without_a_magic_signature_decodes_within_the_texel_budget() {
+ let mut bytes = Vec::new();
+ image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Tga).unwrap();
+ let image = decode_image_within(&bytes, 16).unwrap();
+ assert_eq!((image.width, image.height), (4, 4));
+ assert!((image.rgba[0][1] - 0.2).abs() < 1e-6);
+ assert!(image.srgb);
+ let header = &bytes[..18];
+ assert!(matches!(decode_image_within(header, 15), Err(FormatError::TooLarge(_))));
+ assert!(decode_image(header).is_err());
+ }
+
#[test]
fn decoding_within_a_texel_limit_refuses_big_images_from_the_header() {
let png = {
diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs
index 419eb32a..63c0bb71 100644
--- a/crates/geom/src/mesh.rs
+++ b/crates/geom/src/mesh.rs
@@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4};
use crate::{GeomError, Result};
+/// An edge by the bits of its two end positions, the lower one first
+type EdgePositions = ([u32; 3], [u32; 3]);
+
/// A contiguous index range drawn with one material.
#[derive(Clone, Debug, PartialEq)]
pub struct SubMesh {
@@ -107,6 +110,47 @@ impl Mesh {
.collect()
}
+ /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
+ pub fn uv_seam_edges(&self) -> Vec> {
+ // Signed zero denotes the same position on either side of an imported seam
+ let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
+ let mut seams = vec![Vec::new(); self.materials.len().max(1)];
+ // Match across materials before grouping the lines for texture-set visibility
+ let mut sides: std::collections::HashMap> = std::collections::HashMap::new();
+ for material in 0..seams.len() {
+ for triangle in self.triangles_of(material) {
+ let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
+
+ for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] {
+ let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue };
+
+ let (from_bits, to_bits) = (bits(*from_position), bits(*to_position));
+ let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) };
+ sides.entry(edge).or_default().push((pair.0, pair.1, material));
+ }
+ }
+ }
+
+ let uv = |index: u32| self.uvs.get(index as usize).copied();
+ for pairs in sides.into_values() {
+ let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
+
+ if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
+ for (from, to, material) in pairs {
+ if let Some(edges) = seams.get_mut(material) {
+ edges.push((from.min(to), from.max(to)));
+ }
+ }
+ }
+ }
+ for edges in &mut seams {
+ edges.sort_unstable();
+ edges.dedup();
+ }
+
+ seams
+ }
+
/// Material of triangle `t`.
pub fn material_of(&self, t: usize) -> Option {
let idx = (t * 3) as u32;
@@ -433,6 +477,55 @@ mod tests {
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
}
+ #[test]
+ fn uv_seams_are_where_the_uv_layout_splits() {
+ let mesh = quad();
+ assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam");
+
+ // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut
+ let mut seam = mesh.clone();
+ seam.positions.push(seam.positions[0]);
+ seam.normals.push(seam.normals[0]);
+ seam.tangents.push(seam.tangents[0]);
+ seam.uvs.push(Vec2::new(0.9, 0.9));
+ seam.indices[3] = 4;
+ assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
+
+ // The same split with the same UV is a hard edge, not a seam
+ let mut hard = seam.clone();
+ hard.uvs[4] = hard.uvs[0];
+ assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]);
+ }
+
+ #[test]
+ fn uv_seams_join_positions_with_opposite_signed_zero() {
+ let mut mesh = quad();
+ mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0));
+ mesh.normals.push(mesh.normals[0]);
+ mesh.tangents.push(mesh.tangents[0]);
+ mesh.uvs.push(Vec2::new(0.9, 0.9));
+ mesh.indices[3] = 4;
+ assert_eq!(mesh.positions[0], mesh.positions[4]);
+ assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
+ }
+
+ #[test]
+ fn uv_seams_between_materials_belong_to_both_materials() {
+ let mut mesh = quad();
+ mesh.positions.push(mesh.positions[0]);
+ mesh.normals.push(mesh.normals[0]);
+ mesh.tangents.push(mesh.tangents[0]);
+ mesh.uvs.push(Vec2::new(0.9, 0.9));
+ mesh.indices[3] = 4;
+ mesh.materials.push("second".into());
+ mesh.submeshes[0].count = 3;
+ mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 });
+
+ assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
+ mesh.uvs[4] = mesh.uvs[0];
+ assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam");
+ }
+
#[test]
fn validate_catches_bad_indices() {
let mut m = quad();
diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs
new file mode 100644
index 00000000..8dbc4927
--- /dev/null
+++ b/crates/render/src/bake_visualization.rs
@@ -0,0 +1,12 @@
+//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly
+
+/// Which parts of the bake setup the 3D view draws
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct BakeVisualization {
+ pub high_poly: bool,
+ pub cage: bool,
+ pub uv_seams: bool,
+ pub low_poly: bool,
+ /// Draw the cage, seams and low poly of only this texture set
+ pub only_set: Option,
+}
diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs
new file mode 100644
index 00000000..3ed4f13f
--- /dev/null
+++ b/crates/render/src/cage_gpu.rs
@@ -0,0 +1,9 @@
+/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs
+pub(crate) struct CageGpu {
+ /// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners`
+ pub(crate) topology: u64,
+ pub(crate) corners: wgpu::Buffer,
+ pub(crate) corner_count: u32,
+ pub(crate) edges: wgpu::Buffer,
+ pub(crate) edge_index_count: u32,
+}
diff --git a/crates/render/src/high_poly_gpu.rs b/crates/render/src/high_poly_gpu.rs
new file mode 100644
index 00000000..97da6861
--- /dev/null
+++ b/crates/render/src/high_poly_gpu.rs
@@ -0,0 +1,11 @@
+/// The high poly bake mode draws over the low poly
+pub(crate) struct HighPolyGpu {
+ /// Which mesh the buffers hold
+ pub(crate) id: u64,
+ pub(crate) vertices: wgpu::Buffer,
+ pub(crate) vertex_count: usize,
+ pub(crate) indices: wgpu::Buffer,
+ pub(crate) index_count: u32,
+ /// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it
+ pub(crate) missed: wgpu::Buffer,
+}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index c5ca2221..bb0967c7 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -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;
diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs
index 4bfb13dc..9e720c6c 100644
--- a/crates/render/src/mesh_maps.rs
+++ b/crates/render/src/mesh_maps.rs
@@ -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 {
+ 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::*;
diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs
index 4ce9dac3..ad2bc2bf 100644
--- a/crates/render/src/renderer.rs
+++ b/crates/render/src/renderer.rs
@@ -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,
}
/// 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,
+ bake_high: Option,
+ /// Each texture set's cage, by set index
+ cages: Vec>,
+ uv_seams: Option,
sets: Vec,
/// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least
/// as reduced as the device's texture limit needs).
@@ -808,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 {
const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT);
+/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves
+const SHADOW_SLOPE_BIAS: f32 = 1.5;
+
+/// Anisotropic filtering of the texture sets' sampler
+const MAX_ANISOTROPY: u16 = 8;
+
+/// Size of the environment texture before the first environment loads
+const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256];
+
impl Renderer {
/// `target_format`: the format of the pass [`Renderer::blit`] draws into.
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer {
let shader = |label: &str, source: &str| {
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) })
};
- let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl")));
+ let module =
+ shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl")));
let util_module = shader("tc_util", include_str!("shaders/util.wgsl"));
let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl")));
let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl")));
- let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
+
+ let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries })
};
- let globals_bgl = bgl(
+ let globals_bind_group_layout = bind_group_layout(
"tc_globals",
&[
uniform_entry(0),
@@ -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::() 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::() 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::()),
+ (mesh.indices.len(), std::mem::size_of::()),
+ (mesh.positions.len(), std::mem::size_of::()),
+ ];
+ if mesh.indices.len() > u32::MAX as usize || buffers.iter().any(|&(count, stride)| count.checked_mul(stride).is_none_or(|bytes| bytes as u64 > limit)) {
+ return Err(format!("High-poly visualization exceeds the GPU buffer limit ({limit} bytes). Use a smaller preview mesh or hide the high poly."));
+ }
+
+ self.bake_high = Some(HighPolyGpu {
+ id,
+ vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX),
+ vertex_count: mesh.positions.len(),
+ indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX),
+ index_count: mesh.indices.len() as u32,
+ missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX),
+ });
+ Ok(())
+ }
+
+ /// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count
+ pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) {
+ let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return };
+
+ queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed));
+ self.content_rev += 1;
+ }
+
+ /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners
+ pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) {
+ if self.cages.len() <= texture_set {
+ self.cages.resize_with(texture_set + 1, || None);
+ }
+ let Some(slot) = self.cages.get_mut(texture_set) else { return };
+
+ match (cage, slot.as_mut()) {
+ (None, _) => *slot = None,
+ (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => {
+ queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners));
+ }
+ (Some((corners, edges)), _) => {
+ *slot = Some(CageGpu {
+ topology,
+ corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX),
+ corner_count: corners.len() as u32,
+ edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX),
+ edge_index_count: (edges.len() * 2) as u32,
+ });
+ }
+ }
+ self.content_rev += 1;
+ }
+
+ /// Forget the cages of texture sets from `count` on (sets that were removed)
+ pub fn truncate_bake_cages(&mut self, count: usize) {
+ if self.cages.len() > count {
+ self.cages.truncate(count);
+ self.content_rev += 1;
+ }
+ }
+
+ /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id`
+ pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) {
+ let mut line_indices: Vec = Vec::new();
+ let mut line_draws = Vec::new();
+ for (material, edges) in seams.iter().enumerate() {
+ let start = line_indices.len() as u32;
+ line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to]));
+ line_draws.push((start, line_indices.len() as u32 - start, material));
+ }
+
+ let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX);
+ self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws });
+ self.content_rev += 1;
+ }
+
/// Build the mesh's dense copy for displacement (once per mesh).
fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
let Some(m) = self.mesh.as_mut() else { return };
@@ -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).
diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl
new file mode 100644
index 00000000..1985f980
--- /dev/null
+++ b/crates/render/src/shaders/bake_view.wgsl
@@ -0,0 +1,88 @@
+// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams
+
+struct BakeViewOut {
+ @builtin(position) clip: vec4,
+ @location(0) world_position: vec3,
+ @location(1) normal: vec3,
+ // 1 where the bake's rays miss the high poly, 0 where they reach it
+ @location(2) missed: f32,
+};
+
+const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56);
+const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01);
+const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26);
+const CAGE_OPACITY: f32 = 0.16;
+const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7);
+const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0);
+
+// Brightness of surfaces seen edge-on; facing the camera adds the rest
+const HEADLIGHT_AMBIENT: f32 = 0.3;
+
+// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order
+const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001;
+const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002;
+
+// Lit from the camera: surfaces facing it are brightest
+fn headlight(color: vec3, normal: vec3, world_position: vec3) -> vec3 {
+ let facing = abs(dot(normal, normalize(g.eye.xyz - world_position)));
+ return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing);
+}
+
+fn pulled_toward_eye(world_position: vec3, fraction: f32) -> vec4 {
+ return g.view_proj * vec4(world_position + (g.eye.xyz - world_position) * fraction, 1.0);
+}
+
+// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it
+@vertex
+fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3, @location(4) missed: f32) -> BakeViewOut {
+ var out: BakeViewOut;
+ out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE);
+ out.world_position = position;
+ out.normal = normal;
+ out.missed = missed;
+ return out;
+}
+
+@fragment
+fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 {
+ let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed);
+ return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0);
+}
+
+@vertex
+fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut {
+ var out: BakeViewOut;
+ out.clip = g.view_proj * vec4(position, 1.0);
+ out.world_position = position;
+ out.normal = vec3(0.0, 1.0, 0.0);
+ out.missed = 0.0;
+ return out;
+}
+
+// The cage's own faces: their normal comes from the screen-space change of the position
+@fragment
+fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 {
+ let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position)));
+ return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY);
+}
+
+// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces
+@vertex
+fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut {
+ var out: BakeViewOut;
+ out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE);
+ out.world_position = position;
+ out.normal = vec3(0.0, 1.0, 0.0);
+ out.missed = 0.0;
+ return out;
+}
+
+@fragment
+fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 {
+ return CAGE_WIRE_COLOR;
+}
+
+@fragment
+fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 {
+ return UV_SEAM_COLOR;
+}
diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/uv_seam_gpu.rs
new file mode 100644
index 00000000..0ac80dc9
--- /dev/null
+++ b/crates/render/src/uv_seam_gpu.rs
@@ -0,0 +1,8 @@
+/// The low poly's UV seams as a line list over its vertex buffer
+pub(crate) struct UvSeamGpu {
+ /// The low-poly mesh the lines belong to
+ pub(crate) mesh_id: u64,
+ pub(crate) lines: wgpu::Buffer,
+ /// (first index, count, material) per material
+ pub(crate) line_draws: Vec<(u32, u32, usize)>,
+}
diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs
index 864c70c3..84a6e0e2 100644
--- a/crates/render/tests/headless.rs
+++ b/crates/render/tests/headless.rs
@@ -1,8 +1,9 @@
use texturecraft_compose::{DisplayKind, ImageRes};
+use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{OrbitCamera, primitives};
use texturecraft_render::headless::Headless;
use texturecraft_render::renderer::TAA_SAMPLES;
-use texturecraft_render::{Frame, Shade, ViewKind};
+use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind};
/// The UI's key light (`viewport::shade`).
const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5];
@@ -42,14 +43,18 @@ impl Img {
}
}
+/// The id `setup` uploads the material ball under
+const MESH_ID: u64 = 1;
+
/// A headless renderer with the material ball framed in a 480×360 view (None without a GPU).
fn setup() -> Option<(Headless, Frame)> {
let Ok(mut h) = Headless::new() else {
eprintln!("skipping: no GPU adapter");
return None;
};
+ eprintln!("headless adapter: {:?}", h.device.adapter_info());
let mesh = primitives::material_ball();
- h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1);
+ h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID);
h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2);
let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
let (lo, hi) = mesh.bounds();
@@ -220,6 +225,122 @@ fn wireframe_3d_overlays_the_mesh() {
assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean");
}
+#[test]
+fn bake_visualization_draws_the_high_poly_and_the_cage() {
+ // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color
+ const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3;
+ const CAGE_SCALE: f32 = 2.5;
+ const HIGH_POLY_ID: u64 = 7;
+ const CAGE_TOPOLOGY: u64 = 1;
+ const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]];
+ const COLOR_LEAD: i32 = 30;
+
+ let Some((mut h, frame)) = setup() else { return };
+ let ball = primitives::material_ball();
+ let (low_min, low_max) = ball.bounds();
+ let ball_center = (low_min + low_max) * 0.5;
+ let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16);
+ for position in &mut high.positions {
+ *position += ball_center;
+ }
+ h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap();
+ let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect();
+ h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY);
+ let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None };
+ let center = (frame.size[0] / 2, frame.size[1] / 2);
+
+ let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name);
+ let low_only = only(&mut h, bake, "bake_low_only");
+ let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden");
+ let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly");
+ let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage");
+ assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly");
+ let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background");
+ assert_same(&hidden, &background, "without the low poly only the background is left");
+ let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from);
+ assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]);
+ let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1));
+ assert!(
+ caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue,
+ "the cage tints the ball tan: {:?} → {:?}",
+ [low_red, low_green, low_blue],
+ [caged_red, caged_green, caged_blue]
+ );
+
+ // Vertices the bake's rays miss turn red
+ h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]);
+ let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed");
+ let [red, green, blue] = missed.at(center.0, center.1).map(i32::from);
+ assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]);
+
+ // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out
+ let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set");
+ let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set");
+ assert_ne!(first_set.px, caged.px, "the second set's low poly is left out");
+ assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out");
+ assert_ne!(first_set.px, second_set.px);
+
+ // UV seams draw over the low poly
+ h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges());
+ let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams");
+ assert_ne!(seams.px, low_only.px, "the seams show");
+
+ // A new distance with the same topology only moves the corners
+ let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect();
+ h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY);
+ let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown");
+ assert_ne!(caged.px, bigger.px, "the cage grew");
+}
+
+#[test]
+fn oversized_bake_high_poly_leaves_the_view_renderable() {
+ let Some((mut headless, frame)) = setup() else { return };
+
+ let high = primitives::sphere(0.5, 16, 8);
+ headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap();
+ let limit = headless.device.limits().max_buffer_size;
+ // The viewport vertex contains position, normal, tangent and UV: twelve f32 values
+ let vertex_count = limit as usize / (12 * std::mem::size_of::()) + 1;
+ let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() };
+ let error = headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&oversized), 2).unwrap_err();
+ assert!(error.contains("GPU buffer limit"), "{error}");
+
+ headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]);
+ let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None };
+ let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared");
+ let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background");
+ assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible");
+ headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 3).unwrap();
+ let recovered = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_recovered");
+ assert_ne!(recovered.px, background.px, "a later valid high poly still draws");
+}
+
+#[test]
+fn bake_low_poly_visibility_also_filters_its_wireframe() {
+ let Some((mut headless, frame)) = setup() else { return };
+
+ let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None };
+ let hidden = shaded(&frame, |shade| {
+ shade.bake = Some(bake);
+ shade.wireframe_3d = true;
+ shade.highlight = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] });
+ });
+ let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_wire_background");
+ let hidden_wire = render(&mut headless, &hidden, "bake_wire_hidden");
+ assert_same(&hidden_wire, &background, "hiding the project mesh also hides its wireframe and highlight");
+
+ for texture_set in [0, 1] {
+ let selected = shaded(&hidden, |shade| {
+ shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake });
+ shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] });
+ });
+ let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() };
+ let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}"));
+ let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}"));
+ assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set");
+ }
+}
+
#[test]
fn ortho_background_matches_perspective() {
let Some((mut h, frame)) = setup() else { return };
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index 7887bf26..fdc45c70 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -15,6 +15,8 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"]
egui = { workspace = true }
craft-ui = { workspace = true }
craft-window = { workspace = true }
+craft-keymap = { workspace = true }
+craft-quit = { workspace = true }
egui-phosphor = { version = "0.14", features = ["regular", "fill"] }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -22,7 +24,6 @@ rayon = { workspace = true }
log = { workspace = true }
base64 = "0.22"
image = { workspace = true }
-rfd = { workspace = true }
zip = { workspace = true }
# The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`).
@@ -30,6 +31,10 @@ zip = { workspace = true }
sys-locale = "0.3"
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
+# Help > Check for Updates and the check at start (updates_ui.rs).
+craft-update = { workspace = true }
+# Native file dialogs (file_dialogs.rs); the browser build has none.
+craft-dialogs = { workspace = true }
# build.rs: the interface faces lose their Private Use Area, where the icon font draws (the
# versions craft-libs' craft-fonts-build subsets with).
@@ -39,6 +44,7 @@ skrifa = { version = "0.48", default-features = false, features = ["std"] }
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
[target.'cfg(target_arch = "wasm32")'.dependencies]
+rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs
new file mode 100644
index 00000000..f585d326
--- /dev/null
+++ b/crates/ui-egui/src/bake_job.rs
@@ -0,0 +1,8 @@
+use crate::RunningBake;
+
+/// A background bake of one or more texture sets.
+pub struct BakeJob {
+ pub queue: Vec,
+ pub current: Option,
+ pub total: usize,
+}
diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs
new file mode 100644
index 00000000..42da4393
--- /dev/null
+++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs
@@ -0,0 +1,61 @@
+use egui::collapsing_header::CollapsingState;
+use egui::{Rect, Ui, vec2};
+use egui_phosphor::regular as icon;
+
+use crate::TextureCraftApp;
+use crate::i18n::tr;
+use crate::theme::Tokens;
+use crate::widgets::{icon_button_without_tooltip, section_chevron};
+
+/// The panel's width and its gap from the 3D view's top-left corner
+const PANEL_WIDTH: f32 = 280.0;
+const PANEL_MARGIN: f32 = 12.0;
+
+/// Size of the panel's eye buttons
+const EYE_BUTTON_SIZE: f32 = 22.0;
+
+/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view`
+pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) {
+ let toggles = &mut app.ui.bake_visualization;
+ egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show(
+ ui.ctx(),
+ |ui| {
+ ui.set_width(PANEL_WIDTH);
+ let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true);
+ let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open()));
+ if header.clicked() {
+ collapsing_state.toggle(ui);
+ }
+
+ collapsing_state.show_body_unindented(ui, |ui| {
+ ui.add_enabled_ui(toggles.on, |ui| {
+ ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
+ eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None);
+ eye_row(ui, &mut toggles.cage, tr("Cage"), None);
+ eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None);
+ eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None);
+ });
+ });
+ },
+ );
+}
+
+/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response
+fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response {
+ let tokens = Tokens::get(ui.ctx());
+ ui.horizontal(|ui| {
+ ui.set_min_height(EYE_BUTTON_SIZE);
+ let text = match open {
+ Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())),
+ None => egui::RichText::new(label),
+ };
+ let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click()));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() {
+ *shown = !*shown;
+ }
+ });
+ response
+ })
+ .inner
+}
diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs
new file mode 100644
index 00000000..0603c523
--- /dev/null
+++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs
@@ -0,0 +1,34 @@
+use serde::{Deserialize, Serialize};
+use texturecraft_render::BakeVisualization;
+
+/// The Baking Visualization panel's switches in bake mode's 3D view
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct BakeVisualizationToggles {
+ /// The panel's eye: the whole visualization on or off
+ pub on: bool,
+ pub selected_set_only: bool,
+ pub high_poly: bool,
+ pub cage: bool,
+ pub uv_seams: bool,
+ pub low_poly: bool,
+}
+
+impl Default for BakeVisualizationToggles {
+ fn default() -> Self {
+ Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true }
+ }
+}
+
+impl BakeVisualizationToggles {
+ /// What the renderer draws with these switches while texture set `selected_set` is selected
+ pub fn visualization(&self, selected_set: usize) -> Option {
+ self.on.then_some(BakeVisualization {
+ high_poly: self.high_poly,
+ cage: self.cage,
+ uv_seams: self.uv_seams,
+ low_poly: self.low_poly,
+ only_set: self.selected_set_only.then_some(selected_set),
+ })
+ }
+}
diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs
index 3a308a4a..9013be73 100644
--- a/crates/ui-egui/src/bake_mode/mod.rs
+++ b/crates/ui-egui/src/bake_mode/mod.rs
@@ -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 = app
.session
diff --git a/crates/ui-egui/src/bake_scene.rs b/crates/ui-egui/src/bake_scene.rs
new file mode 100644
index 00000000..1a30780e
--- /dev/null
+++ b/crates/ui-egui/src/bake_scene.rs
@@ -0,0 +1,11 @@
+//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session
+
+mod bake_scene_link;
+mod cage_link;
+mod cage_shell_key;
+mod cage_upload;
+mod reach_link;
+mod shared_handle;
+
+pub use bake_scene_link::BakeSceneLink;
+pub use cage_upload::CageUpload;
diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs
new file mode 100644
index 00000000..b9cecaa9
--- /dev/null
+++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs
@@ -0,0 +1,239 @@
+use std::sync::Arc;
+
+use texturecraft_engine::Session;
+use texturecraft_engine::geom::Mesh;
+use texturecraft_render::BakeVisualization;
+
+use super::CageUpload;
+use super::cage_link::CageLink;
+use super::cage_shell_key::CageShellKey;
+use super::reach_link::ReachLink;
+use super::shared_handle::SharedHandle;
+use crate::gpu::SceneSync;
+
+/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams
+#[derive(Default)]
+pub struct BakeSceneLink {
+ /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one)
+ high: SharedHandle,
+ high_id: u64,
+ /// Whether the GPU has the high poly (a lost frame sends it again under the same id)
+ high_sent: bool,
+ cages: Vec>,
+ /// How many texture sets' cages the GPU was last told to keep
+ sent_cage_count: Option,
+ /// The low-poly mesh whose seams are uploaded
+ seams_mesh_id: Option,
+ next_topology: u64,
+ reach: ReachLink,
+}
+
+impl BakeSceneLink {
+ /// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay
+ pub fn resend(&mut self) {
+ self.high_sent = false;
+ self.sent_cage_count = None;
+ self.seams_mesh_id = None;
+ for link in self.cages.iter_mut().flatten() {
+ link.max_frontal = f32::NAN;
+ }
+ self.reach.resend();
+ }
+
+ /// Whether something is still being worked out off the UI thread
+ pub fn busy(&self) -> bool {
+ self.reach.busy()
+ }
+
+ /// Add to `out` what the GPU needs to draw `visualization` this frame
+ pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) {
+ self.reach.poll();
+
+ let Some(visualization) = visualization else { return };
+
+ if visualization.high_poly {
+ let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone());
+ let handle = SharedHandle::of(high.as_ref());
+ if handle != self.high {
+ self.high = handle;
+ self.high_id += 1;
+ self.high_sent = false;
+ }
+ if !self.high_sent {
+ out.bake_high = Some((high, self.high_id));
+ self.high_sent = true;
+ }
+ self.reach.sync(session, self.high_id, visualization.only_set, out);
+ }
+
+ if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) {
+ self.seams_mesh_id = Some(session.mesh_id);
+ out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges()));
+ }
+
+ if visualization.cage {
+ self.sync_cages(session, out);
+ }
+ }
+
+ /// Rebuild the cages whose inputs changed and move the corners of those whose distance changed
+ fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) {
+ let set_count = session.doc.project.texture_sets.len();
+ if self.sent_cage_count != Some(set_count) {
+ out.bake_cage_count = Some(set_count);
+ self.sent_cage_count = Some(set_count);
+ }
+ self.cages.truncate(set_count);
+ self.cages.resize_with(set_count, || None);
+
+ for (texture_set, link) in self.cages.iter_mut().enumerate() {
+ let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue };
+
+ let max_frontal = set.bake.cage.max_frontal;
+ match link {
+ Some(link) if link.key == key => {
+ if link.max_frontal == max_frontal {
+ continue;
+ }
+ link.max_frontal = max_frontal;
+ }
+ _ => {
+ self.next_topology += 1;
+ let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new);
+ *link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal });
+ }
+ }
+
+ let Some(link) = link.as_ref() else { continue };
+
+ let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() });
+ out.bake_cages.push((texture_set, upload, link.topology));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None };
+
+ /// How long a test waits for the reach worker: frames, and the pause between them
+ const WAIT_FRAMES: usize = 2000;
+ const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5);
+
+ /// The sample project with a high poly a little outside its low poly
+ fn session() -> Session {
+ const HIGH_POLY_OFFSET: f32 = 0.02;
+
+ let mut session = texturecraft_engine::sample_session(128, 128).unwrap();
+ let low = session.mesh.clone();
+ let mut obj = String::new();
+ for (position, normal) in low.positions.iter().zip(&low.normals) {
+ let raised = *position + *normal * HIGH_POLY_OFFSET;
+ obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z);
+ }
+ for corners in low.indices.chunks(3) {
+ obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1);
+ }
+ session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap();
+ session
+ }
+
+ fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync {
+ let mut out = SceneSync::default();
+ link.sync(session, Some(visualization), &mut out);
+ out
+ }
+
+ /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red
+ fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 {
+ for _ in 0..WAIT_FRAMES {
+ if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed {
+ return missed.iter().sum::() / missed.len().max(1) as f32;
+ }
+ std::thread::sleep(WAIT_FRAME_PAUSE);
+ }
+ panic!("the reach never arrived");
+ }
+
+ fn set_distances(session: &mut Session, max_frontal: f32) {
+ texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap();
+ }
+
+ #[test]
+ fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() {
+ let (mut session, mut link) = (session(), BakeSceneLink::default());
+ let first = sync(&mut link, &session, EVERYTHING);
+ assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len()));
+ let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
+
+ let unchanged = sync(&mut link, &session, EVERYTHING);
+ assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent");
+
+ set_distances(&mut session, 0.03);
+ let moved = sync(&mut link, &session, EVERYTHING);
+ let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
+ assert_eq!(moved_topology, topology, "a distance only moves the corners");
+ assert_ne!(moved_cage.corners, cage.corners);
+
+ texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap();
+ let rebuilt = sync(&mut link, &session, EVERYTHING);
+ assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage");
+ // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts
+ red_share(&mut link, &session, EVERYTHING);
+
+ link.resend();
+ let resent = sync(&mut link, &session, EVERYTHING);
+ assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again");
+ assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len());
+ assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame");
+ assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id");
+ assert!(!link.busy(), "a lost frame doesn't work out the reach again");
+ }
+
+ #[test]
+ fn a_reach_finishes_while_nothing_is_drawn() {
+ let session = session();
+ let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING };
+ for hidden in [None, Some(no_high_poly)] {
+ let mut link = BakeSceneLink::default();
+ sync(&mut link, &session, EVERYTHING);
+ assert!(link.busy(), "the first frame starts working out the reach");
+
+ let finished = (0..WAIT_FRAMES).any(|_| {
+ std::thread::sleep(WAIT_FRAME_PAUSE);
+ link.sync(&session, hidden, &mut SceneSync::default());
+ !link.busy()
+ });
+ assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}");
+ }
+ }
+
+ #[test]
+ fn the_red_follows_the_distances_and_the_selected_set() {
+ let (mut session, mut link) = (session(), BakeSceneLink::default());
+ set_distances(&mut session, 0.0);
+ let at_zero = red_share(&mut link, &session, EVERYTHING);
+ assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}");
+
+ set_distances(&mut session, 0.05);
+ let covered = red_share(&mut link, &session, EVERYTHING);
+ assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}");
+
+ set_distances(&mut session, 0.0);
+ let by_name = |session: &mut Session, low_suffix: &str| {
+ for set in &mut session.doc.project.texture_sets {
+ set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName;
+ set.bake.high_poly.low_suffix = low_suffix.into();
+ }
+ };
+ by_name(&mut session, "_no_such_suffix");
+ let by_name_red = red_share(&mut link, &session, EVERYTHING);
+ assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}");
+
+ let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING };
+ assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing");
+ }
+}
diff --git a/crates/ui-egui/src/bake_scene/cage_link.rs b/crates/ui-egui/src/bake_scene/cage_link.rs
new file mode 100644
index 00000000..855d9619
--- /dev/null
+++ b/crates/ui-egui/src/bake_scene/cage_link.rs
@@ -0,0 +1,16 @@
+use std::sync::Arc;
+
+use texturecraft_engine::bake::CageShell;
+
+use super::cage_shell_key::CageShellKey;
+
+/// A texture set's cage as the GPU has it
+pub(super) struct CageLink {
+ pub(super) key: CageShellKey,
+ /// `None`: the set bakes without a high poly or its cage can't be built
+ pub(super) shell: Option>,
+ /// The renderer's name for the shell's corner order and edges
+ pub(super) topology: u64,
+ /// The max frontal distance the GPU's corners are at
+ pub(super) max_frontal: f32,
+}
diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs
new file mode 100644
index 00000000..44e17eca
--- /dev/null
+++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs
@@ -0,0 +1,47 @@
+use std::collections::BTreeMap;
+
+use texturecraft_engine::Session;
+use texturecraft_engine::bake::BakePaintMap;
+use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings};
+use texturecraft_engine::geom::Mesh;
+
+use super::shared_handle::SharedHandle;
+
+/// Everything a texture set's cage shell is built from except the distances, which only move its corners
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct CageShellKey {
+ mesh_id: u64,
+ high: SharedHandle,
+ cage_file: SharedHandle,
+ material: usize,
+ uv_tiles: Vec,
+ tile_resolutions: BTreeMap,
+ cage_kind: CageType,
+ relative_to_bounding_box: bool,
+ average_normals: bool,
+ use_low_as_high: bool,
+ skew: SkewSettings,
+ /// The painted skew and cage maps
+ paint: [SharedHandle; 2],
+}
+
+impl CageShellKey {
+ pub(super) fn of(session: &Session, texture_set: usize) -> Option {
+ let set = session.doc.project.texture_sets.get(texture_set)?;
+ let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target)));
+ Some(CageShellKey {
+ mesh_id: session.mesh_id,
+ high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)),
+ cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)),
+ material: set.material,
+ uv_tiles: set.uv_tiles.clone(),
+ tile_resolutions: set.tile_resolutions.clone(),
+ cage_kind: set.bake.cage.kind,
+ relative_to_bounding_box: set.bake.cage.relative_to_bounding_box,
+ average_normals: set.bake.cage.average_normals,
+ use_low_as_high: set.bake.high_poly.use_low_as_high,
+ skew: set.bake.skew,
+ paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)],
+ })
+ }
+}
diff --git a/crates/ui-egui/src/bake_scene/cage_upload.rs b/crates/ui-egui/src/bake_scene/cage_upload.rs
new file mode 100644
index 00000000..81951645
--- /dev/null
+++ b/crates/ui-egui/src/bake_scene/cage_upload.rs
@@ -0,0 +1,10 @@
+use std::sync::Arc;
+
+use texturecraft_engine::bake::CageShell;
+use texturecraft_engine::geom::glam::Vec3;
+
+/// A texture set's cage for the GPU: its corners at the current distance and the shell they come from
+pub struct CageUpload {
+ pub corners: Vec,
+ pub shell: Arc,
+}
diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs
new file mode 100644
index 00000000..c8a181f5
--- /dev/null
+++ b/crates/ui-egui/src/bake_scene/reach_link.rs
@@ -0,0 +1,140 @@
+use std::sync::mpsc::{Receiver, TryRecvError};
+
+use texturecraft_engine::Session;
+use texturecraft_engine::bake::{HighPolyReach, high_poly_missed};
+use texturecraft_engine::core::HighPolySettings;
+
+use super::cage_shell_key::CageShellKey;
+use crate::gpu::SceneSync;
+
+/// Each set's (max frontal, max rear) and the selected-set filter
+type ShownDistances = (Vec<(f32, f32)>, Option);
+
+/// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show
+#[derive(Default)]
+pub(super) struct ReachLink {
+ /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for
+ keys: Vec>,
+ high_id: u64,
+ job: Option>>>,
+ reach: Vec>,
+ /// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for
+ shown: Option,
+}
+
+impl ReachLink {
+ /// Whether a reach is being worked out (the view must keep drawing to pick it up)
+ pub(super) fn busy(&self) -> bool {
+ self.job.is_some()
+ }
+
+ /// Send the colors again (the GPU lost what it was sent); the reach itself stays
+ pub(super) fn resend(&mut self) {
+ self.shown = None;
+ }
+
+ /// Pick up the reach once the worker finishes; runs every frame, even when nothing is drawn, so `busy` clears
+ pub(super) fn poll(&mut self) {
+ let Some(job) = &self.job else { return };
+
+ match job.try_recv() {
+ Ok(reach) => {
+ self.reach = reach;
+ self.shown = None;
+ self.job = None;
+ }
+ Err(TryRecvError::Disconnected) => self.job = None,
+ Err(TryRecvError::Empty) => {}
+ }
+ }
+
+ /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed
+ pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) {
+ // Coalesce paint edits while a worker runs; after polling it, the next job captures the latest inputs
+ if self.job.is_some() {
+ return;
+ }
+
+ let set_count = session.doc.project.texture_sets.len();
+ let keys: Vec> = session
+ .doc
+ .project
+ .texture_sets
+ .iter()
+ .enumerate()
+ .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone())))
+ .collect();
+ if keys != self.keys || high_id != self.high_id {
+ let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect();
+ self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || {
+ inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect()
+ }));
+ (self.keys, self.high_id) = (keys, high_id);
+ }
+
+ // Colors wait for the reach being worked out: the old ones stay until it arrives
+ if self.job.is_some() {
+ return;
+ }
+
+ let distances: Vec<(f32, f32)> = session.doc.project.texture_sets.iter().map(|set| (set.bake.cage.max_frontal, set.bake.cage.max_rear)).collect();
+ let shown = (distances, only_set);
+ if self.shown.as_ref() == Some(&shown) {
+ return;
+ }
+
+ let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return };
+
+ out.bake_high_missed = Some((self.high_id, high_poly_missed(&self.reach, &shown.0, only_set, vertex_count)));
+ self.shown = Some(shown);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::{Arc, mpsc};
+ use std::time::Duration;
+ use texturecraft_engine::bake::BakePaintMap;
+ use texturecraft_engine::core::BakePaintTarget;
+ use texturecraft_engine::geom::primitives;
+
+ #[test]
+ fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() {
+ let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap();
+ session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap();
+ let (sender, receiver) = mpsc::channel();
+ let mut link = ReachLink { job: Some(receiver), ..Default::default() };
+
+ // Hold the original job open while paint and mesh inputs change
+ for amount in [0.25, 0.5, 0.75] {
+ session.doc.bake_paint.insert((0, BakePaintTarget::Cage), Arc::new(BakePaintMap::constant(amount)));
+ let mut out = SceneSync::default();
+ link.sync(&session, 2, None, &mut out);
+ assert!(out.bake_high_missed.is_none());
+ }
+ assert!(sender.send(Vec::new()).is_ok(), "input changes must keep the running job's receiver");
+ link.poll();
+
+ // The finished job is stale: a new job must capture the latest settings before sending colors
+ session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true;
+ let mut out = SceneSync::default();
+ link.sync(&session, 2, None, &mut out);
+ assert!(link.busy());
+ assert!(out.bake_high_missed.is_none());
+
+ for _ in 0..2000 {
+ link.poll();
+ if !link.busy() {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert!(!link.busy(), "the latest reach must finish");
+ link.sync(&session, 2, None, &mut out);
+ let (high_id, missed) = out.bake_high_missed.unwrap();
+ assert_eq!(high_id, 2);
+ assert_eq!(missed, vec![0.0; session.bake_meshes.merged_high().unwrap().mesh.positions.len()]);
+ assert!(link.reach[0].is_none(), "the latest setting bakes without a high poly");
+ }
+}
diff --git a/crates/ui-egui/src/bake_scene/shared_handle.rs b/crates/ui-egui/src/bake_scene/shared_handle.rs
new file mode 100644
index 00000000..15ceb1d8
--- /dev/null
+++ b/crates/ui-egui/src/bake_scene/shared_handle.rs
@@ -0,0 +1,32 @@
+use std::sync::{Arc, Weak};
+
+/// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it
+#[derive(Debug)]
+pub(super) struct SharedHandle(Option