move to GLSL (rip rust-gpu 😭)

This commit is contained in:
zack 2025-01-12 16:25:52 -05:00
parent c1df7bf365
commit d4623ab21f
No known key found for this signature in database
GPG key ID: EE8A2B709E2401D1
14 changed files with 457 additions and 486 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
/target
sponza/
.direnv/
shader-cache/

424
Cargo.lock generated
View file

@ -24,7 +24,7 @@ version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb"
dependencies = [
"gimli 0.28.1",
"gimli",
]
[[package]]
@ -52,27 +52,12 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "aligned-vec"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aa90d7ce82d4be67b64039a3d588d38dbcc6736577de4a847025ce5b0c468d1"
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "android-activity"
version = "0.5.2"
@ -136,12 +121,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "ar"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d67af77d68a931ecd5cbd8a3b5987d63a1d1d1278f7f6a60ae33db485cdebb69"
[[package]]
name = "arbitrary"
version = "1.4.1"
@ -258,7 +237,7 @@ dependencies = [
"cfg-if",
"libc",
"miniz_oxide 0.7.4",
"object 0.32.2",
"object",
"rustc-demangle",
]
@ -501,6 +480,15 @@ dependencies = [
"error-code",
]
[[package]]
name = "cmake"
version = "0.1.52"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c682c223677e0e5b6b7f63a64b9351844c3f1b1678a68b7ee617e30fb082620e"
dependencies = [
"cc",
]
[[package]]
name = "cocoa"
version = "0.25.0"
@ -583,12 +571,6 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "convert_case"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "core-foundation"
version = "0.9.4"
@ -684,19 +666,6 @@ dependencies = [
"powerfmt",
]
[[package]]
name = "derive_more"
version = "0.99.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"rustc_version",
"syn",
]
[[package]]
name = "dispatch"
version = "0.2.0"
@ -795,16 +764,6 @@ version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "elsa"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d98e71ae4df57d214182a2e5cb90230c0192c6ddfcaa05c36453d46a54713e10"
dependencies = [
"indexmap",
"stable_deref_trait",
]
[[package]]
name = "emath"
version = "0.25.0"
@ -877,12 +836,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fdeflate"
version = "0.3.7"
@ -902,12 +855,6 @@ dependencies = [
"miniz_oxide 0.8.2",
]
[[package]]
name = "foldhash"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f"
[[package]]
name = "foreign-types"
version = "0.5.0"
@ -981,17 +928,6 @@ version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
[[package]]
name = "gimli"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2e1d97fbe9722ba9bbd0c97051c2956e726562b61f86a25a4360398a40edfc9"
dependencies = [
"fallible-iterator",
"indexmap",
"stable_deref_trait",
]
[[package]]
name = "glam"
version = "0.29.2"
@ -1073,24 +1009,11 @@ dependencies = [
"crunchy",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
"allocator-api2",
]
[[package]]
name = "hashbrown"
version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
dependencies = [
"foldhash",
]
[[package]]
name = "heck"
@ -1315,7 +1238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f"
dependencies = [
"equivalent",
"hashbrown 0.15.2",
"hashbrown",
"serde",
]
@ -1325,12 +1248,6 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"
[[package]]
name = "internal-iterator"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "969ee3fc68ec2e88eb21434ce4d9b7e1600d1ce92ff974560a6c4a304f5124b9"
[[package]]
name = "interpolate_name"
version = "0.2.4"
@ -1342,15 +1259,6 @@ dependencies = [
"syn",
]
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.12.1"
@ -1506,12 +1414,6 @@ version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "longest-increasing-subsequence"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3bd0dd2cd90571056fdb71f6275fada10131182f84899f4b2a916e565d81d86"
[[package]]
name = "loop9"
version = "0.1.5"
@ -1675,6 +1577,16 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
dependencies = [
"overload",
"winapi",
]
[[package]]
name = "num-bigint"
version = "0.4.6"
@ -1990,21 +1902,6 @@ dependencies = [
"memchr",
]
[[package]]
name = "object"
version = "0.36.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
dependencies = [
"crc32fast",
"flate2",
"hashbrown 0.15.2",
"indexmap",
"memchr",
"ruzstd",
"wasmparser",
]
[[package]]
name = "once_cell"
version = "1.20.2"
@ -2020,6 +1917,12 @@ dependencies = [
"libredox",
]
[[package]]
name = "overload"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "owned_ttf_parser"
version = "0.25.0"
@ -2296,7 +2199,7 @@ dependencies = [
"built",
"cfg-if",
"interpolate_name",
"itertools 0.12.1",
"itertools",
"libc",
"libfuzzer-sys",
"log",
@ -2332,12 +2235,6 @@ dependencies = [
"rgb",
]
[[package]]
name = "raw-string"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0501e134c6905fee1f10fed25b0a7e1261bf676cffac9543a7d0730dec01af2"
[[package]]
name = "raw-window-handle"
version = "0.5.2"
@ -2409,35 +2306,6 @@ dependencies = [
"bitflags 2.6.0",
]
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "rgb"
version = "0.8.50"
@ -2445,13 +2313,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57397d16646700483b67d2dd6511d79318f9d057fdbd21a4066aeac8b41d310a"
[[package]]
name = "rspirv"
version = "0.12.0+sdk-1.3.268.0"
name = "roxmltree"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cf3a93856b6e5946537278df0d3075596371b1950ccff012f02b0f7eafec8d"
checksum = "921904a62e410e37e215c40381b7117f830d9d89ba60ab5236170541dd25646b"
dependencies = [
"rustc-hash",
"spirv",
"xmlparser",
]
[[package]]
@ -2469,58 +2336,6 @@ version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "rustc-hash"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustc_codegen_spirv"
version = "0.9.0"
source = "git+https://github.com/Rust-GPU/rust-gpu.git#bfa63c15a921357b38aa78986670c15f36df76dc"
dependencies = [
"ahash",
"ar",
"bytemuck",
"either",
"indexmap",
"itertools 0.10.5",
"lazy_static",
"libc",
"log",
"object 0.36.7",
"regex",
"rspirv",
"rustc-demangle",
"rustc_codegen_spirv-types",
"rustix",
"sanitize-filename",
"smallvec",
"spirt",
"spirv-tools",
"thorin-dwp",
]
[[package]]
name = "rustc_codegen_spirv-types"
version = "0.9.0"
source = "git+https://github.com/Rust-GPU/rust-gpu.git#bfa63c15a921357b38aa78986670c15f36df76dc"
dependencies = [
"rspirv",
"serde",
"serde_json",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "0.38.42"
@ -2529,22 +2344,11 @@ checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
dependencies = [
"bitflags 2.6.0",
"errno",
"itoa",
"libc",
"linux-raw-sys",
"once_cell",
"windows-sys 0.59.0",
]
[[package]]
name = "ruzstd"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fad02996bfc73da3e301efe90b1837be9ed8f4a462b6ed410aa35d00381de89f"
dependencies = [
"twox-hash",
]
[[package]]
name = "ryu"
version = "1.0.18"
@ -2560,16 +2364,6 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "sanitize-filename"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c502bdb638f1396509467cb0580ef3b29aa2a45c5d43e5d84928241280296c"
dependencies = [
"lazy_static",
"regex",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
@ -2608,12 +2402,6 @@ dependencies = [
"tiny-skia",
]
[[package]]
name = "semver"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba"
[[package]]
name = "serde"
version = "1.0.216"
@ -2655,6 +2443,27 @@ dependencies = [
"serde",
]
[[package]]
name = "shaderc"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27e07913ada18607bb60d12431cbe3358d3bbebbe95948e1618851dc01e63b7b"
dependencies = [
"libc",
"shaderc-sys",
]
[[package]]
name = "shaderc-sys"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73120d240fe22196300f39ca8547ca2d014960f27b19b47b21288b396272f7f7"
dependencies = [
"cmake",
"libc",
"roxmltree",
]
[[package]]
name = "shaders"
version = "0.1.0"
@ -2715,9 +2524,6 @@ name = "smallvec"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
dependencies = [
"serde",
]
[[package]]
name = "smithay-client-toolkit"
@ -2789,49 +2595,6 @@ dependencies = [
"serde",
]
[[package]]
name = "spirt"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2d5968bd2a36466468aac637b355776f080edfb0c6f769b2b99b9708260c42a"
dependencies = [
"arrayvec",
"bytemuck",
"derive_more",
"elsa",
"indexmap",
"internal-iterator",
"itertools 0.10.5",
"lazy_static",
"longest-increasing-subsequence",
"rustc-hash",
"serde",
"serde_json",
"smallvec",
]
[[package]]
name = "spirv"
version = "0.3.0+sdk-1.3.268.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"
dependencies = [
"bitflags 2.6.0",
]
[[package]]
name = "spirv-builder"
version = "0.9.0"
source = "git+https://github.com/Rust-GPU/rust-gpu.git#bfa63c15a921357b38aa78986670c15f36df76dc"
dependencies = [
"memchr",
"raw-string",
"rustc_codegen_spirv",
"rustc_codegen_spirv-types",
"serde",
"serde_json",
]
[[package]]
name = "spirv-std"
version = "0.9.0"
@ -2860,36 +2623,12 @@ name = "spirv-std-types"
version = "0.9.0"
source = "git+https://github.com/Rust-GPU/rust-gpu.git#bfa63c15a921357b38aa78986670c15f36df76dc"
[[package]]
name = "spirv-tools"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcb3b0832881834994b7ec82b709ec5491043ceb4bf8101e27da6b5234b24261"
dependencies = [
"spirv-tools-sys",
]
[[package]]
name = "spirv-tools-sys"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e68b55a97aa6856e010a6f2477425875a97873e147bb0232160e73c45bdae7"
dependencies = [
"cc",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strict-num"
version = "0.1.1"
@ -2957,18 +2696,6 @@ dependencies = [
"syn",
]
[[package]]
name = "thorin-dwp"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "813ba76597db32dc4f6992fd8bf8f394715b88d352fd97401da67dab6283b4c6"
dependencies = [
"gimli 0.30.0",
"hashbrown 0.14.5",
"object 0.36.7",
"tracing",
]
[[package]]
name = "thread_local"
version = "1.1.8"
@ -3141,15 +2868,29 @@ dependencies = [
"tracing-subscriber",
]
[[package]]
name = "tracing-log"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
dependencies = [
"log",
"once_cell",
"tracing-core",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
dependencies = [
"nu-ansi-term",
"sharded-slab",
"smallvec",
"thread_local",
"tracing-core",
"tracing-log",
]
[[package]]
@ -3158,16 +2899,6 @@ version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
[[package]]
name = "twox-hash"
version = "1.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675"
dependencies = [
"cfg-if",
"static_assertions",
]
[[package]]
name = "unicode-ident"
version = "1.0.14"
@ -3264,10 +2995,12 @@ dependencies = [
"puffin_egui",
"raw-window-handle 0.6.2",
"rayon",
"shaderc",
"shaders-shared",
"spirv-builder",
"spirv-std",
"tobj",
"tracing",
"tracing-subscriber",
"winit 0.30.7",
]
@ -3354,15 +3087,6 @@ version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6"
[[package]]
name = "wasmparser"
version = "0.222.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4adf50fde1b1a49c1add6a80d47aea500c88db70551805853aa8b88f3ea27ab5"
dependencies = [
"bitflags 2.6.0",
]
[[package]]
name = "wayland-backend"
version = "0.3.7"
@ -4006,6 +3730,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]]
name = "xmlparser"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4"
[[package]]
name = "yoke"
version = "0.7.5"

View file

@ -16,6 +16,8 @@ raw-window-handle = "0.6"
gpu-allocator = { version = "0.25.0", features = ["vulkan"] }
glam = { version = "0.22", default-features = false, features = ["libm"] }
bytemuck = "1.21.0"
tracing = "0.1"
tracing-subscriber = "0.3"
spirv-builder = { git = "https://github.com/Rust-GPU/rust-gpu.git" }
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git" }

View file

@ -2,13 +2,23 @@
use spirv_std::glam::{Mat4, Vec3, Vec4};
#[repr(C)]
#[derive(Clone, Copy, Debug)]
#[repr(C, align(16))]
pub struct Material {
pub base_color: Vec4,
pub metallic_factor: f32,
pub roughness_factor: f32,
pub _padding: [f32; 2],
}
#[repr(C, align(16))]
#[derive(Clone)]
pub struct UniformBufferObject {
pub model: Mat4,
pub view: Mat4,
pub proj: Mat4,
pub model_color: Vec3,
// pub camera_pos: Vec3,
// pub material: Material,
}
#[repr(C)]

View file

@ -1,119 +1,69 @@
#![cfg_attr(target_arch = "spirv", no_std)]
use shaders_shared::UniformBufferObject;
use spirv_std::num_traits::Float;
use spirv_std::{
glam::{Mat3, UVec2, Vec2, Vec3, Vec4, Vec4Swizzles},
image::Image2d,
spirv, Sampler,
};
pub const PI: f32 = core::f32::consts::PI;
fn fresnel_schlick(cos_theta: f32, f0: Vec3) -> Vec3 {
f0 + (Vec3::ONE - f0) * (1.0 - cos_theta).powf(5.0)
}
fn distribution_ggx(n: Vec3, h: Vec3, roughness: f32) -> f32 {
let a = roughness * roughness;
let a2 = a * a;
let n_dot_h = n.dot(h).max(0.0);
let n_dot_h2 = n_dot_h * n_dot_h;
let nom = a2;
let denom = (n_dot_h2 * (a2 - 1.0) + 1.0);
let denom = PI * denom * denom;
nom / denom.max(0.001)
}
fn geometry_schlick_ggx(n_dot_v: f32, roughness: f32) -> f32 {
let r = roughness + 1.0;
let k = (r * r) / 8.0;
let nom = n_dot_v;
let denom = n_dot_v * (1.0 - k) + k;
nom / denom
}
fn geometry_smith(n: Vec3, v: Vec3, l: Vec3, roughness: f32) -> f32 {
let n_dot_v = n.dot(v).max(0.0);
let n_dot_l = n.dot(l).max(0.0);
let ggx2 = geometry_schlick_ggx(n_dot_v, roughness);
let ggx1 = geometry_schlick_ggx(n_dot_l, roughness);
ggx1 * ggx2
}
#[spirv(vertex)]
pub fn main_vs(
// Vertex inputs
in_pos: Vec3,
#[spirv(position)] in_pos: Vec3,
in_normal: Vec3,
in_tex_coord: Vec2,
// Uniform buffer
#[spirv(uniform, descriptor_set = 0, binding = 0)] ubo: &UniformBufferObject,
// Vertex outputs
out_world_position: &mut Vec3,
out_world_pos: &mut Vec3,
out_world_normal: &mut Vec3,
out_tex_coord: &mut Vec2,
#[spirv(position)] gl_position: &mut Vec4,
#[spirv(position)] out_pos: &mut Vec4,
) {
// Transform position to world space
let pos = ubo.model * Vec4::from((in_pos, 1.0));
*out_world_position = (pos / pos.w).xyz();
*out_world_pos = pos.truncate();
// Transform normal to world space
let normal_matrix = Mat3::from_mat4(ubo.model).inverse().transpose();
*out_world_normal = normal_matrix * in_normal;
*out_world_normal = (normal_matrix * in_normal).normalize();
// Calculate clip space position
*gl_position = ubo.proj * ubo.view * pos;
*out_pos = ubo.proj * ubo.view * pos;
*out_tex_coord = in_tex_coord;
}
pub fn get_uv_u(pix: UVec2, tex_size: Vec4) -> spirv_std::glam::Vec2 {
(pix.as_vec2() + Vec2::splat(0.5)) * tex_size.zw()
}
fn ray_triangle_intersect(
ray_origin: Vec3,
ray_direction: Vec3,
v0: Vec3,
v1: Vec3,
v2: Vec3,
) -> f32 {
let epsilon = 0.000001;
let edge1 = v1 - v0;
let edge2 = v2 - v0;
let h = ray_direction.cross(edge2);
let a = edge1.dot(h);
if a > -epsilon && a < epsilon {
return -1.0;
}
let f = 1.0 / a;
let s = ray_origin - v0;
let u = f * s.dot(h);
if !(0.0..=1.0).contains(&u) {
return -1.0;
}
let q = s.cross(edge1);
let v = f * ray_direction.dot(q);
if v < 0.0 || u + v > 1.0 {
return -1.0;
}
let t = f * edge2.dot(q);
if t > epsilon {
return t;
}
-1.0
}
fn material_color(
frag_world_position: Vec3,
frag_normal: Vec3,
light_pos: Vec3,
object_color: Vec3,
) -> Vec3 {
let l = (light_pos - frag_world_position).normalize();
let n = frag_normal.normalize();
let lambertian = f32::max(n.dot(l), 0.0);
object_color * lambertian
}
#[spirv(fragment)]
pub fn main_fs(
frag_world_position: Vec3,
frag_world_normal: Vec3,
frag_tex_coord: Vec2,
#[spirv(descriptor_set = 0, binding = 1)] texture: &Image2d,
#[spirv(descriptor_set = 0, binding = 2)] sampler: &Sampler,
out_color: &mut Vec4,
) {
// Convert fragment coordinate to UV coordinate
// Sample the texture
let base_color = texture.sample(*sampler, frag_tex_coord);
// let light_pos = Vec3::new(2.0, 2.0, -2.0);
//
// // Calculate light direction
// let l = (light_pos - frag_world_position).normalize();
// let n = frag_world_normal.normalize();
//
// // Calculate lambertian lighting
// let lambertian = f32::max(n.dot(l), 0.0);
//
// // Ambient lighting
// let ambient = Vec3::splat(0.2);
//
// // Combine texture color with model color
// let color_from_texture = Vec3::new(base_color.x, base_color.y, base_color.z);
// let combined_color = color_from_texture;
//
// // Final color calculation with gamma correction
// let color = (combined_color * lambertian + ambient).powf(2.2);
*out_color = Vec4::new(base_color.x, base_color.y, base_color.z, base_color.w);
}

View file

@ -26,6 +26,8 @@ gltf = { version = "1.4.1", features = ["import"] }
image = "0.25.5"
rayon = "1.10.0"
bytemuck.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
[build-dependencies]
spirv-builder.workspace = true
shaderc = "0.8"

View file

@ -1,33 +1,71 @@
use shaderc::{Compiler, ShaderKind};
use std::{
fs::{self, File},
io::{Read, Write},
io::Write,
path::{Path, PathBuf},
};
use spirv_builder::{MetadataPrintout, SpirvBuilder};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Tell Cargo to rerun this script if the shaders crate or its contents change
println!("cargo:rerun-if-changed=../shaders/src");
println!("cargo:rerun-if-changed=../shaders/Cargo.toml");
// Tell Cargo to rerun if shaders directory changes
println!("cargo:rerun-if-changed=../../shaders");
SpirvBuilder::new("../shaders/", "spirv-unknown-vulkan1.2")
.print_metadata(MetadataPrintout::None)
.multimodule(true)
.build()?
.module
.unwrap_multi()
.iter()
.for_each(|(name, path)| {
let mut data = vec![];
File::open(path).unwrap().read_to_end(&mut data).unwrap();
let shader_dir = Path::new("../../shaders");
let cache_dir = Path::new("../../shader-cache");
fs::create_dir_all("./shaders/").unwrap();
// Create shader cache directory if it doesn't exist
fs::create_dir_all(cache_dir)?;
File::create(format!("./shaders/{name}.spv"))
.unwrap()
.write_all(&data)
.unwrap();
});
let compiler = Compiler::new().expect("Failed to create shader compiler");
// Compile all .vert and .frag files
for entry in fs::read_dir(shader_dir)? {
let entry = entry?;
let path = entry.path();
if let Some(extension) = path.extension() {
let kind = match extension.to_str() {
Some("vert") => ShaderKind::Vertex,
Some("frag") => ShaderKind::Fragment,
_ => continue,
};
let source = fs::read_to_string(&path)?;
let file_name = path.file_name().unwrap().to_str().unwrap();
// Create output path
let spirv_path = cache_dir.join(format!("{}.spv", file_name));
// Check if we need to recompile
if should_compile(&path, &spirv_path) {
println!("Compiling shader: {}", file_name);
let compiled =
compiler.compile_into_spirv(&source, kind, file_name, "main", None)?;
let mut file = File::create(&spirv_path)?;
file.write_all(compiled.as_binary_u8())?;
}
}
}
Ok(())
}
fn should_compile(source_path: &Path, output_path: &PathBuf) -> bool {
// If output doesn't exist, we need to compile
if !output_path.exists() {
return true;
}
// Get modification times
let source_modified = fs::metadata(source_path)
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
let output_modified = fs::metadata(output_path)
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
// Compile if source is newer than output
source_modified > output_modified
}

Binary file not shown.

Binary file not shown.

View file

@ -276,21 +276,21 @@ impl MyAppCreator {
p_callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT,
_p_user_data: *mut std::ffi::c_void,
) -> vk::Bool32 {
let severity = match message_severity {
vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => "[VERBOSE]",
vk::DebugUtilsMessageSeverityFlagsEXT::WARNING => "[WARNING]",
vk::DebugUtilsMessageSeverityFlagsEXT::ERROR => "[ERROR]",
vk::DebugUtilsMessageSeverityFlagsEXT::INFO => "[INFO]",
_ => panic!("[UNKNOWN]"),
};
let types = match message_types {
vk::DebugUtilsMessageTypeFlagsEXT::GENERAL => "[GENERAL]",
vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE => "[PERFORMANCE]",
vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION => "[VALIDATION]",
_ => panic!("[UNKNOWN]"),
};
let message = std::ffi::CStr::from_ptr((*p_callback_data).p_message);
println!("[DEBUG]{}{}{:?}", severity, types, message);
match message_severity {
vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => tracing::trace!("{types}{message:?}"),
vk::DebugUtilsMessageSeverityFlagsEXT::WARNING => tracing::warn!("{types}{message:?}"),
vk::DebugUtilsMessageSeverityFlagsEXT::ERROR => tracing::error!("{types}{message:?}"),
vk::DebugUtilsMessageSeverityFlagsEXT::INFO => tracing::info!("{types}{message:?}"),
_ => tracing::debug!("{types}{message:?}"),
};
vk::FALSE
}
@ -680,6 +680,7 @@ impl AppCreator<Arc<Mutex<Allocator>>> for MyAppCreator {
}
fn main() -> std::process::ExitCode {
tracing_subscriber::fmt().pretty().init();
puffin::set_scopes_on(true);
egui_ash::run(

View file

@ -11,6 +11,7 @@ use spirv_std::glam::{Mat4, Vec3, Vec4};
use std::{
ffi::CString,
mem::ManuallyDrop,
panic,
path::Path,
sync::{Arc, Mutex},
time::Instant,
@ -33,6 +34,91 @@ macro_rules! include_spirv {
}};
}
pub struct DefaultTextures {
white: Texture, // Default albedo (white)
metallic_roughness: Texture, // Default metallic-roughness (black metallic, 0.5 roughness)
normal: Texture, // Default normal map (flat normal)
sampler: vk::Sampler, // Common sampler for all textures
}
pub struct Material {
base_color: Vec4,
metallic_factor: f32,
roughness_factor: f32,
base_color_texture: Option<Arc<Texture>>,
// metallic_roughness_texture: Option<Arc<Texture>>,
// normal_texture: Option<Arc<Texture>>,
}
impl Material {
fn from_gltf(
material: &gltf::Material,
device: &Device,
allocator: Arc<Mutex<Allocator>>,
command_pool: vk::CommandPool,
queue: vk::Queue,
path: &Path,
texture_cache: &mut TextureCache,
buffers: &[gltf::buffer::Data],
) -> Self {
let pbr = material.pbr_metallic_roughness();
let base_color = pbr.base_color_factor();
let metallic_factor = pbr.metallic_factor();
let roughness_factor = pbr.roughness_factor();
let base_color_texture = pbr.base_color_texture().and_then(|tex| {
let key = format!("{:?}", tex.texture().source().source());
texture_cache.get_or_load_texture(key, || {
load_texture_from_gltf(
device,
allocator.clone(),
command_pool,
queue,
&tex.texture(),
buffers,
path,
)
})
});
// let metallic_roughness_texture = pbr.metallic_roughness_texture().and_then(|tex| {
// load_texture_from_gltf(
// device,
// allocator.clone(),
// command_pool,
// queue,
// &tex.texture(),
// buffers,
// path,
// )
// .map(Arc::new)
// });
//
// let normal_texture = material.normal_texture().and_then(|tex| {
// load_texture_from_gltf(
// device,
// allocator.clone(),
// command_pool,
// queue,
// &tex.texture(),
// buffers,
// path,
// )
// .map(Arc::new)
// });
Self {
base_color: Vec4::from(base_color),
metallic_factor,
roughness_factor,
base_color_texture,
// metallic_roughness_texture,
// normal_texture,
}
}
}
#[repr(C)]
#[derive(Debug, Clone)]
struct Vertex {
@ -94,7 +180,7 @@ impl Texture {
let buffer_size = data.len() as u64;
println!("DATA LEN: {}", buffer_size);
tracing::info!("DATA LEN: {}", buffer_size);
let staging_buffer = unsafe {
device
.create_buffer(
@ -348,12 +434,92 @@ impl Texture {
}
}
impl DefaultTextures {
fn new(
device: &Device,
allocator: Arc<Mutex<Allocator>>,
command_pool: vk::CommandPool,
queue: vk::Queue,
) -> Self {
// Create a 1x1 white texture for default albedo
let white_data = vec![255u8, 255, 255, 255];
let white = Texture::new(
device,
allocator.clone(),
command_pool,
queue,
1,
1,
&white_data,
);
// Create a 1x1 default metallic-roughness texture
// R: unused, G: roughness (0.5), B: metallic (0.0)
let metallic_roughness_data = vec![0u8, 128, 0, 255];
let metallic_roughness = Texture::new(
device,
allocator.clone(),
command_pool,
queue,
1,
1,
&metallic_roughness_data,
);
// Create a 1x1 default normal map (pointing up)
let normal_data = vec![128u8, 128, 255, 255];
let normal = Texture::new(device, allocator, command_pool, queue, 1, 1, &normal_data);
// Create a common sampler
let sampler_create_info = vk::SamplerCreateInfo::builder()
.mag_filter(vk::Filter::LINEAR)
.min_filter(vk::Filter::LINEAR)
.address_mode_u(vk::SamplerAddressMode::REPEAT)
.address_mode_v(vk::SamplerAddressMode::REPEAT)
.address_mode_w(vk::SamplerAddressMode::REPEAT)
.anisotropy_enable(true)
.max_anisotropy(16.0)
.border_color(vk::BorderColor::INT_OPAQUE_BLACK)
.unnormalized_coordinates(false)
.compare_enable(false)
.compare_op(vk::CompareOp::ALWAYS)
.mipmap_mode(vk::SamplerMipmapMode::LINEAR)
.mip_lod_bias(0.0)
.min_lod(0.0)
.max_lod(0.0);
let sampler = unsafe {
device
.create_sampler(&sampler_create_info, None)
.expect("Failed to create sampler")
};
Self {
white,
metallic_roughness,
normal,
sampler,
}
}
fn destroy(&mut self, device: &Device, allocator: &mut Allocator) {
unsafe {
self.white.destroy(device, allocator);
self.metallic_roughness.destroy(device, allocator);
self.normal.destroy(device, allocator);
device.destroy_sampler(self.sampler, None);
}
}
}
pub struct Mesh {
vertex_buffer: Buffer,
vertex_buffer_allocation: Option<Allocation>,
vertex_count: u32,
transform: Mat4,
texture: Option<Arc<Texture>>,
material: Material,
default_textures: DefaultTextures,
descriptor_sets: Vec<vk::DescriptorSet>,
}
@ -373,6 +539,7 @@ impl Model {
.expect("Failed to free memory");
}
self.texture_cache.cleanup(device, allocator);
mesh.default_textures.destroy(device, allocator);
}
}
}
@ -390,15 +557,16 @@ fn load_texture_from_gltf(
let img_data =
gltf::image::Data::from_source(texture.source().source(), Some(path), buffers).ok()?;
println!(
tracing::info!(
"Original texture dimensions: {}x{}",
img_data.width, img_data.height
img_data.width,
img_data.height
);
// Convert to RGB/RGBA
let pixels_rgba = if img_data.pixels.len() == (img_data.width * img_data.height * 3) as usize {
// Image is RGB, convert to RGBA
println!("Converting RGB to RGBA");
tracing::info!("Converting RGB to RGBA");
let mut rgba_data = Vec::with_capacity((img_data.width * img_data.height * 4) as usize);
for chunk in img_data.pixels.chunks_exact(3) {
rgba_data.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
@ -482,6 +650,17 @@ fn process_node(
if let Some(mesh) = node.mesh() {
for primitive in mesh.primitives() {
let material = Material::from_gltf(
&primitive.material(),
device,
allocator.clone(),
command_pool,
queue,
path,
texture_cache,
buffers,
);
let texture = primitive
.material()
.pbr_metallic_roughness()
@ -545,6 +724,9 @@ fn process_node(
let (vertex_buffer, vertex_buffer_allocation) =
create_vertex_buffer(device, allocator.clone(), command_pool, queue, &vertices);
let default_textures =
DefaultTextures::new(device, allocator.clone(), command_pool, queue);
meshes.push(Mesh {
vertex_buffer,
vertex_buffer_allocation: Some(vertex_buffer_allocation),
@ -552,6 +734,8 @@ fn process_node(
// Store identity matrix, it is not used here anymore
transform: Mat4::IDENTITY,
texture,
material,
default_textures,
descriptor_sets: Vec::new(),
});
}
@ -1199,7 +1383,7 @@ impl RendererInner {
render_pass: vk::RenderPass,
) -> (vk::Pipeline, vk::PipelineLayout) {
let vertex_shader_module = {
let spirv = include_spirv!("../shaders/main_vs.spv");
let spirv = include_spirv!("../../../shader-cache/main.vert.spv");
let shader_module_create_info = vk::ShaderModuleCreateInfo::builder().code(&spirv);
unsafe {
device
@ -1208,7 +1392,7 @@ impl RendererInner {
}
};
let fragment_shader_module = {
let spirv = include_spirv!("../shaders/main_fs.spv");
let spirv = include_spirv!("../../../shader-cache/main.frag.spv");
let shader_module_create_info = vk::ShaderModuleCreateInfo::builder().code(&spirv);
unsafe {
device
@ -1216,8 +1400,8 @@ impl RendererInner {
.expect("Failed to create shader module")
}
};
let main_function_name_fs = CString::new("main_fs").unwrap();
let main_function_name_vs = CString::new("main_vs").unwrap();
let main_function_name_fs = CString::new("main").unwrap();
let main_function_name_vs = CString::new("main").unwrap();
let pipeline_shader_stages = [
vk::PipelineShaderStageCreateInfo::builder()
.stage(vk::ShaderStageFlags::VERTEX)
@ -1558,7 +1742,7 @@ impl RendererInner {
);
let t = Instant::now();
println!("loading model!");
tracing::info!("loading model!");
let mut model = Model::load(
&device,
allocator.clone(),
@ -1566,7 +1750,7 @@ impl RendererInner {
queue,
"./sponza/NewSponza_Main_glTF_003.gltf",
);
println!(
tracing::info!(
"loaded {} meshes in {:.2} seconds!",
model.meshes.len(),
t.elapsed().as_secs_f32()
@ -1839,7 +2023,10 @@ impl RendererInner {
0.1,
1000.0,
),
model_color: self.model_color,
// camera_pos: self.camera_position,
// metallic_factor: mesh.material.metallic_factor,
// roughness_factor: mesh.material.roughness_factor,
// base_color: mesh.material.base_color,
};
let ptr = self.uniform_buffer_allocations[self.current_frame]

View file

@ -68,6 +68,7 @@
vulkan-headers
vulkan-loader
vulkan-validation-layers
cmake
];
buildInputs = with pkgs; [

17
shaders/main.frag Normal file
View file

@ -0,0 +1,17 @@
#version 450
layout(location = 0) in vec3 frag_world_position;
layout(location = 1) in vec3 frag_world_normal;
layout(location = 2) in vec2 frag_tex_coord;
layout(set = 0, binding = 1) uniform sampler2D tex_sampler;
layout(location = 0) out vec4 out_color;
void main() {
// Sample the texture
vec4 base_color = texture(tex_sampler, frag_tex_coord);
// Output final color
out_color = vec4(base_color.rgb, base_color.a);
}

32
shaders/main.vert Normal file
View file

@ -0,0 +1,32 @@
#version 450
// Vertex inputs
layout(location = 0) in vec3 in_pos;
layout(location = 1) in vec3 in_normal;
layout(location = 2) in vec2 in_tex_coord;
// Uniform buffer
layout(set = 0, binding = 0) uniform UniformBufferObject {
mat4 model;
mat4 view;
mat4 proj;
} ubo;
// Vertex outputs
layout(location = 0) out vec3 out_world_position;
layout(location = 1) out vec3 out_world_normal;
layout(location = 2) out vec2 out_tex_coord;
void main() {
// Transform position to world space
vec4 pos = ubo.model * vec4(in_pos, 1.0);
out_world_position = (pos / pos.w).xyz;
// Transform normal to world space
mat3 normal_matrix = transpose(inverse(mat3(ubo.model)));
out_world_normal = normal_matrix * in_normal;
// Calculate clip space position
gl_Position = ubo.proj * ubo.view * pos;
out_tex_coord = in_tex_coord;
}