Merge upstream main into fix/725-background-project-save

This commit is contained in:
vangel76 committed 2026-11-23 20:40:07 +01:00
commit e981f7e822
470 files changed
+55018 -6232

No files matched your search

+2 -1
View File
@@ -27,7 +27,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
nightly: ${{ github.event_name == 'schedule' }}
app-name: texturecraft
app-title: "TextureCraft"
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
@@ -49,3 +49,4 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+12
View File
@@ -23,6 +23,7 @@ licensed and keep their license file next to them.
| `docs/images/texturecraft-light.png` | README screenshot: the light brightness level with the blue accent | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
| `docs/images/texturecraft-lantern.png` | README render: a storm lantern (original procedural mesh of lathes and swept wires, eight texture sets) in chipped red enamel, rust, soot, tarnished brass and glass with an emissive flame (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 |
| `docs/images/texturecraft-camera.png` | README render: a rangefinder camera (original procedural mesh) in black enamel worn to brass, leatherette, chrome and coated glass; the lens distance scale is an original image drawn in code (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 |
| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) |
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
| `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) |
@@ -40,6 +41,17 @@ These come from Rust crate dependencies (not files in this repository) and keep
Without craft-fonts, Chinese, Japanese, Korean and Arabic UI text uses the operating system's fonts at run
time (nothing is bundled); see [docs/localization-parity.md](docs/localization-parity.md).
## Native eyedropper dependencies
| Crate | Use | Upstream | License |
|---|---|---|---|
| `raw-window-handle` | Identify native application windows | https://github.com/rust-windowing/raw-window-handle | MIT OR Apache-2.0 OR Zlib |
| `winsafe` | Windows pointer and event handling | https://github.com/rodrigocfd/winsafe | MIT |
| `xcap` | Windows screen pixel capture | https://github.com/nashaofu/xcap | Apache-2.0 |
| `widestring` | Windows string handling through `xcap` | https://github.com/VoidStarKat/widestring-rs | MIT OR Apache-2.0 |
| `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 |
| `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT |
## Procedural content (no asset files)
Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedurals
Generated
+646 -9
View File
@@ -80,7 +80,7 @@ dependencies = [
"futures-lite",
"futures-util",
"serde",
"zbus",
"zbus 5.19.0",
]
[[package]]
@@ -132,6 +132,15 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
@@ -193,6 +202,22 @@ dependencies = [
"libc",
]
[[package]]
name = "annotate-snippets"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4"
dependencies = [
"anstyle",
"unicode-width",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "arboard"
version = "3.6.1"
@@ -235,6 +260,22 @@ dependencies = [
"libloading",
]
[[package]]
name = "ashpd"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc"
dependencies = [
"bitflags 2.13.2",
"futures-channel",
"futures-util",
"getrandom 0.4.3",
"pipewire",
"serde",
"serde_repr",
"zbus 6.3.0",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -391,7 +432,7 @@ dependencies = [
"enumflags2",
"serde",
"static_assertions",
"zbus",
"zbus 5.19.0",
"zbus-lockstep",
"zbus-lockstep-macros",
"zbus_names",
@@ -406,7 +447,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc"
dependencies = [
"atspi-common",
"serde",
"zbus",
"zbus 5.19.0",
]
[[package]]
@@ -433,6 +474,25 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bindgen"
version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"annotate-snippets",
"bitflags 2.13.2",
"cexpr",
"clang-sys",
"itertools 0.13.0",
"proc-macro2",
"quote",
"regex",
"rustc-hash 2.1.3",
"shlex 1.3.0",
"syn 2.0.119",
]
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -628,7 +688,26 @@ dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
"shlex 2.0.1",
]
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom 7.1.3",
]
[[package]]
name = "cfg-expr"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff"
dependencies = [
"smallvec",
"target-lexicon",
]
[[package]]
@@ -652,6 +731,17 @@ dependencies = [
"libc",
]
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core",
]
[[package]]
name = "chrono"
version = "0.4.45"
@@ -666,6 +756,17 @@ dependencies = [
"windows-link",
]
[[package]]
name = "clang-sys"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -738,6 +839,12 @@ dependencies = [
"rustversion",
]
[[package]]
name = "cookie-factory"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2"
[[package]]
name = "core-foundation"
version = "0.9.4"
@@ -803,6 +910,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
@@ -1307,6 +1423,61 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
[[package]]
name = "drm"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"drm-ffi",
"drm-fourcc",
"libc",
"rustix 0.38.44",
]
[[package]]
name = "drm"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"bytemuck_derive",
"drm-ffi",
"drm-fourcc",
"libc",
"rustix 1.1.5",
]
[[package]]
name = "drm-ffi"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690"
dependencies = [
"drm-sys",
"rustix 1.1.5",
]
[[package]]
name = "drm-fourcc"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4"
[[package]]
name = "drm-sys"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8"
dependencies = [
"libc",
"linux-raw-sys 0.9.4",
]
[[package]]
name = "dunce"
version = "1.0.5"
@@ -1376,7 +1547,7 @@ dependencies = [
"bitflags 2.13.2",
"emath",
"epaint",
"itertools",
"itertools 0.15.0",
"log",
"nohash-hasher",
"profiling",
@@ -1753,6 +1924,15 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "fs-set-times"
version = "0.20.3"
@@ -1865,6 +2045,30 @@ dependencies = [
"slab",
]
[[package]]
name = "gbm"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a"
dependencies = [
"bitflags 2.13.2",
"drm 0.14.1",
"drm-fourcc",
"gbm-sys",
"libc",
"wayland-backend",
"wayland-server",
]
[[package]]
name = "gbm-sys"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f"
dependencies = [
"libc",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -1918,6 +2122,7 @@ dependencies = [
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core",
"wasm-bindgen",
]
@@ -1931,6 +2136,15 @@ dependencies = [
"weezl",
]
[[package]]
name = "gl"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404"
dependencies = [
"gl_generator",
]
[[package]]
name = "gl_generator"
version = "0.14.0"
@@ -1974,6 +2188,12 @@ dependencies = [
"vello_common",
]
[[package]]
name = "glob"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]]
name = "glow"
version = "0.17.0"
@@ -2176,6 +2396,12 @@ dependencies = [
"fearless_simd",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.3"
@@ -2411,6 +2637,27 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "image"
version = "0.25.10"
@@ -2488,6 +2735,15 @@ version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.15.0"
@@ -2683,6 +2939,54 @@ dependencies = [
"redox_syscall 0.9.4",
]
[[package]]
name = "libspa"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40"
dependencies = [
"bitflags 2.13.2",
"cc",
"cookie-factory",
"libc",
"libspa-sys",
"nom 8.0.0",
"rustix 1.1.5",
"system-deps",
]
[[package]]
name = "libspa-sys"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"
dependencies = [
"bindgen",
"cc",
"system-deps",
]
[[package]]
name = "libwayshot-xcap"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5"
dependencies = [
"drm 0.15.0",
"gbm",
"gl",
"image",
"khronos-egl",
"memmap2",
"rustix 1.1.5",
"thiserror 2.0.21",
"tracing",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-protocols-wlr",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
@@ -2695,6 +2999,12 @@ version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]]
name = "linux-raw-sys"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -2786,6 +3096,12 @@ dependencies = [
"glam 0.15.2",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -2943,6 +3259,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "nom"
version = "8.0.0"
@@ -3064,6 +3390,18 @@ dependencies = [
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-av-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0"
dependencies = [
"objc2 0.6.5",
"objc2-core-graphics",
"objc2-core-media",
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.2.2"
@@ -3088,6 +3426,28 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-core-audio"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"
dependencies = [
"dispatch2",
"objc2 0.6.5",
"objc2-core-audio-types",
"objc2-core-foundation",
]
[[package]]
name = "objc2-core-audio-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"
dependencies = [
"bitflags 2.13.2",
"objc2 0.6.5",
]
[[package]]
name = "objc2-core-data"
version = "0.2.2"
@@ -3119,6 +3479,7 @@ checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
dependencies = [
"bitflags 2.13.2",
"dispatch2",
"libc",
"objc2 0.6.5",
"objc2-core-foundation",
"objc2-io-surface",
@@ -3148,6 +3509,34 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-core-media"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d"
dependencies = [
"bitflags 2.13.2",
"dispatch2",
"objc2 0.6.5",
"objc2-core-audio",
"objc2-core-audio-types",
"objc2-core-foundation",
"objc2-core-video",
]
[[package]]
name = "objc2-core-video"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"
dependencies = [
"bitflags 2.13.2",
"objc2 0.6.5",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-io-surface",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
@@ -3532,6 +3921,31 @@ dependencies = [
"futures-io",
]
[[package]]
name = "pipewire"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c"
dependencies = [
"bitflags 2.13.2",
"libc",
"libspa",
"libspa-sys",
"pipewire-sys",
"rustix 1.1.5",
]
[[package]]
name = "pipewire-sys"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"
dependencies = [
"bindgen",
"libspa-sys",
"system-deps",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
@@ -3777,6 +4191,23 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
dependencies = [
"chacha20",
"getrandom 0.4.3",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "range-alloc"
version = "0.1.5"
@@ -3907,6 +4338,35 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "regex"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "renderdoc-sys"
version = "1.1.0"
@@ -4323,10 +4783,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "shlex"
version = "2.0.1"
@@ -4563,6 +5029,19 @@ dependencies = [
"windows",
]
[[package]]
name = "system-deps"
version = "7.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"
dependencies = [
"cfg-expr",
"heck",
"pkg-config",
"toml",
"version-compare",
]
[[package]]
name = "tar"
version = "0.4.46"
@@ -4573,6 +5052,12 @@ dependencies = [
"libc",
]
[[package]]
name = "target-lexicon"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -4604,6 +5089,7 @@ dependencies = [
"craft-update",
"eframe",
"egui",
"egui_kittest",
"image",
"log",
"rfd",
@@ -4729,7 +5215,6 @@ dependencies = [
"gltf",
"half",
"image",
"lz4_flex",
"png",
"quick-xml 0.41.0",
"rayon",
@@ -4816,6 +5301,7 @@ dependencies = [
"js-sys",
"log",
"pollster 0.4.0",
"raw-window-handle",
"rayon",
"rfd",
"serde",
@@ -4828,6 +5314,10 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"winsafe",
"x11rb",
"xcap",
"zbus 5.19.0",
"zip",
]
@@ -5082,7 +5572,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
dependencies = [
"memchr",
"nom",
"nom 8.0.0",
"petgraph",
]
@@ -5195,6 +5685,18 @@ dependencies = [
"log",
]
[[package]]
name = "url"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "urlencoding"
version = "2.1.3"
@@ -5280,6 +5782,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "version-compare"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -5464,6 +5972,19 @@ dependencies = [
"quote",
]
[[package]]
name = "wayland-server"
version = "0.31.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75"
dependencies = [
"bitflags 2.13.2",
"downcast-rs",
"rustix 1.1.5",
"wayland-backend",
"wayland-scanner",
]
[[package]]
name = "wayland-sys"
version = "0.31.11"
@@ -5471,7 +5992,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
dependencies = [
"dlib",
"libc",
"log",
"memoffset",
"once_cell",
"pkg-config",
]
@@ -5694,6 +6217,12 @@ dependencies = [
"web-sys",
]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]]
name = "winapi"
version = "0.3.9"
@@ -6188,6 +6717,49 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "xcap"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e833d39f662982a09608f2550fd4036725f98d78738e40fa7206a26258b06384"
dependencies = [
"ashpd",
"dispatch2",
"image",
"libwayshot-xcap",
"log",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-av-foundation",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-media",
"objc2-core-video",
"objc2-foundation 0.3.2",
"percent-encoding",
"pipewire",
"pollster 1.0.1",
"rand",
"scopeguard",
"serde",
"thiserror 2.0.21",
"url",
"widestring",
"windows",
"xcb",
]
[[package]]
name = "xcb"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"
dependencies = [
"bitflags 2.13.2",
"libc",
"quick-xml 0.41.0",
]
[[package]]
name = "xcursor"
version = "0.3.11"
@@ -6279,11 +6851,38 @@ dependencies = [
"uuid",
"windows-sys 0.61.2",
"winnow",
"zbus_macros",
"zbus_macros 5.19.0",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4"
dependencies = [
"async-trait",
"bitflags 2.13.2",
"endi",
"futures-core",
"hex",
"libc",
"ordered-stream",
"rustix 1.1.5",
"serde",
"serde_repr",
"socket2",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow",
"zbus_macros 6.3.0",
"zbus_utils",
"zcheapstr",
"zruntime",
]
[[package]]
name = "zbus-lockstep"
version = "0.5.2"
@@ -6323,6 +6922,18 @@ dependencies = [
"zvariant_utils",
]
[[package]]
name = "zbus_macros"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"zbus_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.4"
@@ -6334,6 +6945,19 @@ dependencies = [
"zvariant",
]
[[package]]
name = "zbus_utils"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.9",
"winnow",
]
[[package]]
name = "zbus_xml"
version = "5.2.1"
@@ -6497,6 +7121,19 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "zruntime"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72"
dependencies = [
"futures-core",
"futures-io",
"rustix 1.1.5",
"socket2",
"windows-sys 0.61.2",
]
[[package]]
name = "zune-core"
version = "0.5.3"
-4
View File
@@ -8,8 +8,6 @@ default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose
version = "0.6.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/texturecraft"
[workspace.dependencies]
craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
@@ -53,10 +51,8 @@ rfd = "0.17"
zip = { version = "9", default-features = false, features = ["deflate"] }
gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] }
flate2 = "1"
lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] }
quick-xml = "0.41"
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
proptest = "1"
rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
schemars = "1"
+12
View File
@@ -12,6 +12,18 @@ Third-party material
This product bundles third-party material under its own licenses, listed below. The per-file
list (author, source, license) is in ATTRIBUTION.md.
Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr),
by Sergej Majboroda (Poly Haven) — CC0-1.0.
Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256).
Native eyedropper components:
- raw-window-handle — MIT OR Apache-2.0 OR Zlib. Copyright (c) 2019, 2020 Osspial.
- winsafe — MIT. Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias.
- xcap — Apache-2.0.
- widestring (through xcap on Windows) — MIT OR Apache-2.0.
- x11rb — MIT OR Apache-2.0. Copyright 2019 x11rb contributors.
- zbus — MIT. Copyright (c) 2024 Zeeshan Ali Khan and zbus contributors.
Phosphor Icons (compiled in through the egui-phosphor crate) — MIT.
egui default fonts (compiled in through the epaint_default_fonts crate): Ubuntu-Light — Ubuntu
Font Licence 1.0; Hack — MIT and Bitstream Vera License; Noto Emoji — SIL Open Font License 1.1;
-11
View File
@@ -16,17 +16,6 @@ fn cli_binary_path(runner_path: Option<OsString>) -> OsString {
runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into())
}
#[test]
fn cli_binary_prefers_relocated_runner_path() {
let relocated = OsString::from("relocated archive/texturecraft-cli");
assert_eq!(cli_binary_path(Some(relocated.clone())), relocated);
}
#[test]
fn cli_binary_defaults_to_cargo_path() {
assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli")));
}
fn cli(args: &[&str]) -> Output {
Command::new(cli_binary()).args(args).output().unwrap()
}
+1 -2
View File
@@ -13,12 +13,11 @@ workspace = true
name = "texturecraft-web"
path = "src/main.rs"
[dependencies]
[target.'cfg(target_arch = "wasm32")'.dependencies]
texturecraft-engine = { workspace = true }
texturecraft-ui-egui = { workspace = true }
log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }
wasm-bindgen = "0.2"
+1 -1
View File
@@ -1,6 +1,6 @@
//! TextureCraft in the browser.
//!
//! Runs the same [`texturecraft_ui_egui::TextureCraftApp`] as the desktop app through eframe's web
//! Runs the same `TextureCraftApp` as the desktop app through eframe's web
//! runner (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release`
//! from this directory (`packaging/web/package.sh` zips the result).
//!
+4
View File
@@ -38,5 +38,9 @@ craft-update = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
craft-menu = { workspace = true }
[dev-dependencies]
# The pointer-hold test drives the windowed app's frames (src/main.rs)
egui_kittest = { version = "0.37", features = ["eframe"] }
[build-dependencies]
winresource = "0.1"
+21 -26
View File
@@ -134,7 +134,7 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui
#[cfg(test)]
mod tests {
use std::io::BufRead;
use std::io::{BufRead, Read};
use super::*;
@@ -196,33 +196,28 @@ mod tests {
assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection");
}
fn assert_reply(reader: &mut BufReader<TcpStream>, expected: Value) -> std::io::Result<()> {
let expected = format!("{expected}\n");
let mut received = vec![0; expected.len()];
reader.read_exact(&mut received)?;
assert_eq!(received, expected.as_bytes(), "unexpected control server reply");
Ok(())
}
#[test]
fn connections_are_limited_and_idle_ones_time_out() {
fn authenticated_connections_hold_server_slots() -> std::io::Result<()> {
let addr = server();
let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect();
// Let the server take every idle connection before the one over the limit.
std::thread::sleep(Duration::from_millis(300));
// Read without writing: the server closes at once, and unread input would reset the
// connection before its reply arrives.
let (_, mut r) = connect(addr);
let mut full = String::new();
r.read_line(&mut full).unwrap();
assert_eq!(serde_json::from_str::<Value>(&full).unwrap()["error"], "too many connections");
// Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots.
for (_, mut r) in idle {
let mut rest = String::new();
assert_eq!(r.read_line(&mut rest).unwrap(), 0);
}
// A slot frees once its thread has ended, which can trail the client's EOF a little.
let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#);
let authed = (0..50).any(|_| {
let (mut w, mut r) = connect(addr);
let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true);
if !ok {
std::thread::sleep(Duration::from_millis(100));
}
ok
});
assert!(authed, "slots are freed after the auth deadline");
let mut held = Vec::with_capacity(MAX_CONNECTIONS);
for _ in 0..MAX_CONNECTIONS {
let (mut writer, mut reader) = connect(addr);
writeln!(writer, "{right}")?;
// The reply confirms that this connection is holding a slot.
assert_reply(&mut reader, json!({"ok": true, "id": 1}))?;
held.push((writer, reader));
}
let (_writer, mut reader) = connect(addr);
assert_reply(&mut reader, json!({"id": null, "ok": false, "error": "too many connections"}))
}
}
+63 -16
View File
@@ -164,12 +164,14 @@ impl eframe::App for Shell {
self.app.save(storage);
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw: &mut egui::RawInput) {
// winit gives the window its caption back when it changes the window's flags (maximize,
// restore, …): take it off again before the frame is laid out.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Restore the frameless style after winit changes the window flags
if let Some(guard) = self.window_frame.as_mut() {
guard();
}
// The app's own hook: a drag holding the pointer reads its moves from it
self.app.raw_input_hook(ctx, raw);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
@@ -194,6 +196,13 @@ fn main() {
if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
std::process::exit(i32::from(result.is_err()));
}
// Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument
#[cfg(windows)]
if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) {
std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer());
}
let args = match parse_args() {
Ok(Some(a)) => a,
Ok(None) => return,
@@ -321,19 +330,6 @@ 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 bundled_app_icon_decodes_to_rgba() {
let icon = icon().unwrap();
assert!(icon.width > 0 && icon.height > 0);
assert_eq!(icon.rgba.len(), (icon.width * icon.height * 4) as usize);
}
#[test]
fn rejects_missing_or_invalid_gpu_args() {
assert!(parse_args_from(["--gpu".to_string()]).is_err());
@@ -388,4 +384,55 @@ mod tests {
std::fs::remove_file(&ron_path).unwrap();
assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default());
}
/// How far the test's drag moves the mouse in one frame, in points
const DRAG_STEP: egui::Vec2 = egui::vec2(80.0, 0.0);
/// Points within which a put-back lands on the press point (the system rounds it to whole pixels)
const PUT_BACK_REACH: f32 = 1.0;
/// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window
fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec<egui::Event>) -> Vec<egui::ViewportCommand> {
let ctx = harness.ctx.clone();
let mut raw = harness.input_mut().clone();
raw.events.extend(events);
eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw);
*harness.input_mut() = raw;
harness.step();
harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default()
}
/// Holding the fill's preview square in the window holds the system's pointer: put back to the press point every frame, or locked where the system locks it
#[test]
fn the_window_holds_the_pointer_while_the_preview_square_is_held() {
let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1]));
let mut harness = builder.build_eframe(|cc| Shell {
app: TextureCraftApp::new(cc, session),
window_frame: None,
#[cfg(target_os = "macos")]
movable: None,
});
harness.run_steps(4);
let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone();
harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap();
harness.run_steps(2);
let pad = egui_kittest::kittest::Queryable::get_by_label(&harness, "Move on model").rect().center();
let press = egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
let pressed = window_frame(&mut harness, vec![egui::Event::PointerMoved(pad), press]);
let locked = pressed.contains(&egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked));
// A locked pointer stays still and the system reports only its raw motion
let mut moves = vec![egui::Event::MouseMoved(DRAG_STEP)];
if !locked {
moves.push(egui::Event::PointerMoved(pad + DRAG_STEP));
}
let moved = window_frame(&mut harness, moves);
let put_back = moved.iter().any(|command| matches!(command, egui::ViewportCommand::CursorPosition(to) if to.distance(pad) <= PUT_BACK_REACH));
assert!(locked || put_back, "the window puts the pointer back where the press began, so it never leaves: {moved:?}");
let seen = harness.ctx.input(|input| input.pointer.latest_pos());
assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}");
}
}
Binary file not shown.
+4 -9
View File
@@ -228,14 +228,6 @@ mod tests {
out
}
#[test]
fn the_unlit_switch_decides_whether_a_channel_view_is_lit() {
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
assert!(!shade(&s).solo_lit, "channel views are flat by default");
execute(&mut s, "display.set", &json!({"soloUnlit": false})).unwrap();
assert!(shade(&s).solo_lit);
}
#[test]
fn renders_with_an_imported_hdr_environment() {
let mesh = texturecraft_engine::geom::primitives::material_ball();
@@ -284,8 +276,10 @@ mod tests {
let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1);
mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1));
let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap();
assert_eq!(session.caches.len(), 2);
session.images.insert("red".into(), Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true }));
session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true)));
execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap();
let camera = session.camera;
let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 };
@@ -302,6 +296,7 @@ mod tests {
assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap();
assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
assert_eq!(gpu.h.renderer.aux_size(1), Some(128));
}
-12
View File
@@ -141,18 +141,6 @@ fn sample_for_project_bake(resolution: u32) -> Headless {
backend
}
#[test]
fn project_bake_uses_documented_ray_count() {
let backend = sample_for_project_bake(256);
for texture_set in 0..backend.session.set_count() {
let task = backend.session.bake_task(texture_set).unwrap();
assert_eq!(task.settings.maps.ao.parameters.rays.rays, 32);
assert_eq!(task.settings.maps.thickness.parameters.rays.rays, 32);
assert_eq!(task.settings.maps.bent_normal.parameters.rays.rays, 32);
}
}
/// The whole-project bake at benchmark settings (1024², 32 rays, AA 1), then 2048².
#[test]
#[ignore]
-18
View File
@@ -1056,24 +1056,6 @@ fn occlusion_falls_off_linearly_to_the_max_distance() {
assert!((ambient_occlusion - 0.5).abs() < 0.01, "{ambient_occlusion}");
}
#[test]
fn secondary_ray_defaults_preserve_per_map_distances() {
let parameters = BakeSettings::default();
let expected_rays = RaySettings {
rays: 64,
min_distance: 0.00001,
max_distance: 1.0,
relative_to_bounding_box: true,
spread: 180.0,
distribution: RayDistribution::Cosine,
};
assert_eq!(parameters.maps.ao.parameters.rays, expected_rays);
assert_eq!(parameters.maps.ao.parameters.attenuation, texturecraft_core::AmbientOcclusionAttenuation::Linear);
assert_eq!(parameters.maps.bent_normal.parameters.rays, expected_rays);
assert_eq!(parameters.maps.thickness.parameters.rays, RaySettings { max_distance: 0.1, ..expected_rays });
}
#[test]
fn bent_normals_and_thickness_have_their_own_rays() {
let m = floor_and_wall(false);
+162
View File
@@ -0,0 +1,162 @@
//! The frame an axis planar projection projects from: moving one on the model places it as that frame, so its images land where they did
use texturecraft_core::{Decal, Projection, Projector, Source};
use texturecraft_geom::glam::{EulerRot, Mat3, Vec3};
use crate::frame_placement::culling_folds;
use crate::pattern::{DEPTH_FADE_START, frame_uv_from_corner, mesh_frame, nonzero_stretch, projector_stretch};
/// Place an axis planar on a mesh within `bounds` while keeping its sampling and culling.
/// See [`culling_folds`] for when culling prevents placement.
pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<Projection> {
let Projection::Planar { scale, axis, offset, uv, projector, placed: None } = proj else { return None };
if !culling_folds(projector) {
return None;
}
let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?;
// The frame carries rotation and scale while the projected rectangle keeps axis coverage
let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ignore_image_alpha: true, ..*projector };
// An axis planar turns its image round the top left, a frame round its centre
let uv = frame_uv_from_corner(uv);
Some(Projection::Planar { scale: *scale, axis: *axis, offset: *offset, uv, projector, placed: Some(frame) })
}
/// Whether placing an axis planar that reads `sources` would move a pattern: a procedural reads an axis planar's plane but a placed frame's uv, so such a planar keeps its axis
pub fn placing_moves_pattern<'a>(mut sources: impl Iterator<Item = &'a Source>) -> bool {
sources.any(|source| matches!(source, Source::Procedural { .. }))
}
/// The frame of an axis planar projection: its image's 0..1 square on the plane through the mesh, turned and sized by `projector`
pub fn axis_frame(scale: f32, axis: u8, offset: Vec3, projector: &Projector, bounds: (Vec3, Vec3)) -> Option<Decal> {
let (center, radius) = mesh_frame(bounds);
let [x, y, z] = projector.rotation.map(f32::to_radians);
let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x);
let stretch = projector_stretch(projector);
let scale = nonzero_stretch(scale);
// Where the image's centre sits, then its across, up and out directions with the stretch along each
let origin = center + turn * (stretch * -offset / scale) * radius;
let (across, up, out) = match axis {
0 => (Vec3::Z, Vec3::Y, Vec3::NEG_X),
1 => (Vec3::X, Vec3::NEG_Z, Vec3::Y),
_ => (Vec3::X, Vec3::Y, Vec3::Z),
};
let side = |direction: Vec3| 2.0 * radius * direction.abs().dot(stretch) / scale;
// A negative stretch or scale turns that side over
let flip = |direction: Vec3| direction * side(direction).signum();
let (across, up) = (flip(across), flip(up));
let size = [side(across).abs(), side(up).abs()];
let out = turn * across.cross(up).normalize_or(out);
// Deep enough never to crop the mesh by depth: the fade starts at three quarters of it
let reach = (radius + (origin - center).length()) / DEPTH_FADE_START * DEPTH_SPARE;
let frame = Decal {
center: origin.to_array(),
normal: out.to_array(),
up: (turn * up).to_array(),
size,
rotation: 0.0,
offset: [0.0; 2],
depth: reach,
symmetry: None,
flip: [false; 2],
};
(origin.is_finite() && size.iter().all(|side| side.is_finite() && *side > 0.0) && reach.is_finite()).then_some(frame)
}
/// Extra reach past the farthest mesh point
const DEPTH_SPARE: f32 = 1.01;
#[cfg(test)]
mod tests {
use texturecraft_core::{Backface, ShapeCrop, UvTransform};
use texturecraft_geom::glam::Vec2;
use super::*;
use crate::pattern::{Coords, image_samples};
use crate::projector_cover::{framed_cover, projector_cover};
/// Points spread through the box `lo`..`hi` with varied normals
fn points(lo: Vec3, hi: Vec3) -> Vec<(Vec3, Vec3)> {
(0..64)
.map(|i| {
let spread = |salt: u32| ((i * 37 + salt * 11) % 64) as f32 / 63.0;
let position = lo + (hi - lo) * Vec3::new(spread(1), spread(2), spread(3));
let normal = Vec3::new(spread(4) - 0.4, spread(5) - 0.3, spread(6) - 0.2).normalize_or(Vec3::Z);
(position, normal)
})
.collect()
}
#[test]
fn a_placed_axis_planar_reads_images_where_it_did() {
let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5));
let center = (lo + hi) * 0.5;
let radius = (hi - lo).length() * 0.5;
for axis in 0..3 {
for (rotation, stretch) in [([0.0; 3], [1.0; 3]), ([20.0, -35.0, 50.0], [1.5, 0.7, 2.0])] {
for crop in [ShapeCrop::ExtendsOutside, ShapeCrop::Cropped] {
let projector = Projector { rotation, scale: stretch, crop, ..Projector::default() };
let uv = UvTransform { tiling: [2.0, 3.0], rotation: 30.0, offset: [0.1, -0.2] };
let axis_planar = Projection::Planar { scale: 1.7, axis, offset: [0.3, -0.4, 0.2], uv, projector, placed: None };
let placed = placed_from_axis(&axis_planar, (lo, hi)).expect("an axis planar has a frame");
for (position, normal) in points(lo, hi) {
let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal };
let (before, _) = image_samples(&axis_planar, &coords)[0];
let (uv_after, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers");
let (after, _) = image_samples(&placed, &Coords { uv: uv_after, ..coords })[0];
assert!(before.distance(after) < 1e-3, "axis {axis} {rotation:?}: {before} became {after}");
assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "axis {axis} {crop:?}: cover changed at {position}");
}
}
}
}
}
#[test]
fn a_placed_axis_planar_keeps_what_backface_culling_hides() {
let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5));
let center = (lo + hi) * 0.5;
let radius = (hi - lo).length() * 0.5;
let backface = Backface { on: true, angle: 60.0, hardness: 1.0 };
// An oblique normal exposes tilted and reversed culling under stretch
let halfway = (center, Vec3::new(1.0, 0.0, 1.0).normalize());
for stretch in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] {
let projector = Projector { scale: stretch, backface, ..Projector::default() };
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
let Some(placed) = placed_from_axis(&axis_planar, (lo, hi)) else {
assert!(!culling_folds(&projector), "{stretch:?}: only a stretch culling cannot keep stays unplaced");
continue;
};
for (position, normal) in points(lo, hi).into_iter().chain([halfway]) {
let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal };
let (_, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers");
assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "{stretch:?}: culling changed at {normal}");
}
}
let even = Projector { scale: [1.7; 3], backface, ..Projector::default() };
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: even, placed: None };
assert!(placed_from_axis(&axis_planar, (lo, hi)).is_some(), "an even stretch is still placed");
}
#[test]
fn only_axis_planars_are_placed() {
let bounds = (Vec3::NEG_ONE, Vec3::ONE);
assert!(placed_from_axis(&Projection::default(), bounds).is_none());
let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame");
assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none());
assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none());
}
}
+96 -12
View File
@@ -7,13 +7,15 @@
//! identical to a full evaluation.
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::{Arc, Weak};
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_core::{BakedMap, Channel, EffectKind, Filter, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_geom::Mesh;
use texturecraft_texel::TileImage;
use crate::eval::{Inputs, PaintTarget};
use crate::eval::{Inputs, PaintTarget, lights_material};
use crate::held_fields::HeldFields;
use crate::image_identity::ImageIdentity;
use crate::store::{BakedMaps, ImageStore, PixelStore};
@@ -25,6 +27,8 @@ pub const BELOW_BUDGET: usize = 256 << 20;
/// See the module docs. One per texture set.
#[derive(Debug)]
pub struct BelowCache {
mesh: Weak<Mesh>,
borrowed_mesh_key: Option<u64>,
hot: Option<LayerId>,
key: Option<StackKey>,
/// Tiles with the stamp of their last use.
@@ -52,6 +56,8 @@ pub struct BelowCache {
impl Default for BelowCache {
fn default() -> Self {
BelowCache {
mesh: Weak::new(),
borrowed_mesh_key: None,
hot: None,
key: None,
tiles: HashMap::new(),
@@ -98,6 +104,8 @@ pub struct StackKey {
pixels: Vec<(LayerId, Option<Channel>, Shared)>,
baked: (u32, Vec<(BakedMap, usize)>),
images: Vec<(String, ImageIdentity)>,
/// The viewport environment, its rotation (bits) and its image when it is an imported one, where Baked Lighting Environment lights with them
environment: Option<(String, u32, Option<ImageIdentity>)>,
}
impl StackKey {
@@ -142,18 +150,23 @@ impl StackKey {
let mut referenced_images = BTreeSet::new();
if !images.is_empty() {
let mut record_image_reference = |source: &Source| {
referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name));
let mut record_image_name = |name: &str| {
if let Some((name, _)) = images.get_key_value(name) {
referenced_images.insert(name);
}
};
for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) {
if let LayerKind::Fill(fill) = &layer.kind {
fill.sources.values().for_each(&mut record_image_reference);
fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name);
}
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
// A filter's image inputs, also one its mode leaves unread: that only empties the cache more often
effect.inputs.values().flat_map(Source::images).for_each(&mut record_image_name);
match &effect.kind {
EffectKind::Fill { source, .. } => record_image_reference(source),
EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference),
EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name),
EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name),
EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name),
EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)),
_ => {}
}
}
@@ -163,6 +176,16 @@ impl StackKey {
let image_identities =
referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect();
let lit = render_tree
.iter()
.filter_map(|id| project.layers.get(id))
.flat_map(|layer| layer.content_effects.iter())
.any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. })));
let environment = lit.then(|| {
let image = project.display.environment_resource().and_then(|name| images.get(name)).map(ImageIdentity::new);
(project.display.environment.clone(), project.display.env_rotation.to_bits(), image)
});
Some(StackKey {
set,
roots,
@@ -170,6 +193,7 @@ impl StackKey {
pixels: pixel_handles,
baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()),
images: image_identities,
environment,
})
}
}
@@ -179,12 +203,20 @@ impl StackKey {
/// changed (same set, roots, layers, baked maps and images; the same images by id, channel
/// and size). None when anything else differs: the caller recomposites everything.
pub fn changed_tiles(&self, other: &StackKey) -> Option<BTreeSet<(u32, u32)>> {
if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images {
if self.set != other.set
|| self.roots != other.roots
|| self.layers != other.layers
|| self.baked != other.baked
|| self.images != other.images
|| self.environment != other.environment
{
return None;
}
if self.pixels.len() != other.pixels.len() {
return None;
}
let size = self.set.size();
let mut changed = BTreeSet::new();
for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) {
@@ -199,6 +231,7 @@ impl StackKey {
if !same_shape || (left_image.width(), left_image.height()) != size {
return None;
}
if left_image.same_tiles(right_image) {
continue;
}
@@ -260,6 +293,48 @@ fn render_view(l: &Layer) -> Layer {
}
impl BelowCache {
pub(crate) fn bind_mesh(&mut self, mesh: &Arc<Mesh>) {
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
self.clear();
self.borrowed_mesh_key = None;
self.mesh = Arc::downgrade(mesh);
}
}
pub(crate) fn bind_borrowed_mesh(&mut self, mesh: &Mesh) {
if std::ptr::eq(self.mesh.as_ptr(), mesh) {
return;
}
// A borrow alone cannot distinguish in-place edits or reuse of the same address
let mut key = DefaultHasher::new();
for attribute in [&mesh.positions, &mesh.normals] {
attribute.len().hash(&mut key);
for value in attribute {
value.to_array().map(f32::to_bits).hash(&mut key);
}
}
mesh.tangents.len().hash(&mut key);
for value in &mesh.tangents {
value.to_array().map(f32::to_bits).hash(&mut key);
}
mesh.uvs.len().hash(&mut key);
for value in &mesh.uvs {
value.to_array().map(f32::to_bits).hash(&mut key);
}
mesh.indices.hash(&mut key);
for part in &mesh.submeshes {
(&part.name, part.start, part.count, part.material).hash(&mut key);
}
let key = key.finish();
if self.borrowed_mesh_key != Some(key) {
self.clear();
self.mesh = Weak::new();
self.borrowed_mesh_key = Some(key);
}
}
/// Cache the stack around `hot` from now on (a different layer empties the cache).
pub fn set_hot(&mut self, hot: Option<LayerId>) {
if self.hot != hot {
@@ -363,8 +438,17 @@ impl BelowCache {
let project = inp.project;
let set = project.texture_set(inp.ts).ok()?;
// Anchor readers depend on the stack below them
if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) {
// Replaying cached colors would reuse the material below a lighting or validation effect
if project
.render_tree(&set.stack)
.iter()
.filter_map(|id| project.layers.get(id))
.any(|layer| layer.reads_stack() || layer.content_effects.iter().any(|effect| effect.visible && lights_material(&effect.kind)))
{
if self.key.is_some() {
self.clear();
}
return None;
}
+64
View File
@@ -0,0 +1,64 @@
//! The lower envelope of parabolas that turns a line of squared distances into each place's squared distance to the nearest feature
/// The lower envelope of the parabolas over a line of squared distances, which gives each place's squared distance to the nearest feature along it and the line before
#[derive(Default)]
pub(crate) struct DistanceEnvelope {
/// The parabolas still lowest somewhere: their vertex and where their stretch begins
parabolas: Vec<(usize, f64)>,
/// The line as it was
heights: Vec<f32>,
}
impl DistanceEnvelope {
/// Replace `line` with each place's squared distance to the nearest feature
pub(crate) fn lower(&mut self, line: &mut [f32]) {
self.heights.clear();
self.heights.extend_from_slice(line);
self.parabolas.clear();
let heights = &self.heights;
// In f64, where squared places and their sums stay exact past 4096 texels and a wide line cannot overflow a 32-bit usize
let lifted = |at: usize| f64::from(heights.get(at).copied().unwrap_or(f32::MAX)) + at as f64 * at as f64;
for at in 0..heights.len() {
let mut start = f64::NEG_INFINITY;
while let Some(&(vertex, from)) = self.parabolas.last() {
let crossing = (lifted(at) - lifted(vertex)) / (2.0 * (at - vertex) as f64);
if crossing <= from {
self.parabolas.pop();
} else {
start = crossing;
break;
}
}
self.parabolas.push((at, start));
}
let mut current = 0;
for (at, out) in line.iter_mut().enumerate() {
while self.parabolas.get(current + 1).is_some_and(|(_, from)| *from < at as f64) {
current += 1;
}
if let Some(&(vertex, _)) = self.parabolas.get(current) {
*out = (at as f32 - vertex as f32).powi(2) + heights.get(vertex).copied().unwrap_or(f32::MAX);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Past 4096 texels a squared place is no longer exact in f32: two close features at the end of a wide line still each read 0
#[test]
fn close_features_far_along_a_wide_line_stay_exact() {
const FAR: f32 = 4.0e8;
let mut line = vec![FAR; 10_000];
line[9_950] = 1.0;
line[9_951] = 0.0;
DistanceEnvelope::default().lower(&mut line);
assert_eq!(line[9_949..9_954], [2.0, 1.0, 0.0, 1.0, 4.0]);
}
}
+95
View File
@@ -0,0 +1,95 @@
//! The distribution of the values entering an effect, as the levels editor draws it
use texturecraft_core::lum;
/// Bucket counts over 0..1 of the values entering an effect, pooled and per part of a colour
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EffectHistogram {
/// Every value, a colour's three components pooled
pub all: Vec<u32>,
/// Red, green and blue on their own; empty for a one-value channel or a mask
pub components: Vec<Vec<u32>>,
/// Each colour's luminance; a one-value channel's or a mask's values (the same as `all`)
pub luminance: Vec<u32>,
}
impl EffectHistogram {
/// `bins` empty buckets (at least one), with per-component buckets when it counts colours
pub fn new(bins: usize, color: bool) -> EffectHistogram {
let bins = bins.max(1);
EffectHistogram { all: vec![0; bins], components: if color { vec![vec![0; bins]; 3] } else { Vec::new() }, luminance: vec![0; bins] }
}
/// Counts one value of a one-value channel or a mask
pub fn add_value(&mut self, value: f32) {
bump(&mut self.all, value);
bump(&mut self.luminance, value);
}
/// Counts one colour: each component pooled and on its own, and its luminance
pub fn add_color(&mut self, color: [f32; 3]) {
for (index, component) in color.into_iter().enumerate() {
bump(&mut self.all, component);
if let Some(counts) = self.components.get_mut(index) {
bump(counts, component);
}
}
bump(&mut self.luminance, lum(color));
}
/// Both histograms' counts together (they have the same buckets)
pub fn merged(mut self, other: &EffectHistogram) -> EffectHistogram {
add_counts(&mut self.all, &other.all);
for (counts, more) in self.components.iter_mut().zip(&other.components) {
add_counts(counts, more);
}
add_counts(&mut self.luminance, &other.luminance);
self
}
}
/// One more count in the bucket of `value` (clamped to 0..1)
fn bump(counts: &mut [u32], value: f32) {
let bins = counts.len();
let index = ((value.clamp(0.0, 1.0) * bins as f32) as usize).min(bins.saturating_sub(1));
if let Some(count) = counts.get_mut(index) {
*count = count.saturating_add(1);
}
}
fn add_counts(counts: &mut [u32], more: &[u32]) {
for (count, extra) in counts.iter_mut().zip(more) {
*count = count.saturating_add(*extra);
}
}
#[cfg(test)]
mod tests {
use super::EffectHistogram;
#[test]
fn a_colour_counts_each_component_pooled_and_alone_and_its_luminance() {
let mut histogram = EffectHistogram::new(4, true);
histogram.add_color([1.0, 0.0, 0.3]);
let merged = histogram.clone().merged(&histogram);
assert_eq!(histogram.all, vec![1, 1, 0, 1]);
assert_eq!(histogram.components, vec![vec![0, 0, 0, 1], vec![1, 0, 0, 0], vec![0, 1, 0, 0]]);
assert_eq!(histogram.luminance, vec![0, 1, 0, 0], "luminance 0.33 lands in the second bucket");
assert_eq!(merged.all, vec![2, 2, 0, 2]);
assert_eq!(merged.components.first(), Some(&vec![0, 0, 0, 2]));
}
#[test]
fn a_value_has_no_components() {
let mut histogram = EffectHistogram::new(2, false);
histogram.add_value(f32::NAN);
histogram.add_value(0.9);
assert_eq!(histogram.all, vec![1, 1]);
assert_eq!(histogram.luminance, histogram.all);
assert!(histogram.components.is_empty());
}
}
+217
View File
@@ -0,0 +1,217 @@
//! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it
use std::sync::{Arc, Mutex, Weak};
use texturecraft_core::project::DisplaySettings;
use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3};
use texturecraft_geom::glam::Vec3;
use crate::environment_sky::{VIEWPORT_WIDTH, dir_of, environment_linear, radiance, sh_basis, sh9_averaged};
use crate::store::{ImageRes, ImageStore};
/// The diffuse light of the viewport environment and the turn the viewport gives it
#[derive(Clone, Copy)]
pub struct EnvironmentSh {
coefficients: [[f32; 3]; 9],
/// The viewport's environment rotation (radians)
rotation: f32,
}
/// The last coefficients, keyed by a built-in name or the identity of an imported image
type CacheEntry = (String, Option<Weak<ImageRes>>, [[f32; 3]; 9]);
static CACHE: Mutex<Option<CacheEntry>> = Mutex::new(None);
impl EnvironmentSh {
/// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment
pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh {
let image = display.environment_resource().and_then(|name| images.get(name));
let same = |entry: &CacheEntry| match (&entry.1, &image) {
(Some(identity), Some(image)) => std::ptr::eq(identity.as_ptr(), Arc::as_ptr(image)),
(None, None) => entry.0 == display.environment,
_ => false,
};
let rotation = display.env_rotation.to_radians();
let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2);
if let Some(coefficients) = cached {
return EnvironmentSh { coefficients, rotation };
}
// Average outside the lock so a Rayon worker can take another tile that needs the cache
let coefficients = match image {
Some(image) => image_sh(image),
None => built_in_sh(&display.environment),
};
*CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image.map(Arc::downgrade), coefficients));
EnvironmentSh { coefficients, rotation }
}
/// The diffuse light reaching a surface facing world direction `normal` with the environment turned `horizontal` and tilted `vertical` (radians) past the viewport's turn
pub fn irradiance(&self, normal: Vec3, horizontal: f32, vertical: f32) -> Vec3 {
let (sin_tilt, cos_tilt) = vertical.sin_cos();
let tilted = Vec3::new(normal.x, cos_tilt * normal.y - sin_tilt * normal.z, sin_tilt * normal.y + cos_tilt * normal.z);
// Turned as the viewport turns its environment
let (sin_turn, cos_turn) = (self.rotation + horizontal).sin_cos();
let direction = Vec3::new(cos_turn * tilted.x - sin_turn * tilted.z, tilted.y, sin_turn * tilted.x + cos_turn * tilted.z);
let light = sh_basis(direction).iter().zip(&self.coefficients).fold(Vec3::ZERO, |sum, (basis, coefficient)| sum + Vec3::from(*coefficient) * *basis);
light.max(Vec3::ZERO)
}
/// Baked Lighting Environment's lit base color: linear `albedo`, its metal read from `channels` (straight values by [`Channel::index`]), in `light` (the environment's diffuse light at the surface, exposure applied), darkened by ambient occlusion `ao` by `[diffuse, specular]` occlusion. The viewer looks straight at the surface, so what it reflects is the light around the normal
pub fn shade(albedo: [f32; 3], light: Vec3, ao: f32, [diffuse_occlusion, specular_occlusion]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] {
let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 };
let metal = finite_unit(channels.get(Channel::Metallic.index()).map_or(0.0, |m| m[0]));
let f0 = mix3([DIELECTRIC_REFLECTANCE; 3], albedo, metal);
let diffuse = 1.0 + (ao - 1.0) * finite_unit(diffuse_occlusion);
let specular = 1.0 + (ao - 1.0) * finite_unit(specular_occlusion);
let incoming = light.to_array();
std::array::from_fn(|k| finite_unit(albedo[k] * (1.0 - metal) * incoming[k] * diffuse + f0[k] * incoming[k] * specular))
}
}
/// The coefficients of built-in environment `name` as the viewport works them out: drawn at its width, then averaged
fn built_in_sh(name: &str) -> [[f32; 3]; 9] {
let (width, height) = (VIEWPORT_WIDTH, VIEWPORT_WIDTH / 2);
sh9_averaged(width, height, |x, y| radiance(name, dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32)))
}
/// The coefficients of an imported equirect image, every texel averaged in as the viewport does
fn image_sh(image: &ImageRes) -> [[f32; 3]; 9] {
let linear = |v: f32| environment_linear(v, image.srgb);
sh9_averaged(image.width, image.height, |x, y| {
let texel = image.rgba.get((y as usize) * image.width as usize + x as usize).copied().unwrap_or([0.0; 4]);
Vec3::new(linear(texel[0]), linear(texel[1]), linear(texel[2]))
})
}
#[cfg(test)]
mod tests {
use super::*;
/// A uniform environment lights every direction alike, whatever the turn; brighter skies light more
#[test]
fn a_uniform_image_lights_every_way_alike() {
for (width, height) in [(1, 1), (32, 16)] {
let image = ImageRes::new(width, height, vec![[0.5, 0.5, 0.5, 1.0]; (width * height) as usize], false);
let sh = EnvironmentSh { coefficients: image_sh(&image), rotation: 1.0 };
for normal in [Vec3::Y, Vec3::X, Vec3::NEG_Y, Vec3::new(0.6, 0.0, 0.8)] {
let light = sh.irradiance(normal, 0.3, 0.7);
assert!((light - Vec3::splat(0.5)).abs().max_element() < 0.02, "{width}x{height} {normal}: {light}");
}
}
}
/// The studio's key light is up and to one side: a surface facing up gets more light than one facing down, and turning the environment moves the light around
#[test]
fn a_built_in_lights_by_where_the_surface_faces_and_turns() {
let display = DisplaySettings { environment: "Studio Soft".into(), ..DisplaySettings::default() };
let sh = EnvironmentSh::of(&display, &ImageStore::default());
assert!(sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum() > 2.0 * sh.irradiance(Vec3::NEG_Y, 0.0, 0.0).element_sum());
let side = Vec3::new(0.7, 0.0, 0.7).normalize();
let (here, turned) = (sh.irradiance(side, 0.0, 0.0), sh.irradiance(side, std::f32::consts::PI, 0.0));
assert!((here - turned).abs().max_element() > 0.05, "{here} vs {turned}");
let night = EnvironmentSh::of(&DisplaySettings { environment: "Night".into(), ..DisplaySettings::default() }, &ImageStore::default());
assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment");
}
#[test]
fn replacing_an_imported_environment_releases_its_image() {
let display = DisplaySettings { environment: "resource:lighting".into(), ..DisplaySettings::default() };
for color in [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]] {
let image = Arc::new(ImageRes::new(32, 16, vec![color; 32 * 16], false));
let image_identity = Arc::downgrade(&image);
let images = ImageStore::from([("lighting".into(), image)]);
let lighting = EnvironmentSh::of(&display, &images);
drop(images);
let irradiance = lighting.irradiance(Vec3::Y, 0.0, 0.0);
assert!(irradiance.distance(Vec3::new(color[0], color[1], color[2])) < 0.02);
assert!(image_identity.upgrade().is_none(), "lighting should release the decoded image with its store");
}
}
/// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock
#[test]
fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() {
use rayon::prelude::*;
const WORKERS: usize = 8;
const TILES: usize = 1024;
// One tile in so many asks for the light; the rest finish at once, so their workers are free to steal the averaging's work
const LIT_EVERY: usize = 128;
const ROUNDS: usize = 20;
const PATIENCE: std::time::Duration = std::time::Duration::from_secs(60);
let (done, finished) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let Ok(pool) = rayon::ThreadPoolBuilder::new().num_threads(WORKERS).build() else { return };
pool.install(|| {
for round in 0..ROUNDS {
// Each round shows another environment, so its first tile misses the cache
let environment = if round % 2 == 0 { "Sunset" } else { "Night" };
let display = DisplaySettings { environment: environment.into(), ..DisplaySettings::default() };
(0..TILES).into_par_iter().filter(|tile| tile % LIT_EVERY == 0).for_each(|_| {
EnvironmentSh::of(&display, &ImageStore::default());
});
}
});
let _ = done.send(());
});
assert!(finished.recv_timeout(PATIENCE).is_ok(), "the tiles deadlocked on the cache");
}
/// Diffuse occlusion darkens non-metals by the ambient occlusion; metals take their light from the reflections, which only specular occlusion darkens
#[test]
fn occlusion_darkens_the_diffuse_and_the_reflections_apart() {
let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect();
let light = Vec3::splat(1.0);
let dielectric = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0];
assert!(dielectric([1.0, 0.0]) < dielectric([0.0, 0.0]) * 0.5);
channels[Channel::Metallic.index()] = [1.0; 3];
let metal = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0];
assert_eq!(metal([1.0, 0.0]), metal([0.0, 0.0]));
assert!(metal([0.0, 1.0]) < metal([0.0, 0.0]) * 0.5);
}
/// The coefficients of `radiance` read at every place of a fine grid, the integral the averaged ones must match
fn fine_sh(width: u32, radiance: impl Fn(Vec3) -> Vec3) -> [[f32; 3]; 9] {
let height = width / 2;
crate::environment_sky::sh9(width, height, |x, y| radiance(dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32)))
}
/// Sunset's sun is smaller than a texel of a coarse grid: averaging the viewport's drawing keeps its light, as the viewport does
#[test]
fn a_small_sun_lights_as_the_viewport_shows_it() {
let display = DisplaySettings { environment: "Sunset".into(), ..DisplaySettings::default() };
let baked = EnvironmentSh::of(&display, &ImageStore::default()).coefficients;
let fine = fine_sh(1024, |direction| radiance("Sunset", direction));
for (baked, fine) in baked.iter().zip(&fine) {
for (baked, fine) in baked.iter().zip(fine) {
assert!((baked - fine).abs() < 0.02, "{baked} vs {fine}");
}
}
}
/// An imported image's small bright patch counts though it falls between the texels a coarse read would take
#[test]
fn a_small_bright_patch_of_an_image_counts() {
const BRIGHT: f32 = 500.0;
let (width, height) = (1024u32, 512u32);
let patch = |x: u32, y: u32| (97..101).contains(&x) && (193..197).contains(&y);
let rgba = (0..width * height).map(|i| if patch(i % width, i / width) { [BRIGHT, BRIGHT, BRIGHT, 1.0] } else { [0.0, 0.0, 0.0, 1.0] }).collect();
let image = ImageRes::new(width, height, rgba, false);
let averaged = image_sh(&image)[0][0];
let exact = crate::environment_sky::sh9(width, height, |x, y| if patch(x, y) { Vec3::splat(BRIGHT) } else { Vec3::ZERO })[0][0];
assert!(exact > 0.01 && (averaged - exact).abs() < exact * 0.05, "{averaged} vs {exact}");
}
}
+174
View File
@@ -0,0 +1,174 @@
//! The built-in environments (drawn in code, no image assets) and their diffuse light as spherical harmonics, for the viewport and Baked Lighting Environment
use std::f32::consts::{PI, TAU};
use rayon::prelude::*;
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::soft_box::SoftBox;
/// The width the viewport draws a built-in environment at (half as tall)
pub const VIEWPORT_WIDTH: u32 = 512;
/// The width an environment is box-averaged down to before its diffuse light is worked out: averaging keeps a sun smaller than a texel
const SH_WIDTH: u32 = 128;
/// The brightest radiance the viewport keeps of an imported environment (it stores half floats)
const HALF_FLOAT_MAX: f32 = 65_000.0;
/// The irradiance convolution factor of each SH band (the cosine lobe's π, 2π/3 and π/4), one per coefficient
const COSINE_LOBE_BANDS: [f32; 9] = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0];
/// The linear radiance of a component `v` of an imported environment's texel (sRGB-encoded when `srgb`): not a number is 0, capped at the half-float range, sRGB at 1
pub fn environment_linear(v: f32, srgb: bool) -> f32 {
let v = if v.is_finite() { v.clamp(0.0, HALF_FLOAT_MAX) } else { 0.0 };
if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v }
}
/// The direction at equirect place `u = φ / 2π`, `v = θ / π`: `(sin θ cos φ, cos θ, sin θ sin φ)`, row 0 straight up
pub fn dir_of(u: f32, v: f32) -> Vec3 {
let (theta, phi) = (v * PI, u * TAU);
Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin())
}
/// The equirect place of direction `d`
pub fn uv_of(d: Vec3) -> Vec2 {
let phi = d.z.atan2(d.x);
Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI)
}
/// Smoothstep of `t` over 0..1
pub(crate) fn smooth(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// How fast a sky turns from its horizon to its zenith and to its ground (powers of the height; under 1 turns early)
const ZENITH_FALLOFF: f32 = 0.6;
const GROUND_FALLOFF: f32 = 0.25;
/// A sky blending `horizon` up to `zenith` and down to `ground`
fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 {
if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(ZENITH_FALLOFF)) } else { horizon.lerp(ground, (-d.y).powf(GROUND_FALLOFF)) }
}
/// The Sunset sun's disc: the cosine of its edge from the centre, the width of its soft rim, and its brightness
const SUN_EDGE_COS: f32 = 0.9985;
const SUN_EDGE_WIDTH: f32 = 0.0012;
const SUN_RADIANCE: f32 = 120.0;
/// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio)
pub fn radiance(name: &str, d: Vec3) -> Vec3 {
if name == "Sunset" {
let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05));
let sun_dir = dir_of(0.12, 0.47);
let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE;
return base + Vec3::new(1.0, 0.6, 0.3) * sun;
}
let (azimuth, elevation) = SoftBox::angles(d);
match name {
"Studio Contrast" => {
let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01));
base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(azimuth, elevation)
}
"Overcast" => {
let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15));
base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(azimuth, elevation)
}
"Warehouse" => {
let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06));
for k in 0..6 {
c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }
.eval(azimuth, elevation);
}
c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(azimuth, elevation)
}
"Night" => {
let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005));
base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(azimuth, elevation)
}
// "Studio Soft" (default)
_ => {
let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07));
base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(azimuth, elevation)
+ SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(azimuth, elevation)
}
}
}
/// The 9 real spherical-harmonics basis functions at unit direction `d` (the standard band 0..2 constants)
pub fn sh_basis(d: Vec3) -> [f32; 9] {
let (x, y, z) = (d.x, d.y, d.z);
[
0.282_095,
0.488_603 * y,
0.488_603 * z,
0.488_603 * x,
1.092_548 * x * y,
1.092_548 * y * z,
0.315_392 * (3.0 * z * z - 1.0),
1.092_548 * x * z,
0.546_274 * (x * x - y * y),
]
}
/// Diffuse irradiance as 9 SH coefficients of the equirect image `width` x `height` whose texels `radiance` gives (already convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance)
pub fn sh9(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3) -> [[f32; 3]; 9] {
let (w, h) = (width.max(1), height.max(1));
// Sample each large texel across its angular footprint so a constant sky lights all directions
const MIN_COLUMNS: u32 = 32;
const MIN_ROWS: u32 = 16;
let samples_x = MIN_COLUMNS.div_ceil(w);
let samples_y = MIN_ROWS.div_ceil(h);
let (w, h) = (w * samples_x, h * samples_y);
let mut sums = [Vec3::ZERO; 9];
for y in 0..h {
let theta = PI * (y as f32 + 0.5) / h as f32;
let solid_angle = (TAU / w as f32) * (PI / h as f32) * theta.sin();
for x in 0..w {
let direction = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
// No firefly clamp: the projection integrates, so a bright sun lights diffuse fully
let weighted = radiance(x / samples_x, y / samples_y) * solid_angle;
for (sum, basis) in sums.iter_mut().zip(sh_basis(direction)) {
*sum += weighted * basis;
}
}
}
std::array::from_fn(|k| (sums[k] * COSINE_LOBE_BANDS[k] / PI).to_array())
}
/// [`sh9`] of the equirect image `width` x `height` whose texels `radiance` gives, box-halved while wider than [`SH_WIDTH`] (an odd last row or column is dropped, as the viewport drops it)
pub fn sh9_averaged(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3 + Sync) -> [[f32; 3]; 9] {
if width <= SH_WIDTH {
return sh9(width, height, radiance);
}
let mut image = half(width, height, radiance);
while image.0 > SH_WIDTH {
let (w, h, data) = &image;
image = half(*w, *h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO));
}
let (w, h, data) = image;
sh9(w, h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO))
}
/// The equirect image `width` x `height` whose texels `texel` gives, box-downsampled by 2 (wrapping around, clamped at the poles): its width, height and texels
pub fn half(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> (u32, u32, Vec<Vec3>) {
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
let get = |x: u32, y: u32| texel(x % width.max(1), y.min(height.saturating_sub(1)));
let mut data = vec![Vec3::ZERO; (w * h) as usize];
data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| {
for (x, texel) in row.iter_mut().enumerate() {
let (sx, sy) = (x as u32 * 2, y as u32 * 2);
*texel = (get(sx, sy) + get(sx + 1, sy) + get(sx, sy + 1) + get(sx + 1, sy + 1)) * 0.25;
}
});
(w, h, data)
}
+3851 -653
View File
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
//! Where a layer is drawn inside the current texture set.
use texturecraft_core::{ContentsOffset, Layer, LayerId};
use super::EvaluationInputs;
#[derive(Clone, Copy, Default)]
pub(super) struct DrawPlacement {
pub offset: ContentsOffset,
/// Zero denotes the original folder tree
pub instance: usize,
}
impl From<ContentsOffset> for DrawPlacement {
fn from(offset: ContentsOffset) -> Self {
Self { offset, instance: 0 }
}
}
impl DrawPlacement {
pub(super) fn children(self, inputs: &EvaluationInputs, id: LayerId, source: &Layer) -> Self {
let instance = if id == source.id { self.instance } else { inputs.instance_draw(self.instance, id) };
Self { offset: self.offset.then(inputs.project.contents_offset(source.id)), instance }
}
}
@@ -0,0 +1,131 @@
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use texturecraft_core::{FillSymmetry, Filter, LayerId, PreparedGradient, Project, Projection, Sampling};
use super::Inputs;
use crate::ProjectorDepthCache;
use crate::environment_sh::EnvironmentSh;
use crate::fill_depth::FillDepth;
use crate::pattern::mesh_frame;
use crate::projector_depth_cache::ViewDepth;
use crate::projector_view::ProjectorView;
/// Hold up to 30 MiB of depth maps through an evaluation; later views use the shared cache
const MAX_EVALUATION_VIEWS: usize = 10;
pub(super) struct EvaluationInputs<'a> {
inputs: &'a Inputs<'a>,
projectors: &'a ProjectorDepthCache,
environment: OnceLock<EnvironmentSh>,
instance_draws: OnceLock<HashMap<(usize, LayerId), usize>>,
depth_maps: Mutex<Vec<ViewDepth>>,
gradients: Mutex<HashMap<usize, Arc<PreparedGradient>>>,
}
impl<'a> EvaluationInputs<'a> {
pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self {
Self {
inputs,
projectors,
environment: OnceLock::new(),
instance_draws: OnceLock::new(),
depth_maps: Mutex::new(Vec::new()),
gradients: Mutex::default(),
}
}
pub(super) fn environment(&self) -> EnvironmentSh {
if let Some(environment) = self.environment.get() {
return *environment;
}
// Rayon may enter another plan while taking samples for the first one
let environment = EnvironmentSh::of(&self.project.display, self.images);
let _ = self.environment.set(environment);
environment
}
/// Each path through nested folder instances gets a stable identity within an evaluation.
pub(super) fn instance_draw(&self, parent: usize, id: LayerId) -> usize {
let draws = self.instance_draws.get_or_init(|| {
let mut draws = HashMap::new();
if let Ok(set) = self.project.texture_set(self.ts) {
collect_instance_draws(self.project, &set.stack, 0, 0, &mut draws);
}
draws
});
draws.get(&(parent, id)).copied().unwrap_or_default()
}
pub(super) fn projector_depth(&self, projection: &Projection, sampling: Sampling) -> Option<Arc<FillDepth>> {
let view = ProjectorView::of(projection, self.bounds)?;
let copies = sampling.symmetry.on.then(|| {
let (center, radius) = mesh_frame(self.bounds);
// Flipping the image leaves the projector's depth view unchanged
(FillSymmetry { flip: [false; 2], ..sampling.symmetry }, center, radius)
});
let key = (view, copies);
let mut depth_maps = self.depth_maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some((_, map)) = depth_maps.iter().find(|(cached_key, _)| *cached_key == key) {
return map.clone();
}
if depth_maps.len() >= MAX_EVALUATION_VIEWS {
// Keep overflow work out of the evaluation lock
drop(depth_maps);
return self.projectors.get(self.mesh, key);
}
let depth = self.projectors.get(self.mesh, key);
depth_maps.push((key, depth.clone()));
depth
}
pub(super) fn gradient(&self, filter: &'a Filter) -> Option<Arc<PreparedGradient>> {
if !matches!(filter, Filter::GradientMap { linear: false, .. }) {
return None;
}
// The borrowed project keeps filter addresses stable for this evaluation
let key = std::ptr::from_ref(filter) as usize;
let mut gradients = self.gradients.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(prepared) = gradients.get(&key) {
return Some(Arc::clone(prepared));
}
let prepared = Arc::new(PreparedGradient::of(filter)?);
gradients.insert(key, Arc::clone(&prepared));
Some(prepared)
}
}
impl<'a> Deref for EvaluationInputs<'a> {
type Target = Inputs<'a>;
fn deref(&self) -> &Self::Target {
self.inputs
}
}
fn collect_instance_draws(project: &Project, layers: &[LayerId], parent: usize, depth: usize, draws: &mut HashMap<(usize, LayerId), usize>) {
if depth > texturecraft_core::project::MAX_DEPTH {
return;
}
for &id in layers {
let Some(source) = project.content_layer(id).filter(|layer| !layer.children().is_empty()) else { continue };
let instance = if id == source.id {
parent
} else {
let next = draws.len() + 1;
*draws.entry((parent, id)).or_insert(next)
};
collect_instance_draws(project, source.children(), instance, depth + 1, draws);
}
}
+26 -5
View File
@@ -1,25 +1,46 @@
//! Isolated folder evaluation with the original stack available for anchor inputs.
use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed};
use super::{
Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Tape, Texel, all_tiles, evaluation_channels, evaluation_fields,
plan, tile_texels, to_u16, to_u16_signed,
};
/// Composite one layer over channel defaults, keeping anchors from the stack below it.
pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option<Composite> {
let set = inputs.project.texture_set(inputs.ts).ok()?;
let channels = set.channel_list();
let channels = evaluation_channels(inputs, set.channel_list());
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
let tiles = all_tiles(width, height);
let fields = neighbourhood_fields(inputs, &channels, &tiles);
let projectors = ProjectorDepthCache::default();
let inputs = &EvaluationInputs::new(inputs, &projectors);
let fields = evaluation_fields(inputs, &channels, &tiles);
let mut composite = Composite::with_size(&[channel], width, height);
let output = composite.channels.get_mut(&channel)?;
let mut recorded = Vec::new();
for (tile_x, tile_y) in tiles {
let nodes = plan(inputs, &[layer], &channels, tile_x, tile_y, 0, Some(&fields));
let full_stack = if set.stack.as_slice() == [layer] { Vec::new() } else { plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)) };
for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) {
let mut texel = Texel::new(inputs, x, y, offset, 0.0);
texel.anchors_below(&full_stack, layer);
texel.anchors_below(&full_stack, (layer, 0));
let mut values = Channel::ALL.map(Channel::default_value);
texel.eval(&nodes, &mut values);
if let Some(mut backdrop) = texel.below {
// Evaluate masks against the real backdrop, then show only this folder's contribution
texel.tape = Tape::Record(std::mem::take(&mut recorded));
texel.eval(&nodes, &mut backdrop);
if let Tape::Record(samples) = texel.tape {
recorded = samples;
}
let mut isolated = Texel::new(inputs, x, y, offset, 0.0);
isolated.tape = Tape::Replay(&recorded, 0);
isolated.eval(&nodes, &mut values);
recorded.clear();
} else {
texel.eval(&nodes, &mut values);
}
let value = values.get(channel.index()).copied().unwrap_or_else(|| channel.default_value());
let encoded = value.map(|component| if channel.kind() == ChannelKind::Signed { to_u16_signed(component) } else { to_u16(component) });
output.set(x, y, &encoded[..channel.components()]);
+164
View File
@@ -0,0 +1,164 @@
//! The copies a symmetric fill makes of its projection, as mirrors and turns of the surface point each copy samples
use texturecraft_core::{FULL_TURN_DEGREES, FillSymmetry, SymmetryKind};
use texturecraft_geom::glam::{Mat3, Vec3};
use crate::fill_copy::FillCopy;
/// The copies of a fill's projection one texel shows, the original among them: the one whose half (mirror) or wedge (radial) holds the texel comes first, so it lies on top where copies overlap
pub struct FillCopies {
symmetry: FillSymmetry,
pivot: Vec3,
axis: usize,
step: f32,
first: u32,
count: u32,
next: u32,
}
impl FillCopies {
/// The copies `symmetry` makes for a texel at world point `point`, on a mesh whose bounds have centre `center` and radius `radius`
pub fn new(symmetry: &FillSymmetry, point: Vec3, center: Vec3, radius: f32) -> FillCopies {
let reach = FillSymmetry::REACH;
let position = Vec3::from(symmetry.position.map(|coordinate| if coordinate.is_finite() { coordinate.clamp(-reach, reach) } else { 0.0 }));
let pivot = center + position * radius;
let axis = symmetry.axis_index();
let count = symmetry.copies();
let step = symmetry.step();
let from_pivot = point - pivot;
let first = match symmetry.kind {
// The original keeps the half on the axis's positive side
SymmetryKind::Mirror => u32::from(from_pivot[axis] < 0.0),
SymmetryKind::Radial => {
let turned = from_pivot[(axis + 2) % 3].atan2(from_pivot[(axis + 1) % 3]).to_degrees().rem_euclid(FULL_TURN_DEGREES);
nearest_copy(turned, step, count, symmetry.span)
}
};
FillCopies { symmetry: *symmetry, pivot, axis, step, first, count, next: 0 }
}
/// Copy `index`: the original at 0, then the mirror or the radial copies in turn
pub(crate) fn copy(&self, index: u32) -> FillCopy {
let flip = if index == 0 { [false; 2] } else { self.symmetry.flip };
let turn = match self.symmetry.kind {
_ if index == 0 => Mat3::IDENTITY,
SymmetryKind::Mirror => {
let mut scale = Vec3::ONE;
scale[self.axis] = -1.0;
Mat3::from_diagonal(scale)
}
// Copy `index` is the original turned by `index` steps, so a texel samples the original turned back
SymmetryKind::Radial => Mat3::from_axis_angle(Vec3::AXES[self.axis], -(index as f32 * self.step).to_radians()),
};
FillCopy::new(turn, self.pivot, flip)
}
pub(crate) fn next_indexed(&mut self) -> Option<(usize, FillCopy)> {
if self.next >= self.count {
return None;
}
let index = (self.first + self.next) % self.count;
self.next += 1;
Some((index as usize, self.copy(index)))
}
}
/// The radial copy nearest a texel `turned` degrees round the axis, of `count` copies `step` degrees apart over `span` degrees: copy 0 across the gap a span under a full turn leaves, else the nearest by its step
fn nearest_copy(turned: f32, step: f32, count: u32, span: f32) -> u32 {
// A span of nothing (or no step at all) stacks every copy on the original
if step.is_nan() || step <= 0.0 {
return 0;
}
let by_step = (turned / step).round() as u32;
if span >= FULL_TURN_DEGREES || span.is_nan() {
return by_step % count;
}
let last = by_step.min(count - 1);
let past_last = (turned - last as f32 * step).abs();
let before_first = FULL_TURN_DEGREES - turned;
if before_first <= past_last { 0 } else { last }
}
impl Iterator for FillCopies {
type Item = FillCopy;
fn next(&mut self) -> Option<FillCopy> {
self.next_indexed().map(|(_, copy)| copy)
}
}
#[cfg(test)]
mod tests {
use texturecraft_geom::glam::Vec2;
use super::*;
fn symmetry(kind: SymmetryKind, axis: u8) -> FillSymmetry {
FillSymmetry { on: true, kind, axis, ..FillSymmetry::OFF }
}
#[test]
fn a_mirror_puts_the_texels_own_half_first_and_reflects_across_the_axis_position() {
let mut mirror = symmetry(SymmetryKind::Mirror, 0);
mirror.position = [0.5, 0.0, 0.0];
let left: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
assert_eq!(left.len(), 2);
// The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first
assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5));
assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5));
assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5));
let right: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5));
}
#[test]
fn radial_copies_turn_by_their_step_and_flip_only_the_copies() {
let mut radial = symmetry(SymmetryKind::Radial, 2);
radial.count = 4;
radial.flip = [true, false];
let copies: Vec<FillCopy> = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect();
assert_eq!(copies.len(), 4);
assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5));
assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5));
// Copy 1 sits a quarter turn on: a texel on +Y samples the original on +X
assert!(copies[1].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5));
// A texel on +Y lies in copy 1's wedge, so copy 1 comes first there
let on_y: Vec<FillCopy> = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect();
assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5));
}
#[test]
fn the_nearest_copy_is_found_by_its_step_as_a_search_of_every_copy_finds_it() {
for (count, span) in [(6, 360.0), (5, 360.0), (4, 180.0), (3, 90.0), (64, 300.0), (2, 1.0)] {
let step = radial_step(count, span);
for tenth in 0..3600 {
let turned = tenth as f32 / 10.0 + 0.05;
let gap = |index: u32| {
let past_copy = (turned - index as f32 * step).rem_euclid(FULL_TURN_DEGREES);
past_copy.min(FULL_TURN_DEGREES - past_copy)
};
let searched = (0..count).min_by(|a, b| gap(*a).total_cmp(&gap(*b))).unwrap_or(0);
assert_eq!(nearest_copy(turned, step, count, span), searched, "{count} copies over {span} at {turned}");
}
}
}
fn radial_step(count: u32, span: f32) -> f32 {
FillSymmetry { count, span, ..symmetry(SymmetryKind::Radial, 2) }.step()
}
}
+34
View File
@@ -0,0 +1,34 @@
//! One copy of a symmetric fill's projection: the mirror or turn a texel samples it through
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
/// One copy of a fill's projection: a texel at a point shows what the projection gives at [`FillCopy::point`]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FillCopy {
turn: Mat3,
pivot: Vec3,
flip: [bool; 2],
}
impl FillCopy {
/// A copy sampling the projection at `pivot + turn * (point - pivot)`, its image turned over across and down as `flip` says
pub fn new(turn: Mat3, pivot: Vec3, flip: [bool; 2]) -> FillCopy {
FillCopy { turn, pivot, flip }
}
/// The surface point the projection is sampled at for a texel at world point `point`
pub fn point(&self, point: Vec3) -> Vec3 {
self.pivot + self.turn * (point - self.pivot)
}
/// The normal the projection sees for a texel whose normal is `normal`
pub fn normal(&self, normal: Vec3) -> Vec3 {
self.turn * normal
}
/// `uv` in the copy's image, turned over across and down as its Flip copy says
pub fn uv(&self, uv: Vec2) -> Vec2 {
let [across, down] = self.flip;
Vec2::new(if across { 1.0 - uv.x } else { uv.x }, if down { 1.0 - uv.y } else { uv.y })
}
}
+43
View File
@@ -0,0 +1,43 @@
use texturecraft_core::FillSymmetry;
use texturecraft_geom::{Mesh, glam::Vec3};
use crate::fill_copies::FillCopies;
use crate::projector_depth::{CELL_BUDGET, GRID_SIDE, ProjectorDepth};
use crate::projector_view::ProjectorView;
pub(crate) type FillDepthKey = (ProjectorView, Option<(FillSymmetry, Vec3, f32)>);
/// Depth coverage in the original and optional symmetric views of one fill.
pub(crate) enum FillDepth {
Single(ProjectorDepth),
Copies(Box<[Option<ProjectorDepth>]>),
}
impl FillDepth {
pub(crate) fn build(mesh: &Mesh, (view, symmetry): FillDepthKey) -> Option<Self> {
let Some((symmetry, center, radius)) = symmetry else {
return ProjectorDepth::build(view, mesh).map(Self::Single);
};
let copies = FillCopies::new(&symmetry, center, center, radius);
let count = symmetry.copies() as usize;
// Share one grid's storage and raster budget across the copy views
let grid_side = (GRID_SIDE * GRID_SIDE / count).isqrt();
let cell_budget = CELL_BUDGET / count;
let maps: Box<_> =
(0..count).map(|index| ProjectorDepth::build_for_copy(view, mesh, Some(copies.copy(index as u32)), grid_side, cell_budget)).collect();
maps.iter().any(Option::is_some).then_some(Self::Copies(maps))
}
/// Read coverage at the point already transformed into the selected copy's space.
pub(crate) fn cover(&self, copy_index: usize, position: Vec3, hardness: f32) -> f32 {
let depth = match self {
Self::Single(depth) => Some(depth),
Self::Copies(maps) => maps.get(copy_index).and_then(Option::as_ref),
};
depth.map_or(1.0, |depth| depth.cover(position, hardness))
}
}
+13
View File
@@ -0,0 +1,13 @@
use texturecraft_core::{Fill, Projection};
use crate::fill_depth::FillDepth;
/// A fill as a texel samples it: the fill, its projector's depth map when it culls by depth, and whether it covers every texel
#[derive(Clone, Copy)]
pub(crate) struct FillPlace<'f> {
pub fill: &'f Fill,
pub projection: &'f Projection,
pub depth: Option<&'f FillDepth>,
/// Decided once per tile, so a texel never works its coverage out
pub covers_all: bool,
}
+358
View File
@@ -0,0 +1,358 @@
//! A frame on the surface (a placed planar or a warp) as its 3D projection settings show it: where its centre is, how it is turned and how big it is
use texturecraft_core::{Decal, Projection, Projector};
use texturecraft_geom::glam::{EulerRot, Mat3, Quat, Vec3};
use crate::pattern::{decal_axes, mesh_frame, projector_stretch};
/// The shortest frame side a depth is divided by, so a collapsed frame keeps a finite depth
pub const MIN_FRAME_SIDE: f32 = 1e-6;
/// Below this the frame faces nearly straight up or down, so world up gives no upright direction
const MIN_UP_CROSS_SQUARED: f32 = 1e-6;
/// The longer side of a frame of `size`, at least [`MIN_FRAME_SIDE`]: a warp's Projection Depth counts in it
pub fn longer_side(size: [f32; 2]) -> f32 {
size[0].max(size[1]).max(MIN_FRAME_SIDE)
}
/// How far a warp whose frame has `size` reaches in front of and behind it at Projection Depth `depth`, in world units
pub fn warp_reach(size: [f32; 2], depth: f32) -> f32 {
depth * longer_side(size)
}
/// A frame's Offset (its centre in mesh radii from the mesh's centre), Rotation (degrees round X, Y and Z, as a projector turns) and Scale (its width and height, then how far it reaches in front of and behind it, in mesh diagonals)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FramePlacement {
pub offset: [f32; 3],
pub rotation: [f32; 3],
pub scale: [f32; 3],
}
/// Whether moving the projector's scale into the frame preserves culling
pub fn culling_folds(projector: &Projector) -> bool {
let stretch = projector_stretch(projector);
let size = stretch.abs();
let even = size.x == size.y && size.y == size.z;
let facing_preserved = stretch.x.signum() * stretch.y.signum() * stretch.z.signum() > 0.0;
(!projector.depth.on || facing_preserved) && (!projector.backface.on || (even && facing_preserved))
}
/// Fold a placed planar or warp's turn and scale into its frame while preserving crop and culling.
/// See [`culling_folds`] for when a fold would change culling.
pub fn folded(proj: &Projection) -> Option<Projection> {
let (frame, projector) = match proj {
Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => (frame, projector),
_ => return None,
};
if !projector.turns() {
return Some(proj.clone());
}
if !culling_folds(projector) {
return None;
}
let (origin, across, up, _) = decal_axes(frame)?;
let [x, y, z] = projector.rotation.map(f32::to_radians);
let turn = Mat3::from_cols(across, up, across.cross(up)) * Mat3::from_euler(EulerRot::ZYX, z, y, x);
let stretch = projector_stretch(projector);
// A negative scale turns that side over
let (across, up) = (turn.x_axis * stretch.x.signum(), turn.y_axis * stretch.y.signum());
let size = [frame.size[0] * stretch.x.abs(), frame.size[1] * stretch.y.abs()];
let reach = stretch.z.abs();
let new_frame = Decal {
center: origin.to_array(),
normal: across.cross(up).to_array(),
up: up.to_array(),
size,
rotation: 0.0,
offset: [0.0; 2],
depth: frame.depth * reach,
symmetry: frame.symmetry,
flip: frame.flip,
};
let unturned = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector };
let mut out = proj.clone();
match &mut out {
Projection::Planar { placed: Some(placed), projector, .. } => {
*placed = new_frame;
*projector = unturned;
}
Projection::Warp { frame: warp, projector, depth, .. } => {
// Its depth counts in lengths of the frame's longer side
*depth *= reach * longer_side(frame.size) / longer_side(size);
*warp = new_frame;
*projector = unturned;
}
_ => return None,
}
let finite = new_frame.center.iter().chain(&new_frame.normal).chain(&new_frame.up).chain(&new_frame.size).all(|v| v.is_finite());
finite.then_some(out)
}
/// How far frame projection `proj` reaches in front of and behind its frame, in world units (a warp counts its depth in lengths of the longer side)
fn reach(proj: &Projection) -> Option<f32> {
match proj {
Projection::Planar { placed: Some(frame), .. } => Some(frame.depth),
Projection::Warp { frame, depth, .. } => Some(warp_reach(frame.size, *depth)),
_ => None,
}
}
/// Where frame projection `proj` (a placed planar or a warp) sits on a mesh with bounds `bounds`, its projector folded in (None for other projections)
pub fn placement(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<FramePlacement> {
let proj = folded(proj)?;
let frame = proj.frame()?;
let (center, radius) = mesh_frame(bounds);
let (origin, across, up, out) = decal_axes(frame)?;
let (z, y, x) = Quat::from_mat3(&Mat3::from_cols(across, up, out)).to_euler(EulerRot::ZYX);
let diagonal = 2.0 * radius;
let placement = FramePlacement {
offset: ((origin - center) / radius).to_array(),
rotation: [x, y, z].map(f32::to_degrees),
scale: [frame.size[0] / diagonal, frame.size[1] / diagonal, reach(&proj)? / diagonal],
};
let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale);
values.copied().all(f32::is_finite).then_some(placement)
}
/// Frame projection `proj` (a placed planar or a warp) moved to `placement`; its projector's turn and scale are folded in first, its other settings kept (None for other projections or a degenerate placement)
pub fn placed(proj: &Projection, placement: &FramePlacement, bounds: (Vec3, Vec3)) -> Option<Projection> {
let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale);
let [width_scale, height_scale, reach_scale] = placement.scale;
let valid_reach = reach_scale > 0.0 || (reach_scale == 0.0 && matches!(proj, Projection::Warp { .. }));
if !values.copied().all(f32::is_finite) || width_scale <= 0.0 || height_scale <= 0.0 || !valid_reach {
return None;
}
let mut proj = folded(proj)?;
let old = *proj.frame()?;
let (center, radius) = mesh_frame(bounds);
let diagonal = 2.0 * radius;
let [x, y, z] = placement.rotation.map(f32::to_radians);
let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x);
let [width, height, deep] = placement.scale.map(|scale| scale * diagonal);
let frame = Decal {
center: (center + Vec3::from(placement.offset) * radius).to_array(),
normal: turn.z_axis.to_array(),
up: turn.y_axis.to_array(),
size: [width, height],
rotation: 0.0,
offset: [0.0; 2],
depth: deep,
symmetry: old.symmetry,
flip: old.flip,
};
match &mut proj {
Projection::Planar { placed: Some(placed), .. } => *placed = frame,
Projection::Warp { frame: warp, depth, .. } => {
*depth = deep / longer_side([width, height]);
// The warp's own depth is what reaches; the frame's is unused
*warp = Decal { depth: warp.depth, ..frame };
}
_ => return None,
}
Some(proj)
}
/// A frame's turn round its own normal, as seen face on with the world's up (or, looking straight down, the far side) at the top: degrees
pub fn upright_turn(frame: &Decal) -> Option<f32> {
let (_, _, up, out) = decal_axes(frame)?;
let world_up = if out.cross(Vec3::Y).length_squared() > MIN_UP_CROSS_SQUARED { Vec3::Y } else { Vec3::NEG_Z };
let upright = (world_up - out * out.dot(world_up)).try_normalize()?;
let upright_across = upright.cross(out);
let turn = (-up.dot(upright_across)).atan2(up.dot(upright)).to_degrees();
turn.is_finite().then_some(turn)
}
#[cfg(test)]
mod tests {
use texturecraft_core::{Backface, DecalFlip, DecalSymmetry, ShapeCrop, UvTransform};
use texturecraft_geom::glam::Vec2;
use super::*;
use crate::projector_cover::framed_cover;
const BOUNDS: (Vec3, Vec3) = (Vec3::new(-1.0, -2.0, -0.5), Vec3::new(3.0, 1.0, 1.5));
fn frame() -> Decal {
Decal {
center: [0.4, -0.2, 1.3],
normal: [0.2, 0.1, 1.0],
up: [0.0, 1.0, 0.1],
size: [1.2, 0.8],
rotation: 25.0,
offset: [0.1, -0.2],
depth: 0.6,
symmetry: None,
flip: [false; 2],
}
}
fn planar(projector: Projector) -> Projection {
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame()) }
}
fn warp(projector: Projector) -> Projection {
Projection::Warp { frame: frame(), corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]], depth: 0.7, uv: UvTransform::default(), projector }
}
/// The projection's texture coordinates and cover at points through the frame's neighbourhood with varied normals
fn samples(proj: &Projection) -> Vec<Option<(Vec2, f32)>> {
let mut out = Vec::new();
for across in 0..7 {
for up in 0..7 {
for out_of in 0..3 {
let position = Vec3::new(-0.5 + across as f32 * 0.25, -0.8 + up as f32 * 0.2, 0.7 + out_of as f32 * 0.3);
let normal = Vec3::new(0.1 * across as f32 - 0.3, 0.2, 1.0).normalize();
out.push(framed_cover(proj, position, normal, (BOUNDS.0 + BOUNDS.1) * 0.5));
}
}
}
out
}
fn projector_of(proj: &Projection) -> Projector {
match proj {
Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => *projector,
_ => panic!("a frame projection"),
}
}
fn close(a: &[Option<(Vec2, f32)>], b: &[Option<(Vec2, f32)>]) {
assert_eq!(a.len(), b.len());
for (index, (a, b)) in a.iter().zip(b).enumerate() {
match (a, b) {
(Some((uv_a, cover_a)), Some((uv_b, cover_b))) => {
assert!((cover_a - cover_b).abs() < 1e-3, "{index}: cover {cover_a} vs {cover_b}");
assert!(uv_a.distance(*uv_b) < 1e-3, "{index}: {uv_a} vs {uv_b}");
}
(None, None) => {}
_ => panic!("{index}: sampled on one side only: {a:?} vs {b:?}"),
}
}
}
#[test]
fn folding_a_turned_and_evenly_scaled_projector_into_its_frame_lands_the_same() {
let projector = Projector { rotation: [20.0, -35.0, 50.0], scale: [1.7; 3], crop: ShapeCrop::Cropped, ..Projector::default() };
for proj in [planar(projector), warp(projector)] {
let flat = folded(&proj).unwrap();
let Projector { rotation, scale, crop, .. } = projector_of(&flat);
assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed");
close(&samples(&proj), &samples(&flat));
}
let unturned = planar(Projector::default());
assert_eq!(folded(&unturned), Some(unturned), "nothing to fold: unchanged");
assert_eq!(folded(&Projection::default()), None);
}
#[test]
fn depth_culling_prevents_folding_with_the_opposite_facing() {
let mut projector = Projector::depth_culled();
projector.scale[2] = -1.0;
let bounds = (Vec3::NEG_ONE, Vec3::ONE);
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
assert!(folded(&planar(projector)).is_none(), "an existing frame would face the opposite direction");
assert!(crate::axis_frame::placed_from_axis(&axis_planar, bounds).is_none(), "an axis projector would face the opposite direction");
assert!(folded(&planar(Projector::depth_culled())).is_some(), "unit stretch preserves facing");
}
#[test]
fn folding_keeps_what_backface_culling_hides() {
let backface = Backface { on: true, angle: 60.0, hardness: 1.0 };
let square = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [1.0, 1.0], rotation: 0.0, offset: [0.0; 2], ..frame() };
// An oblique normal distinguishes tilt from reflection
let normal = Vec3::new(1.0, 0.0, 1.0).normalize();
let center = (BOUNDS.0 + BOUNDS.1) * 0.5;
let cover = |proj: &Projection| framed_cover(proj, Vec3::ZERO, normal, center).map(|(_, cover)| cover);
for scale in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] {
let projector = Projector { scale, backface, ..Projector::default() };
let proj = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(square) };
match folded(&proj) {
Some(flat) => {
assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed");
close(&samples(&proj), &samples(&flat));
}
None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"),
}
}
assert!(folded(&planar(Projector { scale: [1.7; 3], backface, ..Projector::default() })).is_some(), "an even scale still folds");
}
#[test]
fn a_placement_read_and_written_back_lands_the_same_and_its_fields_move_the_frame() {
let projector = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() };
for proj in [planar(Projector::default()), warp(Projector::default()), planar(projector), warp(projector)] {
let place = placement(&proj, BOUNDS).unwrap();
let back = placed(&proj, &place, BOUNDS).unwrap();
close(&samples(&folded(&proj).unwrap()), &samples(&back));
let again = placement(&back, BOUNDS).unwrap();
for (a, b) in place.offset.iter().chain(&place.rotation).chain(&place.scale).zip(again.offset.iter().chain(&again.rotation).chain(&again.scale)) {
assert!((a - b).abs() < 1e-3, "{place:?} vs {again:?}");
}
let width = folded(&proj).unwrap().frame().unwrap().size[0];
let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap();
assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width");
let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap();
assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre");
}
let place = placement(&planar(Projector::default()), BOUNDS).unwrap();
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size");
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None);
assert_eq!(placement(&Projection::default(), BOUNDS), None);
}
#[test]
fn a_frames_upright_turn_is_its_turn_round_its_normal() {
let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() };
assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3);
flat.rotation = -100.0;
assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3);
let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() };
assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up");
}
#[test]
fn folding_and_placing_keep_a_frames_mirror_copy_and_image_flip() {
let symmetry = Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.2 });
let mirrored = Decal { symmetry, flip: [true, false], ..frame() };
let turned = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() };
for proj in [
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: turned, placed: Some(mirrored) },
Projection::Warp {
frame: mirrored,
corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]],
depth: 0.7,
uv: UvTransform::default(),
projector: turned,
},
] {
let folded = folded(&proj).unwrap();
let moved = placed(&proj, &placement(&proj, BOUNDS).unwrap(), BOUNDS).unwrap();
for frame in [folded.frame().unwrap(), moved.frame().unwrap()] {
assert_eq!((frame.symmetry, frame.flip), (symmetry, [true, false]));
}
}
}
}
+29 -2
View File
@@ -7,33 +7,60 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod axis_frame;
mod baked_maps;
pub mod below;
mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
mod distance_envelope;
mod effect_histogram;
pub mod environment_sh;
pub mod environment_sky;
pub mod eval;
mod fabric;
pub mod fill_copies;
pub mod fill_copy;
mod fill_depth;
mod fill_place;
pub mod frame_placement;
mod fur_lock;
mod held_fields;
mod image_identity;
mod mask_gray;
pub mod mip_level;
mod organic;
pub mod pattern;
mod pattern_context;
pub mod projector_cover;
pub mod projector_depth;
mod projector_depth_cache;
pub mod projector_view;
mod shape_distance;
mod slope_texel;
mod soft_box;
pub mod solo;
pub mod store;
pub mod thumb;
pub mod tile_length;
mod tile_pattern;
mod tile_random_stream;
mod timber;
pub mod warp;
mod warp_source_sample;
mod warp_texel;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, kinds_for, tile_bytes};
pub use effect_histogram::EffectHistogram;
pub use eval::{
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles,
effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached,
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles,
stack_reads_neighbours,
};
pub use mask_gray::MaskGray;
pub use pattern_context::PatternContext;
pub use projector_depth_cache::ProjectorDepthCache;
pub use solo::solo_project;
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
+62
View File
@@ -0,0 +1,62 @@
//! The gray a mask stroke paints
use std::sync::Arc;
use texturecraft_core::{Filtering, Sampling, UvWrap, lum};
use crate::ImageRes;
/// The gray a mask stroke paints: one value, or the gray of an image laid once over the texture by its UVs
#[derive(Clone, Debug, PartialEq)]
pub enum MaskGray {
Value(f32),
/// Image resource `name`, read as its gray like a mask fill reads an image
Image {
name: String,
image: Arc<ImageRes>,
},
}
impl MaskGray {
/// The gray painted at texel (`x`, `y`) of a `width` × `height` texture (the image read at the texel's centre)
pub fn at(&self, x: u32, y: u32, (width, height): (u32, u32)) -> f32 {
match self {
MaskGray::Value(value) => value.clamp(0.0, 1.0),
MaskGray::Image { image, .. } => {
let u = (x as f32 + 0.5) / width.max(1) as f32;
let v = (y as f32 + 0.5) / height.max(1) as f32;
let sampling = Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::None, ..Sampling::SAVED_BEFORE };
let [r, g, b, _] = image.sample_filtered(u, v, sampling, 1.0);
lum([r, g, b]).clamp(0.0, 1.0)
}
}
}
/// The image resource painted, None for one value
pub fn image_name(&self) -> Option<&str> {
match self {
MaskGray::Value(_) => None,
MaskGray::Image { name, .. } => Some(name),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_mask_image_does_not_wrap_at_texture_edges() {
let black = [0.0, 0.0, 0.0, 1.0];
let white = [1.0; 4];
let image = Arc::new(ImageRes::new(2, 2, vec![black, white, white, white], false));
let brush = MaskGray::Image { name: "brush.png".to_owned(), image };
let near_corner = brush.at(0, 0, (4, 4));
let inside = brush.at(1, 1, (4, 4));
let far_corner = brush.at(3, 3, (4, 4));
assert!(near_corner < 0.01, "opposite edges must leave the black corner black, got {near_corner}");
assert!(near_corner < inside && inside < far_corner, "sampling between image texels stays bilinear");
}
}
+103
View File
@@ -0,0 +1,103 @@
//! One halved copy of an image resource, read by high-quality bilinear filtering when an image is shrunk
use crate::store::texel_of;
/// One halved copy of an image (box-filtered; see `halve` for its edges)
#[derive(Clone, Debug, PartialEq)]
pub struct MipLevel {
pub width: u32,
pub height: u32,
pub rgba: Vec<[f32; 4]>,
}
/// Share of each of the 2 × 2 texels in a halved texel
const TEXEL_SHARE: f32 = 0.25;
/// A halved interval can overlap at most three source texels on each axis
const AREA_FILTER_ROWS: usize = 3;
impl MipLevel {
/// Downsample the whole image by area, including odd trailing rows and columns.
pub(crate) fn halve(rgba: &[[f32; 4]], width: u32, height: u32) -> MipLevel {
Self::halve_with(rgba, width, height, None::<fn([f32; 4]) -> [f32; 4]>)
}
/// Decode stored texels before averaging the first level of an sRGB color chain.
pub(crate) fn halve_with(rgba: &[[f32; 4]], width: u32, height: u32, decode: Option<impl Fn([f32; 4]) -> [f32; 4] + Copy>) -> MipLevel {
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
let mut halved = Vec::with_capacity(w as usize * h as usize);
if (width <= 1 || width.is_multiple_of(2)) && (height <= 1 || height.is_multiple_of(2)) {
for y in 0..i64::from(h) {
for x in 0..i64::from(w) {
let mut sum = [0.0f32; 4];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let stored = texel_of(rgba, width, height, x * 2 + dx, y * 2 + dy, (true, true));
let texel = decode.map_or(stored, |decode| decode(stored));
for (total, value) in sum.iter_mut().zip(texel) {
*total += value * TEXEL_SHARE;
}
}
halved.push(sum);
}
}
} else {
let row_stride = u64::from(width.max(1));
let read = |row_start, source_x| {
let index = usize::try_from(row_start + source_x).ok();
index.and_then(|index| rgba.get(index)).copied().unwrap_or_default()
};
let mut decoded_rows = decode.map(|_| std::array::from_fn::<_, AREA_FILTER_ROWS, _>(|_| (u64::MAX, Vec::with_capacity(row_stride as usize))));
for y in 0..h {
let source_rows = source_weights(y, height, h);
if let Some((decode, rows)) = decode.zip(decoded_rows.as_mut()) {
// Keep decoded rows for adjacent output intervals that share their texels
for (source_y, _) in source_rows.clone() {
let (row, texels) = &mut rows[source_y as usize % AREA_FILTER_ROWS];
if *row != source_y {
let row_start = source_y * row_stride;
texels.clear();
texels.extend((0..row_stride).map(|source_x| decode(read(row_start, source_x))));
*row = source_y;
}
}
}
for x in 0..w {
let source_columns = source_weights(x, width, w);
let mut sum = [0.0; 4];
for (source_y, vertical_weight) in source_rows.clone() {
let row_start = source_y * row_stride;
let row = decoded_rows.as_ref().map(|rows| &rows[source_y as usize % AREA_FILTER_ROWS].1);
for (source_x, horizontal_weight) in source_columns.clone() {
let texel = row.map_or_else(|| read(row_start, source_x), |row| row[source_x as usize]);
let weight = vertical_weight * horizontal_weight;
for (total, value) in sum.iter_mut().zip(texel) {
*total += value * weight;
}
}
}
halved.push(sum);
}
}
}
MipLevel { width: w, height: h, rgba: halved }
}
}
/// Source texels intersecting one output interval and their fractional coverage.
fn source_weights(index: u32, source_size: u32, output_size: u32) -> impl Iterator<Item = (u64, f32)> + Clone {
let source = u64::from(source_size.max(1));
let output = u64::from(output_size);
let inverse_source = 1.0 / source as f32;
// Scale both intervals to integer boundaries for exact overlap at either edge
let start = u64::from(index) * source;
let end = start + source;
(start / output..end.div_ceil(output)).map(move |texel| {
let overlap = end.min((texel + 1) * output) - start.max(texel * output);
(texel, overlap as f32 * inverse_source)
})
}
+372 -135
View File
@@ -1,7 +1,7 @@
//! Procedural patterns and projections.
use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_core::{Decal, FULL_TURN_DEGREES, Procedural, ProceduralKind, Projection, Projector, UvTransform};
use texturecraft_geom::glam::{EulerRot, Mat3, Vec2, Vec3};
use texturecraft_texel::noise;
use crate::pattern_context::PatternContext;
@@ -380,13 +380,21 @@ const TRIPLANAR_SKIP: f32 = 1.0 / 131_072.0;
/// Normalized triplanar blend weights (YZ, XZ, XY planes) for normal `nrm`; planes too light
/// to change a 0..1 value scaled by `gain` afterwards weigh 0 (see [`TRIPLANAR_SKIP`]).
fn triplanar_weights(nrm: Vec3, sharpness: f32, gain: f32) -> Vec3 {
let weights = sharpen(nrm.abs(), sharpness);
let weights = weights / (weights.x + weights.y + weights.z).max(1e-6);
let weights = normalized_triplanar_weights(nrm, sharpness);
let skip_threshold = TRIPLANAR_SKIP / gain.max(1.0);
let retained = Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights);
Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights)
}
// Preserve the blend if thresholding would discard every plane
if retained == Vec3::ZERO { weights } else { retained }
fn normalized_triplanar_weights(normal: Vec3, sharpness: f32) -> Vec3 {
let normal = normal.abs();
let strongest = normal.max_element();
if strongest == 0.0 || !normal.is_finite() {
return Vec3::ZERO;
}
// Keep the strongest weight at one so sharp diagonal blends cannot underflow
let weights = sharpen(normal / strongest, sharpness);
weights / weights.element_sum()
}
fn shape(pattern: &Procedural, value: f32) -> f32 {
@@ -394,6 +402,129 @@ fn shape(pattern: &Procedural, value: f32) -> f32 {
if pattern.invert { 1.0 - adjusted } else { adjusted }
}
/// `point` turned by `rotation` degrees, scaled by `tiling` and moved by `offset`, as UV transformations place it
fn place(point: Vec2, tiling: Vec2, rotation: f32, offset: Vec2) -> Vec2 {
placement(tiling, rotation, offset)(point)
}
/// [`place`] with its turn's sine and cosine worked out once, for a projection that places several points
pub(crate) fn placement(tiling: Vec2, rotation: f32, offset: Vec2) -> impl Fn(Vec2) -> Vec2 {
let (sin, cos) = rotation.to_radians().sin_cos();
move |point| Vec2::new(point.x * cos - point.y * sin, point.x * sin + point.y * cos) * tiling + offset
}
/// `point` placed as a 3D projection's UV transformation `uv` lays its image
fn place_uv(point: Vec2, uv: &UvTransform) -> Vec2 {
uv_placement(uv)(point)
}
/// [`place_uv`] worked out once for every point a projection places
fn uv_placement(uv: &UvTransform) -> impl Fn(Vec2) -> Vec2 {
placement(Vec2::from(uv.tiling), uv.rotation, Vec2::from(uv.offset))
}
/// 0..1 around a cylindrical projection's axis (`depth` over `across`), over an arc of `angle` degrees centred on the front
fn around(across: f32, depth: f32, angle: f32) -> f32 {
let turn = depth.atan2(across) / std::f32::consts::TAU + 0.5;
// A full turn reads the turn untouched, as projects saved before the angle existed did, bit for bit
if angle == FULL_TURN_DEGREES { turn } else { (turn - 0.5) * FULL_TURN_DEGREES / angle.max(MIN_CYLINDER_ANGLE) + 0.5 }
}
/// Narrowest arc in degrees a cylindrical projection wraps its image round, so a zero angle never divides by zero
pub const MIN_CYLINDER_ANGLE: f32 = *Projection::CYLINDER_ANGLE_RANGE.start();
/// How many pattern tiles a procedural lays round and down a spherical projection, so its cells stay near square
const SPHERE_PATTERN_TILES: Vec2 = Vec2::new(4.0, 2.0);
/// How many pattern tiles a procedural lays round a cylindrical projection's axis
const CYLINDER_PATTERN_TILES: f32 = 4.0;
/// Smallest frame side or depth (world units), so a flat frame never divides by zero
const MIN_FRAME_EXTENT: f32 = 1e-6;
/// Where `coords` lies round a spherical projection: 0..1 round its pole axis and down from its top
fn spherical_uv(projector: &Projector, offset: &[f32; 3], coords: &Coords) -> Vec2 {
let direction = (projector_local(projector, coords).pos + Vec3::from(*offset)).try_normalize().unwrap_or(Vec3::Y);
let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5;
let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
Vec2::new(u, v)
}
/// The axis index (0 X, 1 Y, 2 Z) a cylindrical projection's stored `axis` wraps round: any value but X or Z reads as Y
pub fn cylinder_axis_index(axis: u8) -> usize {
match axis {
0 => 0,
2 => 2,
_ => 1,
}
}
/// Where `coords` lies for a cylindrical projection round `axis`: 0..1 round the axis over `angle` degrees, and its height along the axis
fn cylinder_coords(axis: u8, projector: &Projector, offset: &[f32; 3], angle: f32, coords: &Coords) -> (f32, f32) {
let point = projector_local(projector, coords).pos + Vec3::from(*offset);
let (across, height, depth) = match cylinder_axis_index(axis) {
0 => (point.y, point.x, point.z),
2 => (point.x, point.z, point.y),
_ => (point.x, point.y, point.z),
};
(around(across, depth, angle), height)
}
/// Smallest mesh radius projections measure in, so a flat or empty mesh never divides by zero
const MIN_MESH_RADIUS: f32 = 1e-4;
/// Nearest to zero a projection scale or stretch gets, so it never divides by zero
const MIN_STRETCH: f32 = 1e-6;
/// The mesh's centre and its radius (half the diagonal) from its bounds
pub fn mesh_frame((lo, hi): (Vec3, Vec3)) -> (Vec3, f32) {
((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(MIN_MESH_RADIUS))
}
/// `value` kept at least [`MIN_STRETCH`] from zero, on its own side
pub fn nonzero_stretch(value: f32) -> f32 {
value.signum() * value.abs().max(MIN_STRETCH)
}
/// A projector's per-axis scale with no axis at zero, each keeping its sign
pub fn projector_stretch(projector: &Projector) -> Vec3 {
Vec3::from(projector.scale).map(nonzero_stretch)
}
/// The middle of a frame's 0..1 texture coordinates: a frame's image turns round it
pub const FRAME_UV_CENTER: Vec2 = Vec2::splat(0.5);
/// `point` (0..1 across and down a frame) placed as `uv` lays a frame's image: turned round the frame's centre, then tiled and moved from its top left
pub fn place_frame_uv(point: Vec2, uv: &UvTransform) -> Vec2 {
// An unplaced image reads `point` itself, bit for bit as decals saved before image placement did
if *uv == UvTransform::default() {
return point;
}
let tiling = Vec2::from(uv.tiling);
place(point - FRAME_UV_CENTER, tiling, uv.rotation, Vec2::from(uv.offset)) + FRAME_UV_CENTER * tiling
}
/// The image placement a frame needs to lay images exactly as `uv` does from the top left (a frame turns its image round its centre)
pub fn frame_uv_from_corner(uv: &UvTransform) -> UvTransform {
let offset = place_uv(FRAME_UV_CENTER, uv) - FRAME_UV_CENTER * Vec2::from(uv.tiling);
UvTransform { offset: offset.to_array(), ..*uv }
}
/// `coords` inside a projector turned and scaled by `projector`; the default projector returns `coords` unchanged
pub fn projector_local(projector: &Projector, coords: &Coords) -> Coords {
if !projector.turns() {
return *coords;
}
let [x, y, z] = projector.rotation.map(f32::to_radians);
let to_local = Mat3::from_euler(EulerRot::ZYX, z, y, x).transpose();
let scale = projector_stretch(projector);
let nrm = (to_local * coords.nrm * scale).try_normalize().unwrap_or(coords.nrm);
Coords { pos: to_local * coords.pos / scale, nrm, ..*coords }
}
/// Evaluate a procedural through a projection, at full resolution and without images
pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 {
procedural_in(pattern, projection, coords, &PatternContext::default())
@@ -402,51 +533,42 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords
/// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads
pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 {
let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE);
let sample = |point: Vec3| plane_value(pattern, point, context);
let value = match projection {
Projection::Uv { scale, rotation, offset } => {
let (sn, cs) = rotation.to_radians().sin_cos();
let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
// Evaluate two-dimensional patterns on a slice of the volume
sample((uv * pattern_scale).extend(0.0))
}
Projection::Triplanar { scale, sharpness, offset } => {
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
// Evaluate two-dimensional patterns on a slice of the volume
let flat = |point: Vec2| plane_value(pattern, point.extend(0.0), context);
let value = match projection {
Projection::UvTile => flat((coords.uv - coords.uv.floor()) * pattern_scale),
Projection::Uv { scale, rotation, offset } => flat(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset)) * pattern_scale),
Projection::Triplanar { scale, sharpness, offset, uv, projector } => {
let coords = &projector_local(projector, coords);
let point = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
let place_plane = uv_placement(uv);
// Shape scales the blend by the contrast
let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast);
let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))];
planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum()
}
Projection::Planar { scale, axis, offset } => {
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
let q = match axis {
0 => Vec3::new(p.z, p.y, 0.0),
1 => Vec3::new(p.x, p.z, 0.0),
_ => Vec3::new(p.x, p.y, 0.0),
};
sample(q)
}
Projection::Spherical { scale } => {
let d = coords.pos.try_normalize().unwrap_or(Vec3::Y);
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale)
}
Projection::Cylindrical { scale, axis } => {
let p = coords.pos;
let (a, h, b) = match axis {
0 => (p.y, p.x, p.z),
2 => (p.x, p.z, p.y),
_ => (p.x, p.y, p.z),
};
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale)
let weights = triplanar_weights(coords.nrm, *sharpness, pattern.contrast);
let planes = [(weights.x, Vec2::new(point.z, point.y)), (weights.y, Vec2::new(point.x, point.z)), (weights.z, Vec2::new(point.x, point.y))];
planes.into_iter().filter(|(weight, _)| *weight > 0.0).map(|(weight, plane)| flat(place_plane(plane)) * weight).sum()
}
// The decal already supplied coordinates in its local frame
Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)),
// The coordinates are already in the placed or warped frame (see [`placed_uv`] and [`crate::warp::warp_uv`])
Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => flat(place_frame_uv(coords.uv, uv) * pattern_scale),
Projection::Planar { scale, axis, offset, uv, projector, .. } => {
let point = projector_local(projector, coords).pos * *scale * pattern_scale + Vec3::from(*offset);
let plane = match axis {
0 => Vec2::new(point.z, point.y),
1 => Vec2::new(point.x, point.z),
_ => Vec2::new(point.x, point.y),
};
flat(place_uv(plane, uv))
}
Projection::Spherical { scale, uv, offset, projector } => {
let sphere = spherical_uv(projector, offset, coords);
flat(place_uv(sphere * SPHERE_PATTERN_TILES * *scale * pattern_scale, uv))
}
Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => {
let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords);
flat(place_uv(Vec2::new(around_axis * CYLINDER_PATTERN_TILES, height) * *scale * pattern_scale, uv))
}
};
shape(pattern, value)
@@ -476,7 +598,7 @@ fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f
let base = grid.floor();
let fraction = grid - base;
let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context);
let at = |across: f32, down: f32| pattern_value(pattern, ((base + Vec2::new(across, down) + 0.5) / cells).extend(point.z), context);
let top_left = at(0.0, 0.0);
let bottom_left = at(0.0, 1.0);
let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x;
@@ -497,45 +619,36 @@ fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) ->
pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] {
let one = |uv: Vec2| [(uv, 1.0), (Vec2::ZERO, 0.0), (Vec2::ZERO, 0.0)];
match projection {
Projection::Uv { scale, rotation, offset } => {
let (sn, cs) = rotation.to_radians().sin_cos();
let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
one(uv)
}
Projection::Triplanar { scale, sharpness, offset } => {
let p = coords.pos * *scale + Vec3::from(*offset);
Projection::UvTile => one(coords.uv - coords.uv.floor()),
Projection::Uv { scale, rotation, offset } => one(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset))),
Projection::Triplanar { scale, sharpness, offset, uv, projector } => {
let coords = &projector_local(projector, coords);
let point = coords.pos * *scale + Vec3::from(*offset);
let place_plane = uv_placement(uv);
// Float images can exceed 1, so even a tiny plane weight can carry visible detail
let weights = coords.nrm.abs().powf(sharpness.max(1.0));
let weights = weights / (weights.x + weights.y + weights.z).max(1e-6);
[(Vec2::new(p.z, -p.y), weights.x), (Vec2::new(p.x, p.z), weights.y), (Vec2::new(p.x, -p.y), weights.z)]
let weights = normalized_triplanar_weights(coords.nrm, *sharpness);
[
(place_plane(Vec2::new(point.z, -point.y)), weights.x),
(place_plane(Vec2::new(point.x, point.z)), weights.y),
(place_plane(Vec2::new(point.x, -point.y)), weights.z),
]
}
Projection::Planar { scale, axis, offset } => {
let p = coords.pos * *scale + Vec3::from(*offset);
let q = match axis {
0 => Vec2::new(p.z, -p.y),
1 => Vec2::new(p.x, p.z),
_ => Vec2::new(p.x, -p.y),
Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => one(place_frame_uv(coords.uv, uv)),
Projection::Planar { scale, axis, offset, uv, projector, .. } => {
let point = projector_local(projector, coords).pos * *scale + Vec3::from(*offset);
let plane = match axis {
0 => Vec2::new(point.z, -point.y),
1 => Vec2::new(point.x, point.z),
_ => Vec2::new(point.x, -point.y),
};
one(q * 0.5 + Vec2::splat(0.5))
one(place_uv(plane * 0.5 + Vec2::splat(0.5), uv))
}
Projection::Spherical { scale } => {
let d = coords.pos.try_normalize().unwrap_or(Vec3::Y);
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
one(Vec2::new(u, v) * *scale)
Projection::Spherical { scale, uv, offset, projector } => one(place_uv(spherical_uv(projector, offset, coords) * *scale, uv)),
Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => {
let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords);
one(place_uv(Vec2::new(around_axis, 0.5 - height * 0.5) * *scale, uv))
}
Projection::Cylindrical { scale, axis } => {
let p = coords.pos;
let (a, h, b) = match axis {
0 => (p.y, p.x, p.z),
2 => (p.x, p.z, p.y),
_ => (p.x, p.y, p.z),
};
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
one(Vec2::new(u, 0.5 - h * 0.5) * *scale)
}
Projection::Decal(_) => one(coords.uv),
}
}
@@ -561,50 +674,74 @@ pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> {
Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh])
}
/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates
/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its
/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit.
pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
let (o, r, u, n) = decal_axes(d)?;
let facing = nrm.dot(n);
let q = p - o;
let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs());
let depth = d.depth.max(1e-6);
if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) {
return None;
/// World point `point` in frame `frame` turned and scaled by `projector`: across and up in frame sizes, out along its normal in world units
pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option<Vec3> {
let (origin, right, up, normal) = decal_axes(frame)?;
let from_origin = point - origin;
let mut local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal));
if projector.turns() {
local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos;
}
let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz));
Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w))
frame_position(frame, local)
}
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame.
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
}
/// Read the position and facing of one sample when a placed frame culls by angle
pub(crate) fn frame_sample(frame: &Decal, projector: &Projector, position: Vec3, surface_normal: Vec3) -> Option<(Vec3, f32)> {
let (origin, right, up, normal) = decal_axes(frame)?;
let from_origin = position - origin;
let local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal));
/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the
/// point more. The copy is the decal reflected through the plane across `center` (the mesh
/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked.
pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let direct = decal_uv(d, p, nrm);
let Some(symmetry) = d.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
mirrored_normal[axis] = -nrm[axis];
let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| {
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, w)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
if !projector.turns() {
return Some((frame_position(frame, local)?, surface_normal.dot(normal)));
}
let normal = Vec3::new(surface_normal.dot(right), surface_normal.dot(up), surface_normal.dot(normal));
let sample = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: normal });
Some((frame_position(frame, sample.pos)?, sample.nrm.z))
}
fn frame_position(frame: &Decal, local: Vec3) -> Option<Vec3> {
let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z);
local.is_finite().then_some(local)
}
/// How squarely a surface with normal `nrm` faces frame `frame` turned by `projector` (the cosine of the turn)
pub fn frame_facing(frame: &Decal, projector: &Projector, nrm: Vec3) -> f32 {
let Some((_, right, up, normal)) = decal_axes(frame) else { return 0.0 };
if !projector.turns() {
return nrm.dot(normal);
}
let turned = Vec3::new(nrm.dot(right), nrm.dot(up), nrm.dot(normal));
projector_local(projector, &Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: turned }).nrm.z
}
/// Texture coordinates (v down) of a point at `local` in its frame (see [`frame_local`])
pub fn placed_uv(local: Vec3) -> Vec2 {
Vec2::new(local.x + 0.5, 0.5 - local.y)
}
/// How much frame `frame` covers a point at `local` when cropped to its shape: 0 outside the frame or past its depth, fading near the depth
pub fn frame_crop(frame: &Decal, local: Vec3) -> f32 {
if local.x.abs() > 0.5 || local.y.abs() > 0.5 {
return 0.0;
}
depth_fade(local.z, frame.depth)
}
/// Where a frame's depth fade starts, as a share of its depth
pub const DEPTH_FADE_START: f32 = 0.75;
/// How much a frame reaching `depth` in front of and behind it covers a point `z` out from it: 0 past the depth, fading near it
pub fn depth_fade(z: f32, depth: f32) -> f32 {
let (distance, depth) = (z.abs(), depth.max(MIN_FRAME_EXTENT));
if distance > depth {
return 0.0;
}
1.0 - smoothstep(DEPTH_FADE_START * depth, depth, distance)
}
/// World-space noise used by generators (seamless across UV islands).
@@ -637,20 +774,102 @@ mod tests {
// Coarse reads are exact at cell centers and blend between them
assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5);
let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5;
assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse));
assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows");
}
/// A decal saved before image placement reads its frame coordinates bit for bit as it did: its image at them, its procedural at them times the pattern scale
#[test]
fn an_unplaced_decal_reads_its_frame_coordinates_bit_for_bit() {
let frame = Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [1.0; 2],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let decal = Projection::decal(frame);
let pattern = Procedural { scale: 3.0, ..Procedural::new(ProceduralKind::Gradient) };
for across in 0..=1000 {
for down in [0.0, 0.1, 0.37, 1.0] {
let uv = Vec2::new(across as f32 / 1000.0, down);
let coords = Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z };
assert_eq!(image_samples(&decal, &coords)[0].0, uv, "image at {uv}");
let expected = shape(&pattern, raw(pattern.kind, (uv * pattern.scale).extend(0.0), pattern.seed));
assert_eq!(procedural(&pattern, &decal, &coords).to_bits(), expected.to_bits(), "procedural at {uv}");
}
}
}
/// A frame's image turns round the frame's centre: the centre reads the same texel at any Rotation, and an unturned image reads exactly as before for any Tiling and Offset
#[test]
fn a_frame_image_turns_round_the_frame_centre() {
let frame = Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [1.0; 2],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let at = |uv: Vec2| Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z };
let sample = |rotation: f32, tiling: [f32; 2], offset: [f32; 2], uv: Vec2| {
image_samples(
&Projection::Warp {
frame,
corners: Projection::FRAME_CORNERS,
depth: 0.1,
uv: UvTransform { tiling, rotation, offset },
projector: Projector::default(),
},
&at(uv),
)[0]
.0
};
for rotation in [37.0, 90.0, 180.0] {
let center = sample(rotation, [1.0; 2], [0.0; 2], FRAME_UV_CENTER);
assert!((center - FRAME_UV_CENTER).length() < 1e-5, "{rotation}°: the centre stays put, not swung round the top left: {center}");
}
let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO);
assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}");
let placed = Projection::Planar {
scale: 1.0,
axis: 2,
offset: [0.0; 3],
uv: UvTransform { rotation: 90.0, ..UvTransform::default() },
projector: Projector::default(),
placed: Some(frame),
};
assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way");
for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] {
let before = uv * Vec2::from(tiling) + Vec2::from(offset);
assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before");
}
}
#[test]
fn every_pattern_and_projection_stays_in_range() {
let projections = [
Projection::default(),
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] },
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] },
Projection::Spherical { scale: 1.0 },
Projection::Cylindrical { scale: 1.0, axis: 1 },
Projection::Decal(Decal {
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() },
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: Default::default(), projector: Default::default(), placed: None },
Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() },
Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES },
Projection::decal(Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
@@ -662,18 +881,16 @@ mod tests {
flip: [false; 2],
}),
];
for kind in ProceduralKind::ALL {
let pattern = Procedural::new(kind);
for projection in &projections {
for i in 0..50 {
let t = i as f32 * 0.13;
for index in 0..50 {
let position = index as f32 * 0.13;
let coords = Coords {
uv: Vec2::new(t.fract(), (t * 0.7).fract()),
pos: Vec3::new(t.sin(), t.cos(), t * 0.1),
uv: Vec2::new(position.fract(), (position * 0.7).fract()),
pos: Vec3::new(position.sin(), position.cos(), position * 0.1),
nrm: Vec3::new(0.3, 0.9, 0.1).normalize(),
};
let value = procedural(&pattern, projection, &coords);
assert!((0.0..=1.0).contains(&value), "{kind:?} {projection:?} {value}");
@@ -702,7 +919,8 @@ mod tests {
for contrast in [1.0, 4.0, 16.0] {
let pattern = Procedural { contrast, ..Procedural::new(kind) };
for sharpness in [1.0, 4.0, 8.0, 16.0] {
let projection = Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] };
let projection =
Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
for index in 0..400 {
// Cover axis aligned and oblique normals at varied positions
let position = index as f32 / 400.0;
@@ -715,6 +933,7 @@ mod tests {
}
assert!(largest_difference < 1.0 / 65535.0, "worst difference {largest_difference}");
let near_axis = triplanar_weights(Vec3::new(0.2, 1.0, 0.1).normalize(), 8.0, 1.0);
assert_eq!((near_axis.x, near_axis.z), (0.0, 0.0), "{near_axis}");
@@ -722,18 +941,30 @@ mod tests {
let oblique = triplanar_weights(Vec3::ONE.normalize(), 8.0, 16.0);
assert!((oblique - Vec3::splat(1.0 / 3.0)).abs().max_element() < 1e-6, "{oblique}");
// Tiny weights must survive together when their sum exceeds a u16 step
for sharpness in [47.0, 64.0] {
let diagonal = triplanar_weights(Vec3::ONE.normalize(), sharpness, 1.0);
assert!(diagonal.min_element() > 0.0, "sharpness {sharpness}: {diagonal}");
assert!(diagonal.abs_diff_eq(Vec3::splat(1.0 / 3.0), 1e-6), "sharpness {sharpness}: {diagonal}");
}
}
#[test]
fn triplanar_image_hardness_preserves_diagonal_coverage() {
let coords = Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: Vec3::new(1.0, 0.95, 0.90).normalize() };
let projection =
|sharpness| Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
let soft = image_samples(&projection(1.0), &coords).map(|(_, weight)| weight);
let hard = image_samples(&projection(64.0), &coords).map(|(_, weight)| weight);
assert!((hard.into_iter().sum::<f32>() - 1.0).abs() < 1e-6, "{hard:?}");
assert!(hard[0] > soft[0] && hard[1] < soft[1] && hard[2] < soft[2], "{soft:?} {hard:?}");
}
#[test]
fn triplanar_image_sampling_preserves_bright_float_pixels() {
let image = crate::ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], srgb: false };
let image = crate::ImageRes::new(2, 2, vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], false);
let coords = Coords { uv: Vec2::ZERO, pos: Vec3::new(0.25, 0.25, 0.75), nrm: Vec3::new(0.2, 1.0, 0.1).normalize() };
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] };
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
let weights = coords.nrm.abs().powf(8.0);
let expected = 100_000.0 * weights.x / (weights.x + weights.y + weights.z);
@@ -761,6 +992,12 @@ mod tests {
}
}
/// Where frame `frame`'s planar projection lands at `point` facing `nrm`, None where it does not cover
fn decal_uv(frame: &Decal, point: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
let Projection::Planar { projector, .. } = Projection::decal(*frame) else { return None };
crate::projector_cover::placed_cover(frame, &projector, point, nrm).filter(|(_, cover)| *cover > 0.0)
}
#[test]
fn decals_cover_their_frame_facing_them() {
let d = Decal {
+288
View File
@@ -0,0 +1,288 @@
//! How much of a texel a 3D projection reaches: its shape crop and its backface culling
use texturecraft_core::{Backface, Decal, DecalFlip, Projection, Projector, ShapeCrop};
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::frame_placement::warp_reach;
use crate::organic::smoothstep;
use crate::pattern::{Coords, depth_fade, frame_crop, frame_local, frame_sample, placed_uv, projector_local};
use crate::warp::warp_uv;
/// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out
const MIN_AXIS_DISTANCE: f32 = 1e-6;
/// The turn (in cosine) over which backface culling fades at hardness 0
const BACKFACE_FADE: f32 = 0.6;
/// The shape crop and backface culling [`projector_cover`] applies, None where it lets every texel through
fn cropping_projector(proj: &Projection) -> Option<&Projector> {
let projector = match proj {
Projection::Triplanar { projector, .. }
| Projection::Planar { projector, .. }
| Projection::Spherical { projector, .. }
| Projection::Cylindrical { projector, .. } => projector,
// Framed on the surface: see [`framed_cover`]
Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None,
};
Some(projector).filter(|projector| projector.crop != ShapeCrop::ExtendsOutside || projector.backface.on)
}
/// Whether [`projector_cover`] is 1 on every texel, so it needs no texel's place
pub fn projector_covers_all(proj: &Projection) -> bool {
cropping_projector(proj).is_none()
}
/// How much of the texel at `coords` the projection reaches through its shape crop and backface culling; not for placed planars or warps (see [`framed_cover`])
pub fn projector_cover(proj: &Projection, coords: &Coords) -> f32 {
let Some(projector) = cropping_projector(proj) else { return 1.0 };
let local = projector_local(projector, coords);
let (inside, facing) = match proj {
Projection::Triplanar { .. } => (local.pos.abs().max_element() <= 1.0, None),
Projection::Planar { scale, axis, offset, .. } => {
let scaled = local.pos * *scale + Vec3::from(*offset);
// The frame across the axis, and the side the image reads the right way round from
let (frame, facing) = match axis {
0 => (scaled.z.abs().max(scaled.y.abs()), -local.nrm.x),
1 => (scaled.x.abs().max(scaled.z.abs()), local.nrm.y),
_ => (scaled.x.abs().max(scaled.y.abs()), local.nrm.z),
};
(frame <= 1.0, Some(facing))
}
Projection::Spherical { offset, .. } => ((local.pos + Vec3::from(*offset)).length() <= 1.0, None),
Projection::Cylindrical { axis, offset, .. } => {
let position = local.pos + Vec3::from(*offset);
let normal = local.nrm;
let ((across, height, depth), (normal_across, normal_depth)) = match axis {
0 => ((position.y, position.x, position.z), (normal.y, normal.z)),
2 => ((position.x, position.z, position.y), (normal.x, normal.y)),
_ => ((position.x, position.y, position.z), (normal.x, normal.z)),
};
let radius = across.hypot(depth);
let outward = if radius > MIN_AXIS_DISTANCE { (normal_across * across + normal_depth * depth) / radius } else { 1.0 };
(radius <= 1.0 && height.abs() <= 1.0, Some(outward))
}
Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => (true, None),
};
if projector.crop == ShapeCrop::Cropped && !inside {
return 0.0;
}
match facing {
Some(facing) if projector.backface.on => backface_cover(&projector.backface, facing),
_ => 1.0,
}
}
/// How much a face turned `facing` (the cosine of its turn from the projection) keeps
pub fn backface_cover(backface: &Backface, facing: f32) -> f32 {
// A hand-edited NaN angle or hardness keeps the layer visible rather than making its texels NaN
if !(backface.angle.is_finite() && backface.hardness.is_finite()) {
return 1.0;
}
// cos(angle) as sin(90 - angle): exactly 0 at 90 degrees
let threshold = (90.0 - backface.angle).to_radians().sin();
let width = (1.0 - backface.hardness.clamp(0.0, 1.0)) * BACKFACE_FADE;
if width <= f32::EPSILON {
return f32::from(u8::from(facing > threshold));
}
smoothstep(threshold, threshold + width, facing)
}
/// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate)
pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
let (local, mut cover) = if projector.backface.on {
let (local, facing) = frame_sample(frame, projector, p, nrm)?;
(local, backface_cover(&projector.backface, facing))
} else {
(frame_local(frame, projector, p)?, 1.0)
};
if projector.crop == ShapeCrop::Cropped {
cover *= frame_crop(frame, local);
}
Some((flip_uv(placed_uv(local), frame.flip), cover))
}
/// [`placed_cover`] for a frame with a mirrored copy: whichever of the frame and its copy covers the point more. The copy is the frame reflected through the plane `offset` away from `center` (the mesh center) on the symmetry axis, its image flipped as asked
pub fn placed_cover_symmetric(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let direct = placed_cover(frame, projector, p, nrm);
let Some(symmetry) = frame.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
mirrored_normal[axis] = -nrm[axis];
let mirrored = placed_cover(frame, projector, mirrored_position, mirrored_normal).map(|(uv, cover)| {
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, cover)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
}
}
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
}
/// A projection from a frame on the surface (a placed planar or a warp) at world point `p` with normal `nrm`, `center` the mesh center a placed planar's mirrored copy reflects across: its texture coordinates and how much it covers there (None for other projections, a degenerate frame or where nothing lands)
pub fn framed_cover(proj: &Projection, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
match proj {
Projection::Planar { projector, placed: Some(frame), .. } => placed_cover_symmetric(frame, projector, p, nrm, center),
Projection::Warp { frame, corners, depth, projector, .. } => warp_cover(frame, corners, *depth, projector, p),
_ => None,
}
}
/// A warp projection at world point `p`: its texture coordinates in the quad its corners make, and, cropped to its shape, how much of the quad and of its Projection Depth (in lengths of the frame's longer side) cover it
pub fn warp_cover(frame: &Decal, corners: &[[f32; 2]; 4], depth: f32, projector: &Projector, p: Vec3) -> Option<(Vec2, f32)> {
let local = frame_local(frame, projector, p)?;
let uv = warp_uv(corners, local.truncate())?;
if projector.crop == ShapeCrop::ExtendsOutside {
return Some((uv, 1.0));
}
let inside = (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y);
let reach = warp_reach(frame.size, depth);
Some((uv, if inside { depth_fade(local.z, reach) } else { 0.0 }))
}
#[cfg(test)]
mod tests {
use super::*;
/// The decal formula from before decals were placed planar projections, kept to check they still look the same
fn decal_before(frame: &Decal, point: Vec3, surface_normal: Vec3) -> Option<(Vec2, f32)> {
let (origin, right, up, normal) = crate::pattern::decal_axes(frame)?;
let facing = surface_normal.dot(normal);
let offset = point - origin;
let (local_x, local_y, local_z) = (offset.dot(right) / frame.size[0].max(1e-6), offset.dot(up) / frame.size[1].max(1e-6), offset.dot(normal).abs());
let depth = frame.depth.max(1e-6);
if facing <= 0.0 || local_x.abs() > 0.5 || local_y.abs() > 0.5 || local_z > depth || !(local_x.is_finite() && local_y.is_finite()) {
return None;
}
let cover = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, local_z));
Some((Vec2::new(local_x + 0.5, 0.5 - local_y), cover))
}
#[test]
fn a_nan_backface_angle_or_hardness_culls_nothing() {
for backface in [Backface { on: true, angle: f32::NAN, hardness: 0.5 }, Backface { on: true, angle: 60.0, hardness: f32::NAN }] {
assert_eq!(backface_cover(&backface, -0.5), 1.0, "{backface:?}");
}
}
#[test]
fn saved_decals_cover_exactly_as_before() {
let frames = [
Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [2.0, 1.0],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
},
Decal {
center: [0.3, -0.2, 0.1],
normal: [0.4, 0.5, 0.7],
up: [0.0, 1.0, 0.0],
size: [0.7, 1.3],
rotation: 37.0,
offset: [0.2, -0.1],
depth: 0.4,
symmetry: None,
flip: [false; 2],
},
];
for frame in frames {
let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") };
for sample in 0..4000 {
let phase = sample as f32 * 0.137;
let point = Vec3::new(phase.sin() * 1.3, (phase * 0.71).cos() * 1.1, (phase * 0.33).sin() * 0.8);
let normal = Vec3::new((phase * 1.7).cos(), (phase * 0.9).sin(), (phase * 0.4).cos()).normalize();
let now = placed_cover(&placed, &projector, point, normal).filter(|(_, cover)| *cover > 0.0);
match (decal_before(&frame, point, normal), now) {
(Some(before), Some(now)) => assert_eq!(before, now, "{point} {normal}"),
(None, None) => {}
(before, now) => panic!("{point} {normal}: {before:?} became {now:?}"),
}
}
}
}
/// The mirrored copy's formula as the decal model before placed planar projections had it (flip and symmetry on a decal)
fn symmetric_before(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let flip = |uv: Vec2| flip_uv(uv, d.flip);
let direct = decal_before(d, p, nrm).map(|(uv, w)| (flip(uv), w));
let Some(symmetry) = d.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut q, mut m) = (p, nrm);
q[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
m[axis] = -nrm[axis];
let mirrored = decal_before(d, q, m).map(|(uv, w)| {
let uv = flip(uv);
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, w)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
}
}
#[test]
fn saved_mirrored_and_flipped_decals_cover_exactly_as_before() {
let base = Decal {
center: [0.3, -0.2, 0.1],
normal: [0.4, 0.5, 0.7],
up: [0.0, 1.0, 0.0],
size: [0.7, 1.3],
rotation: 37.0,
offset: [0.2, -0.1],
depth: 0.4,
symmetry: None,
flip: [false; 2],
};
let center = Vec3::new(0.1, -0.05, 0.2);
let frames = [
Decal { flip: [true, false], ..base },
Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 }), ..base },
Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: -0.15 }), flip: [false, true], ..base },
];
for frame in frames {
let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") };
let mut mirrored = 0;
for i in 0..4000 {
let t = i as f32 * 0.137;
let p = Vec3::new(t.sin() * 1.3, (t * 0.71).cos() * 1.1, (t * 0.33).sin() * 0.8);
let nrm = Vec3::new((t * 1.7).cos(), (t * 0.9).sin(), (t * 0.4).cos()).normalize();
let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0);
let before = symmetric_before(&frame, p, nrm, center);
mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none());
assert_eq!(before, now, "{p} {nrm}");
}
assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not");
}
}
}
+312
View File
@@ -0,0 +1,312 @@
//! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling
use std::sync::Arc;
use texturecraft_core::Projection;
use texturecraft_geom::Mesh;
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::fill_copy::FillCopy;
use crate::organic::smoothstep;
use crate::projector_view::ProjectorView;
/// The nearest surface in each cell of a grid across a projector's view
pub struct ProjectorDepth {
view: ProjectorView,
/// The view point at the grid's lower corner
origin: Vec2,
grid_side: usize,
/// One cell's size across and up in the view
cell: Vec2,
/// The mesh radius measured along the view's depth axis
nearness_unit: f32,
/// Per cell: the nearness of the nearest surface at the cell centre and its slope across and up (nearness -inf where no surface is)
front: Vec<[f32; 3]>,
}
/// The smallest grid cell across and up, so a flat view still divides
const MIN_CELL_SIZE: f32 = 1e-6;
/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps
const EDGE_TOLERANCE: f32 = 1e-6;
impl ProjectorDepth {
/// Build the depth map of a borrowed mesh, if the projection uses depth culling.
pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option<Arc<ProjectorDepth>> {
let view = ProjectorView::of(projection, bounds)?;
Self::build(view, mesh).map(Arc::new)
}
/// Rasterize the mesh in this view, using a coarser grid when the cell budget requires one.
pub fn build(view: ProjectorView, mesh: &Mesh) -> Option<ProjectorDepth> {
Self::build_for_copy(view, mesh, None, GRID_SIDE, CELL_BUDGET)
}
pub(crate) fn build_for_copy(view: ProjectorView, mesh: &Mesh, copy: Option<FillCopy>, mut grid_side: usize, cell_budget: usize) -> Option<Self> {
let projected: Vec<_> = mesh.positions.iter().map(|&point| view.local(copy.map_or(point, |copy| copy.point(point)))).collect();
let (min, max) = projected
.iter()
.flatten()
.fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate())));
if min.x > max.x || min.y > max.y {
return None;
}
// The one-cell fallback can always afford one visit per triangle
let cell_budget = cell_budget.max(mesh.triangle_count());
let nearness_unit = view.unit();
while grid_side > 0 {
let cell = ((max - min) / grid_side as f32).max(Vec2::splat(MIN_CELL_SIZE));
let front = vec![[f32::NEG_INFINITY, 0.0, 0.0]; grid_side * grid_side];
let mut depth = ProjectorDepth { view, origin: min, grid_side, cell, nearness_unit, front };
let mut remaining = cell_budget;
let mut triangles = mesh.indices.as_chunks::<3>().0.iter().filter_map(|indices| {
let [a, b, c] = indices.map(|index| projected.get(index as usize).copied().flatten());
Some([a?, b?, c?])
});
if triangles.all(|triangle| depth.raster(triangle, &mut remaining)) {
return Some(depth);
}
// Discard any partial grid before retrying the whole mesh
grid_side /= 2;
}
None
}
/// Keep `triangle` where it is nearer than what a cell holds; false once the cell budget runs out
fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool {
let [a, b, c] = triangle;
let (edge_ab, edge_ac) = (b - a, c - a);
let determinant = edge_ab.x * edge_ac.y - edge_ab.y * edge_ac.x;
if !determinant.is_finite() || determinant.abs() < MIN_SCREEN_AREA {
// An edge-on triangle covers no cells
return true;
}
let slope = Vec2::new((edge_ab.z * edge_ac.y - edge_ac.z * edge_ab.y) / determinant, (edge_ab.x * edge_ac.z - edge_ac.x * edge_ab.z) / determinant)
.clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE));
// Evaluate coverage at cell centres
let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell);
let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc));
let first_cell = |position: f32| (position - 0.5).ceil().clamp(0.0, self.grid_side as f32) as usize;
let end_cell = |position: f32| ((position - 0.5).floor() + 1.0).clamp(0.0, self.grid_side as f32) as usize;
let (x0, x1, y0, y1) = (first_cell(lo.x), end_cell(hi.x), first_cell(lo.y), end_cell(hi.y));
let cells = x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0));
let Some(left) = budget.checked_sub(cells) else { return false };
*budget = left;
let area = edge(pa, pb, pc);
for y in y0..y1 {
for x in x0..x1 {
let cell_centre = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
let inside = [edge(pb, pc, cell_centre), edge(pc, pa, cell_centre), edge(pa, pb, cell_centre)]
.iter()
.all(|weight| weight * area.signum() >= -EDGE_TOLERANCE * area.abs());
if !inside {
continue;
}
let near = a.z + slope.dot(self.origin + cell_centre * self.cell - a.truncate());
if let Some(cell) = self.front.get_mut(y * self.grid_side + x)
&& near > cell[0]
{
*cell = [near, slope.x, slope.y];
}
}
}
true
}
/// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front
pub fn cover(&self, position: Vec3, hardness: f32) -> f32 {
// Keep the layer visible when a hand-edited hardness is invalid
if !hardness.is_finite() {
return 1.0;
}
let Some(view_point) = self.view.local(position) else { return 1.0 };
let at = (view_point.truncate() - self.origin) / self.cell;
if !(at.x >= 0.0 && at.y >= 0.0 && at.x <= self.grid_side as f32 && at.y <= self.grid_side as f32) {
return 1.0;
}
let (x, y) = ((at.x as usize).min(self.grid_side - 1), (at.y as usize).min(self.grid_side - 1));
let Some(&[near, across, up]) = self.front.get(y * self.grid_side + x).filter(|cell| cell[0].is_finite()) else { return 1.0 };
// Extend the cell's plane to avoid culling a surface against itself
let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell;
let slope = Vec2::new(across, up);
let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z;
let unit = self.nearness_unit;
// Add slope bias for curvature across adjacent triangles
let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit);
let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit;
if width <= f32::EPSILON {
return f32::from(u8::from(behind <= bias));
}
1.0 - smoothstep(bias, bias + width, behind)
}
}
/// Twice the signed area of triangle `a`, `b`, `q`
fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 {
(b - a).perp_dot(q - a)
}
/// Cells across and up the grid
pub(crate) const GRID_SIDE: usize = 512;
/// A triangle flatter than this on screen is seen edge on
const MIN_SCREEN_AREA: f32 = 1e-12;
/// Cell visits available at each resolution before large overlapping triangles require a coarser grid.
pub(crate) const CELL_BUDGET: usize = 256 * GRID_SIDE * GRID_SIDE;
/// Steepest surface slope kept, in nearness per view unit
const MAX_SLOPE: f32 = 1e4;
/// How far behind the nearest surface a point may sit and keep everything, in mesh radii
const BIAS: f32 = 0.002;
/// Most the slope adds to the bias, in mesh radii
const MAX_SLOPE_BIAS: f32 = 0.05;
/// How far behind the nearest surface culling fades out at hardness 0, in mesh radii
const FADE: f32 = 0.1;
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_core::{Projector, UvTransform};
/// Two squares facing +Z, one at z = `front` covering x 0..1, one at z = `back` covering x -1..1
fn two_squares(front: f32, back: f32) -> Mesh {
let positions = vec![
Vec3::new(0.0, -1.0, front),
Vec3::new(1.0, -1.0, front),
Vec3::new(1.0, 1.0, front),
Vec3::new(0.0, 1.0, front),
Vec3::new(-1.0, -1.0, back),
Vec3::new(1.0, -1.0, back),
Vec3::new(1.0, 1.0, back),
Vec3::new(-1.0, 1.0, back),
];
Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7], ..Mesh::default() }
}
fn planar_z(on: bool, hardness: f32) -> Projection {
let mut projector = Projector::depth_culled();
projector.depth.on = on;
projector.depth.hardness = hardness;
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }
}
#[test]
fn surfaces_behind_others_are_culled_and_the_nearest_keeps_everything() {
let mesh = two_squares(0.5, -0.5);
let bounds = mesh.bounds();
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), bounds).unwrap(), &mesh).unwrap();
assert_eq!(depth.cover(Vec3::new(0.5, 0.3, 0.5), 1.0), 1.0, "the front square");
assert_eq!(depth.cover(Vec3::new(0.5, 0.3, -0.5), 1.0), 0.0, "the back square behind it");
assert_eq!(depth.cover(Vec3::new(-0.5, 0.3, -0.5), 1.0), 1.0, "the back square where nothing is in front");
let soft = depth.cover(Vec3::new(0.5, 0.3, 0.5 - 0.01), 0.0);
assert!(soft > 0.0 && soft < 1.0, "a soft cull fades just behind the front: {soft}");
assert!(ProjectorView::of(&planar_z(false, 1.0), bounds).is_none(), "off, there is nothing to build");
}
#[test]
fn folding_positive_depth_stretch_preserves_soft_culling() {
let mesh = two_squares(0.5, -0.5);
let bounds = mesh.bounds();
let mut projector = Projector::depth_culled();
projector.scale[2] = 2.0;
projector.depth.hardness = 0.0;
let stretched = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
let placed = crate::axis_frame::placed_from_axis(&stretched, bounds).unwrap();
let axis_depth = ProjectorDepth::of(&mesh, bounds, &stretched).unwrap();
let placed_depth = ProjectorDepth::of(&mesh, bounds, &placed).unwrap();
let just_behind = Vec3::new(0.5, 0.3, 0.44);
let before = axis_depth.cover(just_behind, 0.0);
let after = placed_depth.cover(just_behind, 0.0);
assert!(before > 0.0 && before < 1.0 && (before - after).abs() < 1e-4, "axis {before}, placed {after}");
}
#[test]
fn the_upper_right_grid_boundary_can_be_depth_culled() {
let mesh = two_squares(0.5, -0.5);
let depth = ProjectorDepth::of(&mesh, mesh.bounds(), &planar_z(true, 1.0)).unwrap();
assert_eq!(depth.cover(Vec3::new(1.0, 1.0, -0.5), 1.0), 0.0);
}
#[test]
fn raster_budget_fallback_accounts_for_the_last_triangle() {
let mut mesh = two_squares(0.5, -0.5);
let rear_triangles = [4, 5, 6, 4, 6, 7];
let front_triangles = [0, 1, 2, 0, 2, 3];
mesh.indices = rear_triangles.repeat(CELL_BUDGET / (GRID_SIDE * GRID_SIDE));
mesh.indices.extend(front_triangles);
let projection = planar_z(true, 1.0);
let behind = Vec3::new(0.5, 0.3, -0.5);
let front_last = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap();
mesh.indices.rotate_right(front_triangles.len());
let front_first = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap();
assert_eq!(front_last.cover(behind, 1.0), 0.0);
assert_eq!(front_last.cover(behind, 1.0), front_first.cover(behind, 1.0));
}
#[test]
fn a_nan_hardness_culls_nothing() {
let mesh = two_squares(0.5, -0.5);
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap();
let behind = depth.cover(Vec3::new(0.5, 0.3, -0.5), f32::NAN);
assert_eq!(behind, 1.0, "a hand-edited NaN hardness keeps the back square visible");
}
#[test]
fn interleaved_meshes_keep_their_own_projector_depth() {
let mut mesh = two_squares(0.5, -0.5);
// Add enough unused vertices for the old sample to skip the changed edge
mesh.positions.resize(200, Vec3::ZERO);
let mut edited = mesh.clone();
for right in [1, 2] {
edited.positions[right].x = 0.5;
}
assert_eq!(mesh.bounds(), edited.bounds());
let proj = planar_z(true, 1.0);
let behind_the_cut = Vec3::new(0.75, 0.3, -0.5);
let bounds = mesh.bounds();
assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0);
let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap();
assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more");
}
#[test]
fn a_slanted_surface_is_never_behind_itself() {
let positions = vec![Vec3::new(-1.0, -1.0, -0.9), Vec3::new(1.0, -1.0, 0.9), Vec3::new(1.0, 1.0, 0.9), Vec3::new(-1.0, 1.0, -0.9)];
let mesh = Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() };
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap();
for i in 0..1000 {
let (x, y) = ((i as f32 * 0.618).fract() * 1.98 - 0.99, (i as f32 * 0.377).fract() * 1.98 - 0.99);
assert_eq!(depth.cover(Vec3::new(x, y, x * 0.9), 1.0), 1.0, "{x} {y}");
}
}
}
@@ -0,0 +1,95 @@
use std::sync::{Arc, Mutex, Weak};
use texturecraft_geom::Mesh;
use crate::fill_depth::{FillDepth, FillDepthKey};
pub(crate) type ViewDepth = (FillDepthKey, Option<Arc<FillDepth>>);
// Each fill's grids share about 3 MiB
const MAX_CACHED_VIEWS: usize = 8;
/// Reuse projector depth maps for one mesh across tile batches.
#[derive(Default)]
pub struct ProjectorDepthCache {
mesh: Weak<Mesh>,
maps: Mutex<Vec<ViewDepth>>,
}
impl ProjectorDepthCache {
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) {
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
self.maps.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();
self.mesh = Arc::downgrade(mesh);
}
}
pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option<Arc<FillDepth>> {
// Rasterization is serial so tile workers can wait for a single build
let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(index) = maps.iter().position(|(cached_key, _)| *cached_key == key) {
let entry = maps.remove(index);
let depth = entry.1.clone();
maps.insert(0, entry);
return depth;
}
let depth = FillDepth::build(mesh, key).map(Arc::new);
maps.insert(0, (key, depth.clone()));
maps.truncate(MAX_CACHED_VIEWS);
depth
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::projector_view::ProjectorView;
use texturecraft_core::{Projection, Projector, UvTransform};
use texturecraft_geom::primitives;
#[test]
fn eviction_and_mesh_replacement_release_maps_after_the_last_reader() {
let mut cache = ProjectorDepthCache::default();
let mut mesh = Arc::new(primitives::plane(2.0, 2));
let mesh_reference = Arc::downgrade(&mesh);
let bounds = mesh.bounds();
let mut maps = Vec::new();
let mut first_reader = None;
cache.bind(&mesh);
for angle_degrees in 0..MAX_CACHED_VIEWS + 4 {
let mut projector = Projector::depth_culled();
projector.rotation[2] = angle_degrees as f32;
let projection = Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
let view = ProjectorView::of(&projection, bounds).unwrap();
let map = cache.get(&mesh, (view, None)).unwrap();
let reused = cache.get(&mesh, (view, None)).unwrap();
assert!(Arc::ptr_eq(&map, &reused));
maps.push(Arc::downgrade(&map));
if angle_degrees == 0 {
first_reader = Some(map);
}
}
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS + 1);
drop(first_reader);
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS);
// Mutating a uniquely held Arc disassociates its weak references
Arc::make_mut(&mut mesh).positions[0].y += 1.0;
assert!(mesh_reference.upgrade().is_none());
cache.bind(&mesh);
assert!(maps.iter().all(|map| map.upgrade().is_none()));
let projection =
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None };
let view = ProjectorView::of(&projection, mesh.bounds()).unwrap();
let last_map = Arc::downgrade(&cache.get(&mesh, (view, None)).unwrap());
drop(cache);
assert!(last_map.upgrade().is_none());
}
}
+62
View File
@@ -0,0 +1,62 @@
//! Where a planar or warp projection's projector looks from, for depth culling
use texturecraft_core::{Decal, Projection, Projector};
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::pattern::{Coords, frame_local, mesh_frame, nonzero_stretch, projector_local};
/// The view of a depth-culled planar or warp projection: points in it run across, up and towards the projector
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ProjectorView {
/// An axis planar projection, reading positions around the mesh centre in mesh radii
Axis { axis: u8, projector: Projector, center: Vec3, radius: f32 },
/// A planar projection placed on the surface or a warp, from its frame
Frame { frame: Decal, projector: Projector, radius: f32 },
}
impl ProjectorView {
/// The view of `proj` over a mesh within `bounds`, None unless it is a planar or warp projection with depth culling on
pub fn of(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<ProjectorView> {
proj.depth_culling()?;
let (center, radius) = mesh_frame(bounds);
match proj {
Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => {
Some(ProjectorView::Frame { frame: *frame, projector: turn_only(projector), radius })
}
Projection::Planar { axis, projector, .. } => Some(ProjectorView::Axis { axis: *axis, projector: turn_only(projector), center, radius }),
_ => None,
}
}
/// World point `point` in the view: across, up and how near the projector (None where the view is degenerate)
pub fn local(&self, point: Vec3) -> Option<Vec3> {
let local = match self {
ProjectorView::Axis { axis, projector, center, radius } => {
let at = Coords { uv: Vec2::ZERO, pos: (point - *center) / *radius, nrm: Vec3::Z };
let projected = projector_local(projector, &at).pos;
// The side each axis projects from, as its backface culling reads it
match axis {
0 => Vec3::new(projected.z, projected.y, -projected.x),
1 => Vec3::new(projected.x, projected.z, projected.y),
_ => projected,
}
}
ProjectorView::Frame { frame, projector, .. } => frame_local(frame, projector, point)?,
};
local.is_finite().then_some(local)
}
/// The mesh radius in the view's nearness units
pub fn unit(&self) -> f32 {
match self {
ProjectorView::Axis { axis, projector, .. } => 1.0 / nonzero_stretch(projector.scale[usize::from((*axis).min(2))]).abs(),
ProjectorView::Frame { projector, radius, .. } => radius / nonzero_stretch(projector.scale[2]).abs(),
}
}
}
/// Only what moves the view: the turn and stretch, not the culling settings (changing those keeps the depth map)
fn turn_only(projector: &Projector) -> Projector {
Projector { rotation: projector.rotation, scale: projector.scale, ..Projector::default() }
}
+402
View File
@@ -0,0 +1,402 @@
//! Filters drawn from the distance to the shapes' edge: Bevel, Bevel Smooth and Directional Distance
use rayon::prelude::*;
use texturecraft_core::{Bevel, BevelBlur, BevelCorner, DirectionalDistance, Filter, lum};
use crate::distance_envelope::DistanceEnvelope;
use crate::eval::{MIN_ALPHA, blur};
/// From a texel's centre to the edge between it and the nearest texel across: half a texel short of their centres' distance
const EDGE_OFFSET: f32 = 0.5;
/// Components of a texel with color and coverage (red, green, blue, alpha)
const RGBA_COMPONENTS: usize = 4;
/// Color components of a texel, before its alpha
const COLOR_COMPONENTS: usize = 3;
/// Where a texel's alpha sits among its components
const ALPHA_INDEX: usize = 3;
/// What a texel becomes from its index, whether it is inside the shapes and its own value
type TexelResult<'a> = dyn Fn(usize, bool, f32) -> f32 + Sync + 'a;
/// Lay distance filter `filter` over premultiplied `data` (`width` × `height` texels of `components`; content's shapes from its luminance), `tile_resolution` texels across a UV tile, mixed in by `opacity`; its Distance Map `grays` (0..1 a texel) scales the distance texel by texel
pub(crate) fn distance_filter(
data: &mut [f32],
(cover, grays): (&[f32], &[f32]),
components: usize,
(width, height): (usize, usize),
filter: &Filter,
tile_resolution: u32,
opacity: f32,
) {
let map = |texel: usize| grays.get(texel).copied().unwrap_or(1.0);
let value = |pixel: &[f32]| match pixel {
[r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]),
[value] => *value,
_ => 0.0,
};
let shapes = |inside: &(dyn Fn(f32) -> bool + Sync)| -> Vec<bool> {
data.par_chunks(components).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && inside(value(pixel))).collect()
};
let smoothed = |field: &mut [f32], texels: f32| {
let radius = texels.round() as usize;
if radius > 0 {
blur(field, width, height, radius);
}
};
// Per texel: whether it is inside the shapes, and what it becomes from its own value
let (inside, result): (Vec<bool>, Box<TexelResult<'_>>) = match filter {
Filter::DistanceBevel(bevel) => {
let inside = shapes(&|value| value >= Bevel::EDGE);
let edge = edge_distances(&inside, (width, height), bevel.corner == BevelCorner::Angular);
let reach = bevel.reach(tile_resolution);
let mut slope: Vec<f32> = inside.par_iter().zip(edge.par_iter()).map(|(inside, edge)| bevel.slope(*inside, *edge, reach)).collect();
drop(edge);
let smoothing_radius = bevel.smoothing_texels(tile_resolution).round() as usize;
if smoothing_radius > 0 {
match bevel.blur {
BevelBlur::Uniform => blur(&mut slope, width, height, smoothing_radius),
BevelBlur::NonUniform => {
let mut blurred = slope.clone();
blur(&mut blurred, width, height, smoothing_radius);
// Keep the foot sharp and blur the top at full strength
slope.par_iter_mut().zip(blurred).for_each(|(sharp, blurred)| *sharp += (blurred - *sharp) * *sharp);
}
}
}
let bevel = *bevel;
(inside, Box::new(move |texel, inside, value| bevel.apply(inside, value, slope.get(texel).copied().unwrap_or(1.0))))
}
Filter::BevelSmooth(smooth) => {
let inside = shapes(&|value| smooth.inside(value));
let edge = edge_distances(&inside, (width, height), false);
let (reach, curve) = (smooth.reach(tile_resolution), smooth.curve());
let mut ramp: Vec<f32> = inside
.par_iter()
.zip(edge.par_iter())
.enumerate()
.map(|(texel, (inside, edge))| smooth.value(curve, *inside, *edge, reach * map(texel)))
.collect();
drop(edge);
smoothed(&mut ramp, smooth.smoothing_texels(tile_resolution));
(inside, Box::new(move |texel, _, value| ramp.get(texel).copied().unwrap_or(value)))
}
Filter::DirectionalDistance(trail) => {
let inside = shapes(&|value| value >= DirectionalDistance::EDGE);
let along = trail_distances(&inside, (width, height), crate::eval::direction(trail.angle), trail.reach(tile_resolution));
let trail = *trail;
// A share of the full reach is a larger share of a texel's shorter one; no trail where the map is black, the shapes stay
let shortened = move |texel: usize| {
along.get(texel).copied().flatten().and_then(|along| match map(texel) {
_ if along <= 0.0 => Some(0.0),
gray if gray > 0.0 => Some(along / gray),
_ => None,
})
};
(inside, Box::new(move |texel, _, _| trail.value(shortened(texel).filter(|along| *along <= 1.0))))
}
_ => return,
};
let has_alpha = components == RGBA_COMPONENTS;
data.par_chunks_mut(components).zip(inside.par_iter()).zip(cover.par_iter()).enumerate().for_each(|(texel, ((pixel, inside), covered))| {
if *covered <= 0.0 {
return;
}
// Content is premultiplied by its coverage, which stays
let coverage = if has_alpha { pixel.get(ALPHA_INDEX).copied().unwrap_or(0.0) } else { 1.0 };
for slot in pixel.iter_mut().take(components.min(COLOR_COMPONENTS)) {
let before = if has_alpha { if coverage > MIN_ALPHA { *slot / coverage } else { 0.0 } } else { *slot };
let after = result(texel, *inside, before);
*slot = (before + (after - before) * opacity) * coverage;
}
});
}
/// Every texel's distance (texels) to the edge between it and the nearest texel on the other side of the shapes `inside`: straight-line, or the larger axis distance when `angular`
fn edge_distances(inside: &[bool], (width, height): (usize, usize), angular: bool) -> Vec<f32> {
let distances = if angular { chessboard_distances } else { straight_distances };
let mut to_inside = distances(inside, (width, height), true);
let to_outside = distances(inside, (width, height), false);
to_inside
.par_iter_mut()
.zip(to_outside)
.zip(inside)
.for_each(|((to_inside, to_outside), inside)| *to_inside = (if *inside { to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0));
to_inside
}
/// Each texel's straight-line distance to the nearest texel on the requested side.
fn straight_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec<f32> {
// Start beyond the region so a line without a feature stays out of reach
let far = ((width + height) as f32).powi(2);
let mut rows: Vec<f32> = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect();
rows.par_chunks_mut(width.max(1)).for_each_init(DistanceEnvelope::default, |envelope, row| envelope.lower(row));
let mut columns: Vec<f32> = (0..width * height).map(|at| rows.get((at % height.max(1)) * width + at / height.max(1)).copied().unwrap_or(far)).collect();
columns.par_chunks_mut(height.max(1)).for_each_init(DistanceEnvelope::default, |envelope, column| envelope.lower(column));
// Reuse the row buffer for the final distances in row-major order
rows.resize(width * height, far);
for (index, distance) in rows.iter_mut().enumerate() {
*distance = columns.get((index % width.max(1)) * height + index / width.max(1)).copied().unwrap_or(far).sqrt();
}
rows
}
/// Each texel's distance to the nearest texel on the requested side, measured along the larger axis.
fn chessboard_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec<f32> {
let far = (width + height) as f32;
let mut distances: Vec<f32> = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect();
// One pass down from the texels above and left, one up from those below and right
let step = |distances: &mut [f32], (x, y): (usize, usize), neighbours: [(isize, isize); 4]| {
let nearest = neighbours
.iter()
.filter_map(|(dx, dy)| {
let (neighbour_x, neighbour_y) = (x.checked_add_signed(*dx)?, y.checked_add_signed(*dy)?);
(neighbour_x < width && neighbour_y < height).then(|| distances.get(neighbour_y * width + neighbour_x).copied()).flatten()
})
.fold(f32::MAX, f32::min);
if let Some(slot) = distances.get_mut(y * width + x) {
*slot = slot.min(nearest + 1.0);
}
};
for y in 0..height {
for x in 0..width {
step(&mut distances, (x, y), [(-1, 0), (-1, -1), (0, -1), (1, -1)]);
}
}
for y in (0..height).rev() {
for x in (0..width).rev() {
step(&mut distances, (x, y), [(1, 0), (1, 1), (0, 1), (-1, 1)]);
}
}
distances
}
/// For every texel, how far (a share of `reach` texels) the nearest texel of the shapes `inside` lies behind it against `direction`, if one is in reach
fn trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<Option<f32>> {
let steps = trail_steps((width, height), direction, reach);
// Each row of shapes as bits, a row without one as no words: steps landing on it find nothing
let shapes: Vec<Vec<u64>> = inside.par_chunks(width.max(1)).map(row_bits).collect();
let mut distances = vec![None; width * height];
distances.par_chunks_mut(width.max(1)).enumerate().for_each(|(y, row)| trail_row(row, y, &shapes, &steps));
distances
}
/// The texel steps back along a trail against `direction`, nearest first, each with its share of `reach`: texel coordinates are whole, so every texel takes the same steps
fn trail_steps((width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<(isize, isize, f32)> {
// Steps of one texel along the direction's longer axis visit every column (or row) the trail crosses, so no thin shape is stepped over
let longer_axis = direction[0].abs().max(direction[1].abs());
let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 };
let step = if samples > 0 { reach / samples as f32 } else { 0.0 };
let mut steps: Vec<(isize, isize, f32)> = Vec::new();
for sample in 0..=samples {
let back = sample as f32 * step;
// Rounded half up, so a whole texel coordinate added to it rounds the same; a NaN direction lands nowhere
let (across, down) = ((0.5 - direction[0] * back).floor(), (0.5 - direction[1] * back).floor());
if !(across.is_finite() && down.is_finite()) {
break;
}
// A step as long as the region leaves it from every texel, and never comes back in
let (across, down) = (across as isize, down as isize);
if across.unsigned_abs() >= width || down.unsigned_abs() >= height {
break;
}
// Rounding puts several samples on one texel: the nearest counts
if steps.last().is_some_and(|(last_across, last_down, _)| (*last_across, *last_down) == (across, down)) {
continue;
}
steps.push((across, down, if reach > 0.0 { back / reach } else { 0.0 }));
}
steps
}
/// A row of shapes as bits, [`u64::BITS`] texels a word; no words when it has none
fn row_bits(row: &[bool]) -> Vec<u64> {
if !row.contains(&true) {
return Vec::new();
}
let mut words = vec![0u64; row.len().div_ceil(WORD_BITS)];
for (word, texels) in words.iter_mut().zip(row.chunks(WORD_BITS)) {
*word = texels.iter().enumerate().filter(|(_, inside)| **inside).fold(0, |bits, (bit, _)| bits | 1 << bit);
}
words
}
/// Texels in a word of a row's bits
const WORD_BITS: usize = u64::BITS as usize;
/// Row `y`'s trail distances into `row`: a step at a time, every texel the step brings onto a shape takes its share, unless an earlier step did
fn trail_row(row: &mut [Option<f32>], y: usize, shapes: &[Vec<u64>], steps: &[(isize, isize, f32)]) {
let width = row.len();
let mut found = vec![0u64; width.div_ceil(WORD_BITS)];
let mut unfound = width;
// The last word's bits past the row's end are no texels
let last_word = found.len().saturating_sub(1);
let tail = width % WORD_BITS;
let last_word_texels = if tail > 0 { (1u64 << tail) - 1 } else { u64::MAX };
for (across, down, share) in steps {
// A step past the region's top or bottom leaves it for good
let Some(source) = y.checked_add_signed(*down).and_then(|source_y| shapes.get(source_y)) else { break };
if source.is_empty() {
continue;
}
for (word, found_word) in found.iter_mut().enumerate() {
let in_row = if word == last_word { last_word_texels } else { u64::MAX };
let landed = bits_from(source, (word * WORD_BITS) as isize + across) & !*found_word & in_row;
*found_word |= landed;
let mut remaining = landed;
while remaining != 0 {
let bit = remaining.trailing_zeros() as usize;
remaining &= remaining - 1;
if let Some(slot) = row.get_mut(word * WORD_BITS + bit) {
*slot = Some(*share);
}
unfound = unfound.saturating_sub(1);
}
}
if unfound == 0 {
break;
}
}
}
/// The [`WORD_BITS`] bits of row bits `source` from texel `start` on, none past either end
fn bits_from(source: &[u64], start: isize) -> u64 {
let bits = WORD_BITS as isize;
let (word, shift) = (start.div_euclid(bits), start.rem_euclid(bits) as u32);
let at = |index: isize| usize::try_from(index).ok().and_then(|index| source.get(index)).copied().unwrap_or(0);
let low = at(word) >> shift;
if shift == 0 { low } else { low | at(word + 1) << (u64::BITS - shift) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn distances_are_straight_or_chessboard() {
// One feature texel in the middle of a 5 × 5 region
let mut feature = vec![false; 25];
feature[12] = true;
let straight = straight_distances(&feature, (5, 5), true);
let chessboard = chessboard_distances(&feature, (5, 5), true);
assert_eq!((straight[12], straight[13], chessboard[13]), (0.0, 1.0, 1.0));
assert!((straight[0] - 8f32.sqrt()).abs() < 1e-5, "{}", straight[0]);
assert_eq!(chessboard[0], 2.0, "a corner is as far as its larger axis");
let none = straight_distances(&[false; 4], (2, 2), true);
assert!(none.iter().all(|distance| *distance >= 4.0), "no feature is beyond the region");
}
#[test]
fn distances_keep_rows_and_columns_apart_in_a_region_wider_than_tall() {
// One feature texel at column 1, row 0 of a 7 × 3 region
let (width, height) = (7, 3);
let mut feature = vec![false; width * height];
feature[1] = true;
let straight = straight_distances(&feature, (width, height), true);
let chessboard = chessboard_distances(&feature, (width, height), true);
let at = |x: usize, y: usize| y * width + x;
assert_eq!((straight[at(1, 0)], straight[at(6, 0)], straight[at(1, 2)]), (0.0, 5.0, 2.0));
assert!((straight[at(6, 2)] - 29f32.sqrt()).abs() < 1e-5, "{}", straight[at(6, 2)]);
assert_eq!((chessboard[at(6, 0)], chessboard[at(0, 2)], chessboard[at(6, 2)]), (5.0, 2.0, 5.0));
}
#[test]
fn a_trail_finds_the_nearest_shape_behind_a_texel_as_a_share_of_its_reach() {
// A shape at column 0 of a 5 × 2 region; the trail runs towards +x, so a texel looks back towards -x
let (width, height) = (5, 2);
let inside: Vec<bool> = (0..width * height).map(|texel| texel % width == 0).collect();
let trail = trail_distances(&inside, (width, height), [1.0, 0.0], 4.0);
assert_eq!(trail[0], Some(0.0), "on the shape");
assert_eq!(trail[2], Some(0.5), "two texels behind, half the reach");
assert_eq!(trail[width + 4], Some(1.0), "at the reach's end");
}
#[test]
fn a_long_trail_steps_over_no_thin_shape() {
// A one-texel shape at column 0 of an 8 × 1 region, with a reach far longer than the region
let (width, height) = (8, 1);
let inside: Vec<bool> = (0..width * height).map(|texel| texel == 0).collect();
let reach = 128.0;
let trail = trail_distances(&inside, (width, height), [1.0, 0.0], reach);
assert_eq!(trail[3], Some(3.0 / reach), "three texels behind");
assert!(trail.iter().all(Option::is_some), "every texel behind the shape is in its trail: {trail:?}");
}
/// The trail as every texel walks it on its own, one sample at a time: what the shared steps must match
fn walked_trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<Option<f32>> {
let longer_axis = direction[0].abs().max(direction[1].abs());
let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 };
let step = if samples > 0 { reach / samples as f32 } else { 0.0 };
(0..width * height)
.into_par_iter()
.map(|texel| {
let (x, y) = ((texel % width) as f32, (texel / width) as f32);
(0..=samples)
.map(|sample| {
let back = sample as f32 * step;
(back, (x - direction[0] * back + 0.5).floor(), (y - direction[1] * back + 0.5).floor())
})
.take_while(|(_, sample_x, sample_y)| *sample_x >= 0.0 && *sample_y >= 0.0 && (*sample_x as usize) < width && (*sample_y as usize) < height)
.find_map(|(back, sample_x, sample_y)| inside[sample_y as usize * width + sample_x as usize].then(|| back / reach))
})
.collect()
}
#[test]
fn shared_trail_steps_find_what_each_texel_walking_its_own_finds() {
// Sparse rows end partway through a word
// Keep the region small enough to avoid rounding nearly tied rays into different texels
let (width, height) = (150, 97);
let mut seed = 12345u32;
let inside: Vec<bool> = (0..width * height)
.map(|_| {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(seed >> 16) % 97 < 2
})
.collect();
for angle in [0.0, 17.0, 45.0, 90.0, 135.0, 200.0, 290.0, 333.0] {
for reach in [9.3, 60.0, 400.0] {
let direction = crate::eval::direction(angle);
let shared = trail_distances(&inside, (width, height), direction, reach);
let walked = walked_trail_distances(&inside, (width, height), direction, reach);
assert!(walked.iter().any(Option::is_some) && walked.iter().any(Option::is_none), "{angle}° {reach}: a field with texels in and out of reach");
assert_eq!(shared, walked, "{angle}° reach {reach}");
}
}
}
}
+46
View File
@@ -0,0 +1,46 @@
//! What a Blur Slope filter reads for one texel: its source's slope, then the values downhill of it
use texturecraft_core::{SlopeBlending, SourceSlopeBlur, SourceWarp};
use crate::eval::LINE_SAMPLES;
use crate::warp_source_sample::WarpSourceSample;
use crate::warp_texel::{Input, Sample, keep_extreme_read};
/// A source rising less than this across a texel is flat
const FLAT_STEEPNESS: f32 = 1e-6;
/// Blur Slope `slope` at texel `(x, y)` into `acc`: the reads downhill of it, blended
pub(crate) fn slope_texel(
slope: &SourceSlopeBlur,
(x, y): (f32, f32),
(res, comps): (u32, usize),
tile_sizes: ([u32; 2], [u32; 2]),
acc: &mut [f32; 5],
(sample, input): (Sample<'_>, Input<'_>),
) {
let source = WarpSourceSample::new(&slope.source, slope.seed, [x, y], (res, comps), tile_sizes, (sample, input));
let probe = SourceWarp::probe_texels(res);
let downhill = [source.at(x - probe, y) - source.at(x + probe, y), source.at(x, y - probe) - source.at(x, y + probe)];
let steepness = downhill[0].hypot(downhill[1]);
// A flat spot keeps its value
if steepness.is_nan() || steepness <= FLAT_STEEPNESS {
sample(x, y, acc);
return;
}
let [dx, dy] = downhill.map(|rise| rise / steepness);
let reach = slope.move_texels(res);
let read_count = slope.samples((reach.ceil() as u32).clamp(1, LINE_SAMPLES.unsigned_abs()));
let step = reach / read_count as f32;
let along = (0..=read_count).map(|read| read as f32 * step);
if slope.blending == SlopeBlending::Blur {
for t in along {
sample(x + dx * t, y + dy * t, acc);
}
return;
}
let reads = along.map(|t| (x + dx * t, y + dy * t));
keep_extreme_read(reads, slope.blending == SlopeBlending::Max, comps, acc, sample);
}
+35
View File
@@ -0,0 +1,35 @@
//! A soft rectangular light of the built-in environments
use texturecraft_geom::glam::Vec3;
/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees)
pub(crate) struct SoftBox {
pub azimuth: f32,
pub elevation: f32,
pub half_width: f32,
pub half_height: f32,
pub color: Vec3,
}
/// Where the light starts to fade, as a share of its half size, and over how much of it
const EDGE_FADE_START: f32 = 0.8;
const EDGE_FADE_WIDTH: f32 = 0.4;
impl SoftBox {
/// Convert the sampled direction to degrees once for all the lights
pub fn angles(direction: Vec3) -> (f32, f32) {
let elevation = direction.y.clamp(-1.0, 1.0).asin().to_degrees();
let azimuth = direction.z.atan2(direction.x).to_degrees();
(azimuth, elevation)
}
/// The light the box sends along the sampled azimuth and elevation
pub fn eval(&self, azimuth: f32, elevation: f32) -> Vec3 {
// The azimuth difference wrapped to -180..180 degrees
let azimuth_step = ((azimuth - self.azimuth + 540.0).rem_euclid(360.0)) - 180.0;
let (x, y) = (azimuth_step.abs() / self.half_width, (elevation - self.elevation).abs() / self.half_height);
let edge = |t: f32| 1.0 - crate::environment_sky::smooth((t - EDGE_FADE_START) / EDGE_FADE_WIDTH);
self.color * edge(x) * edge(y)
}
}
+15 -8
View File
@@ -103,6 +103,7 @@ mod tests {
p.layer_mut(rust).unwrap().visible = false;
let before = p.clone();
let view = solo_project(&p, rust, false).unwrap();
assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off");
assert!(!view.layers[&below].visible, "the others are hidden");
assert!(view.layers[&other_set].visible, "another texture set keeps its layers");
@@ -113,13 +114,17 @@ mod tests {
fn solo_keeps_the_folders_around_a_layer_and_everything_inside_a_soloed_folder() {
let mut p = project();
let outside = add(&mut p, 0, LayerKind::Paint, None, false);
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let folder =
add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false);
let view = solo_project(&p, inner, false).unwrap();
assert!(view.layers[&folder].visible && view.layers[&inner].visible);
assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible);
let whole = solo_project(&p, folder, false).unwrap();
assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents");
assert!(!whole.layers[&outside].visible);
}
@@ -127,15 +132,19 @@ mod tests {
#[test]
fn ignoring_the_mask_disables_it_on_the_layer_and_its_folders_only() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let folder =
add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let other = add(&mut p, 0, LayerKind::Paint, None, false);
for id in [folder, inner, other] {
masked(&mut p, id);
}
let kept = solo_project(&p, inner, false).unwrap();
assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays");
let view = solo_project(&p, inner, true).unwrap();
assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled);
assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched");
assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask");
@@ -148,6 +157,7 @@ mod tests {
masked(&mut p, source);
let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false);
let view = solo_project(&p, instance, true).unwrap();
assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled);
assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask");
}
@@ -155,15 +165,12 @@ mod tests {
#[test]
fn a_soloed_instance_of_a_folder_keeps_the_folders_contents_drawn() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let folder =
add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false);
let view = solo_project(&p, instance, false).unwrap();
assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible);
}
#[test]
fn a_layer_in_no_stack_gives_nothing() {
assert!(solo_project(&project(), LayerId(99), true).is_none());
}
}
+283 -17
View File
@@ -2,9 +2,12 @@
//! maps. Everything is copy-on-write, so cloning the store for undo is cheap.
use std::collections::HashMap;
use std::sync::OnceLock;
use texturecraft_core::{Channel, ChannelKind, LayerId};
use texturecraft_texel::{TileImage, from_u16, from_u16_signed};
use texturecraft_core::{Channel, ChannelKind, Filtering, LayerId, Sampling};
use texturecraft_texel::{TileImage, from_u16, from_u16_signed, srgb_to_linear};
use crate::mip_level::MipLevel;
/// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per
/// component (height stored signed).
@@ -66,16 +69,71 @@ pub struct ImageRes {
pub rgba: Vec<[f32; 4]>,
/// 8/16-bit images are sRGB-encoded; color channels linearize them.
pub srgb: bool,
/// Halved copies of the image, built on first use by [`Filtering::BilinearHq`]
pub mips: OnceLock<Vec<MipLevel>>,
/// Mip levels for sRGB color reads. RGB is linear, alpha is unchanged.
linear_mips: OnceLock<Vec<MipLevel>>,
}
/// Image resources by name.
pub type ImageStore = HashMap<String, std::sync::Arc<ImageRes>>;
/// Image levels below the full image at most: a 64k image halves 16 times to 1 texel
const MAX_MIP_LEVELS: usize = 16;
/// Texel (`x`, `y`) of `rgba`; an axis that does not `repeat` (across, down) stops at its edge
pub(crate) fn texel_of(rgba: &[[f32; 4]], width: u32, height: u32, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] {
let (w, h) = (width.max(1) as i64, height.max(1) as i64);
let x = if repeat.0 { x.rem_euclid(w) } else { x.clamp(0, w - 1) };
let y = if repeat.1 { y.rem_euclid(h) } else { y.clamp(0, h - 1) };
let i = (y * w + x) as usize;
rgba.get(i).copied().unwrap_or([0.0; 4])
}
/// Bilinear sample of `rgba` (texture coordinates, v down), wrapping around on the axes that `repeat`
fn bilinear(rgba: &[[f32; 4]], width: u32, height: u32, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] {
// Texel centres sit half a texel in from the texel's corner
let texel_x = u * width as f32 - 0.5;
let texel_y = v * height as f32 - 0.5;
let (left, top) = (texel_x.floor() as i64, texel_y.floor() as i64);
let (across, down) = (texel_x - texel_x.floor(), texel_y - texel_y.floor());
// A huge coordinate saturates to the last texel instead of overflowing past it
let (right, bottom) = (left.saturating_add(1), top.saturating_add(1));
let texel = |x, y| texel_of(rgba, width, height, x, y, repeat);
let (top_left, top_right) = (texel(left, top), texel(right, top));
let (bottom_left, bottom_right) = (texel(left, bottom), texel(right, bottom));
let mut blended = [0.0; 4];
for k in 0..4 {
let upper = top_left[k] + (top_right[k] - top_left[k]) * across;
let lower = bottom_left[k] + (bottom_right[k] - bottom_left[k]) * across;
blended[k] = upper + (lower - upper) * down;
}
blended
}
fn linearize_rgb([red, green, blue, alpha]: [f32; 4]) -> [f32; 4] {
[srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha]
}
pub(crate) fn uses_mips(footprint: f32) -> bool {
footprint.is_finite() && footprint > 1.0
}
impl ImageRes {
fn texel(&self, x: i64, y: i64) -> [f32; 4] {
let (w, h) = (self.width.max(1) as i64, self.height.max(1) as i64);
let i = (y.rem_euclid(h) * w + x.rem_euclid(w)) as usize;
self.rgba.get(i).copied().unwrap_or([0.0; 4])
pub fn new(width: u32, height: u32, rgba: Vec<[f32; 4]>, srgb: bool) -> ImageRes {
ImageRes { width, height, rgba, srgb, mips: OnceLock::new(), linear_mips: OnceLock::new() }
}
/// Bytes held by the image's texel buffers, used to budget other image work.
pub fn retained_texel_bytes(&self) -> u64 {
let mip_levels = self.mips.get().into_iter().flatten().chain(self.linear_mips.get().into_iter().flatten());
let capacity = mip_levels.fold(self.rgba.capacity() as u64, |texels, level| texels.saturating_add(level.rgba.capacity() as u64));
capacity.saturating_mul(std::mem::size_of::<[f32; 4]>() as u64)
}
fn texel(&self, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] {
texel_of(&self.rgba, self.width, self.height, x, y, repeat)
}
/// Bilinear sample with wrap-around (texture coordinates, v down).
@@ -83,17 +141,225 @@ impl ImageRes {
if !u.is_finite() || !v.is_finite() {
return [0.0; 4];
}
let fx = u * self.width as f32 - 0.5;
let fy = v * self.height as f32 - 0.5;
let (x0, y0) = (fx.floor() as i64, fy.floor() as i64);
let (tx, ty) = (fx - fx.floor(), fy - fy.floor());
let (a, b, c, d) = (self.texel(x0, y0), self.texel(x0 + 1, y0), self.texel(x0, y0 + 1), self.texel(x0 + 1, y0 + 1));
let mut out = [0.0; 4];
for k in 0..4 {
let top = a[k] + (b[k] - a[k]) * tx;
let bot = c[k] + (d[k] - c[k]) * tx;
out[k] = top + (bot - top) * ty;
bilinear(&self.rgba, self.width, self.height, u, v, (true, true))
}
/// The texel under (`u`, `v`) as stored, wrapping (an ID map's colors must not blend)
pub fn sample_nearest(&self, u: f32, v: f32) -> [f32; 4] {
if !u.is_finite() || !v.is_finite() {
return [0.0; 4];
}
self.nearest(u, v, (true, true))
}
/// The texel under (`u`, `v`), on the axes that do not `repeat` the edge texel past the edge
fn nearest(&self, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] {
self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat)
}
fn build_mips(&self, halve_first: impl FnOnce(&[[f32; 4]], u32, u32) -> MipLevel) -> Vec<MipLevel> {
if self.width <= 1 && self.height <= 1 {
return Vec::new();
}
// Decode while reducing the first level to avoid a full-size linear image
let mut level = halve_first(&self.rgba, self.width, self.height);
let mut levels = Vec::new();
while (level.width > 1 || level.height > 1) && levels.len() + 1 < MAX_MIP_LEVELS {
let next = MipLevel::halve(&level.rgba, level.width, level.height);
levels.push(level);
level = next;
}
levels.push(level);
levels
}
fn mips(&self) -> &[MipLevel] {
self.mips.get_or_init(|| self.build_mips(MipLevel::halve))
}
/// Sample an sRGB image as linear color, preserving the full-resolution filter.
pub(crate) fn sample_srgb_color(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> [f32; 4] {
self.sample_filtered_with(u, v, sampling, footprint, linearize_rgb, || {
self.linear_mips.get_or_init(|| self.build_mips(|rgba, width, height| MipLevel::halve_with(rgba, width, height, Some(linearize_rgb))))
})
}
/// Read coverage from either mip chain since the RGB transfer leaves alpha unchanged.
pub(crate) fn sample_alpha(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> f32 {
self.sample_filtered_with(u, v, sampling, footprint, std::convert::identity, || self.linear_mips.get().map_or_else(|| self.mips(), Vec::as_slice))[3]
}
/// Sample at (`u`, `v`) with `sampling`; `footprint` = image texels per surface texel (1 or less = not shrunk)
pub fn sample_filtered(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> [f32; 4] {
self.sample_filtered_with(u, v, sampling, footprint, std::convert::identity, || self.mips())
}
fn sample_filtered_with<'a>(
&'a self,
u: f32,
v: f32,
sampling: Sampling,
footprint: f32,
decode_full: impl Fn([f32; 4]) -> [f32; 4],
mips: impl FnOnce() -> &'a [MipLevel],
) -> [f32; 4] {
if !u.is_finite() || !v.is_finite() {
return [0.0; 4];
}
let repeat = sampling.wrap.repeats();
let full = || decode_full(bilinear(&self.rgba, self.width, self.height, u, v, repeat));
match sampling.filtering {
Filtering::Nearest => decode_full(self.nearest(u, v, repeat)),
Filtering::BilinearSharp => full(),
Filtering::BilinearHq => {
if !uses_mips(footprint) {
return full();
}
let levels = mips();
let level_of_detail = footprint.log2().min(levels.len() as f32);
let finer_level = level_of_detail.floor() as usize;
let toward_coarser = level_of_detail - finer_level as f32;
// Level zero uses the file image; the first stored level is half-sized
let level = |index: usize| {
index
.checked_sub(1)
.and_then(|mip_index| levels.get(mip_index))
.map_or_else(full, |mip| bilinear(&mip.rgba, mip.width, mip.height, u, v, repeat))
};
let finer = level(finer_level);
if toward_coarser <= 0.0 {
return finer;
}
let coarser = level(finer_level + 1);
[0, 1, 2, 3].map(|component| finer[component] + (coarser[component] - finer[component]) * toward_coarser)
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_core::UvWrap;
#[test]
fn a_huge_texture_coordinate_samples_without_overflowing() {
let image = ImageRes::new(2, 2, vec![[0.5; 4]; 4], false);
let sampled = image.sample(1e30, -1e30);
assert_eq!(sampled, [0.5; 4]);
}
/// A 4 × 1 image of columns 0, 1, 2, 3
fn ramp() -> ImageRes {
ImageRes::new(4, 1, (0..4).map(|column| [column as f32; 4]).collect(), false)
}
fn sampling(filtering: Filtering, wrap: UvWrap) -> Sampling {
Sampling { filtering, wrap, ..Sampling::default() }
}
#[test]
fn nearest_reads_the_texel_under_the_point_and_wraps_or_stops_at_the_edge() {
let image = ramp();
let inside = image.sample_filtered(0.6, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0);
let wrapped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0);
let stopped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::None), 1.0);
assert_eq!(inside, [2.0; 4]);
assert_eq!(wrapped, [0.0; 4], "past the right edge a repeating image starts again");
assert_eq!(stopped, [3.0; 4], "past the right edge a single image keeps its last column");
}
#[test]
fn a_bilinear_read_past_a_single_images_edge_blends_no_far_side_texel() {
let image = ramp();
let repeating = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::Repeat), 1.0);
let single = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::None), 1.0);
assert!(repeating[0] < 3.0, "the far side's 0 blends in: {repeating:?}");
assert_eq!(single, [3.0; 4]);
}
#[test]
fn high_quality_mips_keep_odd_trailing_rows_and_columns() {
let mut pixels = vec![[0.0; 4]; 9];
pixels[8] = [1.0, 0.0, 0.0, 1.0];
let image = ImageRes::new(3, 3, pixels, false);
let [red, _, _, alpha] = image.sample_filtered(0.5, 0.5, sampling(Filtering::BilinearHq, UvWrap::None), 8.0);
assert!((red - 1.0 / 9.0).abs() < 1e-6);
assert_eq!(red, alpha);
}
#[test]
fn high_quality_bilinear_reads_the_mip_the_footprint_asks_for() {
let image = ramp();
let hq = sampling(Filtering::BilinearHq, UvWrap::Repeat);
let full = image.sample_filtered(0.375, 0.5, hq, 1.0);
let halved = image.sample_filtered(0.25, 0.5, hq, 2.0);
let quartered = image.sample_filtered(0.375, 0.5, hq, 4.0);
let past_the_last = image.sample_filtered(0.375, 0.5, hq, 64.0);
let between = image.sample_filtered(0.875, 0.5, hq, 2.0_f32.sqrt());
assert_eq!(full, [1.0; 4], "a footprint of 1 reads the full image at column 1's centre");
assert_eq!(halved, [0.5; 4], "level 1's first texel averages columns 0 and 1");
assert_eq!(quartered, [1.5; 4], "a 1-texel level holds the mean");
assert_eq!(past_the_last, quartered, "a footprint past the last level reads the last one");
assert!(between[0] > 2.0 && between[0] < 3.0, "half a level blends the full image's 3 and level 1's 2: {between:?}");
}
#[test]
fn an_unshrunk_high_quality_read_builds_no_mips() {
let image = ramp();
let full = image.sample_filtered(0.375, 0.5, sampling(Filtering::BilinearHq, UvWrap::Repeat), 1.0);
assert_eq!(full, [1.0; 4]);
assert!(image.mips.get().is_none(), "a footprint of 1 reads only the full image");
}
#[test]
fn srgb_mip_transition_blends_linear_color_and_keeps_coverage() {
let image = ImageRes::new(2, 1, vec![[0.0; 4], [1.0; 4]], true);
let hq = sampling(Filtering::BilinearHq, UvWrap::None);
let half_level_footprint = 2.0_f32.sqrt();
let full = image.sample_srgb_color(0.25, 0.5, hq, 1.0);
let midpoint = image.sample_srgb_color(0.25, 0.5, hq, half_level_footprint);
let coverage = image.sample_alpha(0.25, 0.5, hq, half_level_footprint);
assert_eq!(full, [0.0; 4], "full resolution reads the center of the black texel");
assert!((midpoint[0] - 0.25).abs() < 1e-6, "mix linear black and the half-bright mip: {midpoint:?}");
assert_eq!(midpoint[3], coverage);
assert!(image.mips.get().is_none(), "coverage can use the same mip chain as color");
}
#[test]
fn a_mixed_use_image_reports_the_texels_held_by_both_mip_chains() {
let image = ImageRes::new(4, 4, vec![[0.5; 4]; 16], true);
let hq = sampling(Filtering::BilinearHq, UvWrap::None);
let base = image.retained_texel_bytes();
image.sample_srgb_color(0.5, 0.5, hq, 4.0);
let color_only = image.retained_texel_bytes();
image.sample_filtered(0.5, 0.5, hq, 4.0);
let mixed = image.retained_texel_bytes();
assert!(color_only > base);
assert_eq!(mixed - color_only, color_only - base);
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option<Chan
let mut cut = project.clone();
// Ordinary previews need no neighbouring layers or their filter allocations
if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_anchor(project, *layer)) {
if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_stack(project, *layer)) {
cut.texture_sets.get_mut(texture_set)?.stack = vec![id];
}
+150
View File
@@ -0,0 +1,150 @@
//! How long one repeat of a fill's tile is on the mesh (mesh units): Physical size reads it from the tiling and writes tiling back
use std::f32::consts::TAU;
use texturecraft_core::{FULL_TURN_DEGREES, Projection};
use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch};
mod mesh_size;
pub use mesh_size::MeshSize;
/// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round)
fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> {
let radius = size.radius;
match projection {
Projection::Uv { .. } => Some([size.uv_density; 2]),
Projection::Triplanar { scale, projector, .. } => {
// Every plane repeats in the one length only while the stretch is even
let stretch = projector_stretch(projector).abs();
let even = stretch.x == stretch.y && stretch.y == stretch.z;
even.then_some([radius * stretch.x / scale; 2])
}
Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => {
let stretch = projector_stretch(projector).abs();
Some([frame.size[0] * stretch.x, frame.size[1] * stretch.y])
}
Projection::Planar { scale, axis, projector, .. } => {
let stretch = projector_stretch(projector).abs();
let [across, down] = match axis {
0 => [stretch.z, stretch.y],
1 => [stretch.x, stretch.z],
_ => [stretch.x, stretch.y],
};
Some([2.0 * radius * across / scale, 2.0 * radius * down / scale])
}
Projection::Cylindrical { scale, axis, angle, projector, .. } => {
let stretch = projector_stretch(projector).abs();
let ([across, depth], height) = match cylinder_axis_index(*axis) {
0 => ([stretch.y, stretch.z], stretch.x),
2 => ([stretch.x, stretch.y], stretch.z),
_ => ([stretch.x, stretch.z], stretch.y),
};
// Round an uneven cross-section the turn is no fixed length of surface
if across != depth {
return None;
}
let around = TAU * radius * across * (angle.max(MIN_CYLINDER_ANGLE) / FULL_TURN_DEGREES);
Some([around / scale, 2.0 * radius * height / scale])
}
Projection::UvTile | Projection::Spherical { .. } => None,
}
}
/// The tiling a physical size reads and writes: UV's own tiling, a 3D projection's UV tiling
fn tiling(projection: &Projection) -> Option<[f32; 2]> {
match projection {
Projection::Uv { scale, .. } => Some(*scale),
Projection::Triplanar { uv, .. } | Projection::Planar { uv, .. } | Projection::Cylindrical { uv, .. } | Projection::Warp { uv, .. } => Some(uv.tiling),
Projection::UvTile | Projection::Spherical { .. } => None,
}
}
/// Mesh units one repeat of the tile covers across and down
pub fn tile_length(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> {
let unit = unit_tile(projection, size)?;
let tiling = tiling(projection)?;
Some([unit[0] / tiling[0].max(f32::EPSILON), unit[1] / tiling[1].max(f32::EPSILON)])
}
/// The tiling that makes one repeat `length` mesh units long across and down
pub fn tiling_for_length(projection: &Projection, size: MeshSize, length: [f32; 2]) -> Option<[f32; 2]> {
let unit = unit_tile(projection, size)?;
Some([unit[0] / length[0].max(f32::EPSILON), unit[1] / length[1].max(f32::EPSILON)])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pattern::{Coords, image_samples};
use texturecraft_core::{Projector, UvTransform};
use texturecraft_geom::glam::{Vec2, Vec3};
const SIZE: MeshSize = MeshSize { radius: 2.0, uv_density: 3.0 };
#[test]
fn uv_tile_length_is_the_uv_density_over_the_tiling() {
let uv = Projection::Uv { scale: [2.0, 4.0], rotation: 0.0, offset: [0.0; 2] };
assert_eq!(tile_length(&uv, SIZE), Some([1.5, 0.75]));
}
#[test]
fn a_length_read_back_gives_the_same_tiling() {
let uv = UvTransform { tiling: [3.0, 1.5], ..UvTransform::default() };
for projection in [
Projection::Uv { scale: [3.0, 1.5], rotation: 0.0, offset: [0.0; 2] },
Projection::Triplanar { scale: 1.5, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector: Default::default() },
Projection::Planar { scale: 0.5, axis: 2, offset: [0.0; 3], uv, projector: Default::default(), placed: None },
Projection::Cylindrical { scale: 2.0, axis: 1, uv, offset: [0.0; 3], projector: Default::default(), angle: 360.0 },
] {
let length = tile_length(&projection, SIZE).unwrap();
let tiling = tiling_for_length(&projection, SIZE, length).unwrap();
assert!((tiling[0] - 3.0).abs() < 1e-5 && (tiling[1] - 1.5).abs() < 1e-5, "{projection:?}: {tiling:?}");
}
}
#[test]
fn a_written_length_is_the_repeat_on_the_mesh_through_a_stretched_projector() {
let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() };
let axis_planar = |uv| Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv, projector, placed: None };
let length = 2.0;
let tiling = tiling_for_length(&axis_planar(UvTransform::default()), SIZE, [length; 2]).unwrap();
let planar = axis_planar(UvTransform { tiling, ..UvTransform::default() });
let at = |x: f32, y: f32| image_samples(&planar, &Coords { uv: Vec2::ZERO, pos: Vec3::new(x, y, 0.0) / SIZE.radius, nrm: Vec3::Z })[0].0;
let across = at(0.3 + length, 0.1) - at(0.3, 0.1);
let down = at(0.3, 0.1 + length) - at(0.3, 0.1);
assert_eq!(tile_length(&axis_planar(UvTransform::default()), SIZE), Some([8.0, 4.0]), "the stretch doubles the repeat across");
assert!((across.x.abs() - 1.0).abs() < 1e-4 && across.y.abs() < 1e-4, "one length across is one tile: {across}");
assert!(down.x.abs() < 1e-4 && (down.y.abs() - 1.0).abs() < 1e-4, "one length down is one tile: {down}");
}
#[test]
fn a_stretch_uneven_round_the_planes_has_no_physical_size() {
let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() };
let uv = UvTransform::default();
let triplanar = Projection::Triplanar { scale: 1.0, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector };
let cylinder = Projection::Cylindrical { scale: 1.0, axis: 1, uv, offset: [0.0; 3], projector, angle: 360.0 };
let along_axis = Projection::Cylindrical { scale: 1.0, axis: 0, uv, offset: [0.0; 3], projector, angle: 360.0 };
assert_eq!(tile_length(&triplanar, SIZE), None);
assert_eq!(tile_length(&cylinder, SIZE), None);
assert_eq!(tile_length(&along_axis, SIZE).map(|[_, down]| down), Some(8.0), "a stretch along the axis lengthens the repeat down it");
}
#[test]
fn a_cylinder_of_no_angle_still_has_a_length() {
let flat = Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default(), angle: 0.0 };
let length = tile_length(&flat, SIZE).unwrap();
assert!(length[0] > 0.0, "{length:?}");
assert!(tiling_for_length(&flat, SIZE, length).unwrap()[0] > 0.0, "a written-back tiling is never 0");
}
}
@@ -0,0 +1,6 @@
/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeshSize {
pub radius: f32,
pub uv_density: f32,
}
+1 -1
View File
@@ -599,7 +599,7 @@ mod tests {
fn halves(left: f32, right: f32) -> std::sync::Arc<ImageRes> {
let size = 8;
let rgba = (0..size * size).map(|texel| if texel % size < size / 2 { [left, left, left, 1.0] } else { [right, right, right, 1.0] }).collect();
std::sync::Arc::new(ImageRes { width: size as u32, height: size as u32, rgba, srgb: false })
std::sync::Arc::new(ImageRes::new(size as u32, size as u32, rgba, false))
}
#[test]
+117
View File
@@ -0,0 +1,117 @@
//! Where a point in a warp projection's frame lands in its image: the inverse of the bilinear quad its four corners make
use texturecraft_geom::glam::Vec2;
/// Texture coordinates (v down) of a point in frame units.
/// Corners run from top left clockwise. Coordinates extend past the quad for repeating images.
pub fn warp_uv(corners: &[[f32; 2]; 4], point: Vec2) -> Option<Vec2> {
let [top_left, top_right, bottom_right, bottom_left] = corners.map(Vec2::from);
let top_edge = top_right - top_left;
let left_edge = bottom_left - top_left;
let twist = top_left - top_right + bottom_right - bottom_left;
let relative_point = point - top_left;
let base_area = top_edge.perp_dot(left_edge);
let quadratic = twist.perp_dot(left_edge);
let linear = base_area + relative_point.perp_dot(twist);
let constant = relative_point.perp_dot(top_edge);
let at = |v| across(top_edge, left_edge, twist, relative_point, v).map(|u| Vec2::new(u, v));
let uv = if quadratic.abs() <= RELATIVE_PARALLEL * base_area.abs() {
// Parallel sides make the quad's equation linear in v
at(-constant / linear)?
} else {
let discriminant = linear * linear - 4.0 * constant * quadratic;
if discriminant < 0.0 {
return None;
}
// Avoid subtracting near-equal values when the quad is nearly a parallelogram
let root_term = -0.5 * (linear + discriminant.sqrt().copysign(linear));
// At a double root of zero only the first candidate is finite
let candidates = [at(root_term / quadratic), at(constant / root_term)];
candidates.into_iter().flatten().min_by(|x, y| outside(*x).total_cmp(&outside(*y)))?
};
uv.is_finite().then_some(uv)
}
/// How far across (u) a point lies at height `v`, solved on whichever axis the quad's edge spans most
fn across(top_edge: Vec2, left_edge: Vec2, twist: Vec2, relative_point: Vec2, v: f32) -> Option<f32> {
let span = top_edge + twist * v;
let u = if span.x.abs() >= span.y.abs() { (relative_point.x - left_edge.x * v) / span.x } else { (relative_point.y - left_edge.y * v) / span.y };
u.is_finite().then_some(u)
}
/// How far `uv` lies outside the image's 0..1 square (0 inside)
fn outside(uv: Vec2) -> f32 {
(uv - uv.clamp(Vec2::ZERO, Vec2::ONE)).length_squared()
}
/// Relative area below which the quadratic contribution counts as parallel
const RELATIVE_PARALLEL: f32 = 1e-6;
#[cfg(test)]
mod tests {
use super::*;
const FRAME: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]];
/// The point at texture coordinates `uv` inside the quad `corners`
fn bilinear(corners: &[[f32; 2]; 4], uv: Vec2) -> Vec2 {
let [a, b, c, d] = corners.map(Vec2::from);
let top = a.lerp(b, uv.x);
let bottom = d.lerp(c, uv.x);
top.lerp(bottom, uv.y)
}
#[test]
fn the_unpulled_frame_maps_like_a_planar_frame() {
for (x, y) in [(0.0, 0.0), (-0.5, 0.5), (0.25, -0.4), (1.3, 0.7), (-2.0, -1.5)] {
assert_eq!(warp_uv(&FRAME, Vec2::new(x, y)), Some(Vec2::new(x + 0.5, 0.5 - y)), "{x} {y}");
}
}
#[test]
fn pulled_corners_bend_the_image_to_their_quad() {
let quads = [
[[-0.6, 0.4], [0.5, 0.7], [0.3, -0.5], [-0.4, -0.45]],
[[-0.5, 0.5], [0.9, 0.5], [0.5, -0.5], [-0.5, -0.5]],
[[-0.2, 0.6], [0.2, 0.6], [0.7, -0.6], [-0.7, -0.6]],
// Nearly a parallelogram: one corner a hair out
[[0.0, 0.0], [1.0, 0.0], [1.0 + 1.0 / 262_144.0, 1.0], [0.0, 1.0]],
];
for quad in quads {
for i in 0..=10 {
for j in 0..=10 {
let uv = Vec2::new(i as f32 / 10.0, j as f32 / 10.0);
let found = warp_uv(&quad, bilinear(&quad, uv)).unwrap_or(Vec2::NAN);
assert!((found - uv).length() < 1e-4, "{quad:?} {uv}: {found}");
}
}
}
}
#[test]
fn shrinking_a_distorted_quad_preserves_its_mapping() {
let corners = [[0.0, 0.0], [1.0, 0.0], [2.0, 1.0], [0.0, 1.0]];
let uv = Vec2::splat(0.5);
let point = bilinear(&corners, uv);
let scale = 0.0001;
let smaller = corners.map(|corner| corner.map(|coordinate| coordinate * scale));
let found = warp_uv(&smaller, point * scale).unwrap();
assert!(found.distance(uv) < 1e-5, "the scaled quad still maps to the middle: {found}");
}
#[test]
fn a_collapsed_quad_lands_nowhere_instead_of_failing() {
let point = [[0.0, 0.0]; 4];
assert_eq!(warp_uv(&point, Vec2::new(0.3, 0.2)), None);
assert_eq!(warp_uv(&[[f32::NAN; 2]; 4], Vec2::ZERO), None);
}
}
+127
View File
@@ -0,0 +1,127 @@
//! A warp's or slope blur's source as read around one texel
use texturecraft_core::{WarpSource, WarpSourceMode, lum};
use crate::eval::{MIN_ALPHA, texel_noise};
use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample};
/// A warp's or slope blur's source at one texel's neighbourhood
pub(crate) struct WarpSourceSample<'a> {
source: &'a WarpSource,
/// The default noise's seed
seed: u32,
res: u32,
comps: usize,
sample: Sample<'a>,
input: Input<'a>,
/// Half the texels the source is blurred across, worked out once per texel
half_blur: f32,
tiling: f32,
tile_origin: [f32; 2],
tile_size: [f32; 2],
}
impl<'a> WarpSourceSample<'a> {
/// Read the source around `texel`. Atlas blocks retain their full stride even when a UV tile has fewer texels.
pub(crate) fn new(
source: &'a WarpSource,
seed: u32,
texel: [f32; 2],
(res, comps): (u32, usize),
(block_size, tile_size): ([u32; 2], [u32; 2]),
(sample, input): (Sample<'a>, Input<'a>),
) -> Self {
let tiling = source.tiling_factor();
let tile_origin = if source.mode != WarpSourceMode::DefaultNoise && tiling != 1.0 {
std::array::from_fn(|axis| {
let stride = block_size[axis].max(1) as f32;
(texel[axis] / stride).floor() * stride
})
} else {
[0.0; 2]
};
Self {
source,
seed,
res,
comps,
sample,
input,
half_blur: source.blur_texels(res) / 2.0,
tiling,
tile_origin,
tile_size: tile_size.map(|size| size.max(1) as f32),
}
}
/// The source at texel position `(x, y)` after its blur, Balance and Contrast
pub(crate) fn at(&self, x: f32, y: f32) -> f32 {
let half = self.half_blur;
let value = if half > 0.0 {
let corners = [(-half, -half), (half, -half), (-half, half), (half, half)];
let (sum, count) = corners.iter().filter_map(|(dx, dy)| self.raw(x + dx, y + dy)).fold((0.0f32, 0u8), |(sum, count), read| (sum + read, count + 1));
if count == 0 { WarpSource::MID_GRAY } else { sum / f32::from(count) }
} else {
self.raw(x, y).unwrap_or(WarpSource::MID_GRAY)
};
self.source.shape(value)
}
/// The source at texel position `(x, y)` before it is shaped; None where the values it filters cover nothing
fn raw(&self, x: f32, y: f32) -> Option<f32> {
if self.source.mode == WarpSourceMode::DefaultNoise {
return Some(WarpSource::stretch_noise(texel_noise(x, y, [0.0; 2], self.res, self.source.noise_scale(), self.seed)));
}
let [x, y] = if self.tiling == 1.0 {
[x, y]
} else {
let repeat = |axis: usize, position: f32| {
let origin = self.tile_origin[axis];
let size = self.tile_size[axis];
let repeated = ((position - origin + 0.5) * self.tiling).rem_euclid(size) - 0.5;
// Keep the bilinear taps in this UV tile at the ends of each repeat
origin + repeated.clamp(0.0, size - 1.0)
};
[repeat(0, x), repeat(1, y)]
};
if self.source.mode == WarpSourceMode::CustomNoise {
return (self.input)(x, y);
}
let mut read = [0.0f32; 5];
(self.sample)(x, y, &mut read);
match (self.comps, read) {
// Content stays premultiplied by its own coverage
(4, [r, g, b, alpha, _]) if alpha > MIN_ALPHA => Some(lum([r / alpha, g / alpha, b / alpha])),
(1, [value, .., weight]) if weight > MIN_READ_WEIGHT => Some(value / weight),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tiled_input_reads_stay_within_the_current_atlas_block() {
let source = WarpSource { mode: WarpSourceMode::CustomNoise, tiling: 2.0, ..WarpSource::LIBRARY };
let sample = |_x, _y, _read: &mut [f32; 5]| {};
let input = |x: f32, y: f32| {
assert!((64.0..=95.0).contains(&x) && (128.0..=159.0).contains(&y), "read at {x}, {y}");
Some(((x - 64.0) + (y - 128.0)) / 64.0)
};
let tiled = WarpSourceSample::new(&source, 0, [94.0, 158.0], (32, 1), ([64; 2], [32; 2]), (&sample, &input));
let first_repeat = tiled.at(69.0, 135.0);
let second_repeat = tiled.at(85.0, 151.0);
assert_eq!(first_repeat, second_repeat);
assert_ne!(tiled.at(70.0, 135.0), first_repeat);
assert!(tiled.at(63.0, 160.0).is_finite());
}
}
+80
View File
@@ -0,0 +1,80 @@
//! What a Warp filter reads for one texel: its source, then the moves its mode makes
use texturecraft_core::{SourceWarp, WarpBlending, WarpMode};
use crate::warp_source_sample::WarpSourceSample;
/// Bilinear sample at an absolute texel position into an accumulator (components, then weight), as [`crate::eval`]'s gather reads
pub(crate) type Sample<'a> = &'a dyn Fn(f32, f32, &mut [f32; 5]);
/// The filter's Custom Noise image input at an absolute texel position; None where the values it filters cover nothing
pub(crate) type Input<'a> = &'a dyn Fn(f32, f32) -> Option<f32>;
/// A read weighing less than this covers nothing
pub(crate) const MIN_READ_WEIGHT: f32 = 1e-6;
/// Warp `warp` at texel `(x, y)` into `acc`: where its source sends it, or those reads blended
pub(crate) fn warp_texel(
(warp, directions): (&SourceWarp, &[[f32; 2]]),
(x, y): (f32, f32),
(res, comps): (u32, usize),
tile_sizes: ([u32; 2], [u32; 2]),
acc: &mut [f32; 5],
(sample, input): (Sample<'_>, Input<'_>),
) {
let source = WarpSourceSample::new(&warp.source, warp.seed, [x, y], (res, comps), tile_sizes, (sample, input));
let reach = warp.move_texels(res);
if warp.mode == WarpMode::Warp {
let probe = SourceWarp::probe_texels(res);
let rise = [source.at(x + probe, y) - source.at(x - probe, y), source.at(x, y + probe) - source.at(x, y - probe)];
let [dx, dy] = warp.slope_move(rise, res);
sample(x + dx, y + dy, acc);
return;
}
let directions = directions.iter().copied();
let displacement = |at_x, at_y| SourceWarp::amount(source.at(at_x, at_y)) * reach;
if warp.mode == WarpMode::MultiDirectional && warp.blending == WarpBlending::Chain {
let (end_x, end_y) = directions.fold((x, y), |(at_x, at_y), [dx, dy]| {
let along = displacement(at_x, at_y);
(at_x + dx * along, at_y + dy * along)
});
sample(end_x, end_y, acc);
return;
}
// Independent directions share the source at the original texel
let along = displacement(x, y);
let reads = directions.map(|[dx, dy]| (x + dx * along, y + dy * along));
if warp.mode == WarpMode::MultiDirectional && matches!(warp.blending, WarpBlending::Max | WarpBlending::Min) {
keep_extreme_read(reads, warp.blending == WarpBlending::Max, comps, acc, sample);
} else {
for (at_x, at_y) in reads {
sample(at_x, at_y, acc);
}
}
}
/// Keeps in `acc` the largest (or smallest) of the reads at `positions`, component by component; reads that cover nothing are skipped
pub(crate) fn keep_extreme_read(positions: impl Iterator<Item = (f32, f32)>, larger: bool, comps: usize, acc: &mut [f32; 5], sample: Sample<'_>) {
let mut picked: Option<[f32; 5]> = None;
for (at_x, at_y) in positions {
let mut read = [0.0f32; 5];
sample(at_x, at_y, &mut read);
if read[4] <= MIN_READ_WEIGHT {
continue;
}
let read = read.map(|component| component / read[4]);
picked = Some(match picked {
Some(so_far) => std::array::from_fn(|k| if larger { so_far[k].max(read[k]) } else { so_far[k].min(read[k]) }),
None => read,
});
}
if let Some(picked) = picked {
let kept = comps.min(4);
acc[..kept].copy_from_slice(&picked[..kept]);
acc[4] = 1.0;
}
}
+416 -25
View File
@@ -4,14 +4,23 @@
use std::collections::BTreeMap;
use texturecraft_compose::{BelowCache, Composite, Inputs, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached};
use texturecraft_compose::{
BelowCache, Composite, Inputs, MaskGray, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached,
};
use texturecraft_core::project::ENV_RESOURCE_PREFIX;
use texturecraft_core::{
BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground,
Procedural, ProceduralKind, Project, Projection, Source, TextureSet,
BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind,
GrayscaleConversion, HeightMask, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source,
TextureSet,
};
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
use texturecraft_texel::{TILE, TileImage, to_u16};
#[path = "cache_and_instances/blur_on.rs"]
mod blur_on;
use blur_on::BlurOn;
const RES: u32 = 256;
struct Fixture {
@@ -67,9 +76,9 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position))));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false })));
add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask));
let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false }, None);
let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None);
for b in f.project.layer_mut(group).unwrap().channels.values_mut() {
b.mode = BlendMode::Passthrough;
}
@@ -77,8 +86,11 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
let l = Layer::new(inner, "inner", fill(&[(Channel::Metallic, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), &Channel::DEFAULT_SET);
f.project.insert_layer(0, l, Some(group), true).unwrap();
let mut blurred = Mask::new(MaskBackground::Black);
blurred.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 })));
blurred.effects.push(effect(
f,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0, wrap: false })));
let top = add(f, 0, LayerKind::Paint, Some(blurred));
let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES));
for y in 40..200 {
@@ -203,7 +215,7 @@ fn mask_with_height_follows_the_layer_height() {
let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3], ramp: Vec::new() };
let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() }));
mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default(), sampling: Default::default() }));
f.project.layer_mut(id).unwrap().mask = Some(mask);
let plain = reference(&f, 0);
f.project.layer_mut(id).unwrap().height_mask = HeightMask { enabled: true, contrast: 1.0, offset: 0.0 };
@@ -211,17 +223,19 @@ fn mask_with_height_follows_the_layer_height() {
let row = TILE * 2;
let (left, right) = (16, RES - 16);
let v = |c: &Composite, x| c.value(Channel::BaseColor, x, row)[0];
assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray");
assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left));
assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right));
// Without a mask there is nothing to combine
f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false;
assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3);
}
fn group(f: &mut Fixture, folder: Option<LayerId>, mode: BlendMode, opacity: f32, mask: Option<Mask>) -> LayerId {
let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false }, mask);
let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, mask);
blend(f, id, mode, opacity);
id
}
@@ -241,7 +255,7 @@ fn generator_mask(f: &mut Fixture, kind: GeneratorKind, blur: Option<f32>) -> Ma
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(f, EffectKind::Generator(g)));
if let Some(radius) = blur {
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius })));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius, wrap: false })));
}
mask
}
@@ -290,7 +304,10 @@ fn nested_stack(f: &mut Fixture) -> Nested {
let inner =
put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None);
let mut checker = Mask::new(MaskBackground::Black);
checker.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default() }));
checker.effects.push(effect(
f,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default(), sampling: Default::default() },
));
let g2 = group(f, Some(g1), BlendMode::Passthrough, 1.0, Some(checker));
let mask = generator_mask(f, GeneratorKind::Direction, Some(16.0));
put(f, 0, Some(g2), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), Some(mask));
@@ -302,8 +319,8 @@ fn nested_stack(f: &mut Fixture) -> Nested {
blend(f, g2_above, BlendMode::Overlay, 0.7);
put(f, 0, Some(g2), LayerKind::Instance { source: base }, Some(Mask::new(MaskBackground::White)));
let g1_above = put(f, 0, Some(g1), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Wood, 0.2, 0.8))]), None);
let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0 }));
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0 }));
let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0, perceptive: false }));
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0, wrap: false }));
f.project.layer_mut(g1_above).unwrap().content_effects.extend([hsl, blur]);
blend(f, g1_above, BlendMode::Screen, 0.5);
let mask = generator_mask(f, GeneratorKind::Position, Some(30.0));
@@ -330,7 +347,7 @@ fn stroke(target: LayerId) -> StrokePreview {
opacity: 0.9,
erase: false,
values: [(Channel::BaseColor, [1.0, 0.1, 0.1]), (Channel::Roughness, [0.2; 3])].into_iter().collect(),
mask_value: 1.0,
mask_gray: MaskGray::Value(1.0),
stencil: None,
carried: BTreeMap::new(),
carried_mask: None,
@@ -412,7 +429,7 @@ fn anchor_readers_fall_back_to_full_evaluation() {
f.project.layer_mut(n.base).unwrap().content_effects.push(anchor);
// A mask above the hot layer reads the stack below it
let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default() });
let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() });
f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(reader);
for hot in [n.deep, n.top] {
assert!(check_cached(&f, 0, hot).is_empty(), "anchors read the stack: nothing cached");
@@ -534,15 +551,17 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything");
// Behind a blur the cut reads the filtered field; before it, the unfiltered content
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 }));
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0, wrap: false }));
f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
let blurred = reference(&f, 0);
assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat");
let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
let (images, baked) = (Default::default(), Default::default());
for t in all_tiles(RES, RES) {
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
}
assert!(one_by_one == blurred);
}
@@ -556,13 +575,16 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
None,
);
let mut slope = Mask::new(MaskBackground::Black);
slope.effects.push(effect(&mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 })));
slope.effects.push(effect(
&mut f,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1, divider: 1 })));
let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope));
let top = add(&mut f, 0, LayerKind::Paint, None);
paint_rect(&mut f, top, (30, 40), (150, 100), 0.4);
let plain = reference(&f, 0);
let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3 }));
let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3, divider: 1 }));
f.project.layer_mut(base).unwrap().content_effects.push(warp);
let line = effect(&mut f, EffectKind::Filter(Filter::DirectionalBlur { radius: 40.0, angle: 30.0 }));
f.project.layer_mut(streaks).unwrap().content_effects.push(line);
@@ -575,7 +597,9 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
for t in all_tiles(RES, RES) {
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
}
assert!(one_by_one == want, "per-tile composites differ from one pass");
for hot in [top, streaks] {
assert!(!check_cached(&f, 0, hot).is_empty());
}
@@ -648,14 +672,17 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
// Keep fields for the remaining tiles
cache.ahead = rest.to_vec();
let mut out = run(&fixture, 0, first, Some(&mut cache));
assert!(cache.holds_fields());
// Changing the hot mask must invalidate the retained fields
let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap();
mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 });
let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap();
blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false });
let (images, baked) = (Default::default(), Default::default());
cache.ahead = Vec::new();
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache));
assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it");
assert!(!cache.holds_fields());
@@ -668,6 +695,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
let mut inp = inputs(&fixture, 0, &images, &baked);
inp.preview = Some(&preview);
composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache));
assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs");
}
@@ -685,8 +713,11 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
// Pattern detail exposes any missing blur field
let mut blurred = Mask::new(MaskBackground::Black);
blurred.effects.push(effect(&mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
blurred.effects.push(effect(
&mut fixture,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false })));
add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred));
// Keep the blurred layer visible under the hot layer
@@ -707,7 +738,9 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
cache.set_hot(Some(hot));
let mut out = Composite::new(&channels, SIZE);
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache));
assert_eq!(cache.len(), bottom.len());
cache.budget = cache.bytes();
// Cache eviction during the run must rebuild missing lower-layer fields
@@ -719,6 +752,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
assert!(cache.holds_fields());
}
}
assert!(above.len() > bottom.len());
assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path");
}
@@ -762,7 +796,7 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() {
pattern.tile.get_or_insert_with(Box::default).background_image = Some("plate".into());
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() });
let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false));
let mut images = ImageStore::default();
let baked = Default::default();
let tiles = all_tiles(RES, RES);
@@ -778,13 +812,17 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() {
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
let input = inputs(&fixture, 0, &images, &baked);
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
let retained = cache.len() - 1;
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image");
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
composite_tiles(&input, &mut expected, &tiles);
assert!(output == expected, "{stage}");
}
}
@@ -800,7 +838,7 @@ fn cached_stack_tracks_referenced_images_only() {
let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") };
fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() });
let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false));
let mut images = ImageStore::default();
let baked = Default::default();
let tiles = all_tiles(RES, RES);
@@ -820,11 +858,14 @@ fn cached_stack_tracks_referenced_images_only() {
let replacement = image_with_value(0.4);
let replacement_weak = Arc::downgrade(&replacement);
images.insert("used".into(), replacement);
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels");
previous_image = Some(replacement_weak);
}
"remove" => {
images.remove("used");
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels");
}
"cold" => {}
@@ -836,13 +877,17 @@ fn cached_stack_tracks_referenced_images_only() {
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
let input = inputs(&fixture, 0, &images, &baked);
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
let retained = cache.len() - 1;
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}");
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
composite_tiles(&input, &mut expected, &tiles);
assert!(output == expected, "{stage}");
}
}
@@ -860,7 +905,7 @@ fn generator_input_image_changes_invalidate_stack_key() {
*generator = Generator::new(GeneratorKind::Dirt);
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used"));
let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let image = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false));
let mut images = ImageStore::default();
images.insert("used".into(), image(0.1));
let baked = Default::default();
@@ -869,13 +914,359 @@ fn generator_input_image_changes_invalidate_stack_key() {
let original = key(&images);
images.insert("unrelated".into(), image(0.5));
assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged");
let old_image = Arc::downgrade(&images["used"]);
images.insert("used".into(), image(0.9));
assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels");
assert!(key(&images) != original, "replacing a generator input must invalidate the cache");
images.remove("used");
assert!(key(&images) != original, "removing a generator input must invalidate the cache");
}
#[test]
fn compare_masks_reading_layers_fall_back_to_full_evaluation() {
let mut f = fixture();
let n = nested_stack(&mut f);
let compare = effect(
&mut f,
EffectKind::Compare {
op: CompareOp::GreaterThan,
value: 0.5,
tolerance: 0.0,
left: CompareSource::LayersBelow,
right: CompareSource::ThisLayer,
channel: Channel::Roughness,
hardness: 1.0,
},
);
// A mask above the hot layer compares the stack below it
f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(compare);
for hot in [n.deep, n.top] {
assert!(check_cached(&f, 0, hot).is_empty(), "compare masks read the stack: nothing cached");
}
}
/// The key of set 0's whole stack over `images`
fn stack_key(fixture: &Fixture, images: &texturecraft_compose::ImageStore) -> texturecraft_compose::StackKey {
let roots = &fixture.project.texture_sets[0].stack;
texturecraft_compose::StackKey::new(&fixture.project, &fixture.pixels, &Default::default(), images, 0, roots).unwrap()
}
/// A flat image resource of `value`
fn flat_image(value: f32) -> std::sync::Arc<texturecraft_compose::ImageRes> {
std::sync::Arc::new(texturecraft_compose::ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false))
}
#[test]
fn filter_input_and_id_map_image_changes_invalidate_stack_key() {
let mut fixture = fixture();
heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let conversion = GrayscaleConversion { custom_input: true, ..GrayscaleConversion::LIBRARY };
let mut filter = effect(&mut fixture, EffectKind::Filter(Filter::GrayscaleConversion(conversion)));
filter.inputs.insert(ImageInput::CUSTOM_INPUT.id.into(), Source::image("input"));
let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1);
selection.id_map = Some("id".into());
let selection = effect(&mut fixture, EffectKind::ColorSelection(selection));
let layer = fixture.project.layer_mut(bottom_layer).unwrap();
layer.content_effects.push(filter);
layer.mask = Some(Mask::new(MaskBackground::White));
layer.mask.as_mut().unwrap().effects.push(selection);
let mut images = texturecraft_compose::ImageStore::default();
images.insert("input".into(), flat_image(0.1));
images.insert("id".into(), flat_image(0.1));
for name in ["input", "id"] {
let original = stack_key(&fixture, &images);
images.insert(name.into(), flat_image(0.9));
assert!(stack_key(&fixture, &images) != original, "replacing the {name} image must invalidate the cache");
}
}
#[test]
fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() {
let mut fixture = fixture();
heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let mut images = texturecraft_compose::ImageStore::default();
images.insert("sky".into(), flat_image(0.5));
fixture.project.display.environment = format!("{ENV_RESOURCE_PREFIX}sky");
let unlit = stack_key(&fixture, &images);
fixture.project.display.env_rotation += 90.0;
assert_eq!(stack_key(&fixture, &images), unlit, "without Baked Lighting Environment the turn changes nothing");
let lighting =
Filter::EnvironmentLighting { horizontal: 0.0, vertical: 0.0, exposure: 0.0, height_intensity: 0.0, ambient_occlusion: 0.0, specular_occlusion: 0.0 };
let lighting = effect(&mut fixture, EffectKind::Filter(lighting));
fixture.project.layer_mut(bottom_layer).unwrap().content_effects.push(lighting);
let lit = stack_key(&fixture, &images);
fixture.project.display.env_rotation += 90.0;
let turned = stack_key(&fixture, &images);
assert!(turned != lit, "turning the environment invalidates the cache");
assert_eq!(lit.changed_tiles(&turned), None, "and recomposites every tile");
images.insert("sky".into(), flat_image(0.9));
assert!(stack_key(&fixture, &images) != turned, "replacing the environment image invalidates the cache");
}
#[test]
fn painting_metallic_updates_validation_on_a_layer_above_it() {
let mut fixture = fixture();
let metal = add(&mut fixture, 0, LayerKind::Paint, None);
let color = add(&mut fixture, 0, fill(&[(Channel::BaseColor, Source::Uniform([0.12; 3]))]), None);
let color_layer = fixture.project.layer_mut(color).unwrap();
color_layer.channels.retain(|channel, _| *channel == Channel::BaseColor);
let validation = effect(&mut fixture, EffectKind::Filter(Filter::PbrValidate(texturecraft_core::PbrValidate::LIBRARY)));
fixture.project.layer_mut(color).unwrap().content_effects.push(validation);
let mut cache = BelowCache::default();
cache.set_hot(Some(metal));
let coordinate = RES / 2;
let tiles = [(coordinate / TILE, coordinate / TILE)];
let before = run(&fixture, 0, &tiles, Some(&mut cache)).value(Channel::BaseColor, coordinate, coordinate);
fixture.pixels.layer_mut(metal, Channel::Metallic, (RES, RES)).set(coordinate, coordinate, &[u16::MAX; 2]);
let fresh = run(&fixture, 0, &tiles, None).value(Channel::BaseColor, coordinate, coordinate);
let updated = run(&fixture, 0, &tiles, Some(&mut cache)).value(Channel::BaseColor, coordinate, coordinate);
assert_ne!(fresh, before, "the same color is valid for a dielectric and too dark for a metal");
assert_eq!(updated, fresh, "replaying the stack must reevaluate material-dependent validation");
}
/// A folder of set `ts` holding a Clouds fill whose content or mask is blurred by 8; returns the folder and the fill
fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option<LayerId>, blur_on: BlurOn) -> (LayerId, LayerId) {
let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None);
let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None);
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }));
match blur_on {
BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur),
BlurOn::Mask => {
let mut mask = Mask::new(MaskBackground::Black);
let checker = procedural(ProceduralKind::Checker, 0.0, 1.0);
mask.effects.push(effect(f, EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }));
mask.effects.push(blur);
f.project.layer_mut(clouds).unwrap().mask = Some(mask);
}
}
(held, clouds)
}
/// A top-level folder of set 0 laying Scale 2 and Rotation 25 on the fills inside it
fn offset_folder(f: &mut Fixture) -> LayerId {
let contents = ContentsOffset::new(2.0, 25.0);
put(f, 0, None, LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, None)
}
#[test]
fn a_neighbourhood_filter_in_an_instanced_folder_under_an_offset_folder_reads_its_content_in_the_instances_space() {
let mut mismatches = Vec::new();
for blur_on in [BlurOn::Content, BlurOn::Mask] {
let mut instanced = fixture();
let (source, _) = folder_of_blurred_clouds(&mut instanced, 1, None, blur_on);
let outer = offset_folder(&mut instanced);
put(&mut instanced, 0, Some(outer), LayerKind::Instance { source }, None);
let mut copied = fixture();
let outer = offset_folder(&mut copied);
folder_of_blurred_clouds(&mut copied, 0, Some(outer), blur_on);
let (instanced, copied) = (reference(&instanced, 0), reference(&copied, 0));
let texels = (0..RES).flat_map(|y| (0..RES).map(move |x| (x, y)));
let differences: Vec<f32> = texels
.map(|(x, y)| {
let (a, b) = (instanced.value(Channel::BaseColor, x, y), copied.value(Channel::BaseColor, x, y));
a.iter().zip(&b).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max)
})
.filter(|difference| *difference > 1e-5)
.collect();
let largest = differences.iter().copied().fold(0.0, f32::max);
if !differences.is_empty() {
mismatches.push(format!("{blur_on:?} blur: the instance differs from the copy by up to {largest} on {} texels", differences.len()));
}
}
assert!(mismatches.is_empty(), "{}", mismatches.join("; "));
}
#[test]
fn a_hot_layer_with_a_neighbourhood_filter_in_an_instanced_folder_under_an_offset_folder_composites_exactly_cached() {
for blur_on in [BlurOn::Content, BlurOn::Mask] {
let mut instanced = fixture();
let (source, clouds) = folder_of_blurred_clouds(&mut instanced, 1, None, blur_on);
let outer = offset_folder(&mut instanced);
put(&mut instanced, 0, Some(outer), LayerKind::Instance { source }, None);
let cache = check_cached(&instanced, 0, clouds);
assert!(!cache.is_empty(), "{blur_on:?} blur: the hot layer is cached through its instance");
}
}
fn cache_after_changing_mesh(owned: bool) {
use std::sync::Arc;
use texturecraft_compose::{ProjectorDepthCache, composite_tiles_with_projectors};
let mut fixture = fixture();
let lower = add(&mut fixture, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]), None);
fixture.project.layer_mut(lower).unwrap().geometry_mask = Some(vec!["Lid".into()]);
let hot = add(&mut fixture, 0, LayerKind::Paint, None);
let mut named = fixture.mesh.clone();
named.submeshes[0].name = "Lid".into();
let first = Arc::new(named);
let second = Arc::new(fixture.mesh.clone());
let images = Default::default();
let baked = Default::default();
let mut projectors = ProjectorDepthCache::default();
let mut cache = BelowCache::default();
cache.set_hot(Some(hot));
let mut render = |mesh: &Arc<Mesh>, cache: Option<&mut BelowCache>| {
let mut input = inputs(&fixture, 0, &images, &baked);
input.mesh = mesh;
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
if owned {
composite_tiles_with_projectors(&input, mesh, &mut projectors, &mut output, &[(1, 1)], cache);
} else {
composite_tiles_cached(&input, &mut output, &[(1, 1)], cache);
}
output
};
let before = render(&first, Some(&mut cache));
assert!(!cache.is_empty());
let expected = render(&second, None);
let actual = render(&second, Some(&mut cache));
assert!(before != expected, "the lower fill applies only to the named part");
assert!(actual == expected, "the previous mesh's cached fill was reused");
}
#[test]
fn a_borrowed_mesh_change_invalidates_cached_fills() {
cache_after_changing_mesh(false);
}
#[test]
fn a_projector_rebind_without_below_cache_invalidates_cached_fills() {
cache_after_changing_mesh(true);
}
fn roughness_compare(fixture: &mut Fixture, source: CompareSource) -> Effect {
effect(
fixture,
EffectKind::Compare {
op: CompareOp::GreaterThan,
value: 0.7,
tolerance: 0.0,
left: source,
right: CompareSource::Constant,
channel: Channel::Roughness,
hardness: 1.0,
},
)
}
#[test]
fn compare_uses_the_stack_below_each_draw_of_an_instanced_folder() {
let mut fixture = fixture();
let base = |roughness| fill(&[(Channel::BaseColor, Source::Uniform([0.0, 0.0, 1.0])), (Channel::Roughness, Source::Uniform([roughness; 3]))]);
add(&mut fixture, 0, base(0.2), None);
let folder = add(&mut fixture, 0, LayerKind::folder(), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false })));
let red = fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]);
put(&mut fixture, 0, Some(folder), red, Some(mask));
add(&mut fixture, 0, base(0.9), None);
add(&mut fixture, 0, LayerKind::Instance { source: folder }, None);
let color = run(&fixture, 0, &[(1, 1)], None).value(Channel::BaseColor, 96, 96);
assert!(color[0] > color[2], "the second draw should read the rougher surface: {color:?}");
}
#[test]
fn compare_reads_a_retained_channel_after_it_is_removed_from_the_outputs() {
let mut fixture = fixture();
let roughness = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]);
add(&mut fixture, 0, roughness, None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
let red = fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]);
add(&mut fixture, 0, red, Some(mask));
let before = run(&fixture, 0, &[(1, 1)], None).value(Channel::BaseColor, 96, 96);
fixture.project.texture_sets[0].channels.retain(|(channel, _)| *channel != Channel::Roughness);
let after = run(&fixture, 0, &[(1, 1)], None);
assert!(before[0] > before[1]);
assert_eq!(after.value(Channel::BaseColor, 96, 96), before);
assert!(!after.channels.contains_key(&Channel::Roughness));
}
#[test]
fn sparse_compare_mask_reads_filtered_content_through_the_full_blur_radius() {
use texturecraft_compose::{mask_texels, mask_values};
const SIZE: u32 = 512;
let mut fixture = fixture();
fixture.mesh = primitives::plane(2.0, 2);
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, SIZE, SIZE);
fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, SIZE);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::ThisLayer));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 256.0, wrap: false })));
let roughness = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]);
let layer = add(&mut fixture, 0, roughness, Some(mask));
let edge = effect(&mut fixture, EffectKind::Filter(Filter::EdgeDetect { width: 8.0 }));
fixture.project.layer_mut(layer).unwrap().content_effects.push(edge);
let (images, baked) = (Default::default(), Default::default());
let center = SIZE / 2;
for (wrap, x) in [(false, center), (true, 0)] {
let EffectKind::Filter(Filter::Blur { wrap: enabled, .. }) =
&mut fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().effects.last_mut().unwrap().kind
else {
panic!("expected blur")
};
*enabled = wrap;
let inputs = inputs(&fixture, 0, &images, &baked);
let full = mask_texels(&inputs, layer).unwrap();
let tile = mask_values(&inputs, layer, &[(x / TILE, center / TILE)]).unwrap();
assert_eq!(tile.get(x, center)[0], to_u16(full[(center * SIZE + x) as usize]), "wrap={wrap}");
}
}
#[test]
fn a_folder_thumbnail_reads_compare_inputs_from_its_backdrop() {
use texturecraft_compose::{ThumbTarget, thumb};
let mut fixture = fixture();
let backdrop = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3])), (Channel::BaseColor, Source::Uniform([0.0, 0.0, 1.0]))]);
add(&mut fixture, 0, backdrop, None);
let folder = add(&mut fixture, 0, LayerKind::folder(), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
put(&mut fixture, 0, Some(folder), fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]), Some(mask));
let (images, baked) = (Default::default(), Default::default());
let inputs = inputs(&fixture, 0, &images, &baked);
let thumbnail = thumb::render(&inputs, ThumbTarget::Content { layer: folder, channel: Channel::BaseColor }).unwrap();
let center = 4 * (96 * RES + 96) as usize;
assert!(thumbnail.rgba[center] > thumbnail.rgba[center + 2], "visible red child");
}
@@ -0,0 +1,6 @@
/// Which stack contains a blur in the instanced-folder fixture.
#[derive(Clone, Copy, Debug)]
pub(super) enum BlurOn {
Content,
Mask,
}
+92
View File
@@ -0,0 +1,92 @@
//! Anisotropic Kuwahara's settings: a painterly smoothing that follows the direction of the strokes
use serde::{Deserialize, Serialize};
/// An Anisotropic Kuwahara filter: each texel takes the mean of the calmest sector of an ellipse turned along the local direction
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnisotropicKuwahara {
/// Extract Direction Custom Input: the direction comes from the filter's Custom Input instead of the channel
pub custom_input: bool,
/// Texels at 2K the ellipse reaches (0..10)
pub radius: f32,
/// How much neighbouring sectors overlap (0 = hard sector edges)
pub smoothness: f32,
/// How strongly the calmest sector wins over the others (0.25..1)
pub sharpness: f32,
/// How far around a texel its direction is averaged, as a share of the radius
pub tensor_smoothness: f32,
/// How much the ellipse stretches along the direction where the direction is clear (0 = a circle)
pub anisotropy: f32,
/// Degrees the ellipse turns from the extracted direction
pub angle: f32,
}
impl AnisotropicKuwahara {
/// A new Anisotropic Kuwahara
pub const LIBRARY: AnisotropicKuwahara =
AnisotropicKuwahara { custom_input: false, radius: 5.0, smoothness: 0.25, sharpness: 0.25, tensor_smoothness: 0.1, anisotropy: 1.0, angle: 0.0 };
/// The largest Radius, in texels at 2K
pub const MAX_RADIUS: f32 = 10.0;
/// The least Sharpness
pub const MIN_SHARPNESS: f32 = 0.25;
/// Sectors the ellipse is split into
pub const SECTORS: usize = 8;
/// The sector weighing exponent at a Sharpness of 0 and of 1 (Sharpness stops at [`Self::MIN_SHARPNESS`], so the least it weighs with is 5.5)
const SHARPNESS_EXPONENT_MIN: f32 = 2.0;
const SHARPNESS_EXPONENT_MAX: f32 = 16.0;
/// The sample falloff exponent at no Smoothness (1 at full Smoothness)
const SECTOR_EXPONENT_MAX: f32 = 16.0;
/// How far around a texel its direction is read, as a share of the radius (Tensor Smoothness, 0..1)
pub fn tensor_reach(&self) -> f32 {
if self.tensor_smoothness.is_finite() { self.tensor_smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.tensor_smoothness }
}
/// The exponent a sector's spread is weighed with: higher picks the calmest sector more sharply
pub fn sharpness_exponent(&self) -> f32 {
let sharpness = if self.sharpness.is_finite() { self.sharpness.clamp(Self::MIN_SHARPNESS, 1.0) } else { Self::LIBRARY.sharpness };
Self::SHARPNESS_EXPONENT_MIN + sharpness * (Self::SHARPNESS_EXPONENT_MAX - Self::SHARPNESS_EXPONENT_MIN)
}
/// How sharply a sample's weight falls off away from a sector's middle: smoother sectors overlap more
pub fn sector_exponent(&self) -> f32 {
let smoothness = if self.smoothness.is_finite() { self.smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.smoothness };
1.0 + (1.0 - smoothness) * (Self::SECTOR_EXPONENT_MAX - 1.0)
}
/// The ellipse's semi-axes (along, across the direction) for `radius` texels where the direction is `clear` (0..1)
pub fn axes(&self, radius: f32, clear: f32) -> (f32, f32) {
let stretch = if self.anisotropy.is_finite() { self.anisotropy.clamp(0.0, 1.0) } else { Self::LIBRARY.anisotropy } * clear.clamp(0.0, 1.0);
(radius * (1.0 + stretch), radius / (1.0 + stretch))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_clear_direction_stretches_the_ellipse() {
let filter = AnisotropicKuwahara::LIBRARY;
assert_eq!(filter.axes(4.0, 0.0), (4.0, 4.0));
assert_eq!(filter.axes(4.0, 1.0), (8.0, 2.0));
assert_eq!(AnisotropicKuwahara { anisotropy: 0.0, ..filter }.axes(4.0, 1.0), (4.0, 4.0));
assert!(AnisotropicKuwahara { sharpness: 1.0, ..filter }.sharpness_exponent() > filter.sharpness_exponent());
assert!(AnisotropicKuwahara { smoothness: 1.0, ..filter }.sector_exponent() < filter.sector_exponent());
}
#[test]
fn sharpness_weighs_on_a_line_from_its_exponent_at_0_to_its_exponent_at_1() {
let at = |sharpness: f32| AnisotropicKuwahara { sharpness, ..AnisotropicKuwahara::LIBRARY }.sharpness_exponent();
assert_eq!(at(AnisotropicKuwahara::MIN_SHARPNESS), 5.5, "the least Sharpness, a quarter of the way along");
assert_eq!(at(0.0), 5.5, "below the least, the least");
assert_eq!(at(1.0), 16.0, "the most Sharpness weighs with the most exponent");
}
}
+23
View File
@@ -0,0 +1,23 @@
//! Backface culling of planar and cylindrical projections
use serde::{Deserialize, Serialize};
/// Faces turned more than `angle` degrees from the projection get none of it, faded softer as `hardness` drops
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Backface {
pub on: bool,
pub angle: f32,
pub hardness: f32,
}
impl Backface {
/// The angle culling may take, in degrees from facing the projector
pub const ANGLE_RANGE: std::ops::RangeInclusive<f32> = 0.0..=180.0;
}
impl Default for Backface {
fn default() -> Self {
Backface { on: false, angle: 90.0, hardness: 0.5 }
}
}
+98
View File
@@ -0,0 +1,98 @@
//! The Bevel filter's settings and the slope it gives a shape's edge
use serde::{Deserialize, Serialize};
use crate::{BevelBlur, BevelCorner, SIZE_REFERENCE_RES};
/// Shapes (values at or above [`Bevel::EDGE`]) sloped at their edge: inwards for a negative distance, outwards for a positive one
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Bevel {
/// Reads past the texture's edges from the far side (Bevel Wrap)
pub wrap: bool,
/// How far the slope reaches from the edge, a fraction of the UV tile: inwards below 0, outwards above (−1..1)
pub distance: f32,
pub corner: BevelCorner,
/// How much the slope is blurred (0..5, [`Bevel::SMOOTHING_TEXELS`] texels at 2K each)
pub smoothing: f32,
pub blur: BevelBlur,
}
impl Bevel {
/// The Bevel filter as the library adds it
pub const LIBRARY: Bevel = Bevel { wrap: false, distance: -0.1, corner: BevelCorner::Round, smoothing: 0.0, blur: BevelBlur::NonUniform };
/// Values at or above it are inside the shapes
pub const EDGE: f32 = 0.5;
/// Texels at 2K a unit of Smoothing blurs over
pub const SMOOTHING_TEXELS: f32 = 4.0;
/// The largest Smoothing
pub const SMOOTHING_MAX: f32 = 5.0;
/// Whether the slope lies inside the shapes
pub fn inward(&self) -> bool {
self.distance <= 0.0 || self.distance.is_nan()
}
/// How many texels the slope reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
let distance = if self.distance.is_finite() { self.distance.abs().min(1.0) } else { 0.0 };
distance * res as f32
}
/// How many texels the slope is blurred over at `res` texels across a UV tile
pub fn smoothing_texels(&self, res: u32) -> f32 {
let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 };
smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES
}
/// The slope (0..1) at a texel `edge` texels from the shapes' edge, inside them or not, rising from 0 at its foot to 1 at its top
pub fn slope(&self, inside: bool, edge: f32, reach: f32) -> f32 {
let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 };
match (self.inward(), inside) {
(true, true) => along,
(false, false) => 1.0 - along,
(true, false) => 0.0,
(false, true) => 1.0,
}
}
/// The result at a texel of `value`, inside the shapes or not, on `slope`: an inward slope scales the shapes, an outward one rises around them
pub fn apply(&self, inside: bool, value: f32, slope: f32) -> f32 {
match (self.inward(), inside) {
(true, true) => value * slope,
(false, false) => value.max(slope),
_ => value,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_negative_distance_slopes_inwards_and_a_positive_one_outwards() {
let inward = Bevel::LIBRARY;
assert_eq!(inward.reach(2048), 204.8);
assert_eq!((inward.slope(true, 0.0, 10.0), inward.slope(true, 5.0, 10.0), inward.slope(true, 20.0, 10.0)), (0.0, 0.5, 1.0));
assert_eq!(inward.apply(true, 0.8, 0.5), 0.4, "inside, scaled down towards the edge");
assert_eq!(inward.apply(false, 0.3, 0.0), 0.3, "outside untouched");
let outward = Bevel { distance: 0.1, ..inward };
assert_eq!((outward.slope(false, 0.0, 10.0), outward.slope(false, 5.0, 10.0), outward.slope(false, 20.0, 10.0)), (1.0, 0.5, 0.0));
assert_eq!(outward.apply(false, 0.2, 0.5), 0.5, "rises around the shapes");
assert_eq!(outward.apply(true, 0.7, 1.0), 0.7, "inside untouched");
}
#[test]
fn hostile_settings_stay_in_range() {
let bevel = Bevel { distance: f32::NAN, smoothing: f32::INFINITY, ..Bevel::LIBRARY };
assert_eq!((bevel.reach(2048), bevel.smoothing_texels(2048)), (0.0, 0.0));
assert_eq!(bevel.slope(true, 3.0, 0.0), 1.0, "no reach leaves the shapes whole");
let excessive = Bevel { distance: -9.0, smoothing: 9.0, ..bevel };
assert_eq!(excessive.reach(1024), 1024.0);
assert_eq!(excessive.smoothing_texels(2048), Bevel::SMOOTHING_MAX * Bevel::SMOOTHING_TEXELS, "smoothing stops at its largest");
}
}
+35
View File
@@ -0,0 +1,35 @@
//! How a Bevel's Smoothing spreads over its slope
use serde::{Deserialize, Serialize};
/// Where a Bevel's Smoothing blurs its slope
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelBlur {
/// Sharp at the slope's foot, smoother towards its top
#[default]
NonUniform,
/// The same blur over the whole slope
Uniform,
}
impl BevelBlur {
/// Every blur mode, in the order a switch shows them
pub const ALL: [BevelBlur; 2] = [BevelBlur::NonUniform, BevelBlur::Uniform];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelBlur::NonUniform => "Non-Uniform",
BevelBlur::Uniform => "Uniform",
}
}
/// The id `effect.set {blurMode}` takes
pub fn id(self) -> &'static str {
match self {
BevelBlur::NonUniform => "nonUniform",
BevelBlur::Uniform => "uniform",
}
}
}
+35
View File
@@ -0,0 +1,35 @@
//! The shape a Bevel gives the corners it rounds off
use serde::{Deserialize, Serialize};
/// How a Bevel measures the distance from a shape's edge, which shows at its corners
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelCorner {
/// Straight-line distance: corners the bevel goes around come out round
#[default]
Round,
/// The larger of the horizontal and vertical distance: corners stay square
Angular,
}
impl BevelCorner {
/// Every corner type, in the order a switch shows them
pub const ALL: [BevelCorner; 2] = [BevelCorner::Round, BevelCorner::Angular];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelCorner::Round => "Round",
BevelCorner::Angular => "Angular",
}
}
/// The id `effect.set {cornerType}` takes
pub fn id(self) -> &'static str {
match self {
BevelCorner::Round => "round",
BevelCorner::Angular => "angular",
}
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Which side of a shape's edge a Bevel Smooth ramps on
use serde::{Deserialize, Serialize};
/// The side of the edge a Bevel Smooth's ramp lies on
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelDirection {
/// From the edge outwards, the shapes staying white
#[default]
Out,
/// From the edge inwards, around the shapes staying black
In,
/// Across the edge, mid gray on it
InOut,
}
impl BevelDirection {
/// Every direction, in the order a switch shows them
pub const ALL: [BevelDirection; 3] = [BevelDirection::Out, BevelDirection::In, BevelDirection::InOut];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelDirection::Out => "Out",
BevelDirection::In => "In",
BevelDirection::InOut => "In/Out",
}
}
/// The id `effect.set {direction}` takes
pub fn id(self) -> &'static str {
match self {
BevelDirection::Out => "out",
BevelDirection::In => "in",
BevelDirection::InOut => "inOut",
}
}
}
+117
View File
@@ -0,0 +1,117 @@
//! The Bevel Smooth filter's settings and the ramp it draws from a shape's edge
use serde::{Deserialize, Serialize};
use crate::{BevelDirection, RampCurve, SIZE_REFERENCE_RES, at_or_above_threshold, finite_unit};
/// A smooth ramp from the edge of the shapes (values at or above `threshold`), outwards, inwards or across it
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BevelSmooth {
pub direction: BevelDirection,
/// How far the ramp reaches from the edge, a fraction of the UV tile (0..0.3)
pub distance: f32,
/// How much the ramp is blurred (0..10, [`BevelSmooth::SMOOTHING_TEXELS`] texels at 2K each)
pub smoothing: f32,
/// Moves the ramp up or down before its curve (−1..1)
pub curve_offset: f32,
/// Bends the ramp: below 0 it rises later, above 0 sooner (−1..1)
pub curve_shape: f32,
/// Values at or above it are inside the shapes (Mask Threshold, 0..1)
pub threshold: f32,
/// Scales the distance (Distance Map Multiplier, 0..1)
pub multiplier: f32,
/// Reads past the texture's edges from the far side (Bevel Wrap)
pub wrap: bool,
}
impl BevelSmooth {
/// The Bevel Smooth filter as the library adds it
pub const LIBRARY: BevelSmooth = BevelSmooth {
direction: BevelDirection::Out,
distance: 0.1,
smoothing: 1.0,
curve_offset: 0.0,
curve_shape: 0.0,
threshold: 0.5,
multiplier: 1.0,
wrap: false,
};
/// Texels at 2K a unit of Smoothing blurs over
pub const SMOOTHING_TEXELS: f32 = 2.0;
/// The largest Smoothing
pub const SMOOTHING_MAX: f32 = 10.0;
/// Whether `value` is inside the shapes
pub fn inside(&self, value: f32) -> bool {
at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold)
}
/// How many texels the ramp reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32
}
/// How many texels the ramp is blurred over at `res` texels across a UV tile
pub fn smoothing_texels(&self, res: u32) -> f32 {
let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 };
smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES
}
/// The curve the ramp takes (Curve Offset and Curve Shape), worked out once per filter
pub fn curve(&self) -> RampCurve {
RampCurve::new(self.curve_offset, self.curve_shape)
}
/// The ramp at a texel `edge` texels from the shapes' edge, inside them or not, bent by [`BevelSmooth::curve`]
pub fn value(&self, curve: RampCurve, inside: bool, edge: f32, reach: f32) -> f32 {
let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 };
let curved = curve.apply(along);
match (self.direction, inside) {
(BevelDirection::Out, true) => 1.0,
(BevelDirection::Out, false) => 1.0 - curved,
(BevelDirection::In, true) => curved,
(BevelDirection::In, false) => 0.0,
(BevelDirection::InOut, true) => 0.5 + 0.5 * curved,
(BevelDirection::InOut, false) => 0.5 - 0.5 * curved,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The ramp with the curve worked out as the filter does
fn ramp(filter: BevelSmooth, inside: bool, edge: f32, reach: f32) -> f32 {
filter.value(filter.curve(), inside, edge, reach)
}
#[test]
fn the_ramp_lies_on_its_direction_side() {
let out = BevelSmooth::LIBRARY;
assert_eq!(out.reach(2048), 204.8);
assert!(out.inside(0.5) && !out.inside(0.49));
assert_eq!((ramp(out, true, 3.0, 10.0), ramp(out, false, 0.0, 10.0), ramp(out, false, 5.0, 10.0), ramp(out, false, 20.0, 10.0)), (1.0, 1.0, 0.5, 0.0));
let inward = BevelSmooth { direction: BevelDirection::In, ..out };
assert_eq!((ramp(inward, false, 3.0, 10.0), ramp(inward, true, 5.0, 10.0), ramp(inward, true, 20.0, 10.0)), (0.0, 0.5, 1.0));
let both = BevelSmooth { direction: BevelDirection::InOut, ..out };
assert_eq!(
(ramp(both, true, 0.0, 10.0), ramp(both, false, 0.0, 10.0), ramp(both, true, 10.0, 10.0), ramp(both, false, 10.0, 10.0)),
(0.5, 0.5, 1.0, 0.0)
);
}
#[test]
fn curve_offset_and_shape_bend_the_ramp() {
let inward = BevelSmooth { direction: BevelDirection::In, ..BevelSmooth::LIBRARY };
assert_eq!(ramp(BevelSmooth { curve_offset: 0.25, ..inward }, true, 5.0, 10.0), 0.75);
assert!(ramp(BevelSmooth { curve_shape: 0.5, ..inward }, true, 5.0, 10.0) > 0.5, "rises sooner");
assert!(ramp(BevelSmooth { curve_shape: -0.5, ..inward }, true, 5.0, 10.0) < 0.5, "rises later");
assert_eq!(BevelSmooth { multiplier: 0.5, ..inward }.reach(2048), 102.4);
let hostile = BevelSmooth { distance: f32::NAN, curve_offset: f32::NAN, curve_shape: f32::INFINITY, threshold: f32::NAN, ..inward };
assert_eq!((hostile.reach(2048), ramp(hostile, true, 1.0, 0.0)), (0.0, 1.0));
}
}
+132
View File
@@ -0,0 +1,132 @@
//! Color Match's settings: the colors moved so a source color lands on a target color
use serde::{Deserialize, Serialize};
use crate::{SourceColorMode, TargetColorMode, oklab};
/// A Color Match filter: every color moved, in OKLab, by the step from its source color to its target color
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorMatch {
/// Source Color Mode: the color moved from
pub source_mode: SourceColorMode,
/// Source Color (linear), read in Source Color Mode Parameter
pub source_color: [f32; 3],
/// Target Color Mode: the color moved to
pub target_mode: TargetColorMode,
/// Target Color (linear), read in Target Color Mode Parameter
pub target_color: [f32; 3],
/// Custom Color Variation: the colors keep at most Hue, Chroma and Luma of their difference from the source
pub custom_variation: bool,
/// Hue (degrees): how far a hue may stay from the target's
pub hue: f32,
/// Chroma: how far a chroma may stay from the target's
pub chroma: f32,
/// Luma: how far a lightness may stay from the target's
pub luma: f32,
}
impl ColorMatch {
/// Mid gray (128 sRGB) in linear
const GRAY: [f32; 3] = [0.215_860_5; 3];
/// The most Hue keeps (degrees): two hues are at most half a turn apart
pub const MAX_HUE_DEGREES: f32 = 180.0;
/// The most Chroma keeps (OKLab chroma)
pub const MAX_CHROMA: f32 = 1.0;
/// The most Luma keeps (OKLab lightness, 0..1)
pub const MAX_LUMA: f32 = 1.0;
/// A new Color Match: the texture's mean moves to the target and every texel keeps all of its difference from the mean (Color Variation at its widest), so the layer keeps its pattern until a variation is lowered
pub const LIBRARY: ColorMatch = ColorMatch {
source_mode: SourceColorMode::Average,
source_color: Self::GRAY,
target_mode: TargetColorMode::Parameter,
target_color: Self::GRAY,
custom_variation: true,
hue: Self::MAX_HUE_DEGREES,
chroma: Self::MAX_CHROMA,
luma: Self::MAX_LUMA,
};
/// Linear `color` moved by the step from `source` to `target`; without Custom Color Variation it keeps all of its difference from the source, with it at most Hue, Chroma and Luma of it (all 0: the target color itself). Hostile values give the color back
pub fn apply(&self, color: [f32; 3], source: [f32; 3], target: [f32; 3]) -> [f32; 3] {
let lab = |color: [f32; 3]| oklab::from_linear(color.map(|component| component.max(0.0)));
let [lightness, a, b] = lab(color);
let [source_lightness, source_a, source_b] = lab(source);
let [target_lightness, target_a, target_b] = lab(target);
let moved = if self.custom_variation {
self.move_polar(polar([lightness, a, b]), polar([source_lightness, source_a, source_b]), polar([target_lightness, target_a, target_b]))
} else {
[target_lightness + lightness - source_lightness, target_a + a - source_a, target_b + b - source_b]
};
matched_linear(color, moved)
}
#[inline]
pub(super) fn move_polar(
&self,
[lightness, chroma, hue]: [f32; 3],
[source_lightness, source_chroma, source_hue]: [f32; 3],
[target_lightness, target_chroma, target_hue]: [f32; 3],
) -> [f32; 3] {
let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 };
let keep = |difference: f32, max: f32| difference.clamp(-max, max);
let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI;
let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA));
let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0);
let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians());
[out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()]
}
}
pub(super) fn polar([lightness, a, b]: [f32; 3]) -> [f32; 3] {
[lightness, a.hypot(b), b.atan2(a)]
}
pub(super) fn matched_linear(original: [f32; 3], lab: [f32; 3]) -> [f32; 3] {
let out = oklab::to_linear(lab);
if out.iter().all(|value| value.is_finite()) { out.map(|value| value.clamp(0.0, 1.0)) } else { original }
}
#[cfg(test)]
mod tests {
use super::*;
fn near(a: [f32; 3], b: [f32; 3]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3)
}
#[test]
fn the_source_color_lands_on_the_target_and_variation_is_kept_as_asked() {
let red = [0.6, 0.1, 0.05];
let blue = [0.05, 0.1, 0.6];
let lighter_red = [0.8, 0.2, 0.1];
let lightness = |color: [f32; 3]| oklab::from_linear(color)[0];
// Without Custom Color Variation every difference from the source is kept
let keep_all = ColorMatch { custom_variation: false, ..ColorMatch::LIBRARY };
let moved = keep_all.apply(lighter_red, red, blue);
assert!(near(keep_all.apply(red, red, blue), blue), "the source itself becomes the target");
assert!(lightness(moved) > lightness(blue) + 0.05, "a lighter texel stays lighter than the target");
assert!(moved[2] > moved[0], "and turns blue");
// Custom Color Variation at 0: every color is the target
let flat = ColorMatch { luma: 0.0, chroma: 0.0, hue: 0.0, ..ColorMatch::LIBRARY };
assert!(near(flat.apply(lighter_red, red, blue), blue));
// A new Color Match's widest limits keep the lightness difference again
let library = ColorMatch::LIBRARY;
assert!(lightness(library.apply(lighter_red, red, blue)) > lightness(blue) + 0.05, "a new Color Match keeps the variation");
// Luma alone: the lightness difference kept up to it
let luma_only = ColorMatch { luma: 0.02, ..flat };
let limited = lightness(luma_only.apply(lighter_red, red, blue)) - lightness(blue);
assert!((limited - 0.02).abs() < 1e-3, "lightness kept up to Luma: {limited}");
let hostile = ColorMatch { hue: f32::NAN, chroma: f32::INFINITY, luma: -1.0, ..flat };
assert!(hostile.apply([f32::NAN, 0.5, 0.5], red, blue).iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)));
}
}
+135
View File
@@ -0,0 +1,135 @@
//! A mask effect that selects the parts of an ID map whose colors are in its list
use serde::{Deserialize, Serialize};
use crate::SelectionBackground;
/// Selects ID-map colors within a tolerance: the selected parts get the output value, the rest the background
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ColorSelection {
/// The selected ID colors, as the ID map stores them
pub colors: Vec<[f32; 3]>,
/// How far each component may be from a selected color and still count as it
pub tolerance: f32,
/// The value selected parts get
#[serde(default = "full", skip_serializing_if = "is_full")]
pub output: f32,
/// 1 is a hard edge (what selections saved before hardness did); lower ramps over 1 − hardness past the tolerance
#[serde(default = "full", skip_serializing_if = "is_full")]
pub hardness: f32,
#[serde(default, skip_serializing_if = "SelectionBackground::is_default")]
pub background: SelectionBackground,
/// The image resource read as the ID map; none reads the texture set's ID mesh map
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id_map: Option<String>,
}
fn full() -> f32 {
1.0
}
/// Whether an output or hardness is what selections saved before it existed had (not saved then, so they save as they were)
fn is_full(value: &f32) -> bool {
*value == full()
}
impl ColorSelection {
/// A selection of `colors` with the defaults of a new one
pub fn new(colors: Vec<[f32; 3]>, tolerance: f32) -> ColorSelection {
ColorSelection { colors, tolerance, output: 1.0, hardness: 1.0, background: SelectionBackground::Black, id_map: None }
}
/// How much ID color `id` is selected, 0..1 (none: no ID map there)
pub fn amount(&self, id: Option<[f32; 3]>) -> f32 {
let Some(id) = id else { return 0.0 };
if self.tolerance.is_nan() || self.hardness.is_nan() {
return 0.0;
}
let distance = self
.colors
.iter()
// Carry NaN through the component maximum so a malformed color cannot match
.map(|picked| {
picked
.iter()
.zip(id)
.map(|(picked, component)| (picked - component).abs())
.fold(0.0f32, |far, gap| if gap.is_nan() || gap > far { gap } else { far })
})
.fold(f32::INFINITY, f32::min);
if !distance.is_finite() {
return 0.0;
}
let past = distance - self.tolerance;
if past <= 0.0 {
return 1.0;
}
let width = 1.0 - self.hardness.clamp(0.0, 1.0);
if width <= 0.0 { 0.0 } else { (1.0 - past / width).clamp(0.0, 1.0) }
}
/// The gray this selection gives ID color `id` and how much of it covers the mask below (a transparent background covers only the selection)
pub fn value(&self, id: Option<[f32; 3]>) -> (f32, f32) {
let amount = self.amount(id);
match self.background.value() {
Some(background) => (background + (self.output - background) * amount, 1.0),
None => (self.output, amount),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::EffectKind;
#[test]
fn a_selection_saved_before_loads_hard_on_black_from_the_mesh_map() {
let saved = r#"{"ColorSelection":{"colors":[[1.0,0.0,0.0]],"tolerance":0.1}}"#;
let EffectKind::ColorSelection(selection) = serde_json::from_str::<EffectKind>(saved).unwrap() else { panic!("not a color selection") };
assert_eq!(selection, ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1));
assert_eq!(serde_json::to_string(&EffectKind::ColorSelection(selection)).unwrap(), saved, "it saves as it was saved");
}
#[test]
fn the_hard_edge_selects_as_before_and_softness_ramps_past_the_tolerance() {
let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1);
assert_eq!(selection.value(Some([0.95, 0.05, 0.0])), (1.0, 1.0));
assert_eq!(selection.value(Some([0.8, 0.0, 0.0])), (0.0, 1.0));
assert_eq!(selection.value(None), (0.0, 1.0));
assert_eq!(selection.value(Some([f32::NAN, 0.0, 0.0])), (0.0, 1.0));
selection.hardness = 0.8;
let (ramped, _) = selection.value(Some([0.8, 0.0, 0.0]));
assert!((ramped - 0.5).abs() < 1e-5, "{ramped}");
selection.colors.clear();
assert_eq!(selection.value(Some([1.0, 0.0, 0.0])), (0.0, 1.0));
}
#[test]
fn a_nan_tolerance_or_hardness_selects_nothing() {
let mut nan_tolerance = ColorSelection::new(vec![[1.0, 0.0, 0.0]], f32::NAN);
nan_tolerance.hardness = 0.5;
let mut nan_hardness = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1);
nan_hardness.hardness = f32::NAN;
for selection in [nan_tolerance, nan_hardness] {
assert_eq!(selection.amount(Some([1.0, 0.0, 0.0])), 0.0, "an exact match still needs valid settings");
assert_eq!(selection.amount(Some([0.8, 0.0, 0.0])), 0.0);
}
}
#[test]
fn the_output_and_background_set_both_sides_and_transparent_covers_only_the_selection() {
let mut selection = ColorSelection::new(vec![[0.0, 0.0, 1.0]], 0.1);
selection.output = 0.25;
selection.background = SelectionBackground::White;
assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0));
assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (1.0, 1.0));
selection.background = SelectionBackground::Transparent;
assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0));
assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (0.25, 0.0));
}
}
+60
View File
@@ -0,0 +1,60 @@
//! What one side of a compare mask reads
use serde::{Deserialize, Serialize};
/// One side of a compare mask's comparison
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompareSource {
/// The compared channel of the stack below the layer
LayersBelow,
/// The compared channel of the layer's own content, laid over the stack below by its coverage
ThisLayer,
/// The mask so far (the effects under the compare)
ThisMask,
/// The compare's constant
Constant,
}
impl CompareSource {
/// Menu order
pub const ALL: [CompareSource; 4] = [CompareSource::LayersBelow, CompareSource::ThisLayer, CompareSource::ThisMask, CompareSource::Constant];
/// Command id
pub fn id(self) -> &'static str {
match self {
CompareSource::LayersBelow => "layersBelow",
CompareSource::ThisLayer => "thisLayer",
CompareSource::ThisMask => "thisMask",
CompareSource::Constant => "constant",
}
}
pub fn from_id(id: &str) -> Option<CompareSource> {
CompareSource::ALL.into_iter().find(|source| source.id() == id)
}
/// Reads a material channel of the stack (the layer or the layers below)
pub fn reads_stack(self) -> bool {
matches!(self, CompareSource::LayersBelow | CompareSource::ThisLayer)
}
/// The left side of compare masks saved before sources existed
pub(crate) fn saved_left() -> CompareSource {
CompareSource::ThisMask
}
/// The right side of compare masks saved before sources existed
pub(crate) fn saved_right() -> CompareSource {
CompareSource::Constant
}
/// Whether a left side reads what saved compare masks did (not saved then)
pub(crate) fn is_saved_left(&self) -> bool {
*self == CompareSource::saved_left()
}
/// Whether a right side reads what saved compare masks did (not saved then)
pub(crate) fn is_saved_right(&self) -> bool {
*self == CompareSource::saved_right()
}
}
+126
View File
@@ -0,0 +1,126 @@
//! A folder's Scale and Rotation for the fills inside it
use serde::{Deserialize, Serialize};
use crate::layer::Projection;
/// Scale and Rotation a folder lays on every fill inside it, on top of each fill's own: the tiling is multiplied by `scale` and `rotation` (degrees) is added to the fill's angle; the fills themselves never change, so dropping the offset gives each its own back
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ContentsOffset {
pub scale: f32,
pub rotation: f32,
}
impl Default for ContentsOffset {
/// Nothing changed, as in every folder saved before folders had an offset
fn default() -> Self {
ContentsOffset::NONE
}
}
impl ContentsOffset {
/// The offset that changes nothing
pub const NONE: ContentsOffset = ContentsOffset { scale: 1.0, rotation: 0.0 };
/// The smallest and largest Scale a folder takes
pub const SCALE_RANGE: (f32, f32) = (0.01, 100.0);
/// The Rotation a folder takes, in degrees: a half turn each way
pub const ROTATION_RANGE: (f32, f32) = (-180.0, 180.0);
/// Whether the offset changes nothing
pub fn is_none(&self) -> bool {
*self == ContentsOffset::NONE
}
/// An offset with `scale` kept in [`ContentsOffset::SCALE_RANGE`] and `rotation` wrapped into [`ContentsOffset::ROTATION_RANGE`] (non-finite values change nothing)
pub fn new(scale: f32, rotation: f32) -> ContentsOffset {
let (low, high) = ContentsOffset::SCALE_RANGE;
let scale = if scale.is_finite() { scale.clamp(low, high) } else { 1.0 };
let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE;
let rotation = if rotation.is_finite() { (rotation - turn_start).rem_euclid(turn_end - turn_start) + turn_start } else { 0.0 };
ContentsOffset { scale, rotation }
}
/// The offset of a folder inside one with offset `self` (`inner` is the inner folder's own): scales multiply, rotations add, and the result stays in range however deep folders nest
pub fn then(self, inner: ContentsOffset) -> ContentsOffset {
ContentsOffset::new(self.scale * inner.scale, self.rotation + inner.rotation)
}
/// `projection` with this offset laid on its tiling and rotation (a projection stretched once over each UV tile has neither)
pub fn apply(self, projection: &Projection) -> Projection {
// A loaded offset never went through `new`
let offset = ContentsOffset::new(self.scale, self.rotation);
let mut out = projection.clone();
match &mut out {
Projection::Uv { scale, rotation, .. } => {
*scale = scale.map(|s| s * offset.scale);
*rotation += offset.rotation;
}
Projection::UvTile => {}
Projection::Triplanar { uv, .. }
| Projection::Planar { uv, .. }
| Projection::Spherical { uv, .. }
| Projection::Cylindrical { uv, .. }
| Projection::Warp { uv, .. } => {
uv.tiling = uv.tiling.map(|t| t * offset.scale);
uv.rotation += offset.rotation;
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layer::UvTransform;
#[test]
fn an_offset_multiplies_the_tiling_and_adds_to_the_angle_of_every_projection() {
let offset = ContentsOffset::new(1.5, 30.0);
let uv = offset.apply(&Projection::Uv { scale: [2.0, 4.0], rotation: 10.0, offset: [0.25, 0.0] });
assert_eq!(uv, Projection::Uv { scale: [3.0, 6.0], rotation: 40.0, offset: [0.25, 0.0] });
let spherical = Projection::Spherical {
scale: 1.0,
uv: UvTransform { tiling: [2.0, 1.0], rotation: -5.0, offset: [0.0; 2] },
offset: [0.0; 3],
projector: Default::default(),
};
let Projection::Spherical { scale, uv, .. } = offset.apply(&spherical) else { panic!("expected a spherical projection") };
assert_eq!((scale, uv.tiling, uv.rotation), (1.0, [3.0, 1.5], 25.0));
assert_eq!(offset.apply(&Projection::UvTile), Projection::UvTile);
assert_eq!(ContentsOffset::NONE.apply(&spherical), spherical);
}
#[test]
fn nested_offsets_combine_and_hostile_values_are_kept_in_range() {
let both = ContentsOffset::new(2.0, 170.0).then(ContentsOffset::new(1.5, 20.0));
assert_eq!((both.scale, both.rotation), (3.0, -170.0));
assert_eq!(ContentsOffset::new(f32::NAN, f32::INFINITY), ContentsOffset::NONE);
assert_eq!(ContentsOffset::new(1e9, 190.0), ContentsOffset { scale: 100.0, rotation: -170.0 });
assert_eq!(ContentsOffset::new(-3.0, -180.0), ContentsOffset { scale: 0.01, rotation: -180.0 });
assert!(ContentsOffset::default().is_none());
}
#[test]
fn deep_nesting_and_loaded_offsets_keep_the_scale_in_range() {
let deep = (0..17).fold(ContentsOffset::NONE, |around, _| around.then(ContentsOffset::new(100.0, 0.0)));
assert_eq!(deep.scale, ContentsOffset::SCALE_RANGE.1);
let loaded: ContentsOffset = serde_json::from_str(r#"{"scale":0,"rotation":0}"#).unwrap();
let tiled = loaded.apply(&Projection::Uv { scale: [2.0, 2.0], rotation: 0.0, offset: [0.0; 2] });
assert_eq!(tiled, Projection::Uv { scale: [0.02, 0.02], rotation: 0.0, offset: [0.0; 2] }, "a loaded Scale of 0 is kept at the smallest");
}
}
+63
View File
@@ -0,0 +1,63 @@
//! How Grayscale Conversion turns a color into gray
use serde::{Deserialize, Serialize};
use crate::GrayscaleMode;
/// The gray Grayscale Conversion reads from a color: a [`GrayscaleMode`], or its own weights per component
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ConversionMode {
/// Halfway between the lightest and darkest component
Desaturation,
/// Red, Green, Blue and Alpha times their weights, summed
#[default]
ChannelsWeights,
/// The components' mean
Average,
/// The lightest component
Max,
/// The darkest component
Min,
}
impl ConversionMode {
/// Every mode, in the order a list shows them
pub const ALL: [ConversionMode; 5] =
[ConversionMode::Desaturation, ConversionMode::ChannelsWeights, ConversionMode::Average, ConversionMode::Max, ConversionMode::Min];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
ConversionMode::ChannelsWeights => "Channels Weights",
other => other.mode().map_or("", GrayscaleMode::label),
}
}
/// The id `effect.set {mode}` takes
pub fn id(self) -> &'static str {
match self {
ConversionMode::ChannelsWeights => "channelsWeights",
other => other.mode().map_or("", GrayscaleMode::id),
}
}
/// The gray of straight color `rgb` with coverage `alpha`, `weights` for Red, Green, Blue and Alpha
pub fn gray(self, rgb: [f32; 3], alpha: f32, weights: [f32; 4]) -> f32 {
match self.mode() {
Some(mode) => mode.gray(rgb),
None => rgb[0] * weights[0] + rgb[1] * weights[1] + rgb[2] * weights[2] + alpha * weights[3],
}
}
/// The gradient's grayscale mode this one matches (None for Channels Weights)
fn mode(self) -> Option<GrayscaleMode> {
match self {
ConversionMode::Desaturation => Some(GrayscaleMode::Desaturation),
ConversionMode::ChannelsWeights => None,
ConversionMode::Average => Some(GrayscaleMode::Average),
ConversionMode::Max => Some(GrayscaleMode::Max),
ConversionMode::Min => Some(GrayscaleMode::Min),
}
}
}
+58
View File
@@ -0,0 +1,58 @@
//! The size a cooked source (a MaterialCraft material's maps) is made at
use serde::{Deserialize, Serialize};
use crate::layer::OutputResolution;
use crate::{MAX_RESOLUTION, MIN_RESOLUTION};
/// How big a source is cooked: relative to its texture set (following it when it changes) or a fixed size
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CookResolution {
/// The texture set's resolution times 2 to this power
Relative(i8),
/// Pixels across
Fixed(u32),
}
impl CookResolution {
/// The texture set's own resolution (Auto)
pub const TEXTURE_SET: CookResolution = CookResolution::Relative(0);
/// Powers of two a relative size may scale the texture set's by, as a generator's output resolution does
pub const FACTORS: std::ops::RangeInclusive<i8> = OutputResolution::FACTORS;
/// Pixels across for a texture set `set` pixels across: a power of two the engine can cook, else the texture set's size
pub fn size(self, set: u32) -> u32 {
let size = match self {
CookResolution::Relative(factor) => {
let factor = factor.clamp(*Self::FACTORS.start(), *Self::FACTORS.end());
if factor >= 0 { set.saturating_mul(1 << factor) } else { set >> factor.unsigned_abs() }
}
CookResolution::Fixed(size) => size,
};
if Self::cookable(size) { size } else { set }
}
/// Whether maps may be cooked `size` pixels across
pub fn cookable(size: u32) -> bool {
size.is_power_of_two() && (MIN_RESOLUTION..=MAX_RESOLUTION).contains(&size)
}
}
#[cfg(test)]
mod tests {
use super::CookResolution;
#[test]
fn sizes_follow_the_texture_set_and_stay_cookable() {
assert_eq!(CookResolution::TEXTURE_SET.size(2048), 2048);
assert_eq!(CookResolution::Relative(-1).size(2048), 1024);
assert_eq!(CookResolution::Relative(2).size(1024), 4096);
assert_eq!(CookResolution::Relative(3).size(2048), 2048, "16384 is past the largest cook");
assert_eq!(CookResolution::Relative(i8::MIN).size(1024), 128);
assert_eq!(CookResolution::Fixed(512).size(2048), 512);
assert_eq!(CookResolution::Fixed(300).size(2048), 2048);
assert_eq!(CookResolution::Fixed(u32::MAX).size(2048), 2048);
}
}
+144
View File
@@ -0,0 +1,144 @@
//! The shapes Gradient Curve remaps values through
use serde::{Deserialize, Serialize};
use crate::layer::smoothstep;
/// Stairs climbs in this many flat steps
const STAIRS_STEPS: f32 = 4.0;
/// Triangular rises and falls this many times
const TRIANGULAR_TEETH: f32 = 2.0;
/// A remap curve from 0..1 onto 0..1
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CurvePreset {
/// A quarter circle: rises fast, then flattens
#[default]
Round,
/// A quarter circle the other way: flat, then rises fast
Pinch,
/// Four flat steps
Stairs,
EaseOut,
Ease,
EaseIn,
/// Up to the middle and back down, rounded at the top
PeakOut,
/// Up to the middle and back down in straight lines
Peak,
/// Up to the middle and back down, pointed at the top
PeakIn,
/// Half a sine wave
Bump,
/// Two humps
DoubleBump,
/// Two straight teeth
Triangular,
}
impl CurvePreset {
/// Every preset, in the order the Preset list shows them
pub const ALL: [CurvePreset; 12] = [
CurvePreset::Round,
CurvePreset::Pinch,
CurvePreset::Stairs,
CurvePreset::EaseOut,
CurvePreset::Ease,
CurvePreset::EaseIn,
CurvePreset::PeakOut,
CurvePreset::Peak,
CurvePreset::PeakIn,
CurvePreset::Bump,
CurvePreset::DoubleBump,
CurvePreset::Triangular,
];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
CurvePreset::Round => "Round",
CurvePreset::Pinch => "Pinch",
CurvePreset::Stairs => "Stairs",
CurvePreset::EaseOut => "Ease Out",
CurvePreset::Ease => "Ease",
CurvePreset::EaseIn => "Ease In",
CurvePreset::PeakOut => "Peak Out",
CurvePreset::Peak => "Peak",
CurvePreset::PeakIn => "Peak In",
CurvePreset::Bump => "Bump",
CurvePreset::DoubleBump => "Double Bump",
CurvePreset::Triangular => "Triangular",
}
}
/// The id `effect.set {preset}` takes
pub fn id(self) -> &'static str {
match self {
CurvePreset::Round => "round",
CurvePreset::Pinch => "pinch",
CurvePreset::Stairs => "stairs",
CurvePreset::EaseOut => "easeOut",
CurvePreset::Ease => "ease",
CurvePreset::EaseIn => "easeIn",
CurvePreset::PeakOut => "peakOut",
CurvePreset::Peak => "peak",
CurvePreset::PeakIn => "peakIn",
CurvePreset::Bump => "bump",
CurvePreset::DoubleBump => "doubleBump",
CurvePreset::Triangular => "triangular",
}
}
/// The curve at `t` (clamped to 0..1; a non-finite `t` reads 0)
pub fn at(self, t: f32) -> f32 {
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
let peak = 1.0 - (2.0 * t - 1.0).abs();
let y = match self {
CurvePreset::Round => (1.0 - (1.0 - t) * (1.0 - t)).sqrt(),
CurvePreset::Pinch => 1.0 - (1.0 - t * t).sqrt(),
CurvePreset::Stairs => ((t * STAIRS_STEPS).floor() / (STAIRS_STEPS - 1.0)).min(1.0),
CurvePreset::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
CurvePreset::Ease => smoothstep(0.0, 1.0, t),
CurvePreset::EaseIn => t * t,
CurvePreset::PeakOut => peak.sqrt(),
CurvePreset::Peak => peak,
CurvePreset::PeakIn => peak * peak,
CurvePreset::Bump => (std::f32::consts::PI * t).sin(),
CurvePreset::DoubleBump => (2.0 * std::f32::consts::PI * t).sin().abs(),
CurvePreset::Triangular => 1.0 - ((2.0 * TRIANGULAR_TEETH * t) % 2.0 - 1.0).abs(),
};
y.clamp(0.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Samples across 0..1 that every curve is read at
const SAMPLES: usize = 64;
#[test]
fn every_preset_stays_in_range_and_reads_a_non_finite_t_as_0() {
for preset in CurvePreset::ALL {
let values: Vec<f32> = (0..=SAMPLES).map(|i| preset.at(i as f32 / SAMPLES as f32)).collect();
assert!(values.iter().all(|value| (0.0..=1.0).contains(value)), "{}", preset.id());
assert_eq!(preset.at(f32::NAN), preset.at(0.0), "{}", preset.id());
assert_eq!(preset.at(f32::INFINITY), preset.at(0.0), "{}", preset.id());
}
}
#[test]
fn stairs_has_four_levels_and_triangular_two_teeth() {
let mut levels: Vec<f32> = (0..=SAMPLES).map(|i| CurvePreset::Stairs.at(i as f32 / SAMPLES as f32)).collect();
levels.dedup();
assert_eq!(levels, [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]);
let triangular = |t: f32| CurvePreset::Triangular.at(t);
assert_eq!([triangular(0.0), triangular(0.25), triangular(0.5), triangular(0.75), triangular(1.0)], [0.0, 1.0, 0.0, 1.0, 0.0]);
}
}
+23
View File
@@ -0,0 +1,23 @@
//! Depth culling of planar and warp projections
use serde::{Deserialize, Serialize};
/// Surfaces hidden from the projector behind other surfaces get none of the projection, faded softer as `hardness` drops
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct DepthCulling {
pub on: bool,
pub hardness: f32,
}
impl DepthCulling {
/// What a new planar or warp projection starts with
pub const NEW: DepthCulling = DepthCulling { on: true, hardness: 0.75 };
}
impl Default for DepthCulling {
/// Off, as for every projection saved before depth culling existed
fn default() -> Self {
DepthCulling { on: false, ..DepthCulling::NEW }
}
}
+59
View File
@@ -0,0 +1,59 @@
//! The Directional Distance filter's settings and the trail it draws from the shapes
use serde::{Deserialize, Serialize};
use crate::finite_unit;
/// A trail fading away from the shapes (values at or above [`DirectionalDistance::EDGE`]) towards `angle`
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectionalDistance {
/// How far the trail reaches, a fraction of the UV tile (0..0.3)
pub distance: f32,
/// Where the trail runs to, in degrees counterclockwise from the right (270 runs down)
pub angle: f32,
/// Hardens the trail's fade (0..1)
pub contrast: f32,
/// Scales the distance (Distance Map Multiplier, 0..1)
pub multiplier: f32,
}
impl DirectionalDistance {
/// The Directional Distance filter as the library adds it
pub const LIBRARY: DirectionalDistance = DirectionalDistance { distance: 0.1, angle: 270.0, contrast: 0.0, multiplier: 1.0 };
/// Values at or above it are inside the shapes
pub const EDGE: f32 = 0.5;
/// The most contrast reaches: a hard step, kept off a division by zero
const HARDEST: f32 = 0.99;
/// How many texels the trail reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32
}
/// The trail where the nearest shape behind a texel is `along` of the reach away (0 on a shape), or none is in reach
pub fn value(&self, along: Option<f32>) -> f32 {
let Some(along) = along.filter(|along| along.is_finite()) else { return 0.0 };
let fade = 1.0 - along.clamp(0.0, 1.0);
let contrast = if self.contrast.is_finite() { self.contrast.clamp(0.0, Self::HARDEST) } else { 0.0 };
(0.5 + (fade - 0.5) / (1.0 - contrast)).clamp(0.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_trail_fades_with_distance_and_contrast_hardens_it() {
let trail = DirectionalDistance::LIBRARY;
assert_eq!(trail.reach(2048), 204.8);
assert_eq!((trail.value(Some(0.0)), trail.value(Some(0.25)), trail.value(None)), (1.0, 0.75, 0.0));
let hard = DirectionalDistance { contrast: 0.5, ..trail };
assert_eq!((hard.value(Some(0.25)), hard.value(Some(0.8))), (1.0, 0.0));
let hostile = DirectionalDistance { distance: f32::NAN, contrast: f32::INFINITY, multiplier: -1.0, ..trail };
assert_eq!((hostile.reach(2048), hostile.value(Some(f32::NAN))), (0.0, 0.0));
}
}
+31
View File
@@ -0,0 +1,31 @@
//! One of Baked Lighting Stylized's extra lights
use serde::{Deserialize, Serialize};
/// A light from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), of strength `intensity` in `color`
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct DirectionalLight {
pub azimuth: f32,
pub elevation: f32,
pub intensity: f32,
pub color: [f32; 3],
}
impl DirectionalLight {
/// An unlit white light from `azimuth`, 45 degrees up
pub const fn off(azimuth: f32) -> DirectionalLight {
DirectionalLight { azimuth, elevation: 45.0, intensity: 0.0, color: [1.0; 3] }
}
/// The unit direction toward the light
pub fn direction(&self) -> [f32; 3] {
toward(self.azimuth, self.elevation)
}
}
/// The unit direction toward a light at `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees)
fn toward(azimuth: f32, elevation: f32) -> [f32; 3] {
let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos();
let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos();
[cos_elevation * sin_azimuth, sin_elevation, cos_elevation * cos_azimuth]
}
+93
View File
@@ -0,0 +1,93 @@
//! Symmetry of a fill's 3D projection: mirrored or radial copies of it on the model
use serde::{Deserialize, Serialize};
use crate::{FULL_TURN_DEGREES, SymmetryKind};
/// Copies of a fill's projection: off for every fill saved before symmetry existed
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct FillSymmetry {
pub on: bool,
pub kind: SymmetryKind,
/// 0 = X, 1 = Y, 2 = Z: the mirror plane's normal, or the axis radial copies turn round
pub axis: u8,
/// Whether the copies' images are turned over across (U) and down (V)
pub flip: [bool; 2],
/// Where the mirror plane or the turning axis passes, in mesh radii from the mesh's centre
pub position: [f32; 3],
/// How many radial copies, the original included
pub count: u32,
/// The degrees the radial copies spread over; a full turn spaces them evenly round it
pub span: f32,
}
impl FillSymmetry {
/// Off; switched on, a mirror across X through the mesh's centre, or six radial copies over a full turn
pub const OFF: FillSymmetry =
FillSymmetry { on: false, kind: SymmetryKind::Mirror, axis: 0, flip: [false; 2], position: [0.0; 3], count: 6, span: FULL_TURN_DEGREES };
/// The fewest and most radial copies
pub const COUNTS: std::ops::RangeInclusive<u32> = 2..=64;
/// The degrees an Angle span may be set to: at least one, at most a full turn
pub const SPANS: std::ops::RangeInclusive<f32> = 1.0..=FULL_TURN_DEGREES;
/// How far the axis position reaches from the mesh's centre, in mesh radii
pub const REACH: f32 = 1.0;
/// [`FillSymmetry::axis`] of the last axis, Z
pub const LAST_AXIS: u8 = 2;
/// The degrees between radial copies: a full turn spaces `count` copies evenly, a smaller span puts the first and last at its ends (a span that is not a number is a full turn)
pub fn step(&self) -> f32 {
let count = self.radial_count() as f32;
let span = if self.span.is_nan() { FULL_TURN_DEGREES } else { self.span.clamp(0.0, FULL_TURN_DEGREES) };
if span >= FULL_TURN_DEGREES { span / count } else { span / (count - 1.0) }
}
/// The copies there are, the original included: two for a mirror
pub fn copies(&self) -> u32 {
match self.kind {
SymmetryKind::Mirror => 2,
SymmetryKind::Radial => self.radial_count(),
}
}
/// The axis the copies mirror across or turn round, the last one for an axis past it
pub fn axis_index(&self) -> usize {
usize::from(self.axis.min(Self::LAST_AXIS))
}
/// How many radial copies, kept within [`FillSymmetry::COUNTS`]
fn radial_count(&self) -> u32 {
self.count.clamp(*Self::COUNTS.start(), *Self::COUNTS.end())
}
/// Whether this is the symmetry a new fill starts with, so saves leave it out
pub fn is_default(&self) -> bool {
*self == FillSymmetry::default()
}
}
impl Default for FillSymmetry {
fn default() -> Self {
FillSymmetry::OFF
}
}
#[cfg(test)]
mod tests {
use super::*;
fn radial(count: u32, span: f32) -> FillSymmetry {
FillSymmetry { on: true, kind: SymmetryKind::Radial, count, span, ..FillSymmetry::OFF }
}
#[test]
fn a_span_under_a_full_turn_puts_the_last_copy_at_its_end() {
assert_eq!(radial(4, 180.0).step(), 60.0);
assert_eq!(radial(4, 360.0).step(), 90.0);
}
#[test]
fn a_span_that_is_not_a_number_spaces_the_copies_round_a_full_turn() {
assert_eq!(radial(4, f32::NAN).step(), 90.0);
}
}
+181
View File
@@ -0,0 +1,181 @@
//! Gradient's Input Transformation: how a texel becomes the position it reads on the ramp
use serde::{Deserialize, Serialize};
use crate::grayscale_mode::GrayscaleMode;
use crate::{ChannelKind, finite_unit, lum, per_unit};
/// Keep the transition finite just below full contrast
const MIN_STEEPNESS: f32 = 1e-3;
/// The balance that leaves the gray as it is
pub(crate) const NEUTRAL_BALANCE: f32 = 0.5;
/// The gray, blurred, balanced, contrasted and maybe inverted value a gradient looks up
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GradientInput {
/// How a color becomes gray (masks and scalar channels are gray already)
pub mode: GrayscaleMode,
/// Blurs the gray before the lookup, in texels at 2K (0..16)
pub blur: f32,
/// Shifts the gray: above 0.5 lighter, below darker
pub balance: f32,
/// Steepens the gray around its middle: 1 is a hard step
pub contrast: f32,
pub invert: bool,
}
impl Default for GradientInput {
/// What gradients read in projects saved before the Input Transformation: luma, untouched
fn default() -> Self {
GradientInput { mode: GrayscaleMode::Luma, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false }
}
}
impl GradientInput {
/// The library's starting transformation: the average of the components, untouched
pub const LIBRARY: GradientInput = GradientInput { mode: GrayscaleMode::Average, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false };
/// Whether it reads gradients as projects saved before it did (skipped when saving)
pub fn is_unchanged(&self) -> bool {
*self == GradientInput::default()
}
/// The ramp position of gray `x`
pub fn shape(&self, x: f32) -> f32 {
// Preserve the exact input when the transformation is neutral
if self.balance == NEUTRAL_BALANCE && self.contrast == 0.0 && !self.invert {
return x;
}
shape_gray(x, self.balance, self.contrast, self.invert)
}
/// Apply a gradient to a channel using its ramp sampler
pub fn map(&self, kind: ChannelKind, value: [f32; 3], sample: impl Fn(f32) -> Option<[f32; 3]>) -> Option<[f32; 3]> {
if kind == ChannelKind::Color {
return sample(self.shape(self.mode.gray(value)));
}
// Preserve the signed-channel mapping and leave normals alone
Some(per_unit(kind, value, |gray| sample(self.shape(gray)).map_or(gray, lum)))
}
}
/// Gray `x` balanced (0.5 keeps it), contrasted around mid gray (0 keeps it, 1 is a step at 0.5) and maybe inverted, in 0..1
pub fn shape_gray(x: f32, balance: f32, contrast: f32, invert: bool) -> f32 {
let balanced = finite_unit(x) + finite_unit(balance) - NEUTRAL_BALANCE;
let contrast = finite_unit(contrast);
let shaped = if contrast == 1.0 {
f32::from(balanced >= NEUTRAL_BALANCE)
} else {
let steep = (1.0 - contrast).max(MIN_STEEPNESS);
finite_unit((balanced - NEUTRAL_BALANCE) / steep + NEUTRAL_BALANCE)
};
if invert { 1.0 - shaped } else { shaped }
}
/// A ramp stop's place and color
type Stop = (f32, [f32; 3]);
pub(crate) fn ramp_stops<'a>(colors: &'a [[f32; 3]], positions: &'a [f32]) -> impl ExactSizeIterator<Item = Stop> + 'a {
let last = colors.len().saturating_sub(1);
colors.iter().copied().enumerate().map(move |(index, color)| {
let even_position = || if last == 0 { 0.0 } else { index as f32 / last as f32 };
let position = positions.get(index).copied().filter(|position| position.is_finite()).unwrap_or_else(even_position);
let position = if position <= 0.0 { 0.0 } else { position.min(1.0) };
(position, color)
})
}
/// The color at `t` on a ramp of `colors` placed at `positions` (each 0..1, evenly spaced where missing), blended in linear or sRGB
pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Option<[f32; 3]> {
let stops = ramp_stops(colors, positions);
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
// Keep the last stop at or before the sample and the first stop after it
let (mut before, mut after): (Option<Stop>, Option<Stop>) = (None, None);
for (position, color) in stops {
if position <= t {
if before.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_ge()) {
before = Some((position, color));
}
} else if after.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_lt()) {
after = Some((position, color));
}
}
let ((before_place, before_color), (after_place, after_color)) = match (before, after) {
(Some(before), Some(after)) => (before, after),
(Some(only), None) | (None, Some(only)) => (only, only),
(None, None) => return None,
};
let encode = |color: [f32; 3]| if linear { color } else { color.map(linear_to_srgb) };
Some(interpolate((before_place, encode(before_color)), (after_place, encode(after_color)), linear, t))
}
pub(crate) fn interpolate((before_place, before_color): Stop, (after_place, after_color): Stop, linear: bool, t: f32) -> [f32; 3] {
let share = if after_place > before_place { ((t - before_place) / (after_place - before_place)).clamp(0.0, 1.0) } else { 0.0 };
let color = std::array::from_fn(|component| before_color[component] + (after_color[component] - before_color[component]) * share);
if linear { color } else { color.map(srgb_to_linear) }
}
// A copy of texturecraft_texel's: texel and core are both layer 0, so core cannot use it
/// sRGB transfer of a linear component
pub(crate) fn linear_to_srgb(v: f32) -> f32 {
let v = v.clamp(0.0, 1.0);
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
/// Linear value of an sRGB component
pub(crate) fn srgb_to_linear(v: f32) -> f32 {
let v = v.clamp(0.0, 1.0);
if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_ramp_reads_its_stops_in_place_order_whatever_their_list_order() {
let (black, gray, white) = ([0.0; 3], [0.5; 3], [1.0; 3]);
let colors = [white, black, gray];
let positions = [1.0, 0.0, 0.5];
let quarter = ramp(&colors, &positions, true, 0.25);
let ends = (ramp(&colors, &positions, true, 0.0), ramp(&colors, &positions, true, 1.0));
let past_one_stop = ramp(&[gray, white], &[0.5, 0.5], true, 0.25);
assert_eq!(ramp(&[black, white], &[0.0, -0.0], true, 0.0), Some(white));
assert_eq!(quarter, Some([0.25; 3]));
assert_eq!(ends, (Some(black), Some(white)));
assert_eq!(past_one_stop, Some(gray), "before the first stop, its color");
assert_eq!(ramp(&[], &[], true, 0.5), None);
}
#[test]
fn full_contrast_separates_neighbors_of_mid_gray() {
let below = shape_gray(0.49975, NEUTRAL_BALANCE, 1.0, false);
let above = shape_gray(0.50025, NEUTRAL_BALANCE, 1.0, false);
assert_eq!((below, above), (0.0, 1.0));
assert_eq!(shape_gray(0.50025, NEUTRAL_BALANCE, 1.0, true), below);
}
#[test]
fn an_untouched_input_passes_every_gray_on_bit_for_bit() {
const SAMPLES: u16 = 1000;
let untouched = [GradientInput::default(), GradientInput::LIBRARY];
let grays = (0..=SAMPLES).map(|step| f32::from(step) / f32::from(SAMPLES)).chain([-0.25, 1.5]);
for input in untouched {
for gray in grays.clone() {
assert_eq!(input.shape(gray).to_bits(), gray.to_bits(), "{input:?} at {gray}");
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
//! Grayscale Conversion's settings: which gray it reads and how it shapes it
use serde::{Deserialize, Serialize};
use crate::blend::lum;
use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray};
use crate::layer::per_unit;
use crate::{ChannelKind, ConversionMode};
/// A Grayscale Conversion filter: the gray of the current channel (or of its Custom Input), balanced, contrasted and maybe inverted
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GrayscaleConversion {
/// Channel Input Custom Input: the gray of the filter's Custom Input instead of the channel's
pub custom_input: bool,
pub invert: bool,
pub balance: f32,
pub contrast: f32,
pub mode: ConversionMode,
/// Channels Weights' Red, Green, Blue and Alpha
pub weights: [f32; 4],
}
impl GrayscaleConversion {
/// A new Grayscale Conversion: a third of each color component, alpha left out
pub const LIBRARY: GrayscaleConversion = GrayscaleConversion {
custom_input: false,
invert: false,
balance: NEUTRAL_BALANCE,
contrast: 0.0,
mode: ConversionMode::ChannelsWeights,
weights: [0.33, 0.33, 0.33, 0.0],
};
/// The settings a Grayscale filter saved before them takes on its first edit: its luminance weights, so it looks the same
pub fn of_luminance() -> GrayscaleConversion {
let [red, green, blue] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].map(lum);
GrayscaleConversion { weights: [red, green, blue, 0.0], ..Self::LIBRARY }
}
/// The shaped gray of straight color `rgb` with coverage `alpha`
pub fn gray(&self, rgb: [f32; 3], alpha: f32) -> f32 {
shape_gray(self.mode.gray(rgb, alpha, self.weights), self.balance, self.contrast, self.invert)
}
/// `v` of a `kind` channel (coverage `alpha`) or `custom_input` turned gray: colors gray, scalar and signed in their range, normals as they are
pub fn channel_value(&self, kind: ChannelKind, v: [f32; 3], custom_input: Option<[f32; 3]>, alpha: f32) -> [f32; 3] {
match (kind, custom_input) {
(ChannelKind::NormalMap, _) => v,
(ChannelKind::Color, None) => [self.gray(v, alpha); 3],
(ChannelKind::Color, Some(input)) => [self.gray(input, alpha); 3],
(_, None) => per_unit(kind, v, |x| self.gray([x; 3], alpha)),
(_, Some(input)) => per_unit(kind, v, |_| self.gray(input, alpha)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_saved_grayscale_keeps_its_luminance() {
let color = [0.8, 0.3, 0.1];
assert!((GrayscaleConversion::of_luminance().gray(color, 1.0) - lum(color)).abs() < 1e-5);
}
#[test]
fn weights_balance_contrast_and_invert_shape_the_gray() {
let only_red = GrayscaleConversion { weights: [1.0, 0.0, 0.0, 0.0], ..GrayscaleConversion::LIBRARY };
assert!((only_red.gray([0.6, 1.0, 1.0], 1.0) - 0.6).abs() < 1e-6);
let alpha = GrayscaleConversion { weights: [0.0, 0.0, 0.0, 1.0], ..GrayscaleConversion::LIBRARY };
assert!((alpha.gray([1.0; 3], 0.25) - 0.25).abs() < 1e-6, "Alpha weighs the coverage");
let inverted = GrayscaleConversion { invert: true, mode: ConversionMode::Max, ..GrayscaleConversion::LIBRARY };
assert!((inverted.gray([0.2, 0.7, 0.1], 1.0) - 0.3).abs() < 1e-6);
let contrasted = GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..GrayscaleConversion::LIBRARY };
assert_eq!(contrasted.gray([0.6; 3], 1.0), 1.0);
}
#[test]
fn only_colors_turn_gray() {
let conversion = GrayscaleConversion::LIBRARY;
let height = conversion.channel_value(ChannelKind::Signed, [-0.6; 3], None, 1.0);
let normal = conversion.channel_value(ChannelKind::NormalMap, [0.2, 0.7, 0.9], None, 1.0);
assert!(height.iter().all(|x| (x + 0.6).abs() < 0.02), "a signed height keeps its sign: {height:?}");
assert_eq!(normal, [0.2, 0.7, 0.9]);
}
}
+58
View File
@@ -0,0 +1,58 @@
//! How a color becomes the gray a gradient looks up
use serde::{Deserialize, Serialize};
/// The gray a color reads as, before a gradient maps it
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GrayscaleMode {
/// Halfway between the lightest and darkest component
Desaturation,
/// Weighted by how bright each component looks (what gradients read in projects saved before the modes)
#[default]
Luma,
/// The components' mean
Average,
/// The lightest component
Max,
/// The darkest component
Min,
}
impl GrayscaleMode {
/// Every mode, in the order a list shows them
pub const ALL: [GrayscaleMode; 5] = [GrayscaleMode::Desaturation, GrayscaleMode::Luma, GrayscaleMode::Average, GrayscaleMode::Max, GrayscaleMode::Min];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
GrayscaleMode::Desaturation => "Desaturation",
GrayscaleMode::Luma => "Luma",
GrayscaleMode::Average => "Average",
GrayscaleMode::Max => "Max",
GrayscaleMode::Min => "Min",
}
}
/// The id `effect.set {grayscaleMode}` takes
pub fn id(self) -> &'static str {
match self {
GrayscaleMode::Desaturation => "desaturation",
GrayscaleMode::Luma => "luma",
GrayscaleMode::Average => "average",
GrayscaleMode::Max => "max",
GrayscaleMode::Min => "min",
}
}
/// The gray of linear color `[r, g, b]`
pub fn gray(self, [r, g, b]: [f32; 3]) -> f32 {
match self {
GrayscaleMode::Desaturation => (r.max(g).max(b) + r.min(g).min(b)) / 2.0,
GrayscaleMode::Luma => crate::blend::lum([r, g, b]),
GrayscaleMode::Average => (r + g + b) / 3.0,
GrayscaleMode::Max => r.max(g).max(b),
GrayscaleMode::Min => r.min(g).min(b),
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Height To Normal's settings: the layer's Height turned into its Normal
use serde::{Deserialize, Serialize};
/// A Height To Normal filter: the normal of the slopes of the layer's Height, over or in place of its Normal
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HeightToNormal {
/// Overwrite Existing Normal: the made normal replaces the Normal below instead of being laid over it
pub overwrite: bool,
/// Use World Units: the slope comes from Surface Size and Height Depth instead of Normal Intensity
pub world_units: bool,
/// Surface Size (cm): how wide a UV tile is on the model
pub surface_size: f32,
/// Height Depth (cm): how deep a height of 1 is
pub height_depth: f32,
/// Normal Intensity: how strongly the slopes tilt the normal without world units
pub intensity: f32,
}
impl HeightToNormal {
/// A new Height To Normal
pub const LIBRARY: HeightToNormal = HeightToNormal { overwrite: true, world_units: true, surface_size: 300.0, height_depth: 16.0, intensity: 10.0 };
/// The smallest Surface Size: whole cm, so the reference's 0.1 rounds up to 1
pub const MIN_SURFACE_SIZE: f32 = 1.0;
/// The largest Surface Size (cm)
pub const MAX_SURFACE_SIZE: f32 = 1000.0;
/// The largest Height Depth (cm)
pub const MAX_HEIGHT_DEPTH: f32 = 100.0;
/// The largest Normal Intensity
pub const MAX_INTENSITY: f32 = 50.0;
/// Height Depth over Surface Size a Normal Intensity of 1 tilts like (so the default 10 matches the default 16 cm over 300 cm)
const INTENSITY_UNIT: f32 = Self::LIBRARY.height_depth / Self::LIBRARY.surface_size / Self::LIBRARY.intensity;
/// How much a change of height per texel tilts the normal at `res` texels across a UV tile (0 for hostile values)
pub fn strength(&self, res: u32) -> f32 {
let finite = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 };
if self.world_units && !self.surface_size.is_finite() {
return 0.0;
}
let per_tile = if self.world_units {
finite(self.height_depth, Self::MAX_HEIGHT_DEPTH) / finite(self.surface_size, Self::MAX_SURFACE_SIZE).max(Self::MIN_SURFACE_SIZE)
} else {
finite(self.intensity, Self::MAX_INTENSITY) * Self::INTENSITY_UNIT
};
per_tile * res as f32
}
/// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down
pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] {
let strength = self.strength(res);
let (x, y) = (-gx * strength, gy * strength);
let length = (x * x + y * y + 1.0).sqrt();
if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn world_units_and_normal_intensity_tilt_the_normal_up_the_slope() {
let filter = HeightToNormal::LIBRARY;
assert_eq!(filter.normal([0.0, 0.0], 2048), [0.0, 0.0, 1.0], "a flat height");
let [x, y, z] = filter.normal([0.01, 0.0], 2048);
assert!(x < 0.0 && y == 0.0 && z > 0.0, "rising to the right faces left");
let expected = 0.01 * 16.0 / 300.0 * 2048.0;
assert!((-x / z - expected).abs() < 1e-4, "16 cm over 300 cm");
let intensity = HeightToNormal { world_units: false, ..filter };
assert!((intensity.strength(2048) - filter.strength(2048)).abs() < 1e-3, "Normal Intensity 10 matches the world default");
assert!(HeightToNormal { intensity: 20.0, ..intensity }.strength(2048) > intensity.strength(2048));
assert!(HeightToNormal { height_depth: 32.0, ..filter }.strength(2048) > filter.strength(2048));
assert_eq!(filter.normal([0.0, 0.01], 2048)[1].signum(), 1.0, "rising down the image faces up");
assert_eq!(HeightToNormal { surface_size: f32::NAN, ..filter }.strength(2048), 0.0);
let hostile = HeightToNormal { surface_size: f32::NAN, height_depth: f32::INFINITY, ..filter };
assert!(hostile.normal([1.0, 1.0], 2048).iter().all(|v| v.is_finite()));
}
}
+84
View File
@@ -0,0 +1,84 @@
//! The color space a Highpass filter works in
use serde::{Deserialize, Serialize};
use crate::gradient_input::{linear_to_srgb, srgb_to_linear};
/// ACEScg (AP1) to linear sRGB (Rec. 709) primaries, white point adapted (the published ACES matrix)
const AP1_TO_REC709: [[f32; 3]; 3] = [[1.705_05, -0.621_79, -0.083_26], [-0.130_26, 1.140_80, -0.010_55], [-0.024_00, -0.128_97, 1.152_97]];
/// Linear sRGB (Rec. 709) to ACEScg (AP1) primaries: the inverse of [`AP1_TO_REC709`]
const REC709_TO_AP1: [[f32; 3]; 3] = [[0.613_10, 0.339_52, 0.047_37], [0.070_19, 0.916_35, 0.013_45], [0.020_62, 0.109_57, 0.869_81]];
/// Where a Highpass takes its detail: in the working space (masks always), or in sRGB from linear sRGB or ACEScg colors
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HighpassSpace {
/// The values as they are (what a Highpass did in projects saved before the Color Space)
#[default]
Working,
/// Colors read as linear sRGB, filtered sRGB encoded
SrgbFromLinear,
/// Colors read as ACEScg, filtered sRGB encoded
SrgbFromAcescg,
}
impl HighpassSpace {
/// Every space, in the order a list shows them
pub const ALL: [HighpassSpace; 3] = [HighpassSpace::Working, HighpassSpace::SrgbFromLinear, HighpassSpace::SrgbFromAcescg];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
HighpassSpace::Working => "Working space / Mask",
HighpassSpace::SrgbFromLinear => "sRGB (from Linear sRGB)",
HighpassSpace::SrgbFromAcescg => "sRGB (from ACEScg)",
}
}
/// The id `effect.set {colorSpace}` takes
pub fn id(self) -> &'static str {
match self {
HighpassSpace::Working => "working",
HighpassSpace::SrgbFromLinear => "srgbFromLinear",
HighpassSpace::SrgbFromAcescg => "srgbFromAcescg",
}
}
/// Straight color `rgb` in this space
pub fn encode(self, rgb: [f32; 3]) -> [f32; 3] {
match self {
HighpassSpace::Working => rgb,
HighpassSpace::SrgbFromLinear => rgb.map(linear_to_srgb),
HighpassSpace::SrgbFromAcescg => times(&AP1_TO_REC709, rgb).map(linear_to_srgb),
}
}
/// Straight color `rgb` of this space back in the working space
pub fn decode(self, rgb: [f32; 3]) -> [f32; 3] {
match self {
HighpassSpace::Working => rgb,
HighpassSpace::SrgbFromLinear => rgb.map(srgb_to_linear),
HighpassSpace::SrgbFromAcescg => times(&REC709_TO_AP1, rgb.map(srgb_to_linear)),
}
}
}
/// Matrix `m` times column `v`
fn times(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
m.map(|row| row[0] * v[0] + row[1] * v[1] + row[2] * v[2])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_space_round_trips_a_color_in_its_gamut() {
for space in HighpassSpace::ALL {
let back = space.decode(space.encode([0.5, 0.4, 0.3]));
assert!(back.iter().zip([0.5, 0.4, 0.3]).all(|(a, b)| (a - b).abs() < 2e-3), "{space:?}: {back:?}");
}
assert!((HighpassSpace::SrgbFromLinear.encode([0.214; 3])[0] - 0.5).abs() < 1e-2, "linear mid gray is sRGB 0.5");
}
}
+89
View File
@@ -0,0 +1,89 @@
//! An image a filter reads besides the stack it filters (its image inputs), as a source on the filter's effect
use crate::{Filter, Source, SourceColorMode, TargetColorMode, WarpSourceMode};
/// One image input of a filter: the key its source is stored under on the effect, its name and the gray it reads until a source is set
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ImageInput {
pub id: &'static str,
pub label: &'static str,
/// The gray the input reads while no source is set (what the filter did before it had the input)
pub default: f32,
/// Added by a mode of the filter (shown under that mode), not one of its Image inputs
pub by_mode: bool,
}
impl ImageInput {
/// Bevel Smooth's and Directional Distance's Distance Map: scales the distance per texel
pub const DISTANCE_MAP: ImageInput = ImageInput { id: "distanceMap", label: "Distance Map", default: 1.0, by_mode: false };
/// Warp's and Blur Slope's Custom Noise (Source Type Custom Noise): the source its texels move or read along; mid gray moves nothing
pub const CUSTOM_NOISE: ImageInput = ImageInput { id: "customNoise", label: "Custom Noise", default: 0.5, by_mode: true };
/// The Custom Input of Grayscale Conversion (the color it reads instead of the channel) and Anisotropic Kuwahara (its direction's gray); mid gray until set
pub const CUSTOM_INPUT: ImageInput = ImageInput { id: "customInput", label: "Custom Input", default: 0.5, by_mode: true };
/// Color Match's Input (Source Color Mode Input): the color each texel moves from; mid gray until set
pub const SOURCE_INPUT: ImageInput = ImageInput { id: "input", label: "Input", default: 0.5, by_mode: true };
/// Color Match's Image Input (Target Color Mode Image Input): the color each texel moves to; mid gray until set
pub const TARGET_INPUT: ImageInput = ImageInput { id: "imageInput", label: "Image Input", default: 0.5, by_mode: true };
/// The image inputs `filter` reads now (a mode's input only while that mode is on)
pub fn of(filter: &Filter) -> Vec<ImageInput> {
Self::all(filter).iter().copied().filter(|input| input.is_on(filter)).collect()
}
/// The input of `filter` stored under `id`, also while its mode is off
pub fn named(filter: &Filter, id: &str) -> Option<ImageInput> {
Self::all(filter).iter().find(|input| input.id == id).copied()
}
/// Every image input `filter` has, its modes' inputs also while those modes are off
fn all(filter: &Filter) -> &'static [ImageInput] {
match filter {
Filter::BevelSmooth(_) | Filter::DirectionalDistance(_) => &[Self::DISTANCE_MAP],
Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_) => &[Self::CUSTOM_NOISE],
Filter::GrayscaleConversion(_) | Filter::AnisotropicKuwahara(_) => &[Self::CUSTOM_INPUT],
Filter::ColorMatch(_) => &[Self::SOURCE_INPUT, Self::TARGET_INPUT],
_ => &[],
}
}
/// Whether `filter` reads this input now: an input a mode adds only while that mode is on
fn is_on(&self, filter: &Filter) -> bool {
match filter {
Filter::SourceWarp(warp) => warp.source.mode == WarpSourceMode::CustomNoise,
Filter::SourceSlopeBlur(slope) => slope.source.mode == WarpSourceMode::CustomNoise,
Filter::GrayscaleConversion(conversion) => conversion.custom_input,
Filter::AnisotropicKuwahara(kuwahara) => kuwahara.custom_input,
Filter::ColorMatch(matcher) if *self == Self::SOURCE_INPUT => matcher.source_mode == SourceColorMode::Input,
Filter::ColorMatch(matcher) => matcher.target_mode == TargetColorMode::ImageInput,
_ => true,
}
}
/// The source the input reads while none is set
pub fn default_source(&self) -> Source {
Source::Uniform([self.default; 3])
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{BevelSmooth, SourceWarp, WarpSource};
#[test]
fn a_warp_has_its_custom_noise_only_in_that_source_mode() {
let warp = SourceWarp::LIBRARY;
assert!(ImageInput::of(&Filter::SourceWarp(warp)).is_empty());
let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, ..warp.source }, ..warp };
assert_eq!(ImageInput::of(&Filter::SourceWarp(custom)), vec![ImageInput::CUSTOM_NOISE]);
assert_eq!(ImageInput::named(&Filter::SourceWarp(warp), "customNoise"), Some(ImageInput::CUSTOM_NOISE), "kept while the mode is off");
assert_eq!(ImageInput::of(&Filter::BevelSmooth(BevelSmooth::LIBRARY)), vec![ImageInput::DISTANCE_MAP]);
assert_eq!(ImageInput::named(&Filter::BevelSmooth(BevelSmooth::LIBRARY), "customNoise"), None);
assert_eq!(ImageInput::DISTANCE_MAP.default_source(), Source::Uniform([1.0; 3]));
}
}
+1090 -132
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
use serde::{Deserialize, Serialize};
/// How a fill reads its image sources between texels
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Filtering {
/// Bilinear on the image level that matches the texel's footprint: smooth when the image is shrunk
#[default]
BilinearHq,
/// Bilinear on the full image: sharp, but may shimmer where the image is shrunk
BilinearSharp,
/// The nearest image texel
Nearest,
}
impl Filtering {
pub const ALL: [Filtering; 3] = [Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest];
/// Command id
pub fn id(self) -> &'static str {
match self {
Filtering::BilinearHq => "bilinearHq",
Filtering::BilinearSharp => "bilinearSharp",
Filtering::Nearest => "nearest",
}
}
pub fn from_id(id: &str) -> Option<Filtering> {
Filtering::ALL.into_iter().find(|f| f.id() == id)
}
}
+33
View File
@@ -0,0 +1,33 @@
use serde::{Deserialize, Serialize};
use super::{Filtering, ScaleMode, UvWrap};
use crate::FillSymmetry;
/// How a fill samples its images and what its size is set in; older fills read with [`Sampling::SAVED_BEFORE`]
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Sampling {
#[serde(default)]
pub filtering: Filtering,
#[serde(default)]
pub wrap: UvWrap,
#[serde(default)]
pub scale: ScaleMode,
#[serde(default, skip_serializing_if = "FillSymmetry::is_default")]
pub symmetry: FillSymmetry,
}
impl Sampling {
/// What fills saved before the sampling choices existed did: plain bilinear
pub const SAVED_BEFORE: Sampling =
Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF };
/// Serde default for fills saved before the field existed
pub fn saved_before() -> Sampling {
Sampling::SAVED_BEFORE
}
/// Whether it samples as fills saved before the field existed did (not saved then, so they save as they were)
pub fn is_saved_before(&self) -> bool {
*self == Sampling::SAVED_BEFORE
}
}
+25
View File
@@ -0,0 +1,25 @@
use serde::{Deserialize, Serialize};
/// What a fill's size is set in: repeats of its tile, or the tile's length on the mesh (stored as tiling either way)
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ScaleMode {
#[default]
Tiling,
PhysicalSize,
}
impl ScaleMode {
pub const ALL: [ScaleMode; 2] = [ScaleMode::Tiling, ScaleMode::PhysicalSize];
/// Command id
pub fn id(self) -> &'static str {
match self {
ScaleMode::Tiling => "tiling",
ScaleMode::PhysicalSize => "physicalSize",
}
}
pub fn from_id(id: &str) -> Option<ScaleMode> {
ScaleMode::ALL.into_iter().find(|mode| mode.id() == id)
}
}
+22
View File
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct UvTransform {
pub tiling: [f32; 2],
pub rotation: f32,
pub offset: [f32; 2],
}
impl Default for UvTransform {
fn default() -> Self {
UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }
}
}
impl UvTransform {
/// Whether it changes nothing, as projections saved before it existed did (not saved then)
pub fn is_default(&self) -> bool {
*self == UvTransform::default()
}
}
+40
View File
@@ -0,0 +1,40 @@
use serde::{Deserialize, Serialize};
/// Whether a UV-placed fill repeats past its 0..1 tile, across, down, both or neither
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum UvWrap {
#[default]
Repeat,
RepeatHorizontally,
RepeatVertically,
/// One tile only: outside it the fill does not cover
None,
}
impl UvWrap {
pub const ALL: [UvWrap; 4] = [UvWrap::None, UvWrap::RepeatHorizontally, UvWrap::RepeatVertically, UvWrap::Repeat];
/// Command id
pub fn id(self) -> &'static str {
match self {
UvWrap::Repeat => "repeat",
UvWrap::RepeatHorizontally => "repeatHorizontally",
UvWrap::RepeatVertically => "repeatVertically",
UvWrap::None => "none",
}
}
pub fn from_id(id: &str) -> Option<UvWrap> {
UvWrap::ALL.into_iter().find(|w| w.id() == id)
}
/// Whether the fill repeats across (u) and down (v)
pub fn repeats(self) -> (bool, bool) {
match self {
UvWrap::Repeat => (true, true),
UvWrap::RepeatHorizontally => (true, false),
UvWrap::RepeatVertically => (false, true),
UvWrap::None => (false, false),
}
}
}
+123 -6
View File
@@ -7,15 +7,78 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod anisotropic_kuwahara;
pub mod backface;
pub mod bake;
pub mod bevel;
pub mod bevel_blur;
pub mod bevel_corner;
pub mod bevel_direction;
pub mod bevel_smooth;
pub mod blend;
mod block_scales;
pub mod channel;
pub mod color_match;
pub mod color_selection;
pub mod compare_source;
pub mod contents_offset;
pub mod conversion_mode;
pub mod cook_resolution;
pub mod curve_preset;
pub mod depth_culling;
pub mod directional_distance;
pub mod directional_light;
mod env_alignment;
pub mod fill_symmetry;
pub mod gradient_input;
pub mod grayscale_conversion;
pub mod grayscale_mode;
pub mod height_to_normal;
pub mod highpass_space;
pub mod image_input;
pub mod layer;
pub mod lighting_output;
pub mod mask_outline;
pub mod mirror;
pub mod mirror_corner;
pub mod mirror_mode;
pub mod oklab;
pub mod outline_position;
pub mod pbr_validate;
mod prepared_color_match;
mod prepared_gradient;
pub mod project;
pub mod projector;
pub mod ramp_curve;
pub mod randomized_seed;
mod saved_decal;
mod saved_projection;
pub mod selection_background;
mod shadow_mode;
pub mod shape_crop;
pub mod slope_blending;
pub mod source_color_mode;
pub mod source_slope_blur;
pub mod source_warp;
pub mod stylized_lighting;
pub mod stylized_shading;
pub mod sun_and_sky;
pub mod symmetry_kind;
pub mod target_color_mode;
pub mod threshold_mode;
pub mod tile_transform;
pub mod unit_value;
pub mod validation_mode;
pub mod warp_blending;
pub mod warp_mode;
pub mod warp_source;
pub mod warp_source_mode;
/// A full turn, in degrees
pub const FULL_TURN_DEGREES: f32 = 360.0;
pub use anisotropic_kuwahara::AnisotropicKuwahara;
pub use backface::Backface;
pub use bake::{
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap,
BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization,
@@ -23,18 +86,72 @@ pub use bake::{
NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion,
SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings,
};
pub use bevel::Bevel;
pub use bevel_blur::BevelBlur;
pub use bevel_corner::BevelCorner;
pub use bevel_direction::BevelDirection;
pub use bevel_smooth::BevelSmooth;
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use color_match::ColorMatch;
pub use color_selection::ColorSelection;
pub use compare_source::CompareSource;
pub use contents_offset::ContentsOffset;
pub use conversion_mode::ConversionMode;
pub use cook_resolution::CookResolution;
pub use curve_preset::CurvePreset;
pub use depth_culling::DepthCulling;
pub use directional_distance::DirectionalDistance;
pub use directional_light::DirectionalLight;
pub use fill_symmetry::FillSymmetry;
pub use gradient_input::GradientInput;
pub use grayscale_conversion::GrayscaleConversion;
pub use grayscale_mode::GrayscaleMode;
pub use height_to_normal::HeightToNormal;
pub use highpass_space::HighpassSpace;
pub use image_input::ImageInput;
pub use layer::{
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal,
GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution,
PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode,
TileSymmetry, gradient, hsl_adjust, per_unit,
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator,
GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail,
OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES,
Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient,
hsl_adjust, per_unit, posterize,
};
pub use lighting_output::LightingOutput;
pub use mask_outline::MaskOutline;
pub use mirror::Mirror;
pub use mirror_corner::MirrorCorner;
pub use mirror_mode::MirrorMode;
pub use outline_position::OutlinePosition;
pub use pbr_validate::PbrValidate;
pub use prepared_color_match::PreparedColorMatch;
pub use prepared_gradient::PreparedGradient;
pub use project::{
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing,
Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at,
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat,
NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at,
};
pub use projector::Projector;
pub use ramp_curve::RampCurve;
pub use randomized_seed::RandomizedSeed;
pub use selection_background::SelectionBackground;
pub use shape_crop::ShapeCrop;
pub use slope_blending::SlopeBlending;
pub use source_color_mode::SourceColorMode;
pub use source_slope_blur::SourceSlopeBlur;
pub use source_warp::SourceWarp;
pub use stylized_lighting::{DIELECTRIC_REFLECTANCE, StylizedLighting};
pub use stylized_shading::{FLAT_CURVATURE, StylizedShading};
pub use sun_and_sky::SunAndSky;
pub use symmetry_kind::SymmetryKind;
pub use target_color_mode::TargetColorMode;
pub use threshold_mode::ThresholdMode;
pub use tile_transform::{FlipMode, RepeatMode, TileTransform};
pub use unit_value::{at_or_above_threshold, finite_unit};
pub use validation_mode::ValidationMode;
pub use warp_blending::WarpBlending;
pub use warp_mode::WarpMode;
pub use warp_source::WarpSource;
pub use warp_source_mode::WarpSourceMode;
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum CoreError {
+49
View File
@@ -0,0 +1,49 @@
//! What Baked Lighting Stylized paints into the base color
use serde::{Deserialize, Serialize};
/// The lit parts Baked Lighting Stylized keeps
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LightingOutput {
/// The lit surface and its highlights
#[default]
DiffuseSpecular,
/// The lit surface only (what Baked Lighting painted before it had highlights)
Diffuse,
/// The highlights only
Specular,
}
impl LightingOutput {
/// Every output, in the order a list shows them
pub const ALL: [LightingOutput; 3] = [LightingOutput::DiffuseSpecular, LightingOutput::Diffuse, LightingOutput::Specular];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
LightingOutput::DiffuseSpecular => "Diffuse + Specular",
LightingOutput::Diffuse => "Diffuse only",
LightingOutput::Specular => "Specular only",
}
}
/// The id `effect.set {output}` takes
pub fn id(self) -> &'static str {
match self {
LightingOutput::DiffuseSpecular => "diffuseSpecular",
LightingOutput::Diffuse => "diffuse",
LightingOutput::Specular => "specular",
}
}
/// Whether the lit surface is kept
pub fn diffuse(self) -> bool {
self != LightingOutput::Specular
}
/// Whether the highlights are kept
pub fn specular(self) -> bool {
self != LightingOutput::Diffuse
}
}
+94
View File
@@ -0,0 +1,94 @@
//! The Mask Outline filter's settings and the band it draws
use serde::{Deserialize, Serialize};
use crate::{OutlinePosition, RampCurve, at_or_above_threshold};
/// A band along the edge where values cross a threshold, outside, inside or on both sides of the shapes
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MaskOutline {
pub position: OutlinePosition,
/// The band on black; otherwise it is laid over the values below
pub from_black: bool,
/// Values at or above it are inside the shapes (0..1)
pub threshold: f32,
/// How far the band reaches from the edge, a fraction of the UV tile (0..1)
pub width: f32,
/// How much of the band fades out towards its far side (0..1)
pub blur: f32,
/// Bends that fade: below 0 it falls off sooner, above 0 later (−1..1)
pub curve: f32,
}
impl MaskOutline {
/// The Mask Outline filter as the library adds it
pub const LIBRARY: MaskOutline = MaskOutline { position: OutlinePosition::Outside, from_black: true, threshold: 1.0, width: 0.05, blur: 0.0, curve: 0.0 };
/// Whether `value` is inside the shapes
pub fn inside(&self, value: f32) -> bool {
at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold)
}
/// The curve the band's fade takes (Curve), worked out once per filter
pub fn fade_curve(&self) -> RampCurve {
RampCurve::new(0.0, self.curve)
}
/// The band at a texel inside the shapes or not, `closeness` to the edge going from 1 at it to 0 at the band's reach, its fade bent by [`MaskOutline::fade_curve`]
pub fn band(&self, fade_curve: RampCurve, inside: bool, closeness: f32) -> f32 {
let closeness = if closeness.is_finite() { closeness.clamp(0.0, 1.0) } else { 0.0 };
if !self.position.covers(inside) || closeness <= 0.0 || !self.width.is_finite() || self.width <= 0.0 {
return 0.0;
}
let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 };
if blur <= 0.0 {
return 1.0;
}
fade_curve.apply(closeness / blur)
}
/// The result at a texel of value `value`: the band on black, or over the value
pub fn apply(&self, value: f32, band: f32) -> f32 {
if self.from_black { band } else { value.max(band) }
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The band with the curve worked out as the filter does
fn band(filter: MaskOutline, inside: bool, closeness: f32) -> f32 {
filter.band(filter.fade_curve(), inside, closeness)
}
#[test]
fn the_band_lies_on_its_side_of_the_edge() {
let outline = MaskOutline::LIBRARY;
assert!(outline.inside(1.0) && !outline.inside(0.99));
assert_eq!(band(outline, false, 0.3), 1.0, "a hard band outside");
assert_eq!(band(outline, true, 0.3), 0.0, "nothing inside an outside band");
assert_eq!(band(outline, false, 0.0), 0.0, "nothing past its reach");
let inside = MaskOutline { position: OutlinePosition::Inside, ..outline };
assert_eq!((band(inside, true, 0.3), band(inside, false, 0.3)), (1.0, 0.0));
let both = MaskOutline { position: OutlinePosition::Both, ..outline };
assert_eq!((band(both, true, 0.3), band(both, false, 0.3)), (1.0, 1.0));
assert_eq!(outline.apply(0.4, 0.0), 0.0, "from black");
assert_eq!(MaskOutline { from_black: false, ..outline }.apply(0.4, 0.0), 0.4, "over the values");
}
#[test]
fn blur_fades_the_band_and_curve_shape_bends_the_fade() {
let soft = MaskOutline { blur: 1.0, ..MaskOutline::LIBRARY };
assert!((band(soft, false, 0.5) - 0.5).abs() < 1e-6, "a linear fade");
assert!(band(MaskOutline { curve: 0.5, ..soft }, false, 0.5) > 0.5, "falls off later");
assert!(band(MaskOutline { curve: -0.5, ..soft }, false, 0.5) < 0.5, "falls off sooner");
assert_eq!(band(MaskOutline { blur: 0.5, ..soft }, false, 0.6), 1.0, "only the far part fades");
assert_eq!(band(MaskOutline { width: f32::NAN, threshold: f32::NAN, ..soft }, false, 0.5), 0.0);
}
}
+104
View File
@@ -0,0 +1,104 @@
//! The Mirror filter's settings and where it reads each texel from
use serde::{Deserialize, Serialize};
use crate::{MirrorCorner, MirrorMode};
/// A mirror filter: one side of an axis (or one quarter) of each UV tile copied over the rest
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Mirror {
/// Draws the mirror's axes over the result (Display Debug)
pub debug: bool,
pub mode: MirrorMode,
/// Where the X and Y axes sit across the tile (0..1)
pub offset: [f32; 2],
/// Copies the right (X) or bottom (Y) side instead of the left or top one
pub invert: [bool; 2],
pub corner: MirrorCorner,
}
impl Mirror {
/// The Mirror filter as the library adds it: left onto right across the middle
pub const LIBRARY: Mirror = Mirror { debug: false, mode: MirrorMode::AxisX, offset: [0.5, 0.5], invert: [false, false], corner: MirrorCorner::TopLeft };
/// Half the width of a debug axis line, in texels at 2K
pub const DEBUG_HALF_WIDTH: f32 = 2.0;
/// Where in its tile (0..1 across, 0..1 down) the texel at `uv` reads from; a copy that reaches past an edge folds back at it
pub fn source(&self, [u, v]: [f32; 2]) -> [f32; 2] {
let across = |at: f32, axis: f32, keep_after: bool| {
let copied = if keep_after { at < axis } else { at > axis };
fold(if copied { 2.0 * axis - at } else { at })
};
match self.mode {
MirrorMode::AxisX => [across(u, self.axis(0), self.invert[0]), v],
MirrorMode::AxisY => [u, across(v, self.axis(1), self.invert[1])],
MirrorMode::Corner => {
let (right, bottom) = self.corner.sides();
[across(u, 0.5, right), across(v, 0.5, bottom)]
}
}
}
/// Whether `uv` lies within `half_width` (a fraction of the tile) of one of the mirror's axes
pub fn on_axis(&self, [u, v]: [f32; 2], half_width: f32) -> bool {
let near = |at: f32, axis: f32| (at - axis).abs() <= half_width;
match self.mode {
MirrorMode::AxisX => near(u, self.axis(0)),
MirrorMode::AxisY => near(v, self.axis(1)),
MirrorMode::Corner => near(u, 0.5) || near(v, 0.5),
}
}
/// The axis position along `axis` (0 = X, 1 = Y), within the tile even from a hostile file
fn axis(&self, axis: usize) -> f32 {
let at = self.offset.get(axis).copied().unwrap_or(0.5);
if at.is_finite() { at.clamp(0.0, 1.0) } else { 0.5 }
}
}
/// `at` folded back into 0..1 at the tile's edges, as a mirror reflects
fn fold(at: f32) -> f32 {
let wrapped = at.rem_euclid(2.0);
if wrapped > 1.0 { 2.0 - wrapped } else { wrapped }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_mode_reads_the_kept_side() {
let mut mirror = Mirror::LIBRARY;
assert_eq!(mirror.source([0.25, 0.4]), [0.25, 0.4], "the left side stays");
assert_eq!(mirror.source([0.75, 0.4]), [0.25, 0.4], "the right side reads the left");
mirror.invert[0] = true;
assert_eq!(mirror.source([0.25, 0.4]), [0.75, 0.4], "inverted, the left side reads the right");
mirror.offset[0] = 0.25;
mirror.invert[0] = false;
assert_eq!(mirror.source([0.75, 0.0]), [0.25, 0.0], "a copy past the left edge folds back at it");
mirror.mode = MirrorMode::AxisY;
assert_eq!(mirror.source([0.9, 0.75]), [0.9, 0.25], "Axis Y reads the top for the bottom");
mirror.mode = MirrorMode::Corner;
mirror.corner = MirrorCorner::BottomRight;
assert_eq!(mirror.source([0.25, 0.25]), [0.75, 0.75], "every quarter reads the kept one");
assert_eq!(mirror.source([0.75, 0.75]), [0.75, 0.75]);
assert!(mirror.on_axis([0.5, 0.1], 0.01) && mirror.on_axis([0.1, 0.5], 0.01) && !mirror.on_axis([0.1, 0.1], 0.01));
}
#[test]
fn a_hostile_offset_stays_in_the_tile() {
let mirror = Mirror { offset: [f32::NAN, f32::INFINITY], ..Mirror::LIBRARY };
let [u, v] = mirror.source([0.9, 0.9]);
assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v));
}
}
+49
View File
@@ -0,0 +1,49 @@
//! The quarter a corner mirror copies
use serde::{Deserialize, Serialize};
/// The quarter of each UV tile a corner mirror keeps and copies over the other three
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MirrorCorner {
#[default]
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl MirrorCorner {
/// Every corner, in the order a list shows them
pub const ALL: [MirrorCorner; 4] = [MirrorCorner::TopLeft, MirrorCorner::TopRight, MirrorCorner::BottomLeft, MirrorCorner::BottomRight];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
MirrorCorner::TopLeft => "Top Left",
MirrorCorner::TopRight => "Top Right",
MirrorCorner::BottomLeft => "Bottom Left",
MirrorCorner::BottomRight => "Bottom Right",
}
}
/// The id `effect.set {cornerType}` takes
pub fn id(self) -> &'static str {
match self {
MirrorCorner::TopLeft => "topLeft",
MirrorCorner::TopRight => "topRight",
MirrorCorner::BottomLeft => "bottomLeft",
MirrorCorner::BottomRight => "bottomRight",
}
}
/// Whether the kept quarter is on the right half and on the bottom half
pub fn sides(self) -> (bool, bool) {
match self {
MirrorCorner::TopLeft => (false, false),
MirrorCorner::TopRight => (true, false),
MirrorCorner::BottomLeft => (false, true),
MirrorCorner::BottomRight => (true, true),
}
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Which way a mirror filter copies a texture
use serde::{Deserialize, Serialize};
/// The side of an axis, or the corner, a mirror filter copies over the rest of each UV tile
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MirrorMode {
/// Across a vertical axis, left onto right
#[default]
AxisX,
/// Across a horizontal axis, top onto bottom
AxisY,
/// One quarter onto the other three
Corner,
}
impl MirrorMode {
/// Every mode, in the order a list shows them
pub const ALL: [MirrorMode; 3] = [MirrorMode::AxisX, MirrorMode::AxisY, MirrorMode::Corner];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
MirrorMode::AxisX => "Mirror Axis X",
MirrorMode::AxisY => "Mirror Axis Y",
MirrorMode::Corner => "Mirror Corner",
}
}
/// The id `effect.set {mode}` takes
pub fn id(self) -> &'static str {
match self {
MirrorMode::AxisX => "axisX",
MirrorMode::AxisY => "axisY",
MirrorMode::Corner => "corner",
}
}
}
+40
View File
@@ -0,0 +1,40 @@
//! The OKLab perceptual color space (Björn Ottosson's public construction): hue, chroma and lightness shifts that keep perceived lightness
/// Linear sRGB to OKLab `[L, a, b]`
pub fn from_linear([r, g, b]: [f32; 3]) -> [f32; 3] {
let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt();
let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt();
let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt();
[
0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
]
}
/// OKLab `[L, a, b]` back to linear sRGB (unclamped)
pub fn to_linear([lightness, a, b]: [f32; 3]) -> [f32; 3] {
let l = (lightness + 0.396_337_78 * a + 0.215_803_76 * b).powi(3);
let m = (lightness - 0.105_561_346 * a - 0.063_854_17 * b).powi(3);
let s = (lightness - 0.089_484_18 * a - 1.291_485_5 * b).powi(3);
[
4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
-1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s,
-0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn colors_round_trip_and_white_has_lightness_one() {
let white = from_linear([1.0; 3]);
assert!((white[0] - 1.0).abs() < 1e-3 && white[1].abs() < 1e-3 && white[2].abs() < 1e-3, "{white:?}");
for color in [[0.8, 0.2, 0.1], [0.05, 0.5, 0.9], [0.3, 0.3, 0.3]] {
let back = to_linear(from_linear(color));
assert!(color.iter().zip(back).all(|(a, b)| (a - b).abs() < 1e-3), "{color:?} -> {back:?}");
}
}
}
+48
View File
@@ -0,0 +1,48 @@
//! Which side of a mask's edge a Mask Outline draws on
use serde::{Deserialize, Serialize};
/// The side of the threshold edge a Mask Outline's band lies on
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OutlinePosition {
/// Around the shapes, outside them
#[default]
Outside,
/// Inside the shapes, along their edge
Inside,
/// On both sides of the edge
Both,
}
impl OutlinePosition {
/// Every position, in the order a switch shows them
pub const ALL: [OutlinePosition; 3] = [OutlinePosition::Outside, OutlinePosition::Inside, OutlinePosition::Both];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
OutlinePosition::Outside => "Outside",
OutlinePosition::Inside => "Inside",
OutlinePosition::Both => "Both",
}
}
/// The id `effect.set {maskPosition}` takes
pub fn id(self) -> &'static str {
match self {
OutlinePosition::Outside => "outside",
OutlinePosition::Inside => "inside",
OutlinePosition::Both => "both",
}
}
/// Whether the band covers a texel inside the shapes (`inside`)
pub fn covers(self, inside: bool) -> bool {
match self {
OutlinePosition::Outside => !inside,
OutlinePosition::Inside => inside,
OutlinePosition::Both => true,
}
}
}
+78
View File
@@ -0,0 +1,78 @@
//! PBR Validate (Metallic Roughness): base colors outside the physically plausible ranges shown in red
use serde::{Deserialize, Serialize};
use crate::ValidationMode;
use crate::blend::lum;
use crate::gradient_input::linear_to_srgb;
/// A PBR Validate filter: which texels it checks and the ranges it checks them against
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PbrValidate {
pub mode: ValidationMode,
/// Albedo Dark Range Threshold: the darkest valid non-metal base color, in sRGB steps of 255 (30 or 50)
pub albedo_dark: u8,
/// Metal Reflectance Range: the dimmest valid metal base color, in percent of sRGB white (60 or 70)
pub metal_low: u8,
}
impl PbrValidate {
/// A new PBR Validate: both kinds of texel, the tolerant ranges
pub const LIBRARY: PbrValidate = PbrValidate { mode: ValidationMode::Combined, albedo_dark: 30, metal_low: 60 };
/// Albedo Dark Range Threshold's choices
pub const ALBEDO_DARK: [u8; 2] = [50, 30];
/// Metal Reflectance Range's choices
pub const METAL_LOW: [u8; 2] = [70, 60];
/// The brightest valid non-metal base color, in sRGB steps of 255
const ALBEDO_BRIGHT: f32 = 240.0;
/// Metal from this value up counts as metal
const METAL_THRESHOLD: f32 = 0.5;
/// Metal Reflectance Range's choices are percent of sRGB white
const PERCENT: f32 = 100.0;
/// Base Color Range's choices are sRGB steps of 255
const SRGB_STEPS: f32 = 255.0;
/// The color of a texel outside its range
pub const INVALID: [f32; 3] = [1.0, 0.0, 0.0];
/// Straight linear base color `color` of a texel with metal `metal`: its own color when valid or not checked, red when not
pub fn check(&self, color: [f32; 3], metal: f32) -> [f32; 3] {
let srgb = linear_to_srgb(lum(color).clamp(0.0, 1.0));
let valid = if metal >= Self::METAL_THRESHOLD {
!self.mode.checks_metal() || srgb >= f32::from(self.metal_low) / Self::PERCENT
} else {
!self.mode.checks_albedo() || (f32::from(self.albedo_dark) / Self::SRGB_STEPS..=Self::ALBEDO_BRIGHT / Self::SRGB_STEPS).contains(&srgb)
};
if valid { color } else { Self::INVALID }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gradient_input::srgb_to_linear;
#[test]
fn colors_outside_their_range_turn_red() {
let gray = |srgb: f32| [srgb_to_linear(srgb / 255.0); 3];
let filter = PbrValidate::LIBRARY;
assert_eq!(filter.check(gray(40.0), 0.0), gray(40.0), "above 30 sRGB");
assert_eq!(filter.check(gray(20.0), 0.0), PbrValidate::INVALID, "too dark");
assert_eq!(filter.check(gray(250.0), 0.0), PbrValidate::INVALID, "too bright");
assert_eq!(PbrValidate { albedo_dark: 50, ..filter }.check(gray(40.0), 0.0), PbrValidate::INVALID);
assert_eq!(filter.check(gray(140.0), 1.0), PbrValidate::INVALID, "a dim metal");
assert_eq!(filter.check(gray(170.0), 1.0), gray(170.0), "60% reflective");
assert_eq!(PbrValidate { metal_low: 70, ..filter }.check(gray(170.0), 1.0), PbrValidate::INVALID);
let albedo = PbrValidate { mode: ValidationMode::Albedo, ..filter };
assert_eq!(albedo.check(gray(140.0), 1.0), gray(140.0), "Albedo leaves metal unchecked");
let metal = PbrValidate { mode: ValidationMode::Metal, ..filter };
assert_eq!(metal.check(gray(20.0), 0.0), gray(20.0), "Metal leaves non-metal unchecked");
}
}
+35
View File
@@ -0,0 +1,35 @@
//! Reusable OKLab references for moving a region of colors
use crate::color_match::{matched_linear, polar};
use crate::{ColorMatch, oklab};
/// The settings and converted references for a region with constant source and target colors
#[derive(Clone, Copy, Debug)]
pub struct PreparedColorMatch {
settings: ColorMatch,
source: [f32; 3],
target: [f32; 3],
}
impl PreparedColorMatch {
/// Prepare the fixed reference pair once for the region
pub fn new(settings: ColorMatch, source: [f32; 3], target: [f32; 3]) -> Self {
let reference = |color: [f32; 3]| {
let lab = oklab::from_linear(color.map(|component| component.max(0.0)));
if settings.custom_variation { polar(lab) } else { lab }
};
Self { settings, source: reference(source), target: reference(target) }
}
/// Move a texel using the prepared reference pair
pub fn apply(&self, color: [f32; 3]) -> [f32; 3] {
let lab = oklab::from_linear(color.map(|component| component.max(0.0)));
let moved = if self.settings.custom_variation {
self.settings.move_polar(polar(lab), self.source, self.target)
} else {
std::array::from_fn(|index| self.target[index] + lab[index] - self.source[index])
};
matched_linear(color, moved)
}
}
+35
View File
@@ -0,0 +1,35 @@
use crate::gradient_input::{interpolate, linear_to_srgb, ramp_stops};
use crate::{ChannelKind, Filter, GradientInput};
/// An sRGB gradient prepared for repeated sampling
pub struct PreparedGradient {
stops: Vec<(f32, [f32; 3])>,
input: GradientInput,
}
impl PreparedGradient {
/// Prepare an sRGB ramp by converting its endpoints once
pub fn of(filter: &Filter) -> Option<Self> {
let Filter::GradientMap { positions, linear: false, input, .. } = filter else { return None };
let mut stops: Vec<_> = ramp_stops(filter.ramp_colors(), positions).map(|(position, color)| (position, color.map(linear_to_srgb))).collect();
// Stable order preserves which stop wins at shared positions
stops.sort_by(|left, right| left.0.total_cmp(&right.0));
Some(Self { stops, input: *input })
}
/// Sample the prepared ramp at a normalized position
pub fn at(&self, position: f32) -> Option<[f32; 3]> {
let position = if position.is_finite() { position.clamp(0.0, 1.0) } else { 0.0 };
let split = self.stops.partition_point(|stop| stop.0 <= position);
let before = split.checked_sub(1).and_then(|index| self.stops.get(index)).copied();
let after = self.stops.get(split).copied();
Some(interpolate(before.or(after)?, after.or(before)?, false, position))
}
/// Apply the prepared gradient to one value
pub fn point(&self, kind: ChannelKind, value: [f32; 3]) -> Option<[f32; 3]> {
self.input.map(kind, value, |position| self.at(position))
}
}
+111 -17
View File
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result};
use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result};
pub use crate::env_alignment::EnvAlignment;
pub use crate::shadow_mode::ShadowMode;
@@ -15,6 +15,9 @@ pub const FORMAT_VERSION: u32 = 3;
/// First format whose baked bent normal maps are in tangent space
pub const TANGENT_BENT_NORMAL_VERSION: u32 = 3;
/// Most colour swatches a project keeps
pub const MAX_SWATCHES: usize = 64;
/// Maximum group nesting (also bounds recursion over hostile project files)
pub const MAX_DEPTH: usize = 16;
@@ -314,6 +317,14 @@ pub struct DisplaySettings {
pub ior: f32,
/// Depth of field of the viewport and the path tracer (thin lens).
pub dof: DepthOfField,
/// The selected fill's projection gizmos show in the 3D view (the Projection row's eye)
#[serde(skip_serializing_if = "is_shown")]
pub projection_gizmos: bool,
}
/// Whether a view flag is at its default, shown (saved projects then stay as they were)
fn is_shown(shown: &bool) -> bool {
*shown
}
/// A thin-lens camera's depth of field (Display settings: focus distance and aperture).
@@ -403,6 +414,7 @@ impl Default for DisplaySettings {
scatter_radius: 0.1,
ior: 1.5,
dof: DepthOfField::default(),
projection_gizmos: true,
}
}
}
@@ -430,6 +442,9 @@ pub struct Project {
/// Saved and imported cameras (the viewport's default camera is not in the list).
#[serde(default)]
pub cameras: Vec<Camera>,
/// The project's colour swatches (linear RGB), in the order they were added; projects without any save none
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub swatches: Vec<[f32; 3]>,
}
impl Project {
@@ -446,6 +461,7 @@ impl Project {
next_id: 1,
display: DisplaySettings::default(),
cameras: Vec::new(),
swatches: Vec::new(),
}
}
@@ -625,6 +641,22 @@ impl Project {
self.layers.values().find_map(|l| l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()).find(|e| e.id == id).map(|e| (l.id, e)))
}
/// What reads anchor point `anchor`, bottom to top in its texture set: (layer, the effect reading it, or None for the layer's own fill)
pub fn anchor_readers(&self, anchor: LayerId) -> Vec<(LayerId, Option<LayerId>)> {
let Some((ts, _, _)) = self.effect(anchor).and_then(|(owner, _)| self.locate(owner)) else { return Vec::new() };
let mut out = Vec::new();
for layer in self.walk(ts).into_iter().filter_map(|(id, _)| self.layers.get(&id)) {
if let LayerKind::Fill(fill) = &layer.kind
&& fill.sources.values().any(|s| s.anchor() == Some(anchor))
{
out.push((layer.id, None));
}
let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter());
out.extend(effects.filter(|e| e.reads(Some(anchor))).map(|e| (layer.id, Some(e.id))));
}
out
}
pub fn effect_mut(&mut self, id: LayerId) -> Option<&mut Effect> {
self.layers.values_mut().find_map(|l| {
let in_mask = l.mask.as_mut().and_then(|m| m.effects.iter_mut().find(|e| e.id == id));
@@ -696,6 +728,27 @@ impl Project {
self.layers.values().filter_map(|l| Some((l.id, l.instance_source()?))).find(|(id, s)| self.render_tree(&[*s]).contains(id)).map(|(id, _)| id)
}
/// The Scale and Rotation folder `id` lays on the fills inside it (none for any other layer)
pub fn contents_offset(&self, id: LayerId) -> ContentsOffset {
match self.layers.get(&id).map(|l| &l.kind) {
Some(LayerKind::Group { contents, .. }) => *contents,
_ => ContentsOffset::NONE,
}
}
/// The Scale and Rotation the folders holding layer `id` lay on its fills, combined from the outermost in
pub fn contents_around(&self, id: LayerId) -> ContentsOffset {
let mut folders = Vec::new();
let mut at = id;
while folders.len() <= MAX_DEPTH
&& let Some((_, Some(parent), _)) = self.locate(at)
{
folders.push(parent);
at = parent;
}
folders.iter().rev().fold(ContentsOffset::NONE, |around, folder| around.then(self.contents_offset(*folder)))
}
/// The layer whose content `id` draws: itself, or an instance's source.
pub fn content_layer(&self, id: LayerId) -> Option<&Layer> {
let mut l = self.layers.get(&id)?;
@@ -746,19 +799,25 @@ mod tests {
let b = paint(&mut p, "b");
let b = p.insert_layer(0, b, None, false).unwrap();
let gid = p.alloc_id();
let g = Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &Channel::DEFAULT_SET);
let g = Layer::new(gid, "g", LayerKind::folder(), &Channel::DEFAULT_SET);
p.insert_layer(0, g, Some(a), false).unwrap();
assert_eq!(p.texture_sets[0].stack, vec![a, gid, b]);
p.move_above(b, Some(gid), true).unwrap();
assert_eq!(p.texture_sets[0].stack, vec![a, gid]);
assert_eq!(p.layer(gid).unwrap().children(), &[b]);
assert_eq!(p.locate(b), Some((0, Some(gid), 0)));
assert!(p.move_above(gid, Some(b), true).is_err(), "a group cannot go inside itself");
p.validate().unwrap();
let removed = p.remove_layer(gid).unwrap();
assert_eq!(removed, vec![gid, b]);
assert_eq!(p.texture_sets[0].stack, vec![a]);
assert!(p.layer(b).is_err());
p.validate().unwrap();
}
@@ -770,17 +829,6 @@ mod tests {
assert_eq!(p.next_layer_name(0, "Layer"), "Layer 2");
}
#[test]
fn serde_round_trip_is_stable() {
let mut p = project();
let l = paint(&mut p, "x");
p.insert_layer(0, l, None, false).unwrap();
let json = serde_json::to_string(&p).unwrap();
let back: Project = serde_json::from_str(&json).unwrap();
assert_eq!(back, p);
assert_eq!(serde_json::to_string(&back).unwrap(), json);
}
#[test]
fn per_map_bake_settings_round_trip() {
use crate::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion};
@@ -809,28 +857,37 @@ mod tests {
material.sources.insert(Channel::Roughness, Source::Uniform([0.2; 3]));
l.content_effects = vec![
Effect::new(fill, EffectKind::Material(material)),
Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1 })),
Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1, perceptive: false })),
Effect::new(anchor, EffectKind::Anchor),
];
let id = p.insert_layer(0, l, None, false).unwrap();
let mut top = paint(&mut p, "y");
let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() };
top.mask = Some(Mask {
effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })],
effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })],
..Mask::new(MaskBackground::Black)
});
p.insert_layer(0, top, Some(id), false).unwrap();
let json = serde_json::to_string(&p).unwrap();
let back: Project = serde_json::from_str(&json).unwrap();
assert_eq!(back, p);
assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id));
// The mask fill of the layer above reads it
let top = back.layers.values().find(|l| l.name == "y").unwrap();
let reader = top.mask.as_ref().unwrap().effects[0].id;
assert_eq!(back.anchor_readers(anchor), vec![(top.id, Some(reader))]);
assert!(back.anchor_readers(LayerId(999)).is_empty());
// Projects saved before content effects existed load with empty stacks
let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
for l in v["layers"].as_object_mut().unwrap().values_mut() {
l.as_object_mut().unwrap().remove("content_effects");
}
let old: Project = serde_json::from_value(v).unwrap();
assert!(old.layers.values().all(|l| l.content_effects.is_empty()));
}
@@ -842,20 +899,57 @@ mod tests {
let a = p.insert_layer(0, a, None, false).unwrap();
let inst = Layer::new(p.alloc_id(), "a", LayerKind::Instance { source: a }, &[]);
let inst = p.insert_layer(1, inst, None, false).unwrap();
assert_eq!(p.content_layer(inst).map(|l| l.id), Some(a));
assert_eq!(p.sets_drawing(a), vec![0, 1]);
assert_eq!(p.sets_drawing(inst), vec![1]);
p.validate().unwrap();
// A folder holding an instance of itself draws itself.
// A folder holding an instance of itself draws itself
let gid = p.alloc_id();
p.insert_layer(1, Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &[]), None, false).unwrap();
p.insert_layer(1, Layer::new(gid, "g", LayerKind::folder(), &[]), None, false).unwrap();
let loop_id = p.alloc_id();
p.insert_layer(1, Layer::new(loop_id, "g", LayerKind::Instance { source: gid }, &[]), Some(gid), true).unwrap();
assert_eq!(p.instance_cycle(), Some(loop_id));
assert!(p.validate().is_err());
assert!(p.content_layer(LayerId(999)).is_none());
}
#[test]
fn folder_offsets_load_as_none_from_old_saves_save_only_when_set_and_combine_inward() {
let mut p = project();
let folder = |p: &mut Project, contents: ContentsOffset| {
Layer::new(p.alloc_id(), "g", LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, &[])
};
let outer = folder(&mut p, ContentsOffset::new(2.0, 30.0));
let outer = p.insert_layer(0, outer, None, false).unwrap();
let inner = folder(&mut p, ContentsOffset::new(1.5, -10.0));
let inner = p.insert_layer(0, inner, Some(outer), true).unwrap();
let a = paint(&mut p, "a");
let a = p.insert_layer(0, a, Some(inner), true).unwrap();
let top = paint(&mut p, "top");
let top = p.insert_layer(0, top, None, false).unwrap();
assert_eq!(p.contents_around(a), ContentsOffset { scale: 3.0, rotation: 20.0 });
assert_eq!(p.contents_around(inner), ContentsOffset::new(2.0, 30.0));
assert_eq!(
(p.contents_around(outer), p.contents_around(top), p.contents_offset(a)),
(ContentsOffset::NONE, ContentsOffset::NONE, ContentsOffset::NONE)
);
// A folder saved before folders had an offset has none, and one without an offset saves as before
let old: LayerKind = serde_json::from_str(r#"{"Group":{"children":[],"collapsed":true}}"#).unwrap();
assert_eq!(old, LayerKind::Group { children: vec![], collapsed: true, contents: ContentsOffset::NONE, randomized: Vec::new() });
assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"Group":{"children":[],"collapsed":true}}"#);
let saved = serde_json::to_string(&p).unwrap();
assert_eq!(serde_json::from_str::<Project>(&saved).unwrap().contents_around(a), p.contents_around(a));
}
#[test]
fn tile_grids_map_mesh_uvs_to_atlas_blocks() {
assert_eq!(TileGrid::of(&[]), None);
+50
View File
@@ -0,0 +1,50 @@
//! The 3D projection settings shared by tri-planar, planar, spherical and cylindrical projections
use serde::{Deserialize, Serialize};
use crate::{Backface, DepthCulling, ShapeCrop};
/// Rotation (degrees about X, then Y, then Z) and per-axis scale of a 3D projection's shape; default = unchanged
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Projector {
pub rotation: [f32; 3],
pub scale: [f32; 3],
pub crop: ShapeCrop,
pub backface: Backface,
/// Preserve axis-planar coverage when the projection is placed on a frame.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub ignore_image_alpha: bool,
/// Planar and warp projections only
pub depth: DepthCulling,
}
impl Default for Projector {
fn default() -> Self {
Projector {
rotation: [0.0; 3],
scale: [1.0; 3],
crop: ShapeCrop::default(),
backface: Backface::default(),
ignore_image_alpha: false,
depth: DepthCulling::default(),
}
}
}
impl Projector {
/// The settings a new planar or warp projection starts with: depth culled
pub fn depth_culled() -> Projector {
Projector { depth: DepthCulling::NEW, ..Projector::default() }
}
/// Whether it is the default, which projections saved before it existed load as (not saved then)
pub fn is_default(&self) -> bool {
*self == Projector::default()
}
/// Whether it turns or stretches the projection at all
pub fn turns(&self) -> bool {
self.rotation != [0.0; 3] || self.scale != [1.0; 3]
}
}
+38
View File
@@ -0,0 +1,38 @@
//! The bend Bevel Smooth's ramp and Mask Outline's fade take, sanitised once per filter
/// A Curve Shape of 1 raises a ramp to the power ¼ and −1 to the power 4, 0 leaves it straight
const CURVE_SHAPE_BASE: f32 = 4.0;
/// A 0..1 ramp moved by an offset, then raised to a power: below 0 the shape rises later, above 0 sooner
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RampCurve {
offset: f32,
exponent: f32,
}
impl RampCurve {
/// The curve moving a ramp by `offset` and bending it by `shape` (each −1..1, 0 when not finite)
pub fn new(offset: f32, shape: f32) -> RampCurve {
let bounded = |x: f32| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 };
RampCurve { offset: bounded(offset), exponent: CURVE_SHAPE_BASE.powf(-bounded(shape)) }
}
/// Ramp value `along` (0..1) moved and bent
pub fn apply(self, along: f32) -> f32 {
(along + self.offset).clamp(0.0, 1.0).powf(self.exponent)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_shape_bends_and_the_offset_moves() {
assert_eq!(RampCurve::new(0.0, 0.0).apply(0.3), 0.3, "straight");
assert_eq!(RampCurve::new(0.0, 1.0).apply(0.0625), 0.5, "the power ¼ rises sooner");
assert_eq!(RampCurve::new(0.0, -1.0).apply(0.5), 0.0625, "the power 4 rises later");
assert_eq!(RampCurve::new(0.25, 0.0).apply(0.5), 0.75);
assert_eq!(RampCurve::new(f32::NAN, f32::INFINITY), RampCurve::new(0.0, 0.0), "hostile settings leave it straight");
}
}
+20
View File
@@ -0,0 +1,20 @@
//! One seed a folder's Randomize seeds changed, kept on the folder so its Contents reset can put it back
use serde::{Deserialize, Serialize};
use crate::{Channel, LayerId};
/// A seed changed by a folder, identified by its layer or effect and optional material channel.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RandomizedSeed {
pub layer: LayerId,
/// Position used by older files that did not identify the source.
pub index: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<(LayerId, Option<Channel>)>,
/// Filter input name when the target owns more than one seed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input: Option<String>,
pub before: u32,
pub after: u32,
}
+11
View File
@@ -0,0 +1,11 @@
//! A decal written in the shape saved before decals were planar projections
use serde::Serialize;
use crate::Decal;
/// A decal in the shape saved before decals were planar projections
#[derive(Serialize)]
pub(crate) enum SavedDecal<'a> {
Decal(&'a Decal),
}
+30
View File
@@ -0,0 +1,30 @@
//! Reading and writing saved projections, including decals in the shape saved before they were planar projections placed on the surface
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::saved_decal::SavedDecal;
use crate::{Decal, Projection};
/// A projection as saved: today's, or a decal from before decals were planar projections
#[derive(Deserialize)]
enum SavedProjection {
Decal(Decal),
#[serde(untagged)]
Current(Projection),
}
/// Serde hook for projection fields: an older decal loads as the planar projection that looks the same
pub(crate) fn load<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Projection, D::Error> {
Ok(match SavedProjection::deserialize(deserializer)? {
SavedProjection::Decal(frame) => Projection::decal(frame),
SavedProjection::Current(projection) => projection,
})
}
/// Serde hook for projection fields: a planar projection with a decal's look saves as a decal, so earlier versions still read a decal
pub(crate) fn save<S: Serializer>(projection: &Projection, serializer: S) -> Result<S::Ok, S::Error> {
match projection {
Projection::Planar { placed: Some(frame), .. } if *projection == Projection::decal(*frame) => SavedDecal::Decal(frame).serialize(serializer),
_ => projection.serialize(serializer),
}
}
+58
View File
@@ -0,0 +1,58 @@
//! What a color selection gives the parts it does not select
use serde::{Deserialize, Serialize};
/// The value a color selection gives outside its colors; transparent leaves the mask below as it is
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SelectionBackground {
Transparent,
/// What color selections did before the choice existed
#[default]
Black,
White,
Gray,
}
impl SelectionBackground {
/// Menu order
pub const ALL: [SelectionBackground; 4] =
[SelectionBackground::Transparent, SelectionBackground::Black, SelectionBackground::White, SelectionBackground::Gray];
/// Whether it is what selections saved before the choice had (not saved then)
pub fn is_default(&self) -> bool {
*self == SelectionBackground::default()
}
/// Command id
pub fn id(self) -> &'static str {
match self {
SelectionBackground::Transparent => "transparent",
SelectionBackground::Black => "black",
SelectionBackground::White => "white",
SelectionBackground::Gray => "gray",
}
}
pub fn from_id(id: &str) -> Option<SelectionBackground> {
SelectionBackground::ALL.into_iter().find(|background| background.id() == id)
}
pub fn label(self) -> &'static str {
match self {
SelectionBackground::Transparent => "Transparent",
SelectionBackground::Black => "Black",
SelectionBackground::White => "White",
SelectionBackground::Gray => "Gray",
}
}
/// The gray it gives, none for transparent
pub fn value(self) -> Option<f32> {
match self {
SelectionBackground::Transparent => None,
SelectionBackground::Black => Some(0.0),
SelectionBackground::White => Some(1.0),
SelectionBackground::Gray => Some(0.5),
}
}
}
Loaded 100 of 470 files, more files were not shown because too many files have changed in this diff. Show more