Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

refactor gx and wgpu backend

Layle99c703b70c81
diff --git a/Cargo.lock b/Cargo.lock
index cf7451b..b21efd7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -92,6 +92,17 @@ dependencies = [
"libc",
]
+[[package]]
+name = "annotate-snippets"
+version = "0.12.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74fc7650eedcb2fee505aad48491529e408f0e854c2d9f63eb86c1361b9b3f93"
+dependencies = [
+ "anstyle",
+ "memchr",
+ "unicode-width",
+]
+
[[package]]
name = "anstream"
version = "1.0.0"
@@ -180,6 +191,15 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
+[[package]]
+name = "ascii-canvas"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef1e3e699d84ab1b0911a1010c5c106aa34ae89aeac103be5ce0c3859db1e891"
+dependencies = [
+ "term",
+]
+
[[package]]
name = "ash"
version = "0.38.0+1.3.281"
@@ -207,6 +227,7 @@ version = "0.1.0"
dependencies = [
"bytemuck",
"gecko",
+ "wesl",
"wgpu",
]
@@ -249,6 +270,15 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block2"
version = "0.5.1"
@@ -544,6 +574,15 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "convert_case"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
+dependencies = [
+ "unicode-segmentation",
+]
+
[[package]]
name = "core-foundation"
version = "0.9.4"
@@ -605,6 +644,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.0"
@@ -649,6 +697,16 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
[[package]]
name = "cursor-icon"
version = "1.2.0"
@@ -687,6 +745,39 @@ dependencies = [
"winit",
]
+[[package]]
+name = "derive_more"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
+dependencies = [
+ "derive_more-impl",
+]
+
+[[package]]
+name = "derive_more-impl"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
+dependencies = [
+ "convert_case",
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "syn",
+ "unicode-xid",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
[[package]]
name = "disasm"
version = "0.1.0"
@@ -858,6 +949,15 @@ dependencies = [
"bytemuck",
]
+[[package]]
+name = "ena"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "epaint"
version = "0.33.3"
@@ -959,6 +1059,12 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+[[package]]
+name = "fixedbitset"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
[[package]]
name = "flate2"
version = "1.1.9"
@@ -969,6 +1075,12 @@ dependencies = [
"miniz_oxide",
]
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
[[package]]
name = "foldhash"
version = "0.1.5"
@@ -1094,6 +1206,16 @@ dependencies = [
"winit",
]
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
[[package]]
name = "gethostname"
version = "1.1.0"
@@ -1372,6 +1494,15 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "jni"
version = "0.22.4"
@@ -1442,9 +1573,9 @@ dependencies = [
[[package]]
name = "js-sys"
-version = "0.3.93"
+version = "0.3.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "797146bb2677299a1eb6b7b50a890f4c361b29ef967addf5b2fa45dae1bb6d7d"
+checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9"
dependencies = [
"cfg-if",
"futures-util",
@@ -1452,6 +1583,15 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "keccak"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
+dependencies = [
+ "cpufeatures",
+]
+
[[package]]
name = "khronos-egl"
version = "6.0.0"
@@ -1480,12 +1620,109 @@ dependencies = [
"smallvec",
]
+[[package]]
+name = "lalrpop"
+version = "0.22.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba4ebbd48ce411c1d10fb35185f5a51a7bfa3d8b24b4e330d30c9e3a34129501"
+dependencies = [
+ "ascii-canvas",
+ "bit-set",
+ "ena",
+ "itertools",
+ "lalrpop-util",
+ "petgraph",
+ "regex",
+ "regex-syntax",
+ "sha3",
+ "string_cache",
+ "term",
+ "unicode-xid",
+ "walkdir",
+]
+
+[[package]]
+name = "lalrpop-util"
+version = "0.22.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5baa5e9ff84f1aefd264e6869907646538a52147a755d494517a8007fb48733"
+dependencies = [
+ "regex-automata",
+ "rustversion",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+[[package]]
+name = "lexical"
+version = "7.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bc8a009b2ff1f419ccc62706f04fe0ca6e67b37460513964a3dfdb919bb37d6"
+dependencies = [
+ "lexical-core",
+]
+
+[[package]]
+name = "lexical-core"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d8d125a277f807e55a77304455eb7b1cb52f2b18c143b60e766c120bd64a594"
+dependencies = [
+ "lexical-parse-float",
+ "lexical-parse-integer",
+ "lexical-util",
+ "lexical-write-float",
+ "lexical-write-integer",
+]
+
+[[package]]
+name = "lexical-parse-float"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52a9f232fbd6f550bc0137dcb5f99ab674071ac2d690ac69704593cb4abbea56"
+dependencies = [
+ "lexical-parse-integer",
+ "lexical-util",
+]
+
+[[package]]
+name = "lexical-parse-integer"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a7a039f8fb9c19c996cd7b2fcce303c1b2874fe1aca544edc85c4a5f8489b34"
+dependencies = [
+ "lexical-util",
+]
+
+[[package]]
+name = "lexical-util"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2604dd126bb14f13fb5d1bd6a66155079cb9fa655b37f875b3a742c705dbed17"
+
+[[package]]
+name = "lexical-write-float"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50c438c87c013188d415fbabbb1dceb44249ab81664efbd31b14ae55dabb6361"
+dependencies = [
+ "lexical-util",
+ "lexical-write-integer",
+]
+
+[[package]]
+name = "lexical-write-integer"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "409851a618475d2d5796377cad353802345cba92c867d9fbcde9cf4eac4e14df"
+dependencies = [
+ "lexical-util",
+]
+
[[package]]
name = "libc"
version = "0.2.183"
@@ -1565,6 +1802,38 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+[[package]]
+name = "logos"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f"
+dependencies = [
+ "logos-derive",
+]
+
+[[package]]
+name = "logos-codegen"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970"
+dependencies = [
+ "fnv",
+ "proc-macro2",
+ "quote",
+ "regex-automata",
+ "regex-syntax",
+ "syn",
+]
+
+[[package]]
+name = "logos-derive"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31"
+dependencies = [
+ "logos-codegen",
+]
+
[[package]]
name = "malloc_buf"
version = "0.0.6"
@@ -1715,6 +1984,12 @@ dependencies = [
"jni-sys 0.3.1",
]
+[[package]]
+name = "new_debug_unreachable"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -2144,6 +2419,25 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "petgraph"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"
+dependencies = [
+ "fixedbitset",
+ "indexmap",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
+dependencies = [
+ "siphasher",
+]
+
[[package]]
name = "pin-project"
version = "1.1.11"
@@ -2239,6 +2533,12 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "precomputed-hash"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+
[[package]]
name = "presser"
version = "0.3.1"
@@ -2354,6 +2654,18 @@ dependencies = [
"bitflags 2.11.0",
]
+[[package]]
+name = "regex"
+version = "1.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
[[package]]
name = "regex-automata"
version = "0.4.14"
@@ -2524,6 +2836,16 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "sha3"
+version = "0.10.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60"
+dependencies = [
+ "digest",
+ "keccak",
+]
+
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -2561,6 +2883,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+[[package]]
+name = "siphasher"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"
+
[[package]]
name = "skrifa"
version = "0.40.0"
@@ -2691,6 +3019,18 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+[[package]]
+name = "string_cache"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f"
+dependencies = [
+ "new_debug_unreachable",
+ "parking_lot",
+ "phf_shared",
+ "precomputed-hash",
+]
+
[[package]]
name = "strsim"
version = "0.11.1"
@@ -2719,6 +3059,15 @@ dependencies = [
"syn",
]
+[[package]]
+name = "term"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8c27177b12a6399ffc08b98f76f7c9a1f4fe9fc967c784c5a071fa8d93cf7e1"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "termcolor"
version = "1.4.1"
@@ -2993,6 +3342,12 @@ dependencies = [
"rustc-hash 2.1.1",
]
+[[package]]
+name = "typenum"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
+
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -3011,6 +3366,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
[[package]]
name = "url"
version = "2.5.8"
@@ -3094,9 +3455,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
-version = "0.2.116"
+version = "0.2.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7dc0882f7b5bb01ae8c5215a1230832694481c1a4be062fd410e12ea3da5b631"
+checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0"
dependencies = [
"cfg-if",
"once_cell",
@@ -3107,9 +3468,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
-version = "0.4.66"
+version = "0.4.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "19280959e2844181895ef62f065c63e0ca07ece4771b53d89bfdb967d97cbf05"
+checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -3117,9 +3478,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.116"
+version = "0.2.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "75973d3066e01d035dbedaad2864c398df42f8dd7b1ea057c35b8407c015b537"
+checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -3127,9 +3488,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.116"
+version = "0.2.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "91af5e4be765819e0bcfee7322c14374dc821e35e72fa663a830bbc7dc199eac"
+checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2"
dependencies = [
"bumpalo",
"proc-macro2",
@@ -3140,9 +3501,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.116"
+version = "0.2.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c9bf0406a78f02f336bf1e451799cca198e8acde4ffa278f0fb20487b150a633"
+checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b"
dependencies = [
"unicode-ident",
]
@@ -3284,9 +3645,9 @@ dependencies = [
[[package]]
name = "web-sys"
-version = "0.3.93"
+version = "0.3.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "749466a37ee189057f54748b200186b59a03417a117267baf3fd89cecc9fb837"
+checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -3324,6 +3685,35 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+[[package]]
+name = "wesl"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be113b462f90d3e303324739a4431bc63dfd0b463d7582cc76c1fd2093b5d470"
+dependencies = [
+ "annotate-snippets",
+ "derive_more",
+ "half",
+ "itertools",
+ "num-traits",
+ "thiserror 2.0.18",
+ "wesl-macros",
+ "wgsl-parse",
+ "wgsl-types",
+]
+
+[[package]]
+name = "wesl-macros"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d321ea9e1cc0a2e3de41c02e3a7586695a9c03beccb5460e938a7ccf00cb612"
+dependencies = [
+ "itertools",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "wgpu"
version = "28.0.0"
@@ -3484,6 +3874,34 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "wgsl-parse"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "946419efa46664a8070c512fb358ac4acfc6e6215c2396ae5afeb9b72dd6ca7d"
+dependencies = [
+ "annotate-snippets",
+ "derive_more",
+ "itertools",
+ "lalrpop",
+ "lalrpop-util",
+ "lexical",
+ "logos",
+ "thiserror 2.0.18",
+ "wgsl-types",
+]
+
+[[package]]
+name = "wgsl-types"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7aed068ca1dc8fb182f574c9f2ace45ec988c71ba050f6dd334883fe3b8a88e2"
+dependencies = [
+ "half",
+ "itertools",
+ "num-traits",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -3951,18 +4369,18 @@ dependencies = [
[[package]]
name = "zerocopy"
-version = "0.8.47"
+version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87"
+checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
-version = "0.8.47"
+version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89"
+checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
dependencies = [
"proc-macro2",
"quote",
diff --git a/crates/backend-wgpu/Cargo.toml b/crates/backend-wgpu/Cargo.toml
index 2dfdaa6..3f36cb8 100644
--- a/crates/backend-wgpu/Cargo.toml
+++ b/crates/backend-wgpu/Cargo.toml
@@ -7,3 +7,7 @@ edition = "2024"
wgpu = "28.0.0"
bytemuck = { version = "1.25.0", features = ["derive"] }
gecko = { path = "../gecko" }
+wesl = "0.3.2"
+
+[build-dependencies]
+wesl = "0.3.2"
diff --git a/crates/backend-wgpu/build.rs b/crates/backend-wgpu/build.rs
new file mode 100644
index 0000000..dc0fdea
--- /dev/null
+++ b/crates/backend-wgpu/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ wesl::Wesl::new("src/shaders").build_artifact(&"package::main".parse().unwrap(), "gx_shader");
+}
diff --git a/crates/backend-wgpu/src/gx.wgsl b/crates/backend-wgpu/src/gx.wgsl
deleted file mode 100644
index c77943f..0000000
--- a/crates/backend-wgpu/src/gx.wgsl
+++ /dev/null
@@ -1,363 +0,0 @@
-struct FrameUniforms {
- tev_color_reg0: vec4<f32>,
- tev_color_reg1: vec4<f32>,
- tev_color_reg2: vec4<f32>,
- tev_color_reg3: vec4<f32>,
- tev_konst_colors: array<vec4<f32>, 16>,
- tev_color_env: array<vec4<u32>, 4>,
- tev_alpha_env: array<vec4<u32>, 4>,
- tev_orders: array<vec4<u32>, 4>,
- num_tev_stages: u32,
- alpha_ref0: f32,
- alpha_ref1: f32,
- alpha_comp0: u32,
- alpha_comp1: u32,
- alpha_op: u32,
-};
-
-struct DrawUniforms {
- mvp: mat4x4<f32>,
-};
-
-@group(0) @binding(0)
-var<uniform> frame: FrameUniforms;
-
-@group(0) @binding(1)
-var<uniform> draw: DrawUniforms;
-
-// 8 texture maps (texmap 0-7)
-@group(0) @binding(2) var tex0: texture_2d<f32>;
-@group(0) @binding(3) var tex1: texture_2d<f32>;
-@group(0) @binding(4) var tex2: texture_2d<f32>;
-@group(0) @binding(5) var tex3: texture_2d<f32>;
-@group(0) @binding(6) var tex4: texture_2d<f32>;
-@group(0) @binding(7) var tex5: texture_2d<f32>;
-@group(0) @binding(8) var tex6: texture_2d<f32>;
-@group(0) @binding(9) var tex7: texture_2d<f32>;
-
-// 8 samplers (paired with texmaps)
-@group(0) @binding(10) var samp0: sampler;
-@group(0) @binding(11) var samp1: sampler;
-@group(0) @binding(12) var samp2: sampler;
-@group(0) @binding(13) var samp3: sampler;
-@group(0) @binding(14) var samp4: sampler;
-@group(0) @binding(15) var samp5: sampler;
-@group(0) @binding(16) var samp6: sampler;
-@group(0) @binding(17) var samp7: sampler;
-
-struct VsIn {
- @location(0) position: vec3<f32>,
- @location(1) color: vec4<f32>,
- @location(2) tex0: vec2<f32>,
- @location(3) tex1: vec2<f32>,
- @location(4) tex2: vec2<f32>,
- @location(5) tex3: vec2<f32>,
- @location(6) tex4: vec2<f32>,
- @location(7) tex5: vec2<f32>,
- @location(8) tex6: vec2<f32>,
- @location(9) tex7: vec2<f32>,
-};
-
-struct VsOut {
- @builtin(position) clip_pos: vec4<f32>,
- @location(0) color: vec4<f32>,
- @location(1) uv0: vec2<f32>,
- @location(2) uv1: vec2<f32>,
- @location(3) uv2: vec2<f32>,
- @location(4) uv3: vec2<f32>,
- @location(5) uv4: vec2<f32>,
- @location(6) uv5: vec2<f32>,
- @location(7) uv6: vec2<f32>,
- @location(8) uv7: vec2<f32>,
-};
-
-@vertex
-fn vs_main(in: VsIn) -> VsOut {
- var out: VsOut;
- out.clip_pos = draw.mvp * vec4<f32>(in.position, 1.0);
- // Remap depth: GameCube/OpenGL uses [-1,1], wgpu uses [0,1]
- out.clip_pos.z = out.clip_pos.z * 0.5 + out.clip_pos.w * 0.5;
- out.color = in.color;
- out.uv0 = in.tex0;
- out.uv1 = in.tex1;
- out.uv2 = in.tex2;
- out.uv3 = in.tex3;
- out.uv4 = in.tex4;
- out.uv5 = in.tex5;
- out.uv6 = in.tex6;
- out.uv7 = in.tex7;
- return out;
-}
-
-// Read a single u32 from a packed array<vec4<u32>, 4> by flat index (0-15)
-fn read_packed(arr: array<vec4<u32>, 4>, idx: u32) -> u32 {
- let vi = idx / 4u;
- let ci = idx % 4u;
- return arr[vi][ci];
-}
-
-// Extract `width` bits starting at bit `lo` from `val`
-fn extract_bits(val: u32, lo: u32, width: u32) -> u32 {
- return (val >> lo) & ((1u << width) - 1u);
-}
-
-// Select texcoord by index (from TevOrder.texcoord)
-fn select_texcoord(in: VsOut, idx: u32) -> vec2<f32> {
- switch idx {
- case 0u: { return in.uv0; }
- case 1u: { return in.uv1; }
- case 2u: { return in.uv2; }
- case 3u: { return in.uv3; }
- case 4u: { return in.uv4; }
- case 5u: { return in.uv5; }
- case 6u: { return in.uv6; }
- case 7u: { return in.uv7; }
- default: { return in.uv0; }
- }
-}
-
-// Sample from texmap by index (from TevOrder.texmap)
-fn sample_texmap(texmap: u32, uv: vec2<f32>) -> vec4<f32> {
- switch texmap {
- case 0u: { return textureSample(tex0, samp0, uv); }
- case 1u: { return textureSample(tex1, samp1, uv); }
- case 2u: { return textureSample(tex2, samp2, uv); }
- case 3u: { return textureSample(tex3, samp3, uv); }
- case 4u: { return textureSample(tex4, samp4, uv); }
- case 5u: { return textureSample(tex5, samp5, uv); }
- case 6u: { return textureSample(tex6, samp6, uv); }
- case 7u: { return textureSample(tex7, samp7, uv); }
- default: { return textureSample(tex0, samp0, uv); }
- }
-}
-
-// TEV color input selector (TevColorIn, 4-bit, 16 variants)
-fn tev_color_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>, konst_color: vec4<f32>) -> vec3<f32> {
- switch sel {
- case 0u: { return regs[0].rgb; } // PrevColor
- case 1u: { return vec3(regs[0].a); } // PrevAlpha
- case 2u: { return regs[1].rgb; } // Reg0Color
- case 3u: { return vec3(regs[1].a); } // Reg0Alpha
- case 4u: { return regs[2].rgb; } // Reg1Color
- case 5u: { return vec3(regs[2].a); } // Reg1Alpha
- case 6u: { return regs[3].rgb; } // Reg2Color
- case 7u: { return vec3(regs[3].a); } // Reg2Alpha
- case 8u: { return tex_color.rgb; } // TexColor
- case 9u: { return vec3(tex_color.a); } // TexAlpha
- case 10u: { return ras_color.rgb; } // RasColor
- case 11u: { return vec3(ras_color.a); } // RasAlpha
- case 12u: { return vec3(1.0); } // One
- case 13u: { return vec3(0.5); } // Half
- case 14u: { return konst_color.rgb; } // Konst
- case 15u: { return vec3(0.0); } // Zero
- default: { return vec3(0.0); }
- }
-}
-
-// TEV alpha input selector (TevAlphaIn, 3-bit, 8 variants)
-fn tev_alpha_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>, konst_color: vec4<f32>) -> f32 {
- switch sel {
- case 0u: { return regs[0].a; } // PrevAlpha
- case 1u: { return regs[1].a; } // Reg0Alpha
- case 2u: { return regs[2].a; } // Reg1Alpha
- case 3u: { return regs[3].a; } // Reg2Alpha
- case 4u: { return tex_color.a; } // TexAlpha
- case 5u: { return ras_color.a; } // RasAlpha
- case 6u: { return konst_color.a; } // Konst
- case 7u: { return 0.0; } // Zero
- default: { return 0.0; }
- }
-}
-
-// TEV color combiner: result = (d (+/-) ((1-c)*a + c*b) + bias) * scale
-fn tev_combine_color(a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, d: vec3<f32>,
- bias: u32, sub: bool, scale: u32, do_clamp: bool) -> vec3<f32> {
- let lerp = a * (vec3(1.0) - c) + b * c;
-
- var result: vec3<f32>;
- if sub {
- result = d - lerp;
- } else {
- result = d + lerp;
- }
-
- // Bias
- switch bias {
- case 1u: { result += vec3(0.5); } // AddHalf
- case 2u: { result -= vec3(0.5); } // SubHalf
- default: {} // Zero
- }
-
- // Scale
- switch scale {
- case 1u: { result *= 2.0; } // Scale2
- case 2u: { result *= 4.0; } // Scale4
- case 3u: { result *= 0.5; } // Divide2
- default: {} // Scale1
- }
-
- if do_clamp {
- result = clamp(result, vec3(0.0), vec3(1.0));
- }
-
- return result;
-}
-
-// TEV alpha combiner: same formula as color but per-channel
-fn tev_combine_alpha(a: f32, b: f32, c: f32, d: f32, bias: u32, sub: bool, scale: u32, do_clamp: bool) -> f32 {
- let lerp = a * (1.0 - c) + b * c;
-
- var result: f32;
- if sub {
- result = d - lerp;
- } else {
- result = d + lerp;
- }
-
- switch bias {
- case 1u: { result += 0.5; }
- case 2u: { result -= 0.5; }
- default: {}
- }
-
- switch scale {
- case 1u: { result *= 2.0; }
- case 2u: { result *= 4.0; }
- case 3u: { result *= 0.5; }
- default: {}
- }
-
- if do_clamp {
- result = clamp(result, 0.0, 1.0);
- }
-
- return result;
-}
-
-fn alpha_compare(a: f32, ref_val: f32, func: u32) -> bool {
- switch func {
- case 0u: { return false; } // Never
- case 1u: { return a < ref_val; } // Less
- case 2u: { return a == ref_val; } // Equal
- case 3u: { return a <= ref_val; } // LessEqual
- case 4u: { return a > ref_val; } // Greater
- case 5u: { return a != ref_val; } // NotEqual
- case 6u: { return a >= ref_val; } // GreaterEqual
- case 7u: { return true; } // Always
- default: { return true; }
- }
-}
-
-fn alpha_combine(a: bool, b: bool, op: u32) -> bool {
- switch op {
- case 0u: { return a && b; } // AND
- case 1u: { return a || b; } // OR
- case 2u: { return a != b; } // XOR
- case 3u: { return a == b; } // XNOR
- default: { return true; }
- }
-}
-
-@fragment
-fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- // Initialize TEV registers from uniforms
- var regs: array<vec4<f32>, 4>;
- regs[0] = frame.tev_color_reg0;
- regs[1] = frame.tev_color_reg1;
- regs[2] = frame.tev_color_reg2;
- regs[3] = frame.tev_color_reg3;
-
- let ras_color = in.color;
- let num_stages = frame.num_tev_stages;
-
- var last_color_dest = 0u;
- var last_alpha_dest = 0u;
-
- for (var stage = 0u; stage < 16u; stage++) {
- if stage >= num_stages {
- break;
- }
-
- // Resolve per-stage texture from TevOrder
- // TevStageOrder bit layout: texmap(0-2), texcoord(3-5), tex_enable(6)
- let order = read_packed(frame.tev_orders, stage);
- let texmap_idx = order & 7u;
- let texcoord_idx = (order >> 3u) & 7u;
- let tex_enabled = ((order >> 6u) & 1u) != 0u;
-
- var tex_color: vec4<f32>;
- if tex_enabled {
- let uv = select_texcoord(in, texcoord_idx);
- tex_color = sample_texmap(texmap_idx, uv);
- } else {
- tex_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
- }
-
- // Combine colors
- let cenv = read_packed(frame.tev_color_env, stage);
-
- // TevColorEnv bit layout (LSB0):
- // [3:0]=d [7:4]=c [11:8]=b [15:12]=a
- // [17:16]=bias [18]=sub [19]=clamp [21:20]=scale [23:22]=dest
- let c_d = extract_bits(cenv, 0u, 4u);
- let c_c = extract_bits(cenv, 4u, 4u);
- let c_b = extract_bits(cenv, 8u, 4u);
- let c_a = extract_bits(cenv, 12u, 4u);
- let c_bias = extract_bits(cenv, 16u, 2u);
- let c_sub = extract_bits(cenv, 18u, 1u) != 0u;
- let c_clamp = extract_bits(cenv, 19u, 1u) != 0u;
- let c_scale = extract_bits(cenv, 20u, 2u);
- let c_dest = extract_bits(cenv, 22u, 2u);
-
- let konst_color = frame.tev_konst_colors[stage];
-
- let in_a = tev_color_in(c_a, tex_color, ras_color, regs, konst_color);
- let in_b = tev_color_in(c_b, tex_color, ras_color, regs, konst_color);
- let in_c = tev_color_in(c_c, tex_color, ras_color, regs, konst_color);
- let in_d = tev_color_in(c_d, tex_color, ras_color, regs, konst_color);
-
- let color_result = tev_combine_color(in_a, in_b, in_c, in_d, c_bias, c_sub, c_scale, c_clamp);
- // Write RGB to dest, preserve alpha
- regs[c_dest] = vec4(color_result, regs[c_dest].a);
-
- // Combine alpha
- let aenv = read_packed(frame.tev_alpha_env, stage);
-
- // TevAlphaEnv bit layout (LSB0):
- // [6:4]=d [9:7]=c [12:10]=b [15:13]=a
- // [17:16]=bias [18]=sub [19]=clamp [21:20]=scale [23:22]=dest
- let a_d = extract_bits(aenv, 4u, 3u);
- let a_c = extract_bits(aenv, 7u, 3u);
- let a_b = extract_bits(aenv, 10u, 3u);
- let a_a = extract_bits(aenv, 13u, 3u);
- let a_bias = extract_bits(aenv, 16u, 2u);
- let a_sub = extract_bits(aenv, 18u, 1u) != 0u;
- let a_clamp = extract_bits(aenv, 19u, 1u) != 0u;
- let a_scale = extract_bits(aenv, 20u, 2u);
- let a_dest = extract_bits(aenv, 22u, 2u);
-
- let ain_a = tev_alpha_in(a_a, tex_color, ras_color, regs, konst_color);
- let ain_b = tev_alpha_in(a_b, tex_color, ras_color, regs, konst_color);
- let ain_c = tev_alpha_in(a_c, tex_color, ras_color, regs, konst_color);
- let ain_d = tev_alpha_in(a_d, tex_color, ras_color, regs, konst_color);
-
- let alpha_result = tev_combine_alpha(ain_a, ain_b, ain_c, ain_d, a_bias, a_sub, a_scale, a_clamp);
-
- // Write alpha to dest, preserve RGB
- regs[a_dest] = vec4(regs[a_dest].rgb, alpha_result);
-
- last_color_dest = c_dest;
- last_alpha_dest = a_dest;
- }
-
- // Output from the dest registers of the last active TEV stage (not always TEVPREV)
- let color = vec4<f32>(regs[last_color_dest].rgb, regs[last_alpha_dest].a);
-
- let c0 = alpha_compare(color.a, frame.alpha_ref0, frame.alpha_comp0);
- let c1 = alpha_compare(color.a, frame.alpha_ref1, frame.alpha_comp1);
- if !alpha_combine(c0, c1, frame.alpha_op) {
- discard;
- }
-
- return color;
-}
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 8212c39..f7abb65 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -1,46 +1,18 @@
mod helpers;
+mod pipeline;
+mod render;
pub mod texture;
+mod triangulate;
-use gecko::flipper::gx::draw::{DrawCall, DrawCommands, Primitive, TextureFormat};
-use gecko::flipper::gx::regs::{BlendFactor, CompareFunc, MagFilter, MinFilter, WrapMode};
+use gecko::flipper::gx::draw::TextureFormat;
+use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
+use pipeline::PipelineKey;
use std::collections::HashMap;
+use triangulate::{GpuVertex, align_up};
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
-struct GpuVertex {
- position: [f32; 3],
- color: [f32; 4],
- tex0: [f32; 2],
- tex1: [f32; 2],
- tex2: [f32; 2],
- tex3: [f32; 2],
- tex4: [f32; 2],
- tex5: [f32; 2],
- tex6: [f32; 2],
- tex7: [f32; 2],
-}
-
-impl From<&gecko::flipper::gx::draw::Vertex> for GpuVertex {
- fn from(v: &gecko::flipper::gx::draw::Vertex) -> Self {
- let tc = |i: usize| v.texcoords[i].unwrap_or([0.0, 0.0]);
- Self {
- position: v.position,
- color: v.color0,
- tex0: tc(0),
- tex1: tc(1),
- tex2: tc(2),
- tex3: tc(3),
- tex4: tc(4),
- tex5: tc(5),
- tex6: tc(6),
- tex7: tc(7),
- }
- }
-}
-
-#[repr(C)]
-#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
-struct FrameUniforms {
+pub(crate) struct FrameUniforms {
tev_color_regs: [[f32; 4]; 4],
tev_konst_colors: [[f32; 4]; 16],
tev_color_env: [u32; 16],
@@ -57,67 +29,34 @@ struct FrameUniforms {
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
-struct DrawUniforms {
+pub(crate) struct DrawUniforms {
mvp: [[f32; 4]; 4],
}
-const SHADER: &str = include_str!("gx.wgsl");
-
-#[derive(Clone, Copy, Hash, PartialEq, Eq)]
-struct PipelineKey {
- blend_enable: bool,
- src_factor: BlendFactor,
- dst_factor: BlendFactor,
- subtract: bool,
- z_enable: bool,
- z_func: CompareFunc,
- z_write: bool,
-}
-
-impl PipelineKey {
- fn from_draw_call(dc: &DrawCall) -> Self {
- let blend = dc.bp_blend_mode;
- let zmode = dc.bp_zmode;
- PipelineKey {
- blend_enable: blend.blend_enable(),
- src_factor: blend.src_factor(),
- dst_factor: blend.dst_factor(),
- subtract: blend.subtract(),
- z_enable: zmode.enable(),
- z_func: zmode.func(),
- z_write: zmode.update_enable(),
- }
- }
-}
+const SHADER: &str = wesl::include_wesl!("gx_shader");
pub struct GxRenderer {
- pipeline_cache: HashMap<PipelineKey, wgpu::RenderPipeline>,
- shader: wgpu::ShaderModule,
- pipeline_layout: wgpu::PipelineLayout,
- surface_format: wgpu::TextureFormat,
- bind_group_layout: wgpu::BindGroupLayout,
- #[allow(dead_code)]
- bind_group: wgpu::BindGroup,
- frame_uniform_buffer: wgpu::Buffer,
- draw_uniform_buffer: wgpu::Buffer,
- draw_uniform_stride: u64,
- draw_uniform_capacity: usize,
- vertex_buffer: wgpu::Buffer,
- vertex_capacity: usize,
- depth_texture: wgpu::Texture,
- depth_view: wgpu::TextureView,
- depth_width: u32,
- depth_height: u32,
- /// Cache: (wrap_s, wrap_t, mag_filter, min_filter) -> wgpu Sampler
- sampler_cache: HashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,
- /// Cache: (ram_addr, width, height, format) -> (wgpu Texture, TextureView)
- texture_cache: HashMap<(usize, u32, u32, TextureFormat), (wgpu::Texture, wgpu::TextureView)>,
- /// Fallback 1x1 white texture view used when no texture is bound
- fallback_view: wgpu::TextureView,
- // Scratch buffers reused across frames to avoid per-frame allocations
- scratch_vertices: Vec<GpuVertex>,
- scratch_draws: Vec<(u32, u32)>,
- scratch_uniform_bytes: Vec<u8>,
+ pub(crate) pipeline_cache: HashMap<PipelineKey, wgpu::RenderPipeline>,
+ pub(crate) shader: wgpu::ShaderModule,
+ pub(crate) pipeline_layout: wgpu::PipelineLayout,
+ pub(crate) surface_format: wgpu::TextureFormat,
+ pub(crate) bind_group_layout: wgpu::BindGroupLayout,
+ pub(crate) frame_uniform_buffer: wgpu::Buffer,
+ pub(crate) draw_uniform_buffer: wgpu::Buffer,
+ pub(crate) draw_uniform_stride: u64,
+ pub(crate) draw_uniform_capacity: usize,
+ pub(crate) vertex_buffer: wgpu::Buffer,
+ pub(crate) vertex_capacity: usize,
+ pub(crate) depth_texture: wgpu::Texture,
+ pub(crate) depth_view: wgpu::TextureView,
+ pub(crate) depth_width: u32,
+ pub(crate) depth_height: u32,
+ pub(crate) sampler_cache: HashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,
+ pub(crate) texture_cache: HashMap<(usize, u32, u32, TextureFormat), (wgpu::Texture, wgpu::TextureView)>,
+ pub(crate) fallback_view: wgpu::TextureView,
+ pub(crate) scratch_vertices: Vec<GpuVertex>,
+ pub(crate) scratch_draws: Vec<(u32, u32)>,
+ pub(crate) scratch_uniform_bytes: Vec<u8>,
}
impl GxRenderer {
@@ -248,42 +187,6 @@ impl GxRenderer {
);
let fallback_view = fallback_texture.create_view(&Default::default());
- let mut initial_entries = vec![
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &frame_uniform_buffer,
- offset: 0,
- size: wgpu::BufferSize::new(frame_uniform_size),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &draw_uniform_buffer,
- offset: 0,
- size: wgpu::BufferSize::new(draw_uniform_size),
- }),
- },
- ];
- for i in 0..8u32 {
- initial_entries.push(wgpu::BindGroupEntry {
- binding: 2 + i,
- resource: wgpu::BindingResource::TextureView(&fallback_view),
- });
- }
- for i in 0..8u32 {
- initial_entries.push(wgpu::BindGroupEntry {
- binding: 10 + i,
- resource: wgpu::BindingResource::Sampler(&sampler),
- });
- }
- let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &bind_group_layout,
- entries: &initial_entries,
- });
-
let initial_capacity = 1024;
let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("gx_vertices"),
@@ -302,7 +205,6 @@ impl GxRenderer {
pipeline_layout,
surface_format,
bind_group_layout,
- bind_group,
frame_uniform_buffer,
draw_uniform_buffer,
draw_uniform_stride,
@@ -329,7 +231,7 @@ impl GxRenderer {
self.ensure_depth_texture(device, width, height);
}
- fn ensure_depth_texture(&mut self, device: &wgpu::Device, width: u32, height: u32) {
+ pub(crate) fn ensure_depth_texture(&mut self, device: &wgpu::Device, width: u32, height: u32) {
let width = width.max(1);
let height = height.max(1);
if (width, height) == (self.depth_width, self.depth_height) {
@@ -341,353 +243,6 @@ impl GxRenderer {
self.depth_width = width;
self.depth_height = height;
}
-
- fn create_pipeline(&self, device: &wgpu::Device, key: &PipelineKey) -> wgpu::RenderPipeline {
- let vertex_layout = wgpu::VertexBufferLayout {
- array_stride: std::mem::size_of::<GpuVertex>() as u64,
- step_mode: wgpu::VertexStepMode::Vertex,
- attributes: &[
- // position: vec3<f32>
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 0,
- shader_location: 0,
- },
- // color: vec4<f32>
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x4,
- offset: 12,
- shader_location: 1,
- },
- // tex0-tex7: vec2<f32> each
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 28, shader_location: 2 },
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 36, shader_location: 3 },
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 44, shader_location: 4 },
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 52, shader_location: 5 },
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 60, shader_location: 6 },
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 68, shader_location: 7 },
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 76, shader_location: 8 },
- wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 84, shader_location: 9 },
- ],
- };
-
- let blend = if key.blend_enable {
- let operation = if key.subtract {
- wgpu::BlendOperation::ReverseSubtract
- } else {
- wgpu::BlendOperation::Add
- };
- Some(wgpu::BlendState {
- color: wgpu::BlendComponent {
- src_factor: helpers::map_blend_factor(key.src_factor),
- dst_factor: helpers::map_blend_factor(key.dst_factor),
- operation,
- },
- alpha: wgpu::BlendComponent {
- src_factor: helpers::map_blend_factor(key.src_factor),
- dst_factor: helpers::map_blend_factor(key.dst_factor),
- operation,
- },
- })
- } else {
- None
- };
-
- let depth_stencil = if key.z_enable {
- Some(wgpu::DepthStencilState {
- format: wgpu::TextureFormat::Depth24Plus,
- depth_write_enabled: key.z_write,
- depth_compare: helpers::map_compare_func(key.z_func),
- stencil: wgpu::StencilState::default(),
- bias: wgpu::DepthBiasState::default(),
- })
- } else {
- Some(wgpu::DepthStencilState {
- format: wgpu::TextureFormat::Depth24Plus,
- depth_write_enabled: false,
- depth_compare: wgpu::CompareFunction::Always,
- stencil: wgpu::StencilState::default(),
- bias: wgpu::DepthBiasState::default(),
- })
- };
-
- device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: Some("gx_pipeline"),
- layout: Some(&self.pipeline_layout),
- vertex: wgpu::VertexState {
- module: &self.shader,
- entry_point: Some("vs_main"),
- buffers: &[vertex_layout],
- compilation_options: Default::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &self.shader,
- entry_point: Some("fs_main"),
- targets: &[Some(wgpu::ColorTargetState {
- format: self.surface_format,
- blend,
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: Default::default(),
- }),
- primitive: wgpu::PrimitiveState {
- topology: wgpu::PrimitiveTopology::TriangleList,
- front_face: wgpu::FrontFace::Cw,
- cull_mode: None,
- ..Default::default()
- },
- depth_stencil,
- multisample: wgpu::MultisampleState::default(),
- multiview_mask: None,
- cache: None,
- })
- }
-
- pub fn render(
- &mut self,
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- commands: &DrawCommands,
- ram: &[u8],
- target: &wgpu::TextureView,
- target_width: u32,
- target_height: u32,
- ) {
- self.ensure_depth_texture(device, target_width, target_height);
-
- if commands.commands.is_empty() {
- return;
- }
-
- // Ensure all referenced textures are uploaded and pipelines/samplers created
- for dc in &commands.commands {
- for desc in dc.textures.iter().flatten() {
- let key = (desc.ram_addr, desc.width, desc.height, desc.format);
- if !self.texture_cache.contains_key(&key) {
- let (tex, view) = texture::upload_texture(device, queue, ram, desc);
- self.texture_cache.insert(key, (tex, view));
- }
- let sampler_key = (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);
- if !self.sampler_cache.contains_key(&sampler_key) {
- let s = device.create_sampler(&wgpu::SamplerDescriptor {
- label: Some("gx_sampler"),
- address_mode_u: helpers::map_wrap_mode(sampler_key.0),
- address_mode_v: helpers::map_wrap_mode(sampler_key.1),
- mag_filter: helpers::map_mag_filter(sampler_key.2),
- min_filter: helpers::map_min_filter(sampler_key.3),
- ..Default::default()
- });
- self.sampler_cache.insert(sampler_key, s);
- }
- }
- let pipeline_key = PipelineKey::from_draw_call(dc);
- if !self.pipeline_cache.contains_key(&pipeline_key) {
- let pipeline = self.create_pipeline(device, &pipeline_key);
- self.pipeline_cache.insert(pipeline_key, pipeline);
- }
- }
-
- // Ensure fallback sampler exists
- let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
- if !self.sampler_cache.contains_key(&fallback_sampler_key) {
- let s = device.create_sampler(&wgpu::SamplerDescriptor {
- label: Some("gx_sampler_fallback"),
- ..Default::default()
- });
- self.sampler_cache.insert(fallback_sampler_key, s);
- }
-
- self.scratch_vertices.clear();
- self.scratch_draws.clear();
- self.scratch_uniform_bytes.clear();
-
- let draw_stride = self.draw_uniform_stride as usize;
- let draw_size = std::mem::size_of::<DrawUniforms>();
- let frame_stride = align_up(
- std::mem::size_of::<FrameUniforms>() as u64,
- device.limits().min_uniform_buffer_offset_alignment as u64,
- ) as usize;
- let frame_size = std::mem::size_of::<FrameUniforms>();
- let mut frame_uniform_bytes: Vec<u8> = Vec::new();
- let mut draw_call_indices: Vec<usize> = Vec::new();
-
- for (dc_idx, dc) in commands.commands.iter().enumerate() {
- let prev_len = self.scratch_vertices.len();
- triangulate_into(dc, &mut self.scratch_vertices);
- let added = self.scratch_vertices.len() - prev_len;
- if added == 0 {
- continue;
- }
-
-
-
- let mvp = commands.projection * dc.modelview;
- let draw_uniform = DrawUniforms { mvp: mvp.0 };
- let start = self.scratch_draws.len() * draw_stride;
- self.scratch_uniform_bytes.resize(start + draw_stride, 0);
- self.scratch_uniform_bytes[start..start + draw_size].copy_from_slice(bytemuck::bytes_of(&draw_uniform));
-
- let alpha_cmp = dc.bp_alpha_compare;
- let frame_uniform = FrameUniforms {
- tev_color_regs: dc.tev_color_regs,
- tev_konst_colors: dc.tev_konst_colors,
- tev_color_env: dc.tev_color_env.map(|e| e.raw()),
- tev_alpha_env: dc.tev_alpha_env.map(|e| e.raw()),
- tev_orders: dc.tev_orders.map(|o| o.raw()),
- num_tev_stages: dc.num_tev_stages as u32,
- alpha_ref0: alpha_cmp.ref0() as f32 / 255.0,
- alpha_ref1: alpha_cmp.ref1() as f32 / 255.0,
- alpha_comp0: alpha_cmp.comp0() as u32,
- alpha_comp1: alpha_cmp.comp1() as u32,
- alpha_op: alpha_cmp.op() as u32,
- _padding: [0; 2],
- };
- let fstart = self.scratch_draws.len() * frame_stride;
- frame_uniform_bytes.resize(fstart + frame_stride, 0);
- frame_uniform_bytes[fstart..fstart + frame_size].copy_from_slice(bytemuck::bytes_of(&frame_uniform));
-
- self.scratch_draws.push((prev_len as u32, added as u32));
- draw_call_indices.push(dc_idx);
- }
-
- if self.scratch_draws.is_empty() {
- return;
- }
-
- let num_draws = self.scratch_draws.len();
- self.ensure_draw_capacity(device, num_draws);
-
- if self.scratch_vertices.len() > self.vertex_capacity {
- self.vertex_capacity = self.scratch_vertices.len().next_power_of_two();
- self.vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_vertices"),
- size: (self.vertex_capacity * std::mem::size_of::<GpuVertex>()) as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- }
-
- let needed_frame_size = (num_draws * frame_stride) as u64;
- if needed_frame_size > self.frame_uniform_buffer.size() {
- self.frame_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_frame_uniforms"),
- size: needed_frame_size,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- }
-
- queue.write_buffer(&self.frame_uniform_buffer, 0, &frame_uniform_bytes);
- queue.write_buffer(&self.draw_uniform_buffer, 0, &self.scratch_uniform_bytes);
- queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.scratch_vertices));
-
- let mut encoder = device.create_command_encoder(&Default::default());
- {
- let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("gx_render_pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: target,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
- store: wgpu::StoreOp::Store,
- },
- depth_slice: None,
- })],
- depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
- view: &self.depth_view,
- depth_ops: Some(wgpu::Operations {
- load: wgpu::LoadOp::Clear(1.0),
- store: wgpu::StoreOp::Store,
- }),
- stencil_ops: None,
- }),
- occlusion_query_set: None,
- timestamp_writes: None,
- multiview_mask: None,
- });
- rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
-
- for (index, (first_vertex, vertex_count)) in self.scratch_draws.iter().copied().enumerate() {
- let dc = &commands.commands[draw_call_indices[index]];
- let pipeline_key = PipelineKey::from_draw_call(dc);
- let pipeline = &self.pipeline_cache[&pipeline_key];
- rpass.set_pipeline(pipeline);
-
- // Resolve all 8 texture views + samplers for this draw call
- let mut tex_views: [&wgpu::TextureView; 8] = [&self.fallback_view; 8];
- let mut tex_samplers: [&wgpu::Sampler; 8] =
- [&self.sampler_cache[&fallback_sampler_key]; 8];
- for slot in 0..8 {
- if let Some(desc) = &dc.textures[slot] {
- let tex_key = (desc.ram_addr, desc.width, desc.height, desc.format);
- let sampler_key =
- (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);
- tex_views[slot] = &self.texture_cache[&tex_key].1;
- tex_samplers[slot] = &self.sampler_cache[&sampler_key];
- }
- }
-
- let frame_offset = (index as u64 * frame_stride as u64) as wgpu::BufferAddress;
- let draw_offset = (index as u64 * self.draw_uniform_stride) as u32;
-
- let mut entries = vec![
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.frame_uniform_buffer,
- offset: frame_offset,
- size: wgpu::BufferSize::new(std::mem::size_of::<FrameUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.draw_uniform_buffer,
- offset: 0,
- size: wgpu::BufferSize::new(std::mem::size_of::<DrawUniforms>() as u64),
- }),
- },
- ];
- for i in 0..8u32 {
- entries.push(wgpu::BindGroupEntry {
- binding: 2 + i,
- resource: wgpu::BindingResource::TextureView(tex_views[i as usize]),
- });
- }
- for i in 0..8u32 {
- entries.push(wgpu::BindGroupEntry {
- binding: 10 + i,
- resource: wgpu::BindingResource::Sampler(tex_samplers[i as usize]),
- });
- }
- let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &self.bind_group_layout,
- entries: &entries,
- });
-
- rpass.set_bind_group(0, &bind_group, &[draw_offset]);
- rpass.draw(first_vertex..first_vertex + vertex_count, 0..1);
- }
- }
-
- queue.submit([encoder.finish()]);
- }
-
- fn ensure_draw_capacity(&mut self, device: &wgpu::Device, count: usize) {
- if count <= self.draw_uniform_capacity {
- return;
- }
-
- self.draw_uniform_capacity = count.next_power_of_two();
- self.draw_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_draw_uniforms"),
- size: self.draw_uniform_stride * self.draw_uniform_capacity as u64,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- }
}
fn create_depth_texture(device: &wgpu::Device, w: u32, h: u32) -> (wgpu::Texture, wgpu::TextureView) {
@@ -708,49 +263,3 @@ fn create_depth_texture(device: &wgpu::Device, w: u32, h: u32) -> (wgpu::Texture
let view = tex.create_view(&Default::default());
(tex, view)
}
-
-fn triangulate_into(dc: &DrawCall, out: &mut Vec<GpuVertex>) {
- match dc.primitive {
- Primitive::Triangles => {
- out.extend(dc.vertices.iter().map(GpuVertex::from));
- }
- Primitive::Quads => {
- for quad in dc.vertices.chunks(4) {
- if quad.len() < 4 {
- continue;
- }
- out.push((&quad[0]).into());
- out.push((&quad[1]).into());
- out.push((&quad[2]).into());
- out.push((&quad[0]).into());
- out.push((&quad[2]).into());
- out.push((&quad[3]).into());
- }
- }
- Primitive::TriangleStrip => {
- for i in 2..dc.vertices.len() {
- if i % 2 == 0 {
- out.push((&dc.vertices[i - 2]).into());
- out.push((&dc.vertices[i - 1]).into());
- out.push((&dc.vertices[i]).into());
- } else {
- out.push((&dc.vertices[i - 1]).into());
- out.push((&dc.vertices[i - 2]).into());
- out.push((&dc.vertices[i]).into());
- }
- }
- }
- Primitive::TriangleFan => {
- for i in 2..dc.vertices.len() {
- out.push((&dc.vertices[0]).into());
- out.push((&dc.vertices[i - 1]).into());
- out.push((&dc.vertices[i]).into());
- }
- }
- _ => unimplemented!("triangulation for {:?}", dc.primitive),
- }
-}
-
-fn align_up(value: u64, alignment: u64) -> u64 {
- (value + alignment - 1) & !(alignment - 1)
-}
diff --git a/crates/backend-wgpu/src/pipeline.rs b/crates/backend-wgpu/src/pipeline.rs
new file mode 100644
index 0000000..eb099e9
--- /dev/null
+++ b/crates/backend-wgpu/src/pipeline.rs
@@ -0,0 +1,165 @@
+use crate::{GxRenderer, helpers, triangulate::GpuVertex};
+use gecko::flipper::gx::draw::DrawCall;
+use gecko::flipper::gx::regs::{BlendFactor, CompareFunc};
+
+#[derive(Clone, Copy, Hash, PartialEq, Eq)]
+pub(crate) struct PipelineKey {
+ pub blend_enable: bool,
+ pub src_factor: BlendFactor,
+ pub dst_factor: BlendFactor,
+ pub subtract: bool,
+ pub z_enable: bool,
+ pub z_func: CompareFunc,
+ pub z_write: bool,
+}
+
+impl PipelineKey {
+ pub fn from_draw_call(dc: &DrawCall) -> Self {
+ let blend = dc.bp_blend_mode;
+ let zmode = dc.bp_zmode;
+ PipelineKey {
+ blend_enable: blend.blend_enable(),
+ src_factor: blend.src_factor(),
+ dst_factor: blend.dst_factor(),
+ subtract: blend.subtract(),
+ z_enable: zmode.enable(),
+ z_func: zmode.func(),
+ z_write: zmode.update_enable(),
+ }
+ }
+}
+
+impl GxRenderer {
+ pub(crate) fn create_pipeline(&self, device: &wgpu::Device, key: &PipelineKey) -> wgpu::RenderPipeline {
+ let vertex_layout = wgpu::VertexBufferLayout {
+ array_stride: std::mem::size_of::<GpuVertex>() as u64,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &[
+ // position: vec3<f32>
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x3,
+ offset: 0,
+ shader_location: 0,
+ },
+ // color: vec4<f32>
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x4,
+ offset: 12,
+ shader_location: 1,
+ },
+ // tex0-tex7: vec2<f32> each
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 28,
+ shader_location: 2,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 36,
+ shader_location: 3,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 44,
+ shader_location: 4,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 52,
+ shader_location: 5,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 60,
+ shader_location: 6,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 68,
+ shader_location: 7,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 76,
+ shader_location: 8,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 84,
+ shader_location: 9,
+ },
+ ],
+ };
+
+ let blend = if key.blend_enable {
+ let operation = if key.subtract {
+ wgpu::BlendOperation::ReverseSubtract
+ } else {
+ wgpu::BlendOperation::Add
+ };
+ Some(wgpu::BlendState {
+ color: wgpu::BlendComponent {
+ src_factor: helpers::map_blend_factor(key.src_factor),
+ dst_factor: helpers::map_blend_factor(key.dst_factor),
+ operation,
+ },
+ alpha: wgpu::BlendComponent {
+ src_factor: helpers::map_blend_factor(key.src_factor),
+ dst_factor: helpers::map_blend_factor(key.dst_factor),
+ operation,
+ },
+ })
+ } else {
+ None
+ };
+
+ let depth_stencil = if key.z_enable {
+ Some(wgpu::DepthStencilState {
+ format: wgpu::TextureFormat::Depth24Plus,
+ depth_write_enabled: key.z_write,
+ depth_compare: helpers::map_compare_func(key.z_func),
+ stencil: wgpu::StencilState::default(),
+ bias: wgpu::DepthBiasState::default(),
+ })
+ } else {
+ Some(wgpu::DepthStencilState {
+ format: wgpu::TextureFormat::Depth24Plus,
+ depth_write_enabled: false,
+ depth_compare: wgpu::CompareFunction::Always,
+ stencil: wgpu::StencilState::default(),
+ bias: wgpu::DepthBiasState::default(),
+ })
+ };
+
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("gx_pipeline"),
+ layout: Some(&self.pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &self.shader,
+ entry_point: Some("vs_main"),
+ buffers: &[vertex_layout],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &self.shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: self.surface_format,
+ blend,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ front_face: wgpu::FrontFace::Cw,
+ cull_mode: None,
+ ..Default::default()
+ },
+ depth_stencil,
+ multisample: wgpu::MultisampleState::default(),
+ multiview_mask: None,
+ cache: None,
+ })
+ }
+}
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
new file mode 100644
index 0000000..41adfbf
--- /dev/null
+++ b/crates/backend-wgpu/src/render.rs
@@ -0,0 +1,285 @@
+use crate::{
+ DrawUniforms, FrameUniforms, GxRenderer, helpers,
+ pipeline::PipelineKey,
+ texture,
+ triangulate::{self, GpuVertex, align_up},
+};
+use gecko::flipper::gx::draw::DrawCommands;
+use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
+
+impl GxRenderer {
+ pub fn render(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ commands: &DrawCommands,
+ ram: &[u8],
+ target: &wgpu::TextureView,
+ target_width: u32,
+ target_height: u32,
+ ) {
+ self.ensure_depth_texture(device, target_width, target_height);
+
+ if commands.commands.is_empty() {
+ return;
+ }
+
+ self.prepare_resources(device, queue, commands, ram);
+
+ let (frame_uniform_bytes, draw_call_indices) = self.aggregate_draw_data(device, commands);
+
+ if self.scratch_draws.is_empty() {
+ return;
+ }
+
+ self.upload_buffers(device, queue, &frame_uniform_bytes);
+ self.execute_render_pass(device, queue, commands, target, &draw_call_indices);
+ }
+
+ fn prepare_resources(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, commands: &DrawCommands, ram: &[u8]) {
+ for dc in &commands.commands {
+ for desc in dc.textures.iter().flatten() {
+ let key = (desc.ram_addr, desc.width, desc.height, desc.format);
+ if !self.texture_cache.contains_key(&key) {
+ let (tex, view) = texture::upload_texture(device, queue, ram, desc);
+ self.texture_cache.insert(key, (tex, view));
+ }
+ let sampler_key = (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);
+ if !self.sampler_cache.contains_key(&sampler_key) {
+ let s = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("gx_sampler"),
+ address_mode_u: helpers::map_wrap_mode(sampler_key.0),
+ address_mode_v: helpers::map_wrap_mode(sampler_key.1),
+ mag_filter: helpers::map_mag_filter(sampler_key.2),
+ min_filter: helpers::map_min_filter(sampler_key.3),
+ ..Default::default()
+ });
+ self.sampler_cache.insert(sampler_key, s);
+ }
+ }
+ let pipeline_key = PipelineKey::from_draw_call(dc);
+ if !self.pipeline_cache.contains_key(&pipeline_key) {
+ let pipeline = self.create_pipeline(device, &pipeline_key);
+ self.pipeline_cache.insert(pipeline_key, pipeline);
+ }
+ }
+
+ // Ensure fallback sampler exists
+ let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
+ if !self.sampler_cache.contains_key(&fallback_sampler_key) {
+ let s = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("gx_sampler_fallback"),
+ ..Default::default()
+ });
+ self.sampler_cache.insert(fallback_sampler_key, s);
+ }
+ }
+
+ fn aggregate_draw_data(&mut self, device: &wgpu::Device, commands: &DrawCommands) -> (Vec<u8>, Vec<usize>) {
+ self.scratch_vertices.clear();
+ self.scratch_draws.clear();
+ self.scratch_uniform_bytes.clear();
+
+ let draw_stride = self.draw_uniform_stride as usize;
+ let draw_size = std::mem::size_of::<DrawUniforms>();
+ let frame_stride = align_up(
+ std::mem::size_of::<FrameUniforms>() as u64,
+ device.limits().min_uniform_buffer_offset_alignment as u64,
+ ) as usize;
+ let frame_size = std::mem::size_of::<FrameUniforms>();
+ let mut frame_uniform_bytes: Vec<u8> = Vec::new();
+ let mut draw_call_indices: Vec<usize> = Vec::new();
+
+ for (dc_idx, dc) in commands.commands.iter().enumerate() {
+ let prev_len = self.scratch_vertices.len();
+ triangulate::triangulate_into(dc, &mut self.scratch_vertices);
+ let added = self.scratch_vertices.len() - prev_len;
+ if added == 0 {
+ continue;
+ }
+
+ let mvp = commands.projection * dc.modelview;
+ let draw_uniform = DrawUniforms { mvp: mvp.0 };
+ let start = self.scratch_draws.len() * draw_stride;
+ self.scratch_uniform_bytes.resize(start + draw_stride, 0);
+ self.scratch_uniform_bytes[start..start + draw_size].copy_from_slice(bytemuck::bytes_of(&draw_uniform));
+
+ let alpha_cmp = dc.bp_alpha_compare;
+ let frame_uniform = FrameUniforms {
+ tev_color_regs: dc.tev_color_regs,
+ tev_konst_colors: dc.tev_konst_colors,
+ tev_color_env: dc.tev_color_env.map(|e| e.raw()),
+ tev_alpha_env: dc.tev_alpha_env.map(|e| e.raw()),
+ tev_orders: dc.tev_orders.map(|o| o.raw()),
+ num_tev_stages: dc.num_tev_stages as u32,
+ alpha_ref0: alpha_cmp.ref0() as f32 / 255.0,
+ alpha_ref1: alpha_cmp.ref1() as f32 / 255.0,
+ alpha_comp0: alpha_cmp.comp0() as u32,
+ alpha_comp1: alpha_cmp.comp1() as u32,
+ alpha_op: alpha_cmp.op() as u32,
+ _padding: [0; 2],
+ };
+ let fstart = self.scratch_draws.len() * frame_stride;
+ frame_uniform_bytes.resize(fstart + frame_stride, 0);
+ frame_uniform_bytes[fstart..fstart + frame_size].copy_from_slice(bytemuck::bytes_of(&frame_uniform));
+
+ self.scratch_draws.push((prev_len as u32, added as u32));
+ draw_call_indices.push(dc_idx);
+ }
+
+ (frame_uniform_bytes, draw_call_indices)
+ }
+
+ fn upload_buffers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame_uniform_bytes: &[u8]) {
+ let num_draws = self.scratch_draws.len();
+ self.ensure_draw_capacity(device, num_draws);
+
+ if self.scratch_vertices.len() > self.vertex_capacity {
+ self.vertex_capacity = self.scratch_vertices.len().next_power_of_two();
+ self.vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("gx_vertices"),
+ size: (self.vertex_capacity * std::mem::size_of::<GpuVertex>()) as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+
+ let frame_stride = align_up(
+ std::mem::size_of::<FrameUniforms>() as u64,
+ device.limits().min_uniform_buffer_offset_alignment as u64,
+ ) as usize;
+ let needed_frame_size = (num_draws * frame_stride) as u64;
+ if needed_frame_size > self.frame_uniform_buffer.size() {
+ self.frame_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("gx_frame_uniforms"),
+ size: needed_frame_size,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+
+ queue.write_buffer(&self.frame_uniform_buffer, 0, frame_uniform_bytes);
+ queue.write_buffer(&self.draw_uniform_buffer, 0, &self.scratch_uniform_bytes);
+ queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.scratch_vertices));
+ }
+
+ fn execute_render_pass(
+ &self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ commands: &DrawCommands,
+ target: &wgpu::TextureView,
+ draw_call_indices: &[usize],
+ ) {
+ let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
+ let frame_stride = align_up(
+ std::mem::size_of::<FrameUniforms>() as u64,
+ device.limits().min_uniform_buffer_offset_alignment as u64,
+ ) as usize;
+
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("gx_render_pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ depth_slice: None,
+ })],
+ depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
+ view: &self.depth_view,
+ depth_ops: Some(wgpu::Operations {
+ load: wgpu::LoadOp::Clear(1.0),
+ store: wgpu::StoreOp::Store,
+ }),
+ stencil_ops: None,
+ }),
+ occlusion_query_set: None,
+ timestamp_writes: None,
+ multiview_mask: None,
+ });
+ rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+
+ for (index, (first_vertex, vertex_count)) in self.scratch_draws.iter().copied().enumerate() {
+ let dc = &commands.commands[draw_call_indices[index]];
+ let pipeline_key = PipelineKey::from_draw_call(dc);
+ let pipeline = &self.pipeline_cache[&pipeline_key];
+ rpass.set_pipeline(pipeline);
+
+ // Resolve all 8 texture views + samplers for this draw call
+ let mut tex_views: [&wgpu::TextureView; 8] = [&self.fallback_view; 8];
+ let mut tex_samplers: [&wgpu::Sampler; 8] = [&self.sampler_cache[&fallback_sampler_key]; 8];
+ for slot in 0..8 {
+ if let Some(desc) = &dc.textures[slot] {
+ let tex_key = (desc.ram_addr, desc.width, desc.height, desc.format);
+ let sampler_key = (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);
+ tex_views[slot] = &self.texture_cache[&tex_key].1;
+ tex_samplers[slot] = &self.sampler_cache[&sampler_key];
+ }
+ }
+
+ let frame_offset = (index as u64 * frame_stride as u64) as wgpu::BufferAddress;
+ let draw_offset = (index as u64 * self.draw_uniform_stride) as u32;
+
+ let mut entries = vec![
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.frame_uniform_buffer,
+ offset: frame_offset,
+ size: wgpu::BufferSize::new(std::mem::size_of::<FrameUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.draw_uniform_buffer,
+ offset: 0,
+ size: wgpu::BufferSize::new(std::mem::size_of::<DrawUniforms>() as u64),
+ }),
+ },
+ ];
+ for i in 0..8u32 {
+ entries.push(wgpu::BindGroupEntry {
+ binding: 2 + i,
+ resource: wgpu::BindingResource::TextureView(tex_views[i as usize]),
+ });
+ }
+ for i in 0..8u32 {
+ entries.push(wgpu::BindGroupEntry {
+ binding: 10 + i,
+ resource: wgpu::BindingResource::Sampler(tex_samplers[i as usize]),
+ });
+ }
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &self.bind_group_layout,
+ entries: &entries,
+ });
+
+ rpass.set_bind_group(0, &bind_group, &[draw_offset]);
+ rpass.draw(first_vertex..first_vertex + vertex_count, 0..1);
+ }
+ }
+
+ queue.submit([encoder.finish()]);
+ }
+
+ fn ensure_draw_capacity(&mut self, device: &wgpu::Device, count: usize) {
+ if count <= self.draw_uniform_capacity {
+ return;
+ }
+
+ self.draw_uniform_capacity = count.next_power_of_two();
+ self.draw_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("gx_draw_uniforms"),
+ size: self.draw_uniform_stride * self.draw_uniform_capacity as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+}
diff --git a/crates/backend-wgpu/src/shaders/alpha_test.wesl b/crates/backend-wgpu/src/shaders/alpha_test.wesl
new file mode 100644
index 0000000..018108e
--- /dev/null
+++ b/crates/backend-wgpu/src/shaders/alpha_test.wesl
@@ -0,0 +1,23 @@
+fn alpha_compare(a: f32, ref_val: f32, func: u32) -> bool {
+ switch func {
+ case 0u: { return false; } // Never
+ case 1u: { return a < ref_val; } // Less
+ case 2u: { return a == ref_val; } // Equal
+ case 3u: { return a <= ref_val; } // LessEqual
+ case 4u: { return a > ref_val; } // Greater
+ case 5u: { return a != ref_val; } // NotEqual
+ case 6u: { return a >= ref_val; } // GreaterEqual
+ case 7u: { return true; } // Always
+ default: { return true; }
+ }
+}
+
+fn alpha_combine(a: bool, b: bool, op: u32) -> bool {
+ switch op {
+ case 0u: { return a && b; } // AND
+ case 1u: { return a || b; } // OR
+ case 2u: { return a != b; } // XOR
+ case 3u: { return a == b; } // XNOR
+ default: { return true; }
+ }
+}
diff --git a/crates/backend-wgpu/src/shaders/common.wesl b/crates/backend-wgpu/src/shaders/common.wesl
new file mode 100644
index 0000000..00325ec
--- /dev/null
+++ b/crates/backend-wgpu/src/shaders/common.wesl
@@ -0,0 +1,72 @@
+struct FrameUniforms {
+ tev_color_reg0: vec4<f32>,
+ tev_color_reg1: vec4<f32>,
+ tev_color_reg2: vec4<f32>,
+ tev_color_reg3: vec4<f32>,
+ tev_konst_colors: array<vec4<f32>, 16>,
+ tev_color_env: array<vec4<u32>, 4>,
+ tev_alpha_env: array<vec4<u32>, 4>,
+ tev_orders: array<vec4<u32>, 4>,
+ num_tev_stages: u32,
+ alpha_ref0: f32,
+ alpha_ref1: f32,
+ alpha_comp0: u32,
+ alpha_comp1: u32,
+ alpha_op: u32,
+};
+
+struct DrawUniforms {
+ mvp: mat4x4<f32>,
+};
+
+@group(0) @binding(0)
+var<uniform> frame: FrameUniforms;
+
+@group(0) @binding(1)
+var<uniform> draw: DrawUniforms;
+
+// 8 texture maps (texmap 0-7)
+@group(0) @binding(2) var tex0: texture_2d<f32>;
+@group(0) @binding(3) var tex1: texture_2d<f32>;
+@group(0) @binding(4) var tex2: texture_2d<f32>;
+@group(0) @binding(5) var tex3: texture_2d<f32>;
+@group(0) @binding(6) var tex4: texture_2d<f32>;
+@group(0) @binding(7) var tex5: texture_2d<f32>;
+@group(0) @binding(8) var tex6: texture_2d<f32>;
+@group(0) @binding(9) var tex7: texture_2d<f32>;
+
+// 8 samplers (paired with texmaps)
+@group(0) @binding(10) var samp0: sampler;
+@group(0) @binding(11) var samp1: sampler;
+@group(0) @binding(12) var samp2: sampler;
+@group(0) @binding(13) var samp3: sampler;
+@group(0) @binding(14) var samp4: sampler;
+@group(0) @binding(15) var samp5: sampler;
+@group(0) @binding(16) var samp6: sampler;
+@group(0) @binding(17) var samp7: sampler;
+
+struct VsIn {
+ @location(0) position: vec3<f32>,
+ @location(1) color: vec4<f32>,
+ @location(2) tex0: vec2<f32>,
+ @location(3) tex1: vec2<f32>,
+ @location(4) tex2: vec2<f32>,
+ @location(5) tex3: vec2<f32>,
+ @location(6) tex4: vec2<f32>,
+ @location(7) tex5: vec2<f32>,
+ @location(8) tex6: vec2<f32>,
+ @location(9) tex7: vec2<f32>,
+};
+
+struct VsOut {
+ @builtin(position) clip_pos: vec4<f32>,
+ @location(0) color: vec4<f32>,
+ @location(1) uv0: vec2<f32>,
+ @location(2) uv1: vec2<f32>,
+ @location(3) uv2: vec2<f32>,
+ @location(4) uv3: vec2<f32>,
+ @location(5) uv4: vec2<f32>,
+ @location(6) uv5: vec2<f32>,
+ @location(7) uv6: vec2<f32>,
+ @location(8) uv7: vec2<f32>,
+};
diff --git a/crates/backend-wgpu/src/shaders/main.wesl b/crates/backend-wgpu/src/shaders/main.wesl
new file mode 100644
index 0000000..d5ec303
--- /dev/null
+++ b/crates/backend-wgpu/src/shaders/main.wesl
@@ -0,0 +1,126 @@
+import super::common::{FrameUniforms, DrawUniforms, VsIn, VsOut, frame, draw, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};
+import super::tev_helpers::{read_packed, extract_bits, select_texcoord, sample_texmap, tev_color_in, tev_alpha_in};
+import super::tev_combiners::{tev_combine_color, tev_combine_alpha};
+import super::alpha_test::{alpha_compare, alpha_combine};
+
+@vertex
+fn vs_main(in: VsIn) -> VsOut {
+ var out: VsOut;
+ out.clip_pos = draw.mvp * vec4<f32>(in.position, 1.0);
+ // Remap depth: GameCube/OpenGL uses [-1,1], wgpu uses [0,1]
+ out.clip_pos.z = out.clip_pos.z * 0.5 + out.clip_pos.w * 0.5;
+ out.color = in.color;
+ out.uv0 = in.tex0;
+ out.uv1 = in.tex1;
+ out.uv2 = in.tex2;
+ out.uv3 = in.tex3;
+ out.uv4 = in.tex4;
+ out.uv5 = in.tex5;
+ out.uv6 = in.tex6;
+ out.uv7 = in.tex7;
+ return out;
+}
+
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ // Initialize TEV registers from uniforms
+ var regs: array<vec4<f32>, 4>;
+ regs[0] = frame.tev_color_reg0;
+ regs[1] = frame.tev_color_reg1;
+ regs[2] = frame.tev_color_reg2;
+ regs[3] = frame.tev_color_reg3;
+
+ let ras_color = in.color;
+ let num_stages = frame.num_tev_stages;
+
+ var last_color_dest = 0u;
+ var last_alpha_dest = 0u;
+
+ for (var stage = 0u; stage < 16u; stage++) {
+ if stage >= num_stages {
+ break;
+ }
+
+ // Resolve per-stage texture from TevOrder
+ // TevStageOrder bit layout: texmap(0-2), texcoord(3-5), tex_enable(6)
+ let order = read_packed(frame.tev_orders, stage);
+ let texmap_idx = order & 7u;
+ let texcoord_idx = (order >> 3u) & 7u;
+ let tex_enabled = ((order >> 6u) & 1u) != 0u;
+
+ var tex_color: vec4<f32>;
+ if tex_enabled {
+ let uv = select_texcoord(in, texcoord_idx);
+ tex_color = sample_texmap(texmap_idx, uv);
+ } else {
+ tex_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
+ }
+
+ // Combine colors
+ let cenv = read_packed(frame.tev_color_env, stage);
+
+ // TevColorEnv bit layout (LSB0):
+ // [3:0]=d [7:4]=c [11:8]=b [15:12]=a
+ // [17:16]=bias [18]=sub [19]=clamp [21:20]=scale [23:22]=dest
+ let c_d = extract_bits(cenv, 0u, 4u);
+ let c_c = extract_bits(cenv, 4u, 4u);
+ let c_b = extract_bits(cenv, 8u, 4u);
+ let c_a = extract_bits(cenv, 12u, 4u);
+ let c_bias = extract_bits(cenv, 16u, 2u);
+ let c_sub = extract_bits(cenv, 18u, 1u) != 0u;
+ let c_clamp = extract_bits(cenv, 19u, 1u) != 0u;
+ let c_scale = extract_bits(cenv, 20u, 2u);
+ let c_dest = extract_bits(cenv, 22u, 2u);
+
+ let konst_color = frame.tev_konst_colors[stage];
+
+ let in_a = tev_color_in(c_a, tex_color, ras_color, regs, konst_color);
+ let in_b = tev_color_in(c_b, tex_color, ras_color, regs, konst_color);
+ let in_c = tev_color_in(c_c, tex_color, ras_color, regs, konst_color);
+ let in_d = tev_color_in(c_d, tex_color, ras_color, regs, konst_color);
+
+ let color_result = tev_combine_color(in_a, in_b, in_c, in_d, c_bias, c_sub, c_scale, c_clamp);
+ // Write RGB to dest, preserve alpha
+ regs[c_dest] = vec4(color_result, regs[c_dest].a);
+
+ // Combine alpha
+ let aenv = read_packed(frame.tev_alpha_env, stage);
+
+ // TevAlphaEnv bit layout (LSB0):
+ // [6:4]=d [9:7]=c [12:10]=b [15:13]=a
+ // [17:16]=bias [18]=sub [19]=clamp [21:20]=scale [23:22]=dest
+ let a_d = extract_bits(aenv, 4u, 3u);
+ let a_c = extract_bits(aenv, 7u, 3u);
+ let a_b = extract_bits(aenv, 10u, 3u);
+ let a_a = extract_bits(aenv, 13u, 3u);
+ let a_bias = extract_bits(aenv, 16u, 2u);
+ let a_sub = extract_bits(aenv, 18u, 1u) != 0u;
+ let a_clamp = extract_bits(aenv, 19u, 1u) != 0u;
+ let a_scale = extract_bits(aenv, 20u, 2u);
+ let a_dest = extract_bits(aenv, 22u, 2u);
+
+ let ain_a = tev_alpha_in(a_a, tex_color, ras_color, regs, konst_color);
+ let ain_b = tev_alpha_in(a_b, tex_color, ras_color, regs, konst_color);
+ let ain_c = tev_alpha_in(a_c, tex_color, ras_color, regs, konst_color);
+ let ain_d = tev_alpha_in(a_d, tex_color, ras_color, regs, konst_color);
+
+ let alpha_result = tev_combine_alpha(ain_a, ain_b, ain_c, ain_d, a_bias, a_sub, a_scale, a_clamp);
+
+ // Write alpha to dest, preserve RGB
+ regs[a_dest] = vec4(regs[a_dest].rgb, alpha_result);
+
+ last_color_dest = c_dest;
+ last_alpha_dest = a_dest;
+ }
+
+ // Output from the dest registers of the last active TEV stage (not always TEVPREV)
+ let color = vec4<f32>(regs[last_color_dest].rgb, regs[last_alpha_dest].a);
+
+ let c0 = alpha_compare(color.a, frame.alpha_ref0, frame.alpha_comp0);
+ let c1 = alpha_compare(color.a, frame.alpha_ref1, frame.alpha_comp1);
+ if !alpha_combine(c0, c1, frame.alpha_op) {
+ discard;
+ }
+
+ return color;
+}
diff --git a/crates/backend-wgpu/src/shaders/tev_combiners.wesl b/crates/backend-wgpu/src/shaders/tev_combiners.wesl
new file mode 100644
index 0000000..2d9caf9
--- /dev/null
+++ b/crates/backend-wgpu/src/shaders/tev_combiners.wesl
@@ -0,0 +1,64 @@
+// TEV color combiner: result = (d (+/-) ((1-c)*a + c*b) + bias) * scale
+fn tev_combine_color(a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, d: vec3<f32>,
+ bias: u32, sub: bool, scale: u32, do_clamp: bool) -> vec3<f32> {
+ let lerp = a * (vec3(1.0) - c) + b * c;
+
+ var result: vec3<f32>;
+ if sub {
+ result = d - lerp;
+ } else {
+ result = d + lerp;
+ }
+
+ // Bias
+ switch bias {
+ case 1u: { result += vec3(0.5); } // AddHalf
+ case 2u: { result -= vec3(0.5); } // SubHalf
+ default: {} // Zero
+ }
+
+ // Scale
+ switch scale {
+ case 1u: { result *= 2.0; } // Scale2
+ case 2u: { result *= 4.0; } // Scale4
+ case 3u: { result *= 0.5; } // Divide2
+ default: {} // Scale1
+ }
+
+ if do_clamp {
+ result = clamp(result, vec3(0.0), vec3(1.0));
+ }
+
+ return result;
+}
+
+// TEV alpha combiner: same formula as color but per-channel
+fn tev_combine_alpha(a: f32, b: f32, c: f32, d: f32, bias: u32, sub: bool, scale: u32, do_clamp: bool) -> f32 {
+ let lerp = a * (1.0 - c) + b * c;
+
+ var result: f32;
+ if sub {
+ result = d - lerp;
+ } else {
+ result = d + lerp;
+ }
+
+ switch bias {
+ case 1u: { result += 0.5; }
+ case 2u: { result -= 0.5; }
+ default: {}
+ }
+
+ switch scale {
+ case 1u: { result *= 2.0; }
+ case 2u: { result *= 4.0; }
+ case 3u: { result *= 0.5; }
+ default: {}
+ }
+
+ if do_clamp {
+ result = clamp(result, 0.0, 1.0);
+ }
+
+ return result;
+}
diff --git a/crates/backend-wgpu/src/shaders/tev_helpers.wesl b/crates/backend-wgpu/src/shaders/tev_helpers.wesl
new file mode 100644
index 0000000..f2ec84a
--- /dev/null
+++ b/crates/backend-wgpu/src/shaders/tev_helpers.wesl
@@ -0,0 +1,81 @@
+import super::common::{VsOut, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};
+
+// Read a single u32 from a packed array<vec4<u32>, 4> by flat index (0-15)
+fn read_packed(arr: array<vec4<u32>, 4>, idx: u32) -> u32 {
+ let vi = idx / 4u;
+ let ci = idx % 4u;
+ return arr[vi][ci];
+}
+
+// Extract `width` bits starting at bit `lo` from `val`
+fn extract_bits(val: u32, lo: u32, width: u32) -> u32 {
+ return (val >> lo) & ((1u << width) - 1u);
+}
+
+// Select texcoord by index (from TevOrder.texcoord)
+fn select_texcoord(in: VsOut, idx: u32) -> vec2<f32> {
+ switch idx {
+ case 0u: { return in.uv0; }
+ case 1u: { return in.uv1; }
+ case 2u: { return in.uv2; }
+ case 3u: { return in.uv3; }
+ case 4u: { return in.uv4; }
+ case 5u: { return in.uv5; }
+ case 6u: { return in.uv6; }
+ case 7u: { return in.uv7; }
+ default: { return in.uv0; }
+ }
+}
+
+// Sample from texmap by index (from TevOrder.texmap)
+fn sample_texmap(texmap: u32, uv: vec2<f32>) -> vec4<f32> {
+ switch texmap {
+ case 0u: { return textureSample(tex0, samp0, uv); }
+ case 1u: { return textureSample(tex1, samp1, uv); }
+ case 2u: { return textureSample(tex2, samp2, uv); }
+ case 3u: { return textureSample(tex3, samp3, uv); }
+ case 4u: { return textureSample(tex4, samp4, uv); }
+ case 5u: { return textureSample(tex5, samp5, uv); }
+ case 6u: { return textureSample(tex6, samp6, uv); }
+ case 7u: { return textureSample(tex7, samp7, uv); }
+ default: { return textureSample(tex0, samp0, uv); }
+ }
+}
+
+// TEV color input selector (TevColorIn, 4-bit, 16 variants)
+fn tev_color_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>, konst_color: vec4<f32>) -> vec3<f32> {
+ switch sel {
+ case 0u: { return regs[0].rgb; } // PrevColor
+ case 1u: { return vec3(regs[0].a); } // PrevAlpha
+ case 2u: { return regs[1].rgb; } // Reg0Color
+ case 3u: { return vec3(regs[1].a); } // Reg0Alpha
+ case 4u: { return regs[2].rgb; } // Reg1Color
+ case 5u: { return vec3(regs[2].a); } // Reg1Alpha
+ case 6u: { return regs[3].rgb; } // Reg2Color
+ case 7u: { return vec3(regs[3].a); } // Reg2Alpha
+ case 8u: { return tex_color.rgb; } // TexColor
+ case 9u: { return vec3(tex_color.a); } // TexAlpha
+ case 10u: { return ras_color.rgb; } // RasColor
+ case 11u: { return vec3(ras_color.a); } // RasAlpha
+ case 12u: { return vec3(1.0); } // One
+ case 13u: { return vec3(0.5); } // Half
+ case 14u: { return konst_color.rgb; } // Konst
+ case 15u: { return vec3(0.0); } // Zero
+ default: { return vec3(0.0); }
+ }
+}
+
+// TEV alpha input selector (TevAlphaIn, 3-bit, 8 variants)
+fn tev_alpha_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>, konst_color: vec4<f32>) -> f32 {
+ switch sel {
+ case 0u: { return regs[0].a; } // PrevAlpha
+ case 1u: { return regs[1].a; } // Reg0Alpha
+ case 2u: { return regs[2].a; } // Reg1Alpha
+ case 3u: { return regs[3].a; } // Reg2Alpha
+ case 4u: { return tex_color.a; } // TexAlpha
+ case 5u: { return ras_color.a; } // RasAlpha
+ case 6u: { return konst_color.a; } // Konst
+ case 7u: { return 0.0; } // Zero
+ default: { return 0.0; }
+ }
+}
diff --git a/crates/backend-wgpu/src/triangulate.rs b/crates/backend-wgpu/src/triangulate.rs
new file mode 100644
index 0000000..f30bbf5
--- /dev/null
+++ b/crates/backend-wgpu/src/triangulate.rs
@@ -0,0 +1,80 @@
+use gecko::flipper::gx::draw::{DrawCall, Primitive};
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+pub(crate) struct GpuVertex {
+ pub position: [f32; 3],
+ pub color: [f32; 4],
+ pub tex0: [f32; 2],
+ pub tex1: [f32; 2],
+ pub tex2: [f32; 2],
+ pub tex3: [f32; 2],
+ pub tex4: [f32; 2],
+ pub tex5: [f32; 2],
+ pub tex6: [f32; 2],
+ pub tex7: [f32; 2],
+}
+
+impl From<&gecko::flipper::gx::draw::Vertex> for GpuVertex {
+ fn from(v: &gecko::flipper::gx::draw::Vertex) -> Self {
+ let tc = |i: usize| v.texcoords[i].unwrap_or([0.0, 0.0]);
+ Self {
+ position: v.position,
+ color: v.color0,
+ tex0: tc(0),
+ tex1: tc(1),
+ tex2: tc(2),
+ tex3: tc(3),
+ tex4: tc(4),
+ tex5: tc(5),
+ tex6: tc(6),
+ tex7: tc(7),
+ }
+ }
+}
+
+pub(crate) fn triangulate_into(dc: &DrawCall, out: &mut Vec<GpuVertex>) {
+ match dc.primitive {
+ Primitive::Triangles => {
+ out.extend(dc.vertices.iter().map(GpuVertex::from));
+ }
+ Primitive::Quads => {
+ for quad in dc.vertices.chunks(4) {
+ if quad.len() < 4 {
+ continue;
+ }
+ out.push((&quad[0]).into());
+ out.push((&quad[1]).into());
+ out.push((&quad[2]).into());
+ out.push((&quad[0]).into());
+ out.push((&quad[2]).into());
+ out.push((&quad[3]).into());
+ }
+ }
+ Primitive::TriangleStrip => {
+ for i in 2..dc.vertices.len() {
+ if i % 2 == 0 {
+ out.push((&dc.vertices[i - 2]).into());
+ out.push((&dc.vertices[i - 1]).into());
+ out.push((&dc.vertices[i]).into());
+ } else {
+ out.push((&dc.vertices[i - 1]).into());
+ out.push((&dc.vertices[i - 2]).into());
+ out.push((&dc.vertices[i]).into());
+ }
+ }
+ }
+ Primitive::TriangleFan => {
+ for i in 2..dc.vertices.len() {
+ out.push((&dc.vertices[0]).into());
+ out.push((&dc.vertices[i - 1]).into());
+ out.push((&dc.vertices[i]).into());
+ }
+ }
+ _ => unimplemented!("triangulation for {:?}", dc.primitive),
+ }
+}
+
+pub(crate) fn align_up(value: u64, alignment: u64) -> u64 {
+ (value + alignment - 1) & !(alignment - 1)
+}
diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rs
index 9e45a1e..6444798 100644
--- a/crates/gecko/src/flipper/gx.rs
+++ b/crates/gecko/src/flipper/gx.rs
@@ -1,58 +1,48 @@
+mod bp;
pub mod constants;
pub mod draw;
pub mod fifo;
+mod lighting;
pub mod math;
pub mod regs;
+mod tev;
+mod texgen;
+mod vertex;
+mod xf;
use crate::{
flipper::gx::{
- constants::{
- ARRAY_BASE_REG, ARRAY_CLR0, ARRAY_NRM, ARRAY_POS, ARRAY_STRIDE_REG, ARRAY_TEX0, BP_GEN_MODE,
- BP_PE_ALPHA_COMPARE, BP_PE_CMODE0, BP_PE_DONE, BP_PE_DONE_FINISH_BIT, BP_PE_ZMODE, BP_RAS1_TREF_COUNT,
- BP_RAS1_TREF0, BP_REG_SIZE, BP_TEV_COLOR_ENV_0, BP_TEV_KSEL_0, BP_TEV_REGISTERL_0, BP_TX_SETIMAGE0_I0,
- BP_TX_SETIMAGE0_I4, BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4,
- CP_REG_SIZE, VATA_REG, VATB_REG, VATC_REG, VCD_HI_REG, VCD_LO_REG, XF_ALPHA_CTRL0, XF_AMBIENT_COLOR0,
- XF_COLOR_CTRL0, XF_DUAL_TEX_ENABLE, XF_DUALTEX_BASE, XF_LIGHT_A0, XF_LIGHT_BASE, XF_LIGHT_COLOR,
- XF_LIGHT_K0, XF_LIGHT_NX, XF_LIGHT_PX, XF_LIGHT_STRIDE, XF_MATERIAL_COLOR0, XF_MATRIX_INDEX_A,
- XF_MATRIX_INDEX_B, XF_MEM_SIZE, XF_NRM_MTX_BASE, XF_NUM_TEXGENS, XF_POS_MTX_STRIDE, XF_POST_MTX_BASE,
- XF_PROJECTION_BASE, XF_PROJECTION_END, XF_TEXGEN_BASE,
- },
+ constants::{BP_REG_SIZE, CP_REG_SIZE, XF_MEM_SIZE},
draw::DrawCommands,
- regs::{
- AlphaCompare, AttnFn, BlendMode, ChanCtrl, DualTexGenReg, GenMode, MatrixIndex0, MatrixIndex1, TevAlphaEnv,
- TevColorEnv, TevRegType, TevRegisterH, TevRegisterL, TexGenReg, TxSetImage0, TxSetImage3, TxSetMode0, VatA,
- VatB, VatC, VcdHi, VcdLo, ZMode,
- },
+ regs::{AlphaCompare, BlendMode, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode},
},
gamecube::GameCube,
mmio::Mmio,
};
use fifo::FifoCmd;
-use math::{Vec3, saturating_div, unpack_rgba};
-use std::io::{Cursor, Read};
pub struct GraphicsProcessor {
pub raise_interrupt: bool,
pub draw_commands: DrawCommands,
- bp_regs: Vec<u32>,
- cp_regs: Vec<u32>,
- xf_mem: Vec<u32>,
- fifo: Vec<u8>,
+ pub(crate) bp_regs: Vec<u32>,
+ pub(crate) cp_regs: Vec<u32>,
+ pub(crate) xf_mem: Vec<u32>,
+ pub(crate) fifo: Vec<u8>,
// Current GX state to snapshot into a DrawCall later
- cur_textures: [Option<draw::TextureDescriptor>; 8],
- cur_tev_color_env: [TevColorEnv; 16],
- cur_tev_alpha_env: [TevAlphaEnv; 16],
- cur_tev_color_regs_lo: [TevRegisterL; 4],
- cur_tev_color_regs_hi: [TevRegisterH; 4],
- cur_tev_const_regs_lo: [TevRegisterL; 4],
- cur_tev_const_regs_hi: [TevRegisterH; 4],
- cur_tev_orders: [regs::TevOrder; 8],
- cur_num_tev_stages: u8,
- cur_tev_konst_colors: [[f32; 4]; 16],
- cur_zmode: ZMode,
- cur_blend_mode: BlendMode,
- cur_alpha_compare: AlphaCompare,
+ pub(crate) cur_textures: [Option<draw::TextureDescriptor>; 8],
+ pub(crate) cur_tev_color_env: [TevColorEnv; 16],
+ pub(crate) cur_tev_alpha_env: [TevAlphaEnv; 16],
+ pub(crate) cur_tev_color_regs_lo: [TevRegisterL; 4],
+ pub(crate) cur_tev_color_regs_hi: [TevRegisterH; 4],
+ pub(crate) cur_tev_const_regs_lo: [TevRegisterL; 4],
+ pub(crate) cur_tev_const_regs_hi: [TevRegisterH; 4],
+ pub(crate) cur_tev_orders: [regs::TevOrder; 8],
+ pub(crate) cur_num_tev_stages: u8,
+ pub(crate) cur_tev_konst_colors: [[f32; 4]; 16],
+ pub(crate) cur_zmode: ZMode,
+ pub(crate) cur_blend_mode: BlendMode,
+ pub(crate) cur_alpha_compare: AlphaCompare,
}
impl GraphicsProcessor {
@@ -117,1172 +107,6 @@ impl GraphicsProcessor {
self.drain_fifo(mmio);
self.fifo = saved;
}
-
- fn create_draw_call(&mut self, mmio: &mut Mmio, cmd: u8, data: Vec<u8>) {
- let Some(primitive) = draw::Primitive::from_cmd(cmd) else {
- tracing::error!(cmd, "goofy draw command");
- return;
- };
-
- let fmt = (cmd & 0b111) as usize;
- // VCD is global state (single register), VAT is per-format
- let vcd_lo = VcdLo::from_raw(self.cp_regs[VCD_LO_REG]);
- let vcd_hi = VcdHi::from_raw(self.cp_regs[VCD_HI_REG]);
- let vat_a = VatA::from_raw(self.cp_regs[VATA_REG + fmt]);
- let vat_b = VatB::from_raw(self.cp_regs[VATB_REG + fmt]);
- let vat_c = VatC::from_raw(self.cp_regs[VATC_REG + fmt]);
-
- let attr_stream_size = |attr: regs::AttributeType, direct_size: usize| -> usize {
- match attr {
- regs::AttributeType::Direct => direct_size,
- regs::AttributeType::Index8 => 1,
- regs::AttributeType::Index16 => 2,
- regs::AttributeType::None => 0,
- }
- };
-
- let pos_base = self.cp_regs[ARRAY_BASE_REG + ARRAY_POS] as usize;
- let pos_stride = self.cp_regs[ARRAY_STRIDE_REG + ARRAY_POS] as usize;
- let clr0_base = self.cp_regs[ARRAY_BASE_REG + ARRAY_CLR0] as usize;
- let clr0_stride = self.cp_regs[ARRAY_STRIDE_REG + ARRAY_CLR0] as usize;
-
- let pos_attr = vcd_lo.position();
- let nrm_attr = vcd_lo.normal();
- let clr0_attr = vcd_lo.color0();
- let pos_data_size = vat_a.pos_data_size();
- let nrm_data_size = vat_a.nrm_data_size();
- let clr0_data_size = vat_a.clr0_data_size();
-
- let mtx_idx_size = vcd_lo.mtx_idx_count();
- let pos_stream_size = attr_stream_size(pos_attr, pos_data_size);
- let nrm_stream_size = vat_a.nrm_stream_size(nrm_attr);
- let clr0_stream_size = attr_stream_size(clr0_attr, clr0_data_size);
- let clr1_stream_size = attr_stream_size(vcd_lo.color1(), vat_a.clr1_data_size());
-
- // Build per-texcoord metadata arrays
- let tex_attrs = [
- vcd_hi.tex0(),
- vcd_hi.tex1(),
- vcd_hi.tex2(),
- vcd_hi.tex3(),
- vcd_hi.tex4(),
- vcd_hi.tex5(),
- vcd_hi.tex6(),
- vcd_hi.tex7(),
- ];
- let tex_data_sizes = [
- vat_a.tex0_data_size(),
- vat_b.tex1_data_size(),
- vat_b.tex2_data_size(),
- vat_b.tex3_data_size(),
- vat_b.tex4_data_size(),
- vat_c.tex5_data_size(),
- vat_c.tex6_data_size(),
- vat_c.tex7_data_size(),
- ];
- let tex_fmts = [
- vat_a.tex0_fmt(),
- vat_b.tex1_fmt(),
- vat_b.tex2_fmt(),
- vat_b.tex3_fmt(),
- vat_b.tex4_fmt(),
- vat_c.tex5_fmt(),
- vat_c.tex6_fmt(),
- vat_c.tex7_fmt(),
- ];
- let tex_shifts = [
- vat_a.tex0_shift(),
- vat_b.tex1_shift(),
- vat_b.tex2_shift(),
- vat_b.tex3_shift(),
- vat_c.tex4_shift(),
- vat_c.tex5_shift(),
- vat_c.tex6_shift(),
- vat_c.tex7_shift(),
- ];
- let tex_cnts = [
- vat_a.tex0_cnt(),
- vat_b.tex1_cnt(),
- vat_b.tex2_cnt(),
- vat_b.tex3_cnt(),
- vat_b.tex4_cnt(),
- vat_c.tex5_cnt(),
- vat_c.tex6_cnt(),
- vat_c.tex7_cnt(),
- ];
- let tex_stream_sizes: [usize; 8] = std::array::from_fn(|i| attr_stream_size(tex_attrs[i], tex_data_sizes[i]));
- let tex_bases: [usize; 8] = std::array::from_fn(|i| self.cp_regs[ARRAY_BASE_REG + ARRAY_TEX0 + i] as usize);
- let tex_strides: [usize; 8] = std::array::from_fn(|i| self.cp_regs[ARRAY_STRIDE_REG + ARRAY_TEX0 + i] as usize);
-
- let nrm_base_addr = self.cp_regs[ARRAY_BASE_REG + ARRAY_NRM] as usize;
- let nrm_stride = self.cp_regs[ARRAY_STRIDE_REG + ARRAY_NRM] as usize;
-
- let vertex_stride = mtx_idx_size
- + pos_stream_size
- + nrm_stream_size
- + clr0_stream_size
- + clr1_stream_size
- + tex_stream_sizes.iter().sum::<usize>();
-
- if vertex_stride == 0 {
- tracing::warn!("draw call with zero vertex stride, skipping");
- return;
- }
-
- let vertex_count = data.len() / vertex_stride;
-
- // Per-vertex matrix index handling
- let has_pnmtxidx = vcd_lo.pos_nrm_mtx_idx();
- let tex_mtx_idx_size = mtx_idx_size - has_pnmtxidx as usize; // remaining mtx idx bytes after pnmtxidx
-
- // Default matrix index from register (used when per-vertex index is absent)
- let mtx_index_a = MatrixIndex0::from_raw(self.xf_mem[XF_MATRIX_INDEX_A]);
- let default_pos_mtx_idx = mtx_index_a.pos_mtx_idx();
-
- // Channel 0 lighting state (COLOR0 and ALPHA0 have separate controls)
- let color_ctrl = ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL0]);
- let alpha_ctrl = ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL0]);
- let ambient_reg = unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR0]);
- let material_reg = unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR0]);
-
- let mut vertices: Vec<draw::Vertex> = Vec::with_capacity(vertex_count);
- let mut cur = Cursor::new(&data);
-
- for i in 0..vertex_count {
- // Read per-vertex position/normal matrix index, or use register default
- let pos_mtx_idx = if has_pnmtxidx {
- let mut buf = [0u8; 1];
- cur.read_exact(&mut buf).unwrap();
- buf[0] & 0x3F
- } else {
- default_pos_mtx_idx
- };
-
- // Skip remaining tex matrix index bytes (not yet used)
- cur.set_position(cur.position() + tex_mtx_idx_size as u64);
-
- // Derive per-vertex position and normal matrix bases
- let pos_mtx_base = pos_mtx_idx as usize * XF_POS_MTX_STRIDE;
- let nrm_mtx_idx = (pos_mtx_idx as usize) & 31;
- let nrm_mtx_base = XF_NRM_MTX_BASE + nrm_mtx_idx * 3;
- let nrm_mtx: [f32; 9] = std::array::from_fn(|i| self.xf_f32(nrm_mtx_base + i));
-
- // Read position
- let position = if pos_attr == regs::AttributeType::Direct {
- let start = cur.position() as usize;
- cur.set_position(cur.position() + pos_data_size as u64);
- Self::decode_position(&data[start..start + pos_data_size], &vat_a)
- } else {
- let pos_index = read_index(&mut cur, pos_attr);
- let pos_addr = pos_base + pos_index * pos_stride;
- Self::decode_position(&mmio.ram[pos_addr..pos_addr + pos_data_size], &vat_a)
- };
-
- // Read normal
- let normal = if nrm_attr == regs::AttributeType::Direct {
- let start = cur.position() as usize;
- cur.set_position(cur.position() + nrm_data_size as u64);
- Self::decode_normal(&data[start..start + nrm_data_size], &vat_a)
- } else if nrm_attr != regs::AttributeType::None {
- let nrm_index = read_index(&mut cur, nrm_attr);
- // When nrm_index3 && NBT, the stream contains 3 separate indices
- // (normal, binormal, tangent). Skip the extra 2 — only the normal
- // vector (first index) is needed for lighting.
- if vat_a.nrm_index3() && vat_a.nrm_cnt() == regs::NrmCount::Nbt {
- let idx_size = if nrm_attr == regs::AttributeType::Index8 { 1 } else { 2 };
- cur.set_position(cur.position() + (2 * idx_size) as u64);
- }
- let nrm_addr = nrm_base_addr + nrm_index * nrm_stride;
- Self::decode_normal(&mmio.ram[nrm_addr..nrm_addr + nrm_data_size], &vat_a)
- } else {
- [0.0, 0.0, 1.0]
- };
-
- // Read color0
- let color0 = if clr0_attr == regs::AttributeType::None {
- [1.0, 1.0, 1.0, 1.0]
- } else if clr0_attr == regs::AttributeType::Direct {
- let start = cur.position() as usize;
- cur.set_position(cur.position() + clr0_data_size as u64);
- Self::decode_color(&data[start..start + clr0_data_size], &vat_a)
- } else {
- let clr0_index = read_index(&mut cur, clr0_attr);
- let clr0_addr = clr0_base + clr0_index * clr0_stride;
- Self::decode_color(&mmio.ram[clr0_addr..clr0_addr + clr0_data_size], &vat_a)
- };
-
- // Skip color1 (not yet used for rendering)
- cur.set_position(cur.position() + clr1_stream_size as u64);
-
- // Read all texcoords (tex0-tex7)
- let mut raw_texcoords: [Option<[f32; 2]>; 8] = [None; 8];
- for tc in 0..8 {
- let tc_attr = tex_attrs[tc];
- let tc_data_size = tex_data_sizes[tc];
- if tc_attr == regs::AttributeType::None {
- continue;
- }
- raw_texcoords[tc] = Some(if tc_attr == regs::AttributeType::Direct {
- let start = cur.position() as usize;
- cur.set_position(cur.position() + tc_data_size as u64);
- Self::decode_texcoord(
- &data[start..start + tc_data_size],
- tex_fmts[tc],
- tex_shifts[tc],
- tex_cnts[tc],
- )
- } else {
- let tc_index = read_index(&mut cur, tc_attr);
- let tc_addr = tex_bases[tc] + tc_index * tex_strides[tc];
- Self::decode_texcoord(
- &mmio.ram[tc_addr..tc_addr + tc_data_size],
- tex_fmts[tc],
- tex_shifts[tc],
- tex_cnts[tc],
- )
- });
- }
-
- // Compute per-vertex lighting
- let normal_view = Vec3::from(normal).transform(&nrm_mtx).normalize();
- let pos_view = self.xf_transform_3x4(pos_mtx_base, position);
- let final_color = self.compute_channel_lighting(
- &color_ctrl,
- &alpha_ctrl,
- ambient_reg,
- material_reg,
- color0,
- normal_view,
- pos_view,
- );
-
- // Texture coordinate generation (XF texgen)
- let num_texgens = (self.xf_mem[XF_NUM_TEXGENS] as usize).min(8);
- let mut texcoords: [Option<[f32; 2]>; 8] = [None; 8];
- for tg_idx in 0..num_texgens {
- texcoords[tg_idx] = Some(self.compute_texgen(tg_idx, position, normal, &raw_texcoords));
- }
- // For texcoords beyond num_texgens, pass through raw values
- for tg_idx in num_texgens..8 {
- texcoords[tg_idx] = raw_texcoords[tg_idx];
- }
-
- tracing::debug!(
- vertex = i,
- position = format!("{:02X?}", position),
- color0 = format!("{:?}", final_color),
- "Vertex"
- );
-
- vertices.push(draw::Vertex {
- position,
- color0: final_color,
- texcoords,
- });
- }
-
- // Modelview uses the register-level default matrix (per-vertex transforms are
- // already applied during lighting via xf_transform_3x4 per vertex)
- let default_mtx_base = default_pos_mtx_idx as usize * XF_POS_MTX_STRIDE;
- let modelview = draw::Matrix4([
- [
- self.xf_f32(default_mtx_base),
- self.xf_f32(default_mtx_base + 4),
- self.xf_f32(default_mtx_base + 8),
- 0.0,
- ],
- [
- self.xf_f32(default_mtx_base + 1),
- self.xf_f32(default_mtx_base + 5),
- self.xf_f32(default_mtx_base + 9),
- 0.0,
- ],
- [
- self.xf_f32(default_mtx_base + 2),
- self.xf_f32(default_mtx_base + 6),
- self.xf_f32(default_mtx_base + 10),
- 0.0,
- ],
- [
- self.xf_f32(default_mtx_base + 3),
- self.xf_f32(default_mtx_base + 7),
- self.xf_f32(default_mtx_base + 11),
- 1.0,
- ],
- ]);
-
- tracing::debug!(
- primitive = format!("{:?}", primitive),
- vertices = format!("{:?}", vertices),
- pos_mtx_idx = default_pos_mtx_idx,
- modelview = format!("{:?}", modelview),
- projection = format!("{:?}", self.draw_commands.projection),
- "draw call created"
- );
-
- // Resolve TEV color registers to f32 arrays for the snapshot
- let tev_color_regs = self.resolve_tev_color_regs();
-
- self.draw_commands.commands.push(draw::DrawCall {
- primitive,
- vertices,
- modelview,
- textures: self.cur_textures,
- tev_orders: self.resolve_tev_orders(),
- tev_color_env: self.cur_tev_color_env,
- tev_alpha_env: self.cur_tev_alpha_env,
- tev_color_regs,
- tev_konst_colors: self.cur_tev_konst_colors,
- num_tev_stages: self.cur_num_tev_stages,
- bp_zmode: self.cur_zmode,
- bp_blend_mode: self.cur_blend_mode,
- bp_alpha_compare: self.cur_alpha_compare,
- });
- }
-
- fn decode_position(data: &[u8], vat: &VatA) -> [f32; 3] {
- let num = vat.pos_cnt().components();
- let fmt = vat.pos_fmt();
- let divisor = (1u32 << vat.pos_shift()) as f32;
- let mut result = [0.0f32; 3];
- let mut off = 0;
-
- for i in 0..num {
- result[i] = match fmt {
- regs::ComponentFormat::U8 => {
- let v = data[off] as f32 / divisor;
- off += 1;
- v
- }
- regs::ComponentFormat::S8 => {
- let v = data[off] as i8 as f32 / divisor;
- off += 1;
- v
- }
- regs::ComponentFormat::U16 => {
- let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
- off += 2;
- v
- }
- regs::ComponentFormat::S16 => {
- let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
- off += 2;
- v
- }
- regs::ComponentFormat::F32 => {
- let v = f32::from_bits(u32::from_be_bytes([
- data[off],
- data[off + 1],
- data[off + 2],
- data[off + 3],
- ]));
- off += 4;
- v
- }
- };
- }
- result
- }
-
- fn decode_color(data: &[u8], vat: &VatA) -> [f32; 4] {
- let has_alpha = vat.clr0_cnt() == regs::ColorCount::Rgba;
- match vat.clr0_fmt() {
- regs::ColorFormat::Rgb565 => {
- let raw = u16::from_be_bytes([data[0], data[1]]);
- let r = ((raw >> 11) & 0x1F) as f32 / 31.0;
- let g = ((raw >> 5) & 0x3F) as f32 / 63.0;
- let b = (raw & 0x1F) as f32 / 31.0;
- [r, g, b, 1.0]
- }
- regs::ColorFormat::Rgb8 => [
- data[0] as f32 / 255.0,
- data[1] as f32 / 255.0,
- data[2] as f32 / 255.0,
- 1.0,
- ],
- regs::ColorFormat::Rgbx8 => [
- data[0] as f32 / 255.0,
- data[1] as f32 / 255.0,
- data[2] as f32 / 255.0,
- 1.0,
- ],
- regs::ColorFormat::Rgba4 => {
- let raw = u16::from_be_bytes([data[0], data[1]]);
- let r = ((raw >> 12) & 0xF) as f32 / 15.0;
- let g = ((raw >> 8) & 0xF) as f32 / 15.0;
- let b = ((raw >> 4) & 0xF) as f32 / 15.0;
- let a = (raw & 0xF) as f32 / 15.0;
- [r, g, b, a]
- }
- regs::ColorFormat::Rgba6 => {
- let raw = u32::from_be_bytes([0, data[0], data[1], data[2]]);
- let r = ((raw >> 18) & 0x3F) as f32 / 63.0;
- let g = ((raw >> 12) & 0x3F) as f32 / 63.0;
- let b = ((raw >> 6) & 0x3F) as f32 / 63.0;
- let a = (raw & 0x3F) as f32 / 63.0;
- [r, g, b, a]
- }
- regs::ColorFormat::Rgba8 => {
- let r = data[0] as f32 / 255.0;
- let g = data[1] as f32 / 255.0;
- let b = data[2] as f32 / 255.0;
- let a = if has_alpha { data[3] as f32 / 255.0 } else { 1.0 };
- [r, g, b, a]
- }
- }
- }
-
- fn decode_normal(data: &[u8], vat: &VatA) -> [f32; 3] {
- let cnt = vat.nrm_cnt().components().min(3);
- let fmt = vat.nrm_fmt();
- let mut result = [0.0f32; 3];
- let mut off = 0;
-
- for i in 0..cnt {
- result[i] = match fmt {
- regs::ComponentFormat::U8 => {
- let v = data[off] as f32 / 255.0;
- off += 1;
- v
- }
- regs::ComponentFormat::S8 => {
- let v = data[off] as i8 as f32 / 127.0;
- off += 1;
- v
- }
- regs::ComponentFormat::U16 => {
- let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / 65535.0;
- off += 2;
- v
- }
- regs::ComponentFormat::S16 => {
- let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / 32767.0;
- off += 2;
- v
- }
- regs::ComponentFormat::F32 => {
- let v = f32::from_bits(u32::from_be_bytes([
- data[off],
- data[off + 1],
- data[off + 2],
- data[off + 3],
- ]));
- off += 4;
- v
- }
- };
- }
-
- result
- }
-
- fn decode_texcoord(data: &[u8], fmt: regs::ComponentFormat, shift: u8, cnt: regs::TexCount) -> [f32; 2] {
- let num = cnt.components();
- let divisor = (1u32 << shift) as f32;
- let mut result = [0.0f32; 2];
- let mut off = 0;
-
- for i in 0..num {
- result[i] = match fmt {
- regs::ComponentFormat::U8 => {
- let v = data[off] as f32 / divisor;
- off += 1;
- v
- }
- regs::ComponentFormat::S8 => {
- let v = data[off] as i8 as f32 / divisor;
- off += 1;
- v
- }
- regs::ComponentFormat::U16 => {
- let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
- off += 2;
- v
- }
- regs::ComponentFormat::S16 => {
- let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
- off += 2;
- v
- }
- regs::ComponentFormat::F32 => {
- let v = f32::from_bits(u32::from_be_bytes([
- data[off],
- data[off + 1],
- data[off + 2],
- data[off + 3],
- ]));
- off += 4;
- v
- }
- };
- }
- result
- }
-
- fn compute_channel_lighting(
- &self,
- color_ctrl: &ChanCtrl,
- alpha_ctrl: &ChanCtrl,
- ambient_reg: [f32; 4],
- material_reg: [f32; 4],
- vertex_color: [f32; 4],
- normal: Vec3,
- pos: Vec3,
- ) -> [f32; 4] {
- let mat_rgb: [f32; 3] = if color_ctrl.mat_src() {
- [vertex_color[0], vertex_color[1], vertex_color[2]]
- } else {
- [material_reg[0], material_reg[1], material_reg[2]]
- };
- let amb_rgb: [f32; 3] = if color_ctrl.amb_src() {
- [vertex_color[0], vertex_color[1], vertex_color[2]]
- } else {
- [ambient_reg[0], ambient_reg[1], ambient_reg[2]]
- };
-
- let mat_a = if alpha_ctrl.mat_src() {
- vertex_color[3]
- } else {
- material_reg[3]
- };
- let amb_a = if alpha_ctrl.amb_src() {
- vertex_color[3]
- } else {
- ambient_reg[3]
- };
-
- // When lighting is disabled, return material color directly
- let color_lit_off = !color_ctrl.enable();
- let alpha_lit_off = !alpha_ctrl.enable();
- if color_lit_off && alpha_lit_off {
- return [mat_rgb[0], mat_rgb[1], mat_rgb[2], mat_a];
- }
-
- // Compute RGB lighting accumulator
- let mut rgb_out = mat_rgb;
- if !color_lit_off {
- let light_mask = color_ctrl.light_mask();
- let mut acc = amb_rgb;
- for light_id in 0..8u32 {
- if (light_mask >> light_id) & 1 == 0 {
- continue;
- }
- let base = XF_LIGHT_BASE + (light_id as usize) * XF_LIGHT_STRIDE;
- let light_color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);
- let factor = self.compute_light_factor(color_ctrl, base, normal, pos);
- acc[0] += light_color[0] * factor;
- acc[1] += light_color[1] * factor;
- acc[2] += light_color[2] * factor;
- }
- rgb_out = std::array::from_fn(|i| mat_rgb[i] * acc[i].clamp(0.0, 1.0));
- }
-
- // Compute Alpha lighting accumulator
- let mut a_out = mat_a;
- if !alpha_lit_off {
- let light_mask = alpha_ctrl.light_mask();
- let mut acc_a = amb_a;
- for light_id in 0..8u32 {
- if (light_mask >> light_id) & 1 == 0 {
- continue;
- }
- let base = XF_LIGHT_BASE + (light_id as usize) * XF_LIGHT_STRIDE;
- let light_color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);
- let factor = self.compute_light_factor(alpha_ctrl, base, normal, pos);
- acc_a += light_color[3] * factor;
- }
- a_out = mat_a * acc_a.clamp(0.0, 1.0);
- }
-
- [rgb_out[0], rgb_out[1], rgb_out[2], a_out]
- }
-
- fn compute_light_factor(&self, ctrl: &ChanCtrl, base: usize, normal: Vec3, pos: Vec3) -> f32 {
- let cosatt = self.xf_vec3(base + XF_LIGHT_A0);
- let distatt = self.xf_vec3(base + XF_LIGHT_K0);
- let light_pos = self.xf_vec3(base + XF_LIGHT_PX);
- let light_dir = self.xf_vec3(base + XF_LIGHT_NX);
-
- // ldir starts as light_pos - vertex_pos for all modes
- // In Spot mode, light_pos is a world position
- // In Spec mode, light_pos is repurposed as the half-angle direction vector
- let mut ldir = light_pos - pos;
-
- let attn = match ctrl.attn_fn() {
- AttnFn::None => {
- ldir = ldir.normalize();
- 1.0
- }
- AttnFn::Spot => {
- let dist = ldir.length();
- ldir = ldir.normalize();
- let cos_angle = light_dir.dot(ldir);
- let angle_attn = (cosatt.0 + cosatt.1 * cos_angle + cosatt.2 * cos_angle * cos_angle).max(0.0);
- saturating_div(angle_attn, distatt.0 + distatt.1 * dist + distatt.2 * dist * dist)
- }
- AttnFn::Spec => {
- ldir = ldir.normalize();
- let half_dot = ldir.dot(normal);
- if half_dot < 0.0 {
- return 0.0;
- }
- let s = normal.dot(light_dir).max(0.0);
- let att_len = Vec3(1.0, s, s * s);
- let da = if ctrl.diff_fn() != regs::DiffuseFn::None {
- distatt.normalize()
- } else {
- distatt
- };
- saturating_div(att_len.dot(cosatt).max(0.0), att_len.dot(da))
- }
- };
-
- // Diffuse is computed from ldir dotted with normal
- let dif_attn = ldir.dot(normal);
- let diffuse = match ctrl.diff_fn() {
- regs::DiffuseFn::None => 1.0,
- regs::DiffuseFn::Signed => dif_attn,
- regs::DiffuseFn::Clamp => dif_attn.max(0.0),
- };
-
- attn * diffuse
- }
-
- fn compute_texgen(
- &self,
- texgen_idx: usize,
- position: [f32; 3],
- normal: [f32; 3],
- raw_texcoords: &[Option<[f32; 2]>; 8],
- ) -> [f32; 2] {
- let tg = TexGenReg::from_raw(self.xf_mem[XF_TEXGEN_BASE + texgen_idx]);
- let dt = DualTexGenReg::from_raw(self.xf_mem[XF_DUALTEX_BASE + texgen_idx]);
-
- // Select the source input vector based on texgen source_row
- let src = match tg.source_row() {
- regs::TexGenSrc::Pos => position,
- regs::TexGenSrc::Nrm => normal,
- regs::TexGenSrc::Tex0 => {
- let t = raw_texcoords[0].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- regs::TexGenSrc::Tex1 => {
- let t = raw_texcoords[1].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- regs::TexGenSrc::Tex2 => {
- let t = raw_texcoords[2].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- regs::TexGenSrc::Tex3 => {
- let t = raw_texcoords[3].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- regs::TexGenSrc::Tex4 => {
- let t = raw_texcoords[4].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- regs::TexGenSrc::Tex5 => {
- let t = raw_texcoords[5].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- regs::TexGenSrc::Tex6 => {
- let t = raw_texcoords[6].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- regs::TexGenSrc::Tex7 => {
- let t = raw_texcoords[7].unwrap_or([0.0, 0.0]);
- [t[0], t[1], 1.0]
- }
- // TODO: ???
- _ => [0.0, 0.0, 1.0],
- };
-
- // Form input vector based on input_form
- let input = match tg.input_form() {
- regs::TexGenInputForm::Ab11 => [src[0], src[1], 1.0, 1.0],
- regs::TexGenInputForm::Abc1 => [src[0], src[1], src[2], 1.0],
- };
-
- // Texture matrix base from MatrixIndex register
- let tex_mtx_idx = if texgen_idx < 4 {
- let mtx_index_a = MatrixIndex0::from_raw(self.xf_mem[XF_MATRIX_INDEX_A]);
- mtx_index_a.tex_mtx_idx(texgen_idx) as usize
- } else {
- let mtx_index_b = MatrixIndex1::from_raw(self.xf_mem[XF_MATRIX_INDEX_B]);
- mtx_index_b.tex_mtx_idx(texgen_idx) as usize
- };
- let tex_mtx_base = tex_mtx_idx * XF_POS_MTX_STRIDE;
-
- // Multiply input by texture matrix (2x4 or 3x4 depending on projection)
- let (s, t, q) = match tg.projection() {
- regs::TexGenProjection::St => {
- // 2x4 matrix -> (s, t)
- let s = self.xf_f32(tex_mtx_base) * input[0]
- + self.xf_f32(tex_mtx_base + 1) * input[1]
- + self.xf_f32(tex_mtx_base + 2) * input[2]
- + self.xf_f32(tex_mtx_base + 3) * input[3];
- let t = self.xf_f32(tex_mtx_base + 4) * input[0]
- + self.xf_f32(tex_mtx_base + 5) * input[1]
- + self.xf_f32(tex_mtx_base + 6) * input[2]
- + self.xf_f32(tex_mtx_base + 7) * input[3];
- (s, t, 1.0)
- }
- regs::TexGenProjection::Stq => {
- // 3x4 matrix -> (s, t, q)
- let s = self.xf_f32(tex_mtx_base) * input[0]
- + self.xf_f32(tex_mtx_base + 1) * input[1]
- + self.xf_f32(tex_mtx_base + 2) * input[2]
- + self.xf_f32(tex_mtx_base + 3) * input[3];
- let t = self.xf_f32(tex_mtx_base + 4) * input[0]
- + self.xf_f32(tex_mtx_base + 5) * input[1]
- + self.xf_f32(tex_mtx_base + 6) * input[2]
- + self.xf_f32(tex_mtx_base + 7) * input[3];
- let q = self.xf_f32(tex_mtx_base + 8) * input[0]
- + self.xf_f32(tex_mtx_base + 9) * input[1]
- + self.xf_f32(tex_mtx_base + 10) * input[2]
- + self.xf_f32(tex_mtx_base + 11) * input[3];
- (s, t, q)
- }
- };
-
- // Dual texgen post-transform (normalization + post-matrix multiply)
- let dual_tex_enabled = self.xf_mem[XF_DUAL_TEX_ENABLE] != 0;
- let (s, t, q) = if dual_tex_enabled {
- let post_base = XF_POST_MTX_BASE + dt.post_mtx_idx() as usize * 4;
- // Normalize (s, t, q) only if dt.normalize() is set
- let (ns, nt, nq) = if dt.normalize() {
- let inv_q = if q.abs() > f32::EPSILON { 1.0 / q } else { 1.0 };
- (s * inv_q, t * inv_q, inv_q)
- } else {
- (s, t, q)
- };
- // Post-transform: 3x4 matrix multiply on (ns, nt, nq)
- let ps = self.xf_f32(post_base) * ns
- + self.xf_f32(post_base + 1) * nt
- + self.xf_f32(post_base + 2) * nq
- + self.xf_f32(post_base + 3);
- let pt = self.xf_f32(post_base + 4) * ns
- + self.xf_f32(post_base + 5) * nt
- + self.xf_f32(post_base + 6) * nq
- + self.xf_f32(post_base + 7);
- let pq = self.xf_f32(post_base + 8) * ns
- + self.xf_f32(post_base + 9) * nt
- + self.xf_f32(post_base + 10) * nq
- + self.xf_f32(post_base + 11);
- (ps, pt, pq)
- } else {
- (s, t, q)
- };
-
- // When q is 0, the GameCube has a special case (Dolphin VertexShaderGen.cpp)
- if q.abs() < f32::EPSILON {
- [(s / 2.0).clamp(-1.0, 1.0), (t / 2.0).clamp(-1.0, 1.0)]
- } else {
- [s / q, t / q]
- }
- }
-
- fn xf_f32(&self, reg: usize) -> f32 {
- f32::from_bits(self.xf_mem[reg])
- }
-
- fn xf_vec3(&self, reg: usize) -> Vec3 {
- Vec3(self.xf_f32(reg), self.xf_f32(reg + 1), self.xf_f32(reg + 2))
- }
-
- fn s11_to_f32(val: u16) -> f32 {
- let signed = if val & 0x400 != 0 {
- val as i32 - 0x800
- } else {
- val as i32
- };
- signed as f32 / 255.0
- }
-
- /// Resolve TEV color registers (lo+hi) into [r,g,b,a] float arrays
- fn resolve_tev_orders(&self) -> [regs::TevStageOrder; 16] {
- let mut orders = [regs::TevStageOrder::default(); 16];
- for i in 0..8 {
- let reg = self.cur_tev_orders[i];
- orders[2 * i] = regs::TevStageOrder::default()
- .with_texmap(reg.texmap0())
- .with_texcoord(reg.texcoord0())
- .with_tex_enable(reg.tex_enable0());
- orders[2 * i + 1] = regs::TevStageOrder::default()
- .with_texmap(reg.texmap1())
- .with_texcoord(reg.texcoord1())
- .with_tex_enable(reg.tex_enable1());
- }
- orders
- }
-
- fn resolve_tev_color_regs(&self) -> [[f32; 4]; 4] {
- std::array::from_fn(|i| {
- let lo = self.cur_tev_color_regs_lo[i];
- let hi = self.cur_tev_color_regs_hi[i];
- [
- Self::s11_to_f32(lo.r()),
- Self::s11_to_f32(hi.g()),
- Self::s11_to_f32(hi.b()),
- Self::s11_to_f32(lo.a()),
- ]
- })
- }
-
- /// Resolve per-stage Konst colors from KSEL registers + Konst color registers
- fn resolve_konst_colors(&mut self) {
- let kregs: [[f32; 4]; 4] = std::array::from_fn(|i| {
- let lo = self.cur_tev_const_regs_lo[i];
- let hi = self.cur_tev_const_regs_hi[i];
- [
- Self::s11_to_f32(lo.r()),
- Self::s11_to_f32(hi.g()),
- Self::s11_to_f32(hi.b()),
- Self::s11_to_f32(lo.a()),
- ]
- });
-
- for stage in 0..16usize {
- let ksel_reg = self.bp_regs[BP_TEV_KSEL_0 + stage / 2];
- let (kcsel, kasel) = if stage % 2 == 0 {
- ((ksel_reg >> 4) & 0x1F, (ksel_reg >> 9) & 0x1F)
- } else {
- ((ksel_reg >> 14) & 0x1F, (ksel_reg >> 19) & 0x1F)
- };
-
- let rgb = Self::resolve_kcsel(kcsel, &kregs);
- let a = Self::resolve_kasel(kasel, &kregs);
- self.cur_tev_konst_colors[stage] = [rgb[0], rgb[1], rgb[2], a];
- }
- }
-
- fn resolve_kcsel(sel: u32, kregs: &[[f32; 4]; 4]) -> [f32; 3] {
- match sel {
- 0 => [1.0, 1.0, 1.0], // 1
- 1 => [0.875, 0.875, 0.875], // 7/8
- 2 => [0.75, 0.75, 0.75], // 3/4
- 3 => [0.625, 0.625, 0.625], // 5/8
- 4 => [0.5, 0.5, 0.5], // 1/2
- 5 => [0.375, 0.375, 0.375], // 3/8
- 6 => [0.25, 0.25, 0.25], // 1/4
- 7 => [0.125, 0.125, 0.125], // 1/8
- 12 => [kregs[0][0], kregs[0][1], kregs[0][2]], // K0.RGB
- 13 => [kregs[1][0], kregs[1][1], kregs[1][2]], // K1.RGB
- 14 => [kregs[2][0], kregs[2][1], kregs[2][2]], // K2.RGB
- 15 => [kregs[3][0], kregs[3][1], kregs[3][2]], // K3.RGB
- 16 => [kregs[0][0]; 3], // K0.RRR
- 17 => [kregs[1][0]; 3], // K1.RRR
- 18 => [kregs[2][0]; 3], // K2.RRR
- 19 => [kregs[3][0]; 3], // K3.RRR
- 20 => [kregs[0][1]; 3], // K0.GGG
- 21 => [kregs[1][1]; 3], // K1.GGG
- 22 => [kregs[2][1]; 3], // K2.GGG
- 23 => [kregs[3][1]; 3], // K3.GGG
- 24 => [kregs[0][2]; 3], // K0.BBB
- 25 => [kregs[1][2]; 3], // K1.BBB
- 26 => [kregs[2][2]; 3], // K2.BBB
- 27 => [kregs[3][2]; 3], // K3.BBB
- 28 => [kregs[0][3]; 3], // K0.AAA
- 29 => [kregs[1][3]; 3], // K1.AAA
- 30 => [kregs[2][3]; 3], // K2.AAA
- 31 => [kregs[3][3]; 3], // K3.AAA
- _ => [0.0, 0.0, 0.0],
- }
- }
-
- fn resolve_kasel(sel: u32, kregs: &[[f32; 4]; 4]) -> f32 {
- match sel {
- 0 => 1.0, // 1
- 1 => 0.875, // 7/8
- 2 => 0.75, // 3/4
- 3 => 0.625, // 5/8
- 4 => 0.5, // 1/2
- 5 => 0.375, // 3/8
- 6 => 0.25, // 1/4
- 7 => 0.125, // 1/8
- 16 => kregs[0][0], // K0.R
- 17 => kregs[1][0], // K1.R
- 18 => kregs[2][0], // K2.R
- 19 => kregs[3][0], // K3.R
- 20 => kregs[0][1], // K0.G
- 21 => kregs[1][1], // K1.G
- 22 => kregs[2][1], // K2.G
- 23 => kregs[3][1], // K3.G
- 24 => kregs[0][2], // K0.B
- 25 => kregs[1][2], // K1.B
- 26 => kregs[2][2], // K2.B
- 27 => kregs[3][2], // K3.B
- 28 => kregs[0][3], // K0.A
- 29 => kregs[1][3], // K1.A
- 30 => kregs[2][3], // K2.A
- 31 => kregs[3][3], // K3.A
- _ => 0.0,
- }
- }
-
- fn xf_transform_3x4(&self, base: usize, v: [f32; 3]) -> Vec3 {
- Vec3(
- self.xf_f32(base) * v[0]
- + self.xf_f32(base + 1) * v[1]
- + self.xf_f32(base + 2) * v[2]
- + self.xf_f32(base + 3),
- self.xf_f32(base + 4) * v[0]
- + self.xf_f32(base + 5) * v[1]
- + self.xf_f32(base + 6) * v[2]
- + self.xf_f32(base + 7),
- self.xf_f32(base + 8) * v[0]
- + self.xf_f32(base + 9) * v[1]
- + self.xf_f32(base + 10) * v[2]
- + self.xf_f32(base + 11),
- )
- }
-
- fn rebuild_projection(&mut self) {
- let pm1 = self.xf_f32(XF_PROJECTION_BASE);
- let pm2 = self.xf_f32(XF_PROJECTION_BASE + 1);
- let pm3 = self.xf_f32(XF_PROJECTION_BASE + 2);
- let pm4 = self.xf_f32(XF_PROJECTION_BASE + 3);
- let pm5 = self.xf_f32(XF_PROJECTION_BASE + 4);
- let pm6 = self.xf_f32(XF_PROJECTION_BASE + 5);
- let proj_type = self.xf_mem[XF_PROJECTION_END];
-
- self.draw_commands.projection = if proj_type == 0 {
- // Perspective
- draw::Matrix4([
- [pm1, 0.0, 0.0, 0.0],
- [0.0, pm3, 0.0, 0.0],
- [pm2, pm4, pm5, -1.0],
- [0.0, 0.0, pm6, 0.0],
- ])
- } else {
- // Orthographic
- draw::Matrix4([
- [pm1, 0.0, 0.0, 0.0],
- [0.0, pm3, 0.0, 0.0],
- [0.0, 0.0, pm5, 0.0],
- [pm2, pm4, pm6, 1.0],
- ])
- };
- }
-
- fn load_bp(&mut self, data: &[u8]) {
- let idx = data[0] as usize;
- let val = u32::from_be_bytes([0, data[1], data[2], data[3]]);
- self.bp_regs[idx] = val;
-
- tracing::debug!(
- reg_idx = format!("{idx:02X}"),
- value = format!("{val:08X}"),
- "BP register write"
- );
-
- // TX_SETIMAGE3 is written last for each texture slot, so we use it as
- // the trigger to snapshot the full texture descriptor
- let texture_slot = if idx >= BP_TX_SETIMAGE3_I0 && idx < BP_TX_SETIMAGE3_I0 + 4 {
- Some(idx - BP_TX_SETIMAGE3_I0)
- } else if idx >= BP_TX_SETIMAGE3_I4 && idx < BP_TX_SETIMAGE3_I4 + 4 {
- Some(idx - BP_TX_SETIMAGE3_I4 + 4)
- } else {
- None
- };
-
- if let Some(slot) = texture_slot {
- let image0_reg = if slot < 4 {
- BP_TX_SETIMAGE0_I0 + slot
- } else {
- BP_TX_SETIMAGE0_I4 + (slot - 4)
- };
-
- let image0 = TxSetImage0::from_raw(self.bp_regs[image0_reg]);
- let image3 = TxSetImage3::from_raw(val);
-
- let mode0_reg = if slot < 4 {
- BP_TX_SETMODE0_I0 + slot
- } else {
- BP_TX_SETMODE0_I4 + (slot - 4)
- };
- let mode0 = TxSetMode0::from_raw(self.bp_regs[mode0_reg]);
-
- let width = image0.width() + 1;
- let height = image0.height() + 1;
- let ram_addr = image3.ram_addr();
-
- tracing::debug!(
- slot,
- width,
- height,
- format = format!("{:?}", image0.format()),
- ram_addr = format!("{ram_addr:#010X}"),
- wrap_s = format!("{:?}", mode0.wrap_s()),
- wrap_t = format!("{:?}", mode0.wrap_t()),
- "texture descriptor updated"
- );
-
- self.cur_textures[slot] = Some(draw::TextureDescriptor {
- ram_addr,
- width: width as u32,
- height: height as u32,
- format: image0.format(),
- wrap_s: mode0.wrap_s(),
- wrap_t: mode0.wrap_t(),
- mag_filter: mode0.mag_filter(),
- min_filter: mode0.min_filter(),
- });
- }
-
- // Forward PE render state
- match idx {
- BP_PE_ZMODE => self.cur_zmode = ZMode::from_raw(val),
- BP_PE_CMODE0 => self.cur_blend_mode = BlendMode::from_raw(val),
- BP_PE_ALPHA_COMPARE => self.cur_alpha_compare = AlphaCompare::from_raw(val),
- _ => {}
- }
-
- // TEV color/alpha environment registers (0xC0-0xDF)
- // Even addresses = color env, odd = alpha env
- if idx >= BP_TEV_COLOR_ENV_0 && idx < BP_TEV_COLOR_ENV_0 + 32 {
- let stage = (idx - BP_TEV_COLOR_ENV_0) / 2;
- if idx % 2 == 0 {
- let env = TevColorEnv::from_raw(val);
- tracing::debug!(
- stage,
- a = format!("{:?}", env.a()),
- b = format!("{:?}", env.b()),
- c = format!("{:?}", env.c()),
- d = format!("{:?}", env.d()),
- bias = format!("{:?}", env.bias()),
- sub = env.sub(),
- scale = format!("{:?}", env.scale()),
- dest = format!("{:?}", env.dest()),
- "TEV color env"
- );
- self.cur_tev_color_env[stage] = env;
- } else {
- let env = TevAlphaEnv::from_raw(val);
- tracing::debug!(
- stage,
- a = format!("{:?}", env.a()),
- b = format!("{:?}", env.b()),
- c = format!("{:?}", env.c()),
- d = format!("{:?}", env.d()),
- bias = format!("{:?}", env.bias()),
- sub = env.sub(),
- scale = format!("{:?}", env.scale()),
- dest = format!("{:?}", env.dest()),
- "TEV alpha env"
- );
- self.cur_tev_alpha_env[stage] = env;
- }
- }
-
- // TEV rasterizer order registers (RAS1_TREF0-7, 0x28-0x2F)
- if idx >= BP_RAS1_TREF0 && idx < BP_RAS1_TREF0 + BP_RAS1_TREF_COUNT {
- self.cur_tev_orders[idx - BP_RAS1_TREF0] = regs::TevOrder::from_raw(val);
- }
-
- // TEV color registers (0xE0-0xE7): pairs of lo/hi writes
- if idx >= BP_TEV_REGISTERL_0 && idx <= BP_TEV_REGISTERL_0 + 7 {
- let reg_idx = (idx - BP_TEV_REGISTERL_0) / 2;
- if idx % 2 == 0 {
- let reg = TevRegisterL::from_raw(val);
- tracing::debug!(
- reg_idx,
- r = reg.r(),
- a = reg.a(),
- reg_type = format!("{:?}", reg.reg_type()),
- "TEV register lo"
- );
- match reg.reg_type() {
- TevRegType::Color => self.cur_tev_color_regs_lo[reg_idx] = reg,
- TevRegType::Constant => self.cur_tev_const_regs_lo[reg_idx] = reg,
- }
- } else {
- let reg = TevRegisterH::from_raw(val);
- tracing::debug!(
- reg_idx,
- g = reg.g(),
- b = reg.b(),
- reg_type = format!("{:?}", reg.reg_type()),
- "TEV register hi"
- );
- match reg.reg_type() {
- TevRegType::Color => self.cur_tev_color_regs_hi[reg_idx] = reg,
- TevRegType::Constant => self.cur_tev_const_regs_hi[reg_idx] = reg,
- }
- }
- }
-
- // GEN_MODE, extract num TEV stages
- if idx == BP_GEN_MODE {
- let gen_mode = GenMode::from_raw(val);
- let stages = gen_mode.num_tev_stages() + 1;
- tracing::debug!(num_tev_stages = stages, "GEN_MODE");
- self.cur_num_tev_stages = stages;
- self.resolve_konst_colors();
- }
-
- // PE finish
- if idx == BP_PE_DONE && (val & BP_PE_DONE_FINISH_BIT) != 0 {
- self.raise_interrupt = true;
- }
- }
-
- fn load_cp(&mut self, data: &[u8]) {
- let idx = data[0] as usize;
- let val = u32::from_be_bytes([data[1], data[2], data[3], data[4]]);
- self.cp_regs[idx] = val;
-
- tracing::debug!(
- reg_idx = format!("{idx:02X}"),
- value = format!("{val:08X}"),
- "CP register write"
- );
- }
-
- fn load_xf(&mut self, data: &[u8]) {
- let length = u16::from_be_bytes([data[0], data[1]]) as usize;
- let addr = u16::from_be_bytes([data[2], data[3]]) as usize;
- let n = length + 1;
- let end = addr + n;
-
- for i in 0..n {
- let offset = 4 + i * 4;
- let val = u32::from_be_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
- let reg = addr + i;
- if reg < self.xf_mem.len() {
- self.xf_mem[reg] = val;
- }
-
- tracing::debug!(
- reg_idx = format!("{reg:04X}"),
- value = format!("{val:08X}"),
- "XF register write"
- );
- }
-
- // Rebuild projection if the write touched its address range
- // (modelview is resolved lazily at draw call time from the current position matrix slot)
- if addr <= XF_PROJECTION_END && end > XF_PROJECTION_BASE {
- self.rebuild_projection();
- }
- }
-}
-
-fn read_index(cur: &mut Cursor<&Vec<u8>>, attr: regs::AttributeType) -> usize {
- match attr {
- regs::AttributeType::Index8 => {
- let mut buf = [0u8; 1];
- cur.read_exact(&mut buf).unwrap();
- buf[0] as usize
- }
- regs::AttributeType::Index16 => {
- let mut buf = [0u8; 2];
- cur.read_exact(&mut buf).unwrap();
- u16::from_be_bytes(buf) as usize
- }
- _ => 0,
- }
}
impl GameCube {
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
new file mode 100644
index 0000000..9f2c20a
--- /dev/null
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -0,0 +1,189 @@
+use super::{
+ GraphicsProcessor,
+ constants::{
+ BP_GEN_MODE, BP_PE_ALPHA_COMPARE, BP_PE_CMODE0, BP_PE_DONE, BP_PE_DONE_FINISH_BIT, BP_PE_ZMODE,
+ BP_RAS1_TREF_COUNT, BP_RAS1_TREF0, BP_TEV_COLOR_ENV_0, BP_TEV_REGISTERL_0, BP_TX_SETIMAGE0_I0,
+ BP_TX_SETIMAGE0_I4, BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4,
+ },
+ draw,
+ regs::{
+ AlphaCompare, BlendMode, GenMode, TevAlphaEnv, TevColorEnv, TevOrder, TevRegType, TevRegisterH, TevRegisterL,
+ TxSetImage0, TxSetImage3, TxSetMode0, ZMode,
+ },
+};
+
+impl GraphicsProcessor {
+ pub(crate) fn load_bp(&mut self, data: &[u8]) {
+ let idx = data[0] as usize;
+ let val = u32::from_be_bytes([0, data[1], data[2], data[3]]);
+ self.bp_regs[idx] = val;
+
+ tracing::debug!(
+ reg_idx = format!("{idx:02X}"),
+ value = format!("{val:08X}"),
+ "BP register write"
+ );
+
+ // TX_SETIMAGE3 is written last for each texture slot, so we use it as
+ // the trigger to snapshot the full texture descriptor
+ let texture_slot = if idx >= BP_TX_SETIMAGE3_I0 && idx < BP_TX_SETIMAGE3_I0 + 4 {
+ Some(idx - BP_TX_SETIMAGE3_I0)
+ } else if idx >= BP_TX_SETIMAGE3_I4 && idx < BP_TX_SETIMAGE3_I4 + 4 {
+ Some(idx - BP_TX_SETIMAGE3_I4 + 4)
+ } else {
+ None
+ };
+
+ if let Some(slot) = texture_slot {
+ self.snapshot_texture(slot, val);
+ }
+
+ // Forward PE render state
+ match idx {
+ BP_PE_ZMODE => self.cur_zmode = ZMode::from_raw(val),
+ BP_PE_CMODE0 => self.cur_blend_mode = BlendMode::from_raw(val),
+ BP_PE_ALPHA_COMPARE => self.cur_alpha_compare = AlphaCompare::from_raw(val),
+ _ => {}
+ }
+
+ // TEV color/alpha environment registers (0xC0-0xDF)
+ // Even addresses = color env, odd = alpha env
+ if idx >= BP_TEV_COLOR_ENV_0 && idx < BP_TEV_COLOR_ENV_0 + 32 {
+ self.load_tev_env(idx, val);
+ }
+
+ // TEV rasterizer order registers (RAS1_TREF0-7, 0x28-0x2F)
+ if idx >= BP_RAS1_TREF0 && idx < BP_RAS1_TREF0 + BP_RAS1_TREF_COUNT {
+ self.cur_tev_orders[idx - BP_RAS1_TREF0] = TevOrder::from_raw(val);
+ }
+
+ // TEV color registers (0xE0-0xE7): pairs of lo/hi writes
+ if idx >= BP_TEV_REGISTERL_0 && idx <= BP_TEV_REGISTERL_0 + 7 {
+ self.load_tev_register(idx, val);
+ }
+
+ // GEN_MODE, extract num TEV stages
+ if idx == BP_GEN_MODE {
+ let gen_mode = GenMode::from_raw(val);
+ let stages = gen_mode.num_tev_stages() + 1;
+ tracing::debug!(num_tev_stages = stages, "GEN_MODE");
+ self.cur_num_tev_stages = stages;
+ self.resolve_konst_colors();
+ }
+
+ // PE finish
+ if idx == BP_PE_DONE && (val & BP_PE_DONE_FINISH_BIT) != 0 {
+ self.raise_interrupt = true;
+ }
+ }
+
+ fn snapshot_texture(&mut self, slot: usize, image3_val: u32) {
+ let image0_reg = if slot < 4 {
+ BP_TX_SETIMAGE0_I0 + slot
+ } else {
+ BP_TX_SETIMAGE0_I4 + (slot - 4)
+ };
+
+ let image0 = TxSetImage0::from_raw(self.bp_regs[image0_reg]);
+ let image3 = TxSetImage3::from_raw(image3_val);
+
+ let mode0_reg = if slot < 4 {
+ BP_TX_SETMODE0_I0 + slot
+ } else {
+ BP_TX_SETMODE0_I4 + (slot - 4)
+ };
+ let mode0 = TxSetMode0::from_raw(self.bp_regs[mode0_reg]);
+
+ let width = image0.width() + 1;
+ let height = image0.height() + 1;
+ let ram_addr = image3.ram_addr();
+
+ tracing::debug!(
+ slot,
+ width,
+ height,
+ format = format!("{:?}", image0.format()),
+ ram_addr = format!("{ram_addr:#010X}"),
+ wrap_s = format!("{:?}", mode0.wrap_s()),
+ wrap_t = format!("{:?}", mode0.wrap_t()),
+ "texture descriptor updated"
+ );
+
+ self.cur_textures[slot] = Some(draw::TextureDescriptor {
+ ram_addr,
+ width: width as u32,
+ height: height as u32,
+ format: image0.format(),
+ wrap_s: mode0.wrap_s(),
+ wrap_t: mode0.wrap_t(),
+ mag_filter: mode0.mag_filter(),
+ min_filter: mode0.min_filter(),
+ });
+ }
+
+ fn load_tev_env(&mut self, idx: usize, val: u32) {
+ let stage = (idx - BP_TEV_COLOR_ENV_0) / 2;
+ if idx % 2 == 0 {
+ let env = TevColorEnv::from_raw(val);
+ tracing::debug!(
+ stage,
+ a = format!("{:?}", env.a()),
+ b = format!("{:?}", env.b()),
+ c = format!("{:?}", env.c()),
+ d = format!("{:?}", env.d()),
+ bias = format!("{:?}", env.bias()),
+ sub = env.sub(),
+ scale = format!("{:?}", env.scale()),
+ dest = format!("{:?}", env.dest()),
+ "TEV color env"
+ );
+ self.cur_tev_color_env[stage] = env;
+ } else {
+ let env = TevAlphaEnv::from_raw(val);
+ tracing::debug!(
+ stage,
+ a = format!("{:?}", env.a()),
+ b = format!("{:?}", env.b()),
+ c = format!("{:?}", env.c()),
+ d = format!("{:?}", env.d()),
+ bias = format!("{:?}", env.bias()),
+ sub = env.sub(),
+ scale = format!("{:?}", env.scale()),
+ dest = format!("{:?}", env.dest()),
+ "TEV alpha env"
+ );
+ self.cur_tev_alpha_env[stage] = env;
+ }
+ }
+
+ fn load_tev_register(&mut self, idx: usize, val: u32) {
+ let reg_idx = (idx - BP_TEV_REGISTERL_0) / 2;
+ if idx % 2 == 0 {
+ let reg = TevRegisterL::from_raw(val);
+ tracing::debug!(
+ reg_idx,
+ r = reg.r(),
+ a = reg.a(),
+ reg_type = format!("{:?}", reg.reg_type()),
+ "TEV register lo"
+ );
+ match reg.reg_type() {
+ TevRegType::Color => self.cur_tev_color_regs_lo[reg_idx] = reg,
+ TevRegType::Constant => self.cur_tev_const_regs_lo[reg_idx] = reg,
+ }
+ } else {
+ let reg = TevRegisterH::from_raw(val);
+ tracing::debug!(
+ reg_idx,
+ g = reg.g(),
+ b = reg.b(),
+ reg_type = format!("{:?}", reg.reg_type()),
+ "TEV register hi"
+ );
+ match reg.reg_type() {
+ TevRegType::Color => self.cur_tev_color_regs_hi[reg_idx] = reg,
+ TevRegType::Constant => self.cur_tev_const_regs_hi[reg_idx] = reg,
+ }
+ }
+ }
+}
diff --git a/crates/gecko/src/flipper/gx/draw.rs b/crates/gecko/src/flipper/gx/draw.rs
index 5a389ce..d66d896 100644
--- a/crates/gecko/src/flipper/gx/draw.rs
+++ b/crates/gecko/src/flipper/gx/draw.rs
@@ -1,4 +1,6 @@
-use super::regs::{AlphaCompare, BlendMode, MagFilter, MinFilter, TevAlphaEnv, TevColorEnv, TevStageOrder, WrapMode, ZMode};
+use super::regs::{
+ AlphaCompare, BlendMode, MagFilter, MinFilter, TevAlphaEnv, TevColorEnv, TevStageOrder, WrapMode, ZMode,
+};
use chapa::BitEnum;
#[derive(Debug)]
diff --git a/crates/gecko/src/flipper/gx/lighting.rs b/crates/gecko/src/flipper/gx/lighting.rs
new file mode 100644
index 0000000..3d50daa
--- /dev/null
+++ b/crates/gecko/src/flipper/gx/lighting.rs
@@ -0,0 +1,137 @@
+use super::{
+ GraphicsProcessor,
+ constants::{XF_LIGHT_A0, XF_LIGHT_BASE, XF_LIGHT_COLOR, XF_LIGHT_K0, XF_LIGHT_NX, XF_LIGHT_PX, XF_LIGHT_STRIDE},
+ math::{Vec3, saturating_div, unpack_rgba},
+ regs::{AttnFn, ChanCtrl},
+};
+
+impl GraphicsProcessor {
+ pub(crate) fn compute_channel_lighting(
+ &self,
+ color_ctrl: &ChanCtrl,
+ alpha_ctrl: &ChanCtrl,
+ ambient_reg: [f32; 4],
+ material_reg: [f32; 4],
+ vertex_color: [f32; 4],
+ normal: Vec3,
+ pos: Vec3,
+ ) -> [f32; 4] {
+ let mat_rgb: [f32; 3] = if color_ctrl.mat_src() {
+ [vertex_color[0], vertex_color[1], vertex_color[2]]
+ } else {
+ [material_reg[0], material_reg[1], material_reg[2]]
+ };
+ let amb_rgb: [f32; 3] = if color_ctrl.amb_src() {
+ [vertex_color[0], vertex_color[1], vertex_color[2]]
+ } else {
+ [ambient_reg[0], ambient_reg[1], ambient_reg[2]]
+ };
+
+ let mat_a = if alpha_ctrl.mat_src() {
+ vertex_color[3]
+ } else {
+ material_reg[3]
+ };
+ let amb_a = if alpha_ctrl.amb_src() {
+ vertex_color[3]
+ } else {
+ ambient_reg[3]
+ };
+
+ // When lighting is disabled, return material color directly
+ let color_lit_off = !color_ctrl.enable();
+ let alpha_lit_off = !alpha_ctrl.enable();
+ if color_lit_off && alpha_lit_off {
+ return [mat_rgb[0], mat_rgb[1], mat_rgb[2], mat_a];
+ }
+
+ // Compute RGB lighting accumulator
+ let mut rgb_out = mat_rgb;
+ if !color_lit_off {
+ let light_mask = color_ctrl.light_mask();
+ let mut acc = amb_rgb;
+ for light_id in 0..8u32 {
+ if (light_mask >> light_id) & 1 == 0 {
+ continue;
+ }
+ let base = XF_LIGHT_BASE + (light_id as usize) * XF_LIGHT_STRIDE;
+ let light_color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);
+ let factor = self.compute_light_factor(color_ctrl, base, normal, pos);
+ acc[0] += light_color[0] * factor;
+ acc[1] += light_color[1] * factor;
+ acc[2] += light_color[2] * factor;
+ }
+ rgb_out = std::array::from_fn(|i| mat_rgb[i] * acc[i].clamp(0.0, 1.0));
+ }
+
+ // Compute Alpha lighting accumulator
+ let mut a_out = mat_a;
+ if !alpha_lit_off {
+ let light_mask = alpha_ctrl.light_mask();
+ let mut acc_a = amb_a;
+ for light_id in 0..8u32 {
+ if (light_mask >> light_id) & 1 == 0 {
+ continue;
+ }
+ let base = XF_LIGHT_BASE + (light_id as usize) * XF_LIGHT_STRIDE;
+ let light_color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);
+ let factor = self.compute_light_factor(alpha_ctrl, base, normal, pos);
+ acc_a += light_color[3] * factor;
+ }
+ a_out = mat_a * acc_a.clamp(0.0, 1.0);
+ }
+
+ [rgb_out[0], rgb_out[1], rgb_out[2], a_out]
+ }
+
+ fn compute_light_factor(&self, ctrl: &ChanCtrl, base: usize, normal: Vec3, pos: Vec3) -> f32 {
+ let cosatt = self.xf_vec3(base + XF_LIGHT_A0);
+ let distatt = self.xf_vec3(base + XF_LIGHT_K0);
+ let light_pos = self.xf_vec3(base + XF_LIGHT_PX);
+ let light_dir = self.xf_vec3(base + XF_LIGHT_NX);
+
+ // ldir starts as light_pos - vertex_pos for all modes
+ // In Spot mode, light_pos is a world position
+ // In Spec mode, light_pos is repurposed as the half-angle direction vector
+ let mut ldir = light_pos - pos;
+
+ let attn = match ctrl.attn_fn() {
+ AttnFn::None => {
+ ldir = ldir.normalize();
+ 1.0
+ }
+ AttnFn::Spot => {
+ let dist = ldir.length();
+ ldir = ldir.normalize();
+ let cos_angle = light_dir.dot(ldir);
+ let angle_attn = (cosatt.0 + cosatt.1 * cos_angle + cosatt.2 * cos_angle * cos_angle).max(0.0);
+ saturating_div(angle_attn, distatt.0 + distatt.1 * dist + distatt.2 * dist * dist)
+ }
+ AttnFn::Spec => {
+ ldir = ldir.normalize();
+ let half_dot = ldir.dot(normal);
+ if half_dot < 0.0 {
+ return 0.0;
+ }
+ let s = normal.dot(light_dir).max(0.0);
+ let att_len = Vec3(1.0, s, s * s);
+ let da = if ctrl.diff_fn() != super::regs::DiffuseFn::None {
+ distatt.normalize()
+ } else {
+ distatt
+ };
+ saturating_div(att_len.dot(cosatt).max(0.0), att_len.dot(da))
+ }
+ };
+
+ // Diffuse is computed from ldir dotted with normal
+ let dif_attn = ldir.dot(normal);
+ let diffuse = match ctrl.diff_fn() {
+ super::regs::DiffuseFn::None => 1.0,
+ super::regs::DiffuseFn::Signed => dif_attn,
+ super::regs::DiffuseFn::Clamp => dif_attn.max(0.0),
+ };
+
+ attn * diffuse
+ }
+}
diff --git a/crates/gecko/src/flipper/gx/tev.rs b/crates/gecko/src/flipper/gx/tev.rs
new file mode 100644
index 0000000..ab5e5a9
--- /dev/null
+++ b/crates/gecko/src/flipper/gx/tev.rs
@@ -0,0 +1,131 @@
+use super::{GraphicsProcessor, constants::BP_TEV_KSEL_0, regs::TevStageOrder};
+
+impl GraphicsProcessor {
+ pub(crate) fn resolve_tev_orders(&self) -> [TevStageOrder; 16] {
+ let mut orders = [TevStageOrder::default(); 16];
+ for i in 0..8 {
+ let reg = self.cur_tev_orders[i];
+ orders[2 * i] = TevStageOrder::default()
+ .with_texmap(reg.texmap0())
+ .with_texcoord(reg.texcoord0())
+ .with_tex_enable(reg.tex_enable0());
+ orders[2 * i + 1] = TevStageOrder::default()
+ .with_texmap(reg.texmap1())
+ .with_texcoord(reg.texcoord1())
+ .with_tex_enable(reg.tex_enable1());
+ }
+ orders
+ }
+
+ pub(crate) fn resolve_tev_color_regs(&self) -> [[f32; 4]; 4] {
+ std::array::from_fn(|i| {
+ let lo = self.cur_tev_color_regs_lo[i];
+ let hi = self.cur_tev_color_regs_hi[i];
+ [
+ s11_to_f32(lo.r()),
+ s11_to_f32(hi.g()),
+ s11_to_f32(hi.b()),
+ s11_to_f32(lo.a()),
+ ]
+ })
+ }
+
+ pub(crate) fn resolve_konst_colors(&mut self) {
+ let kregs: [[f32; 4]; 4] = std::array::from_fn(|i| {
+ let lo = self.cur_tev_const_regs_lo[i];
+ let hi = self.cur_tev_const_regs_hi[i];
+ [
+ s11_to_f32(lo.r()),
+ s11_to_f32(hi.g()),
+ s11_to_f32(hi.b()),
+ s11_to_f32(lo.a()),
+ ]
+ });
+
+ for stage in 0..16usize {
+ let ksel_reg = self.bp_regs[BP_TEV_KSEL_0 + stage / 2];
+ let (kcsel, kasel) = if stage % 2 == 0 {
+ ((ksel_reg >> 4) & 0x1F, (ksel_reg >> 9) & 0x1F)
+ } else {
+ ((ksel_reg >> 14) & 0x1F, (ksel_reg >> 19) & 0x1F)
+ };
+
+ let rgb = resolve_kcsel(kcsel, &kregs);
+ let a = resolve_kasel(kasel, &kregs);
+ self.cur_tev_konst_colors[stage] = [rgb[0], rgb[1], rgb[2], a];
+ }
+ }
+}
+
+pub(crate) fn s11_to_f32(val: u16) -> f32 {
+ let signed = if val & 0x400 != 0 {
+ val as i32 - 0x800
+ } else {
+ val as i32
+ };
+ signed as f32 / 255.0
+}
+
+fn resolve_kcsel(sel: u32, kregs: &[[f32; 4]; 4]) -> [f32; 3] {
+ match sel {
+ 0 => [1.0, 1.0, 1.0], // 1
+ 1 => [0.875, 0.875, 0.875], // 7/8
+ 2 => [0.75, 0.75, 0.75], // 3/4
+ 3 => [0.625, 0.625, 0.625], // 5/8
+ 4 => [0.5, 0.5, 0.5], // 1/2
+ 5 => [0.375, 0.375, 0.375], // 3/8
+ 6 => [0.25, 0.25, 0.25], // 1/4
+ 7 => [0.125, 0.125, 0.125], // 1/8
+ 12 => [kregs[0][0], kregs[0][1], kregs[0][2]], // K0.RGB
+ 13 => [kregs[1][0], kregs[1][1], kregs[1][2]], // K1.RGB
+ 14 => [kregs[2][0], kregs[2][1], kregs[2][2]], // K2.RGB
+ 15 => [kregs[3][0], kregs[3][1], kregs[3][2]], // K3.RGB
+ 16 => [kregs[0][0]; 3], // K0.RRR
+ 17 => [kregs[1][0]; 3], // K1.RRR
+ 18 => [kregs[2][0]; 3], // K2.RRR
+ 19 => [kregs[3][0]; 3], // K3.RRR
+ 20 => [kregs[0][1]; 3], // K0.GGG
+ 21 => [kregs[1][1]; 3], // K1.GGG
+ 22 => [kregs[2][1]; 3], // K2.GGG
+ 23 => [kregs[3][1]; 3], // K3.GGG
+ 24 => [kregs[0][2]; 3], // K0.BBB
+ 25 => [kregs[1][2]; 3], // K1.BBB
+ 26 => [kregs[2][2]; 3], // K2.BBB
+ 27 => [kregs[3][2]; 3], // K3.BBB
+ 28 => [kregs[0][3]; 3], // K0.AAA
+ 29 => [kregs[1][3]; 3], // K1.AAA
+ 30 => [kregs[2][3]; 3], // K2.AAA
+ 31 => [kregs[3][3]; 3], // K3.AAA
+ _ => [0.0, 0.0, 0.0],
+ }
+}
+
+fn resolve_kasel(sel: u32, kregs: &[[f32; 4]; 4]) -> f32 {
+ match sel {
+ 0 => 1.0, // 1
+ 1 => 0.875, // 7/8
+ 2 => 0.75, // 3/4
+ 3 => 0.625, // 5/8
+ 4 => 0.5, // 1/2
+ 5 => 0.375, // 3/8
+ 6 => 0.25, // 1/4
+ 7 => 0.125, // 1/8
+ 16 => kregs[0][0], // K0.R
+ 17 => kregs[1][0], // K1.R
+ 18 => kregs[2][0], // K2.R
+ 19 => kregs[3][0], // K3.R
+ 20 => kregs[0][1], // K0.G
+ 21 => kregs[1][1], // K1.G
+ 22 => kregs[2][1], // K2.G
+ 23 => kregs[3][1], // K3.G
+ 24 => kregs[0][2], // K0.B
+ 25 => kregs[1][2], // K1.B
+ 26 => kregs[2][2], // K2.B
+ 27 => kregs[3][2], // K3.B
+ 28 => kregs[0][3], // K0.A
+ 29 => kregs[1][3], // K1.A
+ 30 => kregs[2][3], // K2.A
+ 31 => kregs[3][3], // K3.A
+ _ => 0.0,
+ }
+}
diff --git a/crates/gecko/src/flipper/gx/texgen.rs b/crates/gecko/src/flipper/gx/texgen.rs
new file mode 100644
index 0000000..e07903b
--- /dev/null
+++ b/crates/gecko/src/flipper/gx/texgen.rs
@@ -0,0 +1,163 @@
+use super::{
+ GraphicsProcessor,
+ constants::{
+ XF_DUAL_TEX_ENABLE, XF_DUALTEX_BASE, XF_MATRIX_INDEX_A, XF_MATRIX_INDEX_B, XF_POS_MTX_STRIDE, XF_POST_MTX_BASE,
+ XF_TEXGEN_BASE,
+ },
+ regs::{DualTexGenReg, MatrixIndex0, MatrixIndex1, TexGenReg},
+};
+
+impl GraphicsProcessor {
+ pub(crate) fn compute_texgen(
+ &self,
+ texgen_idx: usize,
+ position: [f32; 3],
+ normal: [f32; 3],
+ raw_texcoords: &[Option<[f32; 2]>; 8],
+ ) -> [f32; 2] {
+ let tg = TexGenReg::from_raw(self.xf_mem[XF_TEXGEN_BASE + texgen_idx]);
+ let dt = DualTexGenReg::from_raw(self.xf_mem[XF_DUALTEX_BASE + texgen_idx]);
+
+ // Select the source input vector based on texgen source_row
+ let src = self.select_texgen_source(&tg, position, normal, raw_texcoords);
+
+ // Form input vector based on input_form
+ let input = match tg.input_form() {
+ super::regs::TexGenInputForm::Ab11 => [src[0], src[1], 1.0, 1.0],
+ super::regs::TexGenInputForm::Abc1 => [src[0], src[1], src[2], 1.0],
+ };
+
+ // Texture matrix base from MatrixIndex register
+ let tex_mtx_idx = if texgen_idx < 4 {
+ let mtx_index_a = MatrixIndex0::from_raw(self.xf_mem[XF_MATRIX_INDEX_A]);
+ mtx_index_a.tex_mtx_idx(texgen_idx) as usize
+ } else {
+ let mtx_index_b = MatrixIndex1::from_raw(self.xf_mem[XF_MATRIX_INDEX_B]);
+ mtx_index_b.tex_mtx_idx(texgen_idx) as usize
+ };
+ let tex_mtx_base = tex_mtx_idx * XF_POS_MTX_STRIDE;
+
+ // Multiply input by texture matrix (2x4 or 3x4 depending on projection)
+ let (s, t, q) = self.apply_tex_matrix(&tg, tex_mtx_base, &input);
+
+ // Dual texgen post-transform (normalization + post-matrix multiply)
+ let (s, t, q) = self.apply_dual_texgen(s, t, q, &dt);
+
+ // When q is 0, the GameCube has a special case (Dolphin VertexShaderGen.cpp)
+ if q.abs() < f32::EPSILON {
+ [(s / 2.0).clamp(-1.0, 1.0), (t / 2.0).clamp(-1.0, 1.0)]
+ } else {
+ [s / q, t / q]
+ }
+ }
+
+ fn select_texgen_source(
+ &self,
+ tg: &TexGenReg,
+ position: [f32; 3],
+ normal: [f32; 3],
+ raw_texcoords: &[Option<[f32; 2]>; 8],
+ ) -> [f32; 3] {
+ match tg.source_row() {
+ super::regs::TexGenSrc::Pos => position,
+ super::regs::TexGenSrc::Nrm => normal,
+ super::regs::TexGenSrc::Tex0 => {
+ let t = raw_texcoords[0].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ super::regs::TexGenSrc::Tex1 => {
+ let t = raw_texcoords[1].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ super::regs::TexGenSrc::Tex2 => {
+ let t = raw_texcoords[2].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ super::regs::TexGenSrc::Tex3 => {
+ let t = raw_texcoords[3].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ super::regs::TexGenSrc::Tex4 => {
+ let t = raw_texcoords[4].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ super::regs::TexGenSrc::Tex5 => {
+ let t = raw_texcoords[5].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ super::regs::TexGenSrc::Tex6 => {
+ let t = raw_texcoords[6].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ super::regs::TexGenSrc::Tex7 => {
+ let t = raw_texcoords[7].unwrap_or([0.0, 0.0]);
+ [t[0], t[1], 1.0]
+ }
+ // TODO: ???
+ _ => [0.0, 0.0, 1.0],
+ }
+ }
+
+ fn apply_tex_matrix(&self, tg: &TexGenReg, tex_mtx_base: usize, input: &[f32; 4]) -> (f32, f32, f32) {
+ match tg.projection() {
+ super::regs::TexGenProjection::St => {
+ // 2x4 matrix -> (s, t)
+ let s = self.xf_f32(tex_mtx_base) * input[0]
+ + self.xf_f32(tex_mtx_base + 1) * input[1]
+ + self.xf_f32(tex_mtx_base + 2) * input[2]
+ + self.xf_f32(tex_mtx_base + 3) * input[3];
+ let t = self.xf_f32(tex_mtx_base + 4) * input[0]
+ + self.xf_f32(tex_mtx_base + 5) * input[1]
+ + self.xf_f32(tex_mtx_base + 6) * input[2]
+ + self.xf_f32(tex_mtx_base + 7) * input[3];
+ (s, t, 1.0)
+ }
+ super::regs::TexGenProjection::Stq => {
+ // 3x4 matrix -> (s, t, q)
+ let s = self.xf_f32(tex_mtx_base) * input[0]
+ + self.xf_f32(tex_mtx_base + 1) * input[1]
+ + self.xf_f32(tex_mtx_base + 2) * input[2]
+ + self.xf_f32(tex_mtx_base + 3) * input[3];
+ let t = self.xf_f32(tex_mtx_base + 4) * input[0]
+ + self.xf_f32(tex_mtx_base + 5) * input[1]
+ + self.xf_f32(tex_mtx_base + 6) * input[2]
+ + self.xf_f32(tex_mtx_base + 7) * input[3];
+ let q = self.xf_f32(tex_mtx_base + 8) * input[0]
+ + self.xf_f32(tex_mtx_base + 9) * input[1]
+ + self.xf_f32(tex_mtx_base + 10) * input[2]
+ + self.xf_f32(tex_mtx_base + 11) * input[3];
+ (s, t, q)
+ }
+ }
+ }
+
+ fn apply_dual_texgen(&self, s: f32, t: f32, q: f32, dt: &DualTexGenReg) -> (f32, f32, f32) {
+ let dual_tex_enabled = self.xf_mem[XF_DUAL_TEX_ENABLE] != 0;
+ if !dual_tex_enabled {
+ return (s, t, q);
+ }
+
+ let post_base = XF_POST_MTX_BASE + dt.post_mtx_idx() as usize * 4;
+ // Normalize (s, t, q) only if dt.normalize() is set
+ let (ns, nt, nq) = if dt.normalize() {
+ let inv_q = if q.abs() > f32::EPSILON { 1.0 / q } else { 1.0 };
+ (s * inv_q, t * inv_q, inv_q)
+ } else {
+ (s, t, q)
+ };
+ // Post-transform: 3x4 matrix multiply on (ns, nt, nq)
+ let ps = self.xf_f32(post_base) * ns
+ + self.xf_f32(post_base + 1) * nt
+ + self.xf_f32(post_base + 2) * nq
+ + self.xf_f32(post_base + 3);
+ let pt = self.xf_f32(post_base + 4) * ns
+ + self.xf_f32(post_base + 5) * nt
+ + self.xf_f32(post_base + 6) * nq
+ + self.xf_f32(post_base + 7);
+ let pq = self.xf_f32(post_base + 8) * ns
+ + self.xf_f32(post_base + 9) * nt
+ + self.xf_f32(post_base + 10) * nq
+ + self.xf_f32(post_base + 11);
+ (ps, pt, pq)
+ }
+}
diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rs
new file mode 100644
index 0000000..6bc2e93
--- /dev/null
+++ b/crates/gecko/src/flipper/gx/vertex.rs
@@ -0,0 +1,610 @@
+use super::{
+ GraphicsProcessor,
+ constants::{
+ ARRAY_BASE_REG, ARRAY_CLR0, ARRAY_NRM, ARRAY_POS, ARRAY_STRIDE_REG, ARRAY_TEX0, VATA_REG, VATB_REG, VATC_REG,
+ VCD_HI_REG, VCD_LO_REG, XF_ALPHA_CTRL0, XF_AMBIENT_COLOR0, XF_COLOR_CTRL0, XF_MATERIAL_COLOR0,
+ XF_MATRIX_INDEX_A, XF_NRM_MTX_BASE, XF_NUM_TEXGENS, XF_POS_MTX_STRIDE,
+ },
+ draw,
+ math::{Vec3, unpack_rgba},
+ regs::{self, AttributeType, ChanCtrl, ComponentFormat, MatrixIndex0, TexCount, VatA, VatB, VatC, VcdHi, VcdLo},
+};
+use crate::mmio::Mmio;
+use std::io::{Cursor, Read};
+
+/// Parsed vertex format descriptor from CP/VAT registers.
+struct VertexFormat {
+ vat_a: VatA,
+ pos_base: usize,
+ pos_stride: usize,
+ pos_data_size: usize,
+ clr0_base: usize,
+ clr0_stride: usize,
+ clr0_data_size: usize,
+ nrm_base_addr: usize,
+ nrm_stride: usize,
+ nrm_data_size: usize,
+ tex_attrs: [AttributeType; 8],
+ tex_data_sizes: [usize; 8],
+ tex_fmts: [ComponentFormat; 8],
+ tex_shifts: [u8; 8],
+ tex_cnts: [TexCount; 8],
+ tex_bases: [usize; 8],
+ tex_strides: [usize; 8],
+ vertex_stride: usize,
+ has_pnmtxidx: bool,
+ tex_mtx_idx_size: usize,
+ default_pos_mtx_idx: u8,
+ pos_attr: AttributeType,
+ nrm_attr: AttributeType,
+ clr0_attr: AttributeType,
+ clr1_stream_size: usize,
+}
+
+impl GraphicsProcessor {
+ pub(crate) fn create_draw_call(&mut self, mmio: &mut Mmio, cmd: u8, data: Vec<u8>) {
+ let Some(primitive) = draw::Primitive::from_cmd(cmd) else {
+ tracing::error!(cmd, "goofy draw command");
+ return;
+ };
+
+ let vf = self.build_vertex_format(cmd);
+
+ if vf.vertex_stride == 0 {
+ tracing::warn!("draw call with zero vertex stride, skipping");
+ return;
+ }
+
+ let vertex_count = data.len() / vf.vertex_stride;
+
+ // Channel 0 lighting state (COLOR0 and ALPHA0 have separate controls)
+ let color_ctrl = ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL0]);
+ let alpha_ctrl = ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL0]);
+ let ambient_reg = unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR0]);
+ let material_reg = unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR0]);
+
+ let mut vertices: Vec<draw::Vertex> = Vec::with_capacity(vertex_count);
+ let mut cur = Cursor::new(&data);
+
+ for i in 0..vertex_count {
+ let vertex = self.decode_vertex(
+ &mut cur,
+ &data,
+ &mmio.ram,
+ &vf,
+ &color_ctrl,
+ &alpha_ctrl,
+ ambient_reg,
+ material_reg,
+ i,
+ );
+ vertices.push(vertex);
+ }
+
+ let modelview = self.build_modelview_matrix(vf.default_pos_mtx_idx);
+
+ tracing::debug!(
+ primitive = format!("{:?}", primitive),
+ vertices = format!("{:?}", vertices),
+ pos_mtx_idx = vf.default_pos_mtx_idx,
+ modelview = format!("{:?}", modelview),
+ projection = format!("{:?}", self.draw_commands.projection),
+ "draw call created"
+ );
+
+ // Resolve TEV color registers to f32 arrays for the snapshot
+ let tev_color_regs = self.resolve_tev_color_regs();
+
+ self.draw_commands.commands.push(draw::DrawCall {
+ primitive,
+ vertices,
+ modelview,
+ textures: self.cur_textures,
+ tev_orders: self.resolve_tev_orders(),
+ tev_color_env: self.cur_tev_color_env,
+ tev_alpha_env: self.cur_tev_alpha_env,
+ tev_color_regs,
+ tev_konst_colors: self.cur_tev_konst_colors,
+ num_tev_stages: self.cur_num_tev_stages,
+ bp_zmode: self.cur_zmode,
+ bp_blend_mode: self.cur_blend_mode,
+ bp_alpha_compare: self.cur_alpha_compare,
+ });
+ }
+
+ fn build_vertex_format(&self, cmd: u8) -> VertexFormat {
+ let fmt = (cmd & 0b111) as usize;
+ let vcd_lo = VcdLo::from_raw(self.cp_regs[VCD_LO_REG]);
+ let vcd_hi = VcdHi::from_raw(self.cp_regs[VCD_HI_REG]);
+ let vat_a = VatA::from_raw(self.cp_regs[VATA_REG + fmt]);
+ let vat_b = VatB::from_raw(self.cp_regs[VATB_REG + fmt]);
+ let vat_c = VatC::from_raw(self.cp_regs[VATC_REG + fmt]);
+
+ let attr_stream_size = |attr: AttributeType, direct_size: usize| -> usize {
+ match attr {
+ AttributeType::Direct => direct_size,
+ AttributeType::Index8 => 1,
+ AttributeType::Index16 => 2,
+ AttributeType::None => 0,
+ }
+ };
+
+ let pos_attr = vcd_lo.position();
+ let nrm_attr = vcd_lo.normal();
+ let clr0_attr = vcd_lo.color0();
+ let pos_data_size = vat_a.pos_data_size();
+ let nrm_data_size = vat_a.nrm_data_size();
+ let clr0_data_size = vat_a.clr0_data_size();
+
+ let mtx_idx_size = vcd_lo.mtx_idx_count();
+ let pos_stream_size = attr_stream_size(pos_attr, pos_data_size);
+ let nrm_stream_size = vat_a.nrm_stream_size(nrm_attr);
+ let clr0_stream_size = attr_stream_size(clr0_attr, clr0_data_size);
+ let clr1_stream_size = attr_stream_size(vcd_lo.color1(), vat_a.clr1_data_size());
+
+ let tex_attrs = [
+ vcd_hi.tex0(),
+ vcd_hi.tex1(),
+ vcd_hi.tex2(),
+ vcd_hi.tex3(),
+ vcd_hi.tex4(),
+ vcd_hi.tex5(),
+ vcd_hi.tex6(),
+ vcd_hi.tex7(),
+ ];
+ let tex_data_sizes = [
+ vat_a.tex0_data_size(),
+ vat_b.tex1_data_size(),
+ vat_b.tex2_data_size(),
+ vat_b.tex3_data_size(),
+ vat_b.tex4_data_size(),
+ vat_c.tex5_data_size(),
+ vat_c.tex6_data_size(),
+ vat_c.tex7_data_size(),
+ ];
+ let tex_fmts = [
+ vat_a.tex0_fmt(),
+ vat_b.tex1_fmt(),
+ vat_b.tex2_fmt(),
+ vat_b.tex3_fmt(),
+ vat_b.tex4_fmt(),
+ vat_c.tex5_fmt(),
+ vat_c.tex6_fmt(),
+ vat_c.tex7_fmt(),
+ ];
+ let tex_shifts = [
+ vat_a.tex0_shift(),
+ vat_b.tex1_shift(),
+ vat_b.tex2_shift(),
+ vat_b.tex3_shift(),
+ vat_c.tex4_shift(),
+ vat_c.tex5_shift(),
+ vat_c.tex6_shift(),
+ vat_c.tex7_shift(),
+ ];
+ let tex_cnts = [
+ vat_a.tex0_cnt(),
+ vat_b.tex1_cnt(),
+ vat_b.tex2_cnt(),
+ vat_b.tex3_cnt(),
+ vat_b.tex4_cnt(),
+ vat_c.tex5_cnt(),
+ vat_c.tex6_cnt(),
+ vat_c.tex7_cnt(),
+ ];
+ let tex_stream_sizes: [usize; 8] = std::array::from_fn(|i| attr_stream_size(tex_attrs[i], tex_data_sizes[i]));
+ let tex_bases: [usize; 8] = std::array::from_fn(|i| self.cp_regs[ARRAY_BASE_REG + ARRAY_TEX0 + i] as usize);
+ let tex_strides: [usize; 8] = std::array::from_fn(|i| self.cp_regs[ARRAY_STRIDE_REG + ARRAY_TEX0 + i] as usize);
+
+ let has_pnmtxidx = vcd_lo.pos_nrm_mtx_idx();
+ let tex_mtx_idx_size = mtx_idx_size - has_pnmtxidx as usize;
+
+ let mtx_index_a = MatrixIndex0::from_raw(self.xf_mem[XF_MATRIX_INDEX_A]);
+ let default_pos_mtx_idx = mtx_index_a.pos_mtx_idx();
+
+ let vertex_stride = mtx_idx_size
+ + pos_stream_size
+ + nrm_stream_size
+ + clr0_stream_size
+ + clr1_stream_size
+ + tex_stream_sizes.iter().sum::<usize>();
+
+ VertexFormat {
+ vat_a,
+ pos_base: self.cp_regs[ARRAY_BASE_REG + ARRAY_POS] as usize,
+ pos_stride: self.cp_regs[ARRAY_STRIDE_REG + ARRAY_POS] as usize,
+ pos_data_size,
+ clr0_base: self.cp_regs[ARRAY_BASE_REG + ARRAY_CLR0] as usize,
+ clr0_stride: self.cp_regs[ARRAY_STRIDE_REG + ARRAY_CLR0] as usize,
+ clr0_data_size,
+ nrm_base_addr: self.cp_regs[ARRAY_BASE_REG + ARRAY_NRM] as usize,
+ nrm_stride: self.cp_regs[ARRAY_STRIDE_REG + ARRAY_NRM] as usize,
+ nrm_data_size,
+ tex_attrs,
+ tex_data_sizes,
+ tex_fmts,
+ tex_shifts,
+ tex_cnts,
+ tex_bases,
+ tex_strides,
+ vertex_stride,
+ has_pnmtxidx,
+ tex_mtx_idx_size,
+ default_pos_mtx_idx,
+ pos_attr,
+ nrm_attr,
+ clr0_attr,
+ clr1_stream_size,
+ }
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn decode_vertex(
+ &self,
+ cur: &mut Cursor<&Vec<u8>>,
+ data: &[u8],
+ ram: &[u8],
+ vf: &VertexFormat,
+ color_ctrl: &ChanCtrl,
+ alpha_ctrl: &ChanCtrl,
+ ambient_reg: [f32; 4],
+ material_reg: [f32; 4],
+ vertex_idx: usize,
+ ) -> draw::Vertex {
+ // Read per-vertex position/normal matrix index, or use register default
+ let pos_mtx_idx = if vf.has_pnmtxidx {
+ let mut buf = [0u8; 1];
+ cur.read_exact(&mut buf).unwrap();
+ buf[0] & 0x3F
+ } else {
+ vf.default_pos_mtx_idx
+ };
+
+ // Skip remaining tex matrix index bytes (not yet used)
+ cur.set_position(cur.position() + vf.tex_mtx_idx_size as u64);
+
+ // Derive per-vertex position and normal matrix bases
+ let pos_mtx_base = pos_mtx_idx as usize * XF_POS_MTX_STRIDE;
+ let nrm_mtx_idx = (pos_mtx_idx as usize) & 31;
+ let nrm_mtx_base = XF_NRM_MTX_BASE + nrm_mtx_idx * 3;
+ let nrm_mtx: [f32; 9] = std::array::from_fn(|i| self.xf_f32(nrm_mtx_base + i));
+
+ // Read position
+ let position = if vf.pos_attr == AttributeType::Direct {
+ let start = cur.position() as usize;
+ cur.set_position(cur.position() + vf.pos_data_size as u64);
+ decode_position(&data[start..start + vf.pos_data_size], &vf.vat_a)
+ } else {
+ let pos_index = read_index(cur, vf.pos_attr);
+ let pos_addr = vf.pos_base + pos_index * vf.pos_stride;
+ decode_position(&ram[pos_addr..pos_addr + vf.pos_data_size], &vf.vat_a)
+ };
+
+ // Read normal
+ let normal = if vf.nrm_attr == AttributeType::Direct {
+ let start = cur.position() as usize;
+ cur.set_position(cur.position() + vf.nrm_data_size as u64);
+ decode_normal(&data[start..start + vf.nrm_data_size], &vf.vat_a)
+ } else if vf.nrm_attr != AttributeType::None {
+ let nrm_index = read_index(cur, vf.nrm_attr);
+ // When nrm_index3 && NBT, the stream contains 3 separate indices
+ // (normal, binormal, tangent). Skip the extra 2, only the normal
+ // vector (first index) is needed for lighting.
+ if vf.vat_a.nrm_index3() && vf.vat_a.nrm_cnt() == regs::NrmCount::Nbt {
+ let idx_size = if vf.nrm_attr == AttributeType::Index8 { 1 } else { 2 };
+ cur.set_position(cur.position() + (2 * idx_size) as u64);
+ }
+ let nrm_addr = vf.nrm_base_addr + nrm_index * vf.nrm_stride;
+ decode_normal(&ram[nrm_addr..nrm_addr + vf.nrm_data_size], &vf.vat_a)
+ } else {
+ [0.0, 0.0, 1.0]
+ };
+
+ // Read color0
+ let color0 = if vf.clr0_attr == AttributeType::None {
+ [1.0, 1.0, 1.0, 1.0]
+ } else if vf.clr0_attr == AttributeType::Direct {
+ let start = cur.position() as usize;
+ cur.set_position(cur.position() + vf.clr0_data_size as u64);
+ decode_color(&data[start..start + vf.clr0_data_size], &vf.vat_a)
+ } else {
+ let clr0_index = read_index(cur, vf.clr0_attr);
+ let clr0_addr = vf.clr0_base + clr0_index * vf.clr0_stride;
+ decode_color(&ram[clr0_addr..clr0_addr + vf.clr0_data_size], &vf.vat_a)
+ };
+
+ // Skip color1 (TODO: not yet used for rendering)
+ cur.set_position(cur.position() + vf.clr1_stream_size as u64);
+
+ // Read all texcoords (tex0-tex7)
+ let mut raw_texcoords: [Option<[f32; 2]>; 8] = [None; 8];
+ for tc in 0..8 {
+ let tc_attr = vf.tex_attrs[tc];
+ let tc_data_size = vf.tex_data_sizes[tc];
+ if tc_attr == AttributeType::None {
+ continue;
+ }
+ raw_texcoords[tc] = Some(if tc_attr == AttributeType::Direct {
+ let start = cur.position() as usize;
+ cur.set_position(cur.position() + tc_data_size as u64);
+ decode_texcoord(
+ &data[start..start + tc_data_size],
+ vf.tex_fmts[tc],
+ vf.tex_shifts[tc],
+ vf.tex_cnts[tc],
+ )
+ } else {
+ let tc_index = read_index(cur, tc_attr);
+ let tc_addr = vf.tex_bases[tc] + tc_index * vf.tex_strides[tc];
+ decode_texcoord(
+ &ram[tc_addr..tc_addr + tc_data_size],
+ vf.tex_fmts[tc],
+ vf.tex_shifts[tc],
+ vf.tex_cnts[tc],
+ )
+ });
+ }
+
+ // Compute per-vertex lighting
+ let normal_view = Vec3::from(normal).transform(&nrm_mtx).normalize();
+ let pos_view = self.xf_transform_3x4(pos_mtx_base, position);
+ let final_color = self.compute_channel_lighting(
+ color_ctrl,
+ alpha_ctrl,
+ ambient_reg,
+ material_reg,
+ color0,
+ normal_view,
+ pos_view,
+ );
+
+ // Texture coordinate generation (XF texgen)
+ let num_texgens = (self.xf_mem[XF_NUM_TEXGENS] as usize).min(8);
+ let mut texcoords: [Option<[f32; 2]>; 8] = [None; 8];
+ for tg_idx in 0..num_texgens {
+ texcoords[tg_idx] = Some(self.compute_texgen(tg_idx, position, normal, &raw_texcoords));
+ }
+ // For texcoords beyond num_texgens, pass through raw values
+ for tg_idx in num_texgens..8 {
+ texcoords[tg_idx] = raw_texcoords[tg_idx];
+ }
+
+ tracing::debug!(
+ vertex = vertex_idx,
+ position = format!("{:02X?}", position),
+ color0 = format!("{:?}", final_color),
+ "Vertex"
+ );
+
+ draw::Vertex {
+ position,
+ color0: final_color,
+ texcoords,
+ }
+ }
+
+ fn build_modelview_matrix(&self, pos_mtx_idx: u8) -> draw::Matrix4 {
+ let default_mtx_base = pos_mtx_idx as usize * XF_POS_MTX_STRIDE;
+ draw::Matrix4([
+ [
+ self.xf_f32(default_mtx_base),
+ self.xf_f32(default_mtx_base + 4),
+ self.xf_f32(default_mtx_base + 8),
+ 0.0,
+ ],
+ [
+ self.xf_f32(default_mtx_base + 1),
+ self.xf_f32(default_mtx_base + 5),
+ self.xf_f32(default_mtx_base + 9),
+ 0.0,
+ ],
+ [
+ self.xf_f32(default_mtx_base + 2),
+ self.xf_f32(default_mtx_base + 6),
+ self.xf_f32(default_mtx_base + 10),
+ 0.0,
+ ],
+ [
+ self.xf_f32(default_mtx_base + 3),
+ self.xf_f32(default_mtx_base + 7),
+ self.xf_f32(default_mtx_base + 11),
+ 1.0,
+ ],
+ ])
+ }
+}
+
+fn read_index(cur: &mut Cursor<&Vec<u8>>, attr: AttributeType) -> usize {
+ match attr {
+ AttributeType::Index8 => {
+ let mut buf = [0u8; 1];
+ cur.read_exact(&mut buf).unwrap();
+ buf[0] as usize
+ }
+ AttributeType::Index16 => {
+ let mut buf = [0u8; 2];
+ cur.read_exact(&mut buf).unwrap();
+ u16::from_be_bytes(buf) as usize
+ }
+ _ => 0,
+ }
+}
+
+fn decode_position(data: &[u8], vat: &VatA) -> [f32; 3] {
+ let num = vat.pos_cnt().components();
+ let fmt = vat.pos_fmt();
+ let divisor = (1u32 << vat.pos_shift()) as f32;
+ let mut result = [0.0f32; 3];
+ let mut off = 0;
+
+ for i in 0..num {
+ result[i] = match fmt {
+ ComponentFormat::U8 => {
+ let v = data[off] as f32 / divisor;
+ off += 1;
+ v
+ }
+ ComponentFormat::S8 => {
+ let v = data[off] as i8 as f32 / divisor;
+ off += 1;
+ v
+ }
+ ComponentFormat::U16 => {
+ let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
+ off += 2;
+ v
+ }
+ ComponentFormat::S16 => {
+ let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
+ off += 2;
+ v
+ }
+ ComponentFormat::F32 => {
+ let v = f32::from_bits(u32::from_be_bytes([
+ data[off],
+ data[off + 1],
+ data[off + 2],
+ data[off + 3],
+ ]));
+ off += 4;
+ v
+ }
+ };
+ }
+ result
+}
+
+fn decode_color(data: &[u8], vat: &VatA) -> [f32; 4] {
+ let has_alpha = vat.clr0_cnt() == regs::ColorCount::Rgba;
+ match vat.clr0_fmt() {
+ regs::ColorFormat::Rgb565 => {
+ let raw = u16::from_be_bytes([data[0], data[1]]);
+ let r = ((raw >> 11) & 0x1F) as f32 / 31.0;
+ let g = ((raw >> 5) & 0x3F) as f32 / 63.0;
+ let b = (raw & 0x1F) as f32 / 31.0;
+ [r, g, b, 1.0]
+ }
+ regs::ColorFormat::Rgb8 => [
+ data[0] as f32 / 255.0,
+ data[1] as f32 / 255.0,
+ data[2] as f32 / 255.0,
+ 1.0,
+ ],
+ regs::ColorFormat::Rgbx8 => [
+ data[0] as f32 / 255.0,
+ data[1] as f32 / 255.0,
+ data[2] as f32 / 255.0,
+ 1.0,
+ ],
+ regs::ColorFormat::Rgba4 => {
+ let raw = u16::from_be_bytes([data[0], data[1]]);
+ let r = ((raw >> 12) & 0xF) as f32 / 15.0;
+ let g = ((raw >> 8) & 0xF) as f32 / 15.0;
+ let b = ((raw >> 4) & 0xF) as f32 / 15.0;
+ let a = (raw & 0xF) as f32 / 15.0;
+ [r, g, b, a]
+ }
+ regs::ColorFormat::Rgba6 => {
+ let raw = u32::from_be_bytes([0, data[0], data[1], data[2]]);
+ let r = ((raw >> 18) & 0x3F) as f32 / 63.0;
+ let g = ((raw >> 12) & 0x3F) as f32 / 63.0;
+ let b = ((raw >> 6) & 0x3F) as f32 / 63.0;
+ let a = (raw & 0x3F) as f32 / 63.0;
+ [r, g, b, a]
+ }
+ regs::ColorFormat::Rgba8 => {
+ let r = data[0] as f32 / 255.0;
+ let g = data[1] as f32 / 255.0;
+ let b = data[2] as f32 / 255.0;
+ let a = if has_alpha { data[3] as f32 / 255.0 } else { 1.0 };
+ [r, g, b, a]
+ }
+ }
+}
+
+fn decode_normal(data: &[u8], vat: &VatA) -> [f32; 3] {
+ let cnt = vat.nrm_cnt().components().min(3);
+ let fmt = vat.nrm_fmt();
+ let mut result = [0.0f32; 3];
+ let mut off = 0;
+
+ for i in 0..cnt {
+ result[i] = match fmt {
+ ComponentFormat::U8 => {
+ let v = data[off] as f32 / 255.0;
+ off += 1;
+ v
+ }
+ ComponentFormat::S8 => {
+ let v = data[off] as i8 as f32 / 127.0;
+ off += 1;
+ v
+ }
+ ComponentFormat::U16 => {
+ let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / 65535.0;
+ off += 2;
+ v
+ }
+ ComponentFormat::S16 => {
+ let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / 32767.0;
+ off += 2;
+ v
+ }
+ ComponentFormat::F32 => {
+ let v = f32::from_bits(u32::from_be_bytes([
+ data[off],
+ data[off + 1],
+ data[off + 2],
+ data[off + 3],
+ ]));
+ off += 4;
+ v
+ }
+ };
+ }
+
+ result
+}
+
+fn decode_texcoord(data: &[u8], fmt: ComponentFormat, shift: u8, cnt: TexCount) -> [f32; 2] {
+ let num = cnt.components();
+ let divisor = (1u32 << shift) as f32;
+ let mut result = [0.0f32; 2];
+ let mut off = 0;
+
+ for i in 0..num {
+ result[i] = match fmt {
+ ComponentFormat::U8 => {
+ let v = data[off] as f32 / divisor;
+ off += 1;
+ v
+ }
+ ComponentFormat::S8 => {
+ let v = data[off] as i8 as f32 / divisor;
+ off += 1;
+ v
+ }
+ ComponentFormat::U16 => {
+ let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
+ off += 2;
+ v
+ }
+ ComponentFormat::S16 => {
+ let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;
+ off += 2;
+ v
+ }
+ ComponentFormat::F32 => {
+ let v = f32::from_bits(u32::from_be_bytes([
+ data[off],
+ data[off + 1],
+ data[off + 2],
+ data[off + 3],
+ ]));
+ off += 4;
+ v
+ }
+ };
+ }
+ result
+}
diff --git a/crates/gecko/src/flipper/gx/xf.rs b/crates/gecko/src/flipper/gx/xf.rs
new file mode 100644
index 0000000..a4bc14d
--- /dev/null
+++ b/crates/gecko/src/flipper/gx/xf.rs
@@ -0,0 +1,101 @@
+use super::{
+ GraphicsProcessor,
+ constants::{XF_PROJECTION_BASE, XF_PROJECTION_END},
+ draw,
+ math::Vec3,
+};
+
+impl GraphicsProcessor {
+ pub(crate) fn xf_f32(&self, reg: usize) -> f32 {
+ f32::from_bits(self.xf_mem[reg])
+ }
+
+ pub(crate) fn xf_vec3(&self, reg: usize) -> Vec3 {
+ Vec3(self.xf_f32(reg), self.xf_f32(reg + 1), self.xf_f32(reg + 2))
+ }
+
+ pub(crate) fn xf_transform_3x4(&self, base: usize, v: [f32; 3]) -> Vec3 {
+ Vec3(
+ self.xf_f32(base) * v[0]
+ + self.xf_f32(base + 1) * v[1]
+ + self.xf_f32(base + 2) * v[2]
+ + self.xf_f32(base + 3),
+ self.xf_f32(base + 4) * v[0]
+ + self.xf_f32(base + 5) * v[1]
+ + self.xf_f32(base + 6) * v[2]
+ + self.xf_f32(base + 7),
+ self.xf_f32(base + 8) * v[0]
+ + self.xf_f32(base + 9) * v[1]
+ + self.xf_f32(base + 10) * v[2]
+ + self.xf_f32(base + 11),
+ )
+ }
+
+ pub(crate) fn rebuild_projection(&mut self) {
+ let pm1 = self.xf_f32(XF_PROJECTION_BASE);
+ let pm2 = self.xf_f32(XF_PROJECTION_BASE + 1);
+ let pm3 = self.xf_f32(XF_PROJECTION_BASE + 2);
+ let pm4 = self.xf_f32(XF_PROJECTION_BASE + 3);
+ let pm5 = self.xf_f32(XF_PROJECTION_BASE + 4);
+ let pm6 = self.xf_f32(XF_PROJECTION_BASE + 5);
+ let proj_type = self.xf_mem[XF_PROJECTION_END];
+
+ self.draw_commands.projection = if proj_type == 0 {
+ // Perspective
+ draw::Matrix4([
+ [pm1, 0.0, 0.0, 0.0],
+ [0.0, pm3, 0.0, 0.0],
+ [pm2, pm4, pm5, -1.0],
+ [0.0, 0.0, pm6, 0.0],
+ ])
+ } else {
+ // Orthographic
+ draw::Matrix4([
+ [pm1, 0.0, 0.0, 0.0],
+ [0.0, pm3, 0.0, 0.0],
+ [0.0, 0.0, pm5, 0.0],
+ [pm2, pm4, pm6, 1.0],
+ ])
+ };
+ }
+
+ pub(crate) fn load_cp(&mut self, data: &[u8]) {
+ let idx = data[0] as usize;
+ let val = u32::from_be_bytes([data[1], data[2], data[3], data[4]]);
+ self.cp_regs[idx] = val;
+
+ tracing::debug!(
+ reg_idx = format!("{idx:02X}"),
+ value = format!("{val:08X}"),
+ "CP register write"
+ );
+ }
+
+ pub(crate) fn load_xf(&mut self, data: &[u8]) {
+ let length = u16::from_be_bytes([data[0], data[1]]) as usize;
+ let addr = u16::from_be_bytes([data[2], data[3]]) as usize;
+ let n = length + 1;
+ let end = addr + n;
+
+ for i in 0..n {
+ let offset = 4 + i * 4;
+ let val = u32::from_be_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
+ let reg = addr + i;
+ if reg < self.xf_mem.len() {
+ self.xf_mem[reg] = val;
+ }
+
+ tracing::debug!(
+ reg_idx = format!("{reg:04X}"),
+ value = format!("{val:08X}"),
+ "XF register write"
+ );
+ }
+
+ // Rebuild projection if the write touched its address range
+ // (modelview is resolved lazily at draw call time from the current position matrix slot)
+ if addr <= XF_PROJECTION_END && end > XF_PROJECTION_BASE {
+ self.rebuild_projection();
+ }
+ }
+}
diff --git a/crates/image/Cargo.toml b/crates/image/Cargo.toml
index 7376c71..ae92478 100644
--- a/crates/image/Cargo.toml
+++ b/crates/image/Cargo.toml
@@ -5,4 +5,4 @@ edition = "2024"
[dependencies]
object = { version = "0.36.7", default-features = false, features = ["elf", "read"] }
-zerocopy = { version = "0.8.47", features = ["derive"] }
+zerocopy = { version = "0.8.48", features = ["derive"] }
diff --git a/crates/web/Cargo.toml b/crates/web/Cargo.toml
index e816906..7d4b865 100644
--- a/crates/web/Cargo.toml
+++ b/crates/web/Cargo.toml
@@ -20,9 +20,9 @@ winit = { version = "0.30.13", features = ["rwh_06"] }
egui = "0.33.3"
egui-wgpu = "0.33.3"
egui-winit = { version = "0.33.3", default-features = false, features = ["links"] }
-wasm-bindgen = "0.2.116"
-wasm-bindgen-futures = "0.4.66"
-web-sys = { version = "0.3.93", features = [
+wasm-bindgen = "0.2.117"
+wasm-bindgen-futures = "0.4.67"
+web-sys = { version = "0.3.94", features = [
"Document",
"Window",
"Element",
@@ -35,6 +35,6 @@ web-sys = { version = "0.3.93", features = [
"Performance",
"console",
] }
-js-sys = "0.3.93"
+js-sys = "0.3.94"
console_error_panic_hook = "0.1.7"
tracing = "0.1.44"
diff --git a/roms/silentskate.dol b/roms/silentskate.dol
new file mode 100644
index 0000000..22fb426
Binary files /dev/null and b/roms/silentskate.dol differ