From 13bc77fd6c8945a9feac6a30e19d8eb3015580fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20Gastinel?= <264859180+gastinelt@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:55:43 +0200 Subject: [PATCH] Premier commit --- .gitignore | 67 ++ Cargo.lock | 2105 +++++++++++++++++++++++++++++++++++ Cargo.toml | 9 + src/camera.rs | 110 ++ src/inventory.rs | 262 +++++ src/main.rs | 33 + src/math.rs | 286 +++++ src/physics.rs | 463 ++++++++ src/raycast.rs | 171 +++ src/renderer/device.rs | 151 +++ src/renderer/mesh.rs | 234 ++++ src/renderer/mod.rs | 390 +++++++ src/renderer/pipeline.rs | 275 +++++ src/renderer/render_pass.rs | 45 + src/renderer/swapchain.rs | 170 +++ src/renderer/texture.rs | 268 +++++ src/window.rs | 405 +++++++ src/world/chunk.rs | 230 ++++ src/world/mesh_builder.rs | 303 +++++ src/world/mod.rs | 9 + src/world/world.rs | 183 +++ 21 files changed, 6169 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/camera.rs create mode 100644 src/inventory.rs create mode 100644 src/main.rs create mode 100644 src/math.rs create mode 100644 src/physics.rs create mode 100644 src/raycast.rs create mode 100644 src/renderer/device.rs create mode 100644 src/renderer/mesh.rs create mode 100644 src/renderer/mod.rs create mode 100644 src/renderer/pipeline.rs create mode 100644 src/renderer/render_pass.rs create mode 100644 src/renderer/swapchain.rs create mode 100644 src/renderer/texture.rs create mode 100644 src/window.rs create mode 100644 src/world/chunk.rs create mode 100644 src/world/mesh_builder.rs create mode 100644 src/world/mod.rs create mode 100644 src/world/world.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7c787e4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,67 @@ +/target + +# --- double-push : exclusions generiques (secrets, builds, binaires, gros fichiers) --- +target/ +node_modules/ +build/ +build-*/ +dist/ +out/ +.gradle/ +.idea/ +venv/ +.venv/ +env/ +__pycache__/ +*.pyc +.cache/ +.next/ +.env +.env.* +!.env.example +accounts.json +Clee.API/ +*.pem +*.key +*.p12 +*.pfx +*.jks +*.keystore +keystore.properties +id_rsa* +id_ed25519* +*.kdbx +*.odt +*.sqlite +*.sqlite3 +*.db +*.log +*.exe +*.dll +*.msi +*.jar +*.zip +*.7z +*.rar +*.tar +*.tar.gz +*.tgz +*.gguf +*.safetensors +*.onnx +*.pt +*.pth +*.bin +*.iso +*.gws +*.apk +*.aab +*.so +*.o +*.a +*.lib +*.pdb +*.mp4 +*.mkv +*.wav +*.flac diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..eba4b78 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2105 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "MC" +version = "0.1.0" +dependencies = [ + "vulkano", + "vulkano-shaders", + "winit", +] + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.2", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.4", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "bytemuck", + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.4", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2 0.5.2", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.2", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.4", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2", + "objc2 0.5.2", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2", + "dispatch", + "libc", + "objc2 0.5.2", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.4", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2", + "objc2 0.5.2", + "objc2-app-kit", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.2", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "roxmltree" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "921904a62e410e37e215c40381b7117f830d9d89ba60ab5236170541dd25646b" +dependencies = [ + "xmlparser", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shaderc" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27e07913ada18607bb60d12431cbe3358d3bbebbe95948e1618851dc01e63b7b" +dependencies = [ + "libc", + "shaderc-sys", +] + +[[package]] +name = "shaderc-sys" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73120d240fe22196300f39ca8547ca2d014960f27b19b47b21288b396272f7f7" +dependencies = [ + "cmake", + "libc", + "roxmltree", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slabbin" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9db491c0d4152a069911a0fbdaca959691bf0b9d7110d98a7ed1c8e59b79ab30" + +[[package]] +name = "smallvec" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.15+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vk-parse" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3859da4d7b98bec73e68fb65815d47a263819c415c90eed42b80440a02cbce8c" +dependencies = [ + "xml-rs", +] + +[[package]] +name = "vulkano" +version = "0.35.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee487adf7c13e5aa46d4d7fac6ffb8e172eb7e6472aaf815e9ade4992f8f2414" +dependencies = [ + "ash", + "bytemuck", + "crossbeam-queue", + "foldhash", + "half", + "heck", + "indexmap", + "libloading", + "nom", + "once_cell", + "parking_lot", + "proc-macro2", + "quote", + "raw-window-handle", + "raw-window-metal", + "serde", + "serde_json", + "slabbin", + "smallvec", + "thread_local", + "vk-parse", + "vulkano-macros", + "x11-dl", + "x11rb", +] + +[[package]] +name = "vulkano-macros" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dc929c42c9336fd082079ac3ea30126e4a0dfe36fd2e2b3581303f7d140d20f" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "vulkano-shaders" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bf501461be7cef2893c0e62c50945add9763cc482051d29053f6157089d5ea9" +dependencies = [ + "foldhash", + "heck", + "proc-macro2", + "quote", + "shaderc", + "syn 2.0.119", + "vulkano", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.5", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.5", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.2", + "objc2-app-kit", + "objc2-foundation 0.2.2", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + +[[package]] +name = "zerocopy" +version = "0.8.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17e8fafad82b542ff3717217ecdc736231b59e387768c9630123b4ce4d2db44" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "595f56e044df4f46a0c9a626f65c3d99eb8488f7e8a8baa12dd76326d9710bf2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c2d31c7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "MC" +version = "0.1.0" +edition = "2024" + +[dependencies] +vulkano = "0.35.2" +vulkano-shaders = "0.35.0" +winit = "0.30.13" diff --git a/src/camera.rs b/src/camera.rs new file mode 100644 index 0000000..7f0f07f --- /dev/null +++ b/src/camera.rs @@ -0,0 +1,110 @@ +use crate::math::{Mat4, Vec3}; + +/// Caméra 3D libre de type "FPS free-fly". +pub struct Camera { + pub position: Vec3, + pub yaw: f32, // Rotation horizontale (lacet en radians) + pub pitch: f32, // Rotation verticale (tangage en radians) + pub speed: f32, // Vitesse de déplacement (unités/sec) + pub sensitivity: f32, // Sensibilité de la souris (radians/pixel) + + // État des touches de déplacement + pub move_forward: bool, + pub move_backward: bool, + pub move_left: bool, + pub move_right: bool, + pub move_up: bool, + pub move_down: bool, +} + +#[allow(dead_code)] +impl Camera { + pub fn new(position: Vec3) -> Self { + Self { + position, + yaw: 0.0, + pitch: 0.0, + speed: 5.0, + sensitivity: 0.0025, + move_forward: false, + move_backward: false, + move_left: false, + move_right: false, + move_up: false, + move_down: false, + } + } + + /// Vecteur directionnel unitaire dans lequel regarde la caméra. + /// Pour yaw = 0 et pitch = 0, la caméra regarde vers -Z (convention standard). + pub fn forward(&self) -> Vec3 { + let cos_pitch = self.pitch.cos(); + Vec3::new( + self.yaw.sin() * cos_pitch, + self.pitch.sin(), + -self.yaw.cos() * cos_pitch, + ) + .normalize() + } + + /// Vecteur pointant vers la droite relative de la caméra. + pub fn right(&self) -> Vec3 { + self.forward().cross(Vec3::new(0.0, 1.0, 0.0)).normalize() + } + + /// Vecteur pointant vers le haut relatif de la caméra. + pub fn up(&self) -> Vec3 { + self.right().cross(self.forward()).normalize() + } + + /// Oriente la caméra en fonction du déplacement relatif de la souris (dx, dy). + pub fn rotate(&mut self, dx: f32, dy: f32) { + self.yaw += dx * self.sensitivity; + // Inversion de dy pour que déplacer la souris vers le haut regarde vers le haut + self.pitch -= dy * self.sensitivity; + + // Limite le pitch à ~89 degrés pour éviter le gimbal lock et l'inversion de tête + let max_pitch = 89.0f32.to_radians(); + self.pitch = self.pitch.clamp(-max_pitch, max_pitch); + } + + /// Met à jour la position de la caméra selon les touches pressées et le delta-time (dt en secondes). + pub fn update(&mut self, dt: f32) { + let mut move_dir = Vec3::zero(); + let forward = self.forward(); + let right = self.right(); + let world_up = Vec3::new(0.0, 1.0, 0.0); + + if self.move_forward { + move_dir = move_dir + forward; + } + if self.move_backward { + move_dir = move_dir - forward; + } + if self.move_right { + move_dir = move_dir + right; + } + if self.move_left { + move_dir = move_dir - right; + } + if self.move_up { + move_dir = move_dir + world_up; + } + if self.move_down { + move_dir = move_dir - world_up; + } + + if move_dir.length_squared() > 0.0001 { + self.position = self.position + move_dir.normalize() * (self.speed * dt); + } + } + + /// Calcule la matrice de vue correspondante. + pub fn view_matrix(&self) -> Mat4 { + Mat4::look_at( + self.position, + self.position + self.forward(), + Vec3::new(0.0, 1.0, 0.0), + ) + } +} diff --git a/src/inventory.rs b/src/inventory.rs new file mode 100644 index 0000000..1537425 --- /dev/null +++ b/src/inventory.rs @@ -0,0 +1,262 @@ +use crate::renderer::mesh::CubeVertex; +use crate::world::BlockType; + +pub const HOTBAR_SLOTS: usize = 6; + +/// Représente un emplacement d'inventaire avec un type de bloc et un compteur. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Slot { + pub block: BlockType, + pub count: u32, +} + +/// Gestion de l'inventaire du joueur (Hotbar de 6 slots façon Minecraft). +pub struct Inventory { + pub slots: [Slot; HOTBAR_SLOTS], + pub selected_slot: usize, +} + +impl Inventory { + pub fn new() -> Self { + Self { + slots: [ + Slot { block: BlockType::Grass, count: 64 }, + Slot { block: BlockType::Dirt, count: 64 }, + Slot { block: BlockType::Stone, count: 64 }, + Slot { block: BlockType::Wood, count: 32 }, + Slot { block: BlockType::Leaves, count: 32 }, + Slot { block: BlockType::Sand, count: 32 }, + ], + selected_slot: 0, + } + } + + /// Sélectionne un slot par son index (0..HOTBAR_SLOTS - 1). + pub fn select_slot(&mut self, slot: usize) { + if slot < HOTBAR_SLOTS { + self.selected_slot = slot; + } + } + + /// Fait défiler le slot actif (ex: molette souris, delta = +1 ou -1). + pub fn cycle_slot(&mut self, delta: i32) { + let count = HOTBAR_SLOTS as i32; + let next = (self.selected_slot as i32 + delta).rem_euclid(count); + self.selected_slot = next as usize; + } + + /// Retourne le type de bloc sélectionné. + pub fn selected_block(&self) -> BlockType { + self.slots[self.selected_slot].block + } + + /// Retourne la quantité disponible dans le slot actif. + pub fn selected_count(&self) -> u32 { + self.slots[self.selected_slot].count + } + + /// Ajoute un bloc récolté au slot correspondant. + pub fn add_block(&mut self, block: BlockType) -> bool { + if block == BlockType::Air { + return false; + } + for slot in &mut self.slots { + if slot.block == block { + slot.count = slot.count.saturating_add(1); + return true; + } + } + false + } + + /// Tente de consommer un bloc du slot actif pour le poser. + /// Retourne Some(BlockType) si le stock est > 0 (et décrémente), + /// ou None si le slot est vide (refus silencieux sans sous-dépassement). + pub fn consume_selected(&mut self) -> Option { + let slot = &mut self.slots[self.selected_slot]; + if slot.count > 0 { + slot.count -= 1; + Some(slot.block) + } else { + None + } + } + + /// Couleur représentative du type de bloc pour la vignette UI. + fn block_ui_color(block: BlockType) -> [f32; 3] { + match block { + BlockType::Grass => [0.35, 0.75, 0.30], + BlockType::Dirt => [0.55, 0.38, 0.25], + BlockType::Stone => [0.58, 0.58, 0.60], + BlockType::Wood => [0.45, 0.32, 0.22], + BlockType::Leaves => [0.22, 0.58, 0.22], + BlockType::Sand => [0.86, 0.80, 0.52], + BlockType::Air => [0.0, 0.0, 0.0], + } + } + + /// Génère le maillage 2D en coordonnées écran NDC [-1..1] pour afficher la hotbar. + pub fn generate_ui_mesh(&self, aspect_ratio: f32) -> (Vec, Vec) { + let mut vertices = Vec::new(); + let mut indices = Vec::new(); + + // Dimensions de la hotbar en bas de l'écran (Vulkan Y descend vers +1.0) + let slot_w = 0.075f32; + let slot_h = slot_w * aspect_ratio; + let margin = 0.008f32; + let total_w = HOTBAR_SLOTS as f32 * slot_w + (HOTBAR_SLOTS - 1) as f32 * margin; + let start_x = -total_w * 0.5; + let y_bottom = 0.94f32; + let y_top = y_bottom - slot_h; + + // Fonction locale d'ajout de quad 2D + let mut add_quad = |x0: f32, y0: f32, x1: f32, y1: f32, color: [f32; 3]| { + let base = vertices.len() as u32; + let normal = [0.0, 0.0, 1.0]; + let uv = [0.0, 0.0]; + + vertices.push(CubeVertex { position: [x0, y0, 0.0], color, normal, uv }); + vertices.push(CubeVertex { position: [x1, y0, 0.0], color, normal, uv }); + vertices.push(CubeVertex { position: [x1, y1, 0.0], color, normal, uv }); + vertices.push(CubeVertex { position: [x0, y1, 0.0], color, normal, uv }); + + indices.push(base); + indices.push(base + 1); + indices.push(base + 2); + indices.push(base + 2); + indices.push(base + 3); + indices.push(base); + }; + + for i in 0..HOTBAR_SLOTS { + let x_left = start_x + i as f32 * (slot_w + margin); + let x_right = x_left + slot_w; + + let is_selected = i == self.selected_slot; + + // 1. Fond du slot (ou surbrillance dorée/blanche si actif) + if is_selected { + // Cadre extérieur actif éclatant (blanc / doré) + let border = 0.005; + add_quad( + x_left - border, + y_top - border * aspect_ratio, + x_right + border, + y_bottom + border * aspect_ratio, + [1.0, 0.95, 0.4], + ); + } + + // Fond sombre du slot + let bg_color = if is_selected { + [0.28, 0.28, 0.32] + } else { + [0.15, 0.15, 0.17] + }; + add_quad(x_left, y_top, x_right, y_bottom, bg_color); + + // 2. Carré intérieur représentant le bloc + let inner_pad = 0.012; + let block_color = Self::block_ui_color(self.slots[i].block); + + // Si le stock est à 0, le bloc est atténué (semi-grisé) + let final_color = if self.slots[i].count > 0 { + block_color + } else { + [block_color[0] * 0.3, block_color[1] * 0.3, block_color[2] * 0.3] + }; + + add_quad( + x_left + inner_pad, + y_top + inner_pad * aspect_ratio, + x_right - inner_pad, + y_bottom - inner_pad * aspect_ratio, + final_color, + ); + } + + (vertices, indices) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_inventory_add_and_consume() { + let mut inv = Inventory::new(); + inv.select_slot(0); // Grass + let initial_grass = inv.selected_count(); + + // Pose 1 bloc + let consumed = inv.consume_selected(); + assert_eq!(consumed, Some(BlockType::Grass)); + assert_eq!(inv.selected_count(), initial_grass - 1); + + // Ajoute 1 bloc récolté + let added = inv.add_block(BlockType::Grass); + assert!(added); + assert_eq!(inv.selected_count(), initial_grass); + } + + #[test] + fn test_consume_at_zero_refused_silently() { + let mut inv = Inventory::new(); + inv.select_slot(2); // Stone + inv.slots[2].count = 0; + + // Tenter de poser avec 0 bloc + let consumed = inv.consume_selected(); + assert_eq!(consumed, None, "Poser un bloc à 0 doit renvoyer None"); + assert_eq!(inv.selected_count(), 0, "Le stock ne doit pas passer sous 0"); + } + + #[test] + fn test_inventory_cycle_slots() { + let mut inv = Inventory::new(); + inv.select_slot(0); + + inv.cycle_slot(1); + assert_eq!(inv.selected_slot, 1); + + inv.cycle_slot(-1); + assert_eq!(inv.selected_slot, 0); + + // Débordement négatif -> boucle vers le dernier slot + inv.cycle_slot(-1); + assert_eq!(inv.selected_slot, HOTBAR_SLOTS - 1); + + // Débordement positif -> boucle vers le premier slot + inv.cycle_slot(1); + assert_eq!(inv.selected_slot, 0); + } + + #[test] + fn test_place_block_with_zero_stock_does_not_modify_world() { + use crate::world::{Chunk, World}; + + let mut inv = Inventory::new(); + inv.select_slot(3); // Wood + inv.slots[3].count = 0; // Stock vide + + let mut world = World::new(); + let chunk = Chunk::new_empty(0, 0); + world.chunks.insert((0, 0), chunk); + + // Simulation de la pose : consume_selected() échoue -> le monde n'est pas modifié + let block_opt = inv.consume_selected(); + assert_eq!(block_opt, None); + + if let Some(block) = block_opt { + world.set_block(5, 5, 5, block); + } + + assert_eq!( + world.get_block(5, 5, 5), + BlockType::Air, + "Le monde ne doit pas être modifié si le stock est à 0" + ); + assert_eq!(inv.slots[3].count, 0, "Le compteur doit rester à 0"); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..fbfefc9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,33 @@ +mod camera; +mod inventory; +mod math; +mod physics; +mod raycast; +mod renderer; +mod window; +mod world; + +use std::error::Error; +use window::App; +use winit::event_loop::EventLoop; + +fn main() -> Result<(), Box> { + println!("=== Moteur Voxel (Moteur Physique, Gravité & Collisions AABB) ==="); + println!("Contrôles :"); + println!(" - Z / Q / S / D (ou W / A / S / D) : Déplacement (Marche / Vol)"); + println!(" - Espace : Sauter (au sol) / Monter (en vol)"); + println!(" - Maj : Descendre (en vol)"); + println!(" - F : Basculer Vol libre / Marche avec gravité"); + println!(" - Souris : Regarder autour (Pitch / Yaw)"); + println!(" - Clic Gauche : Casser le bloc ciblé (Air)"); + println!(" - Clic Droit : Poser un bloc sur la face ciblée"); + println!(" - Touches 1 à 9 : Sélectionner le bloc dans l'inventaire"); + println!(" - Échap : Basculer la capture du curseur souris"); + + let event_loop = EventLoop::new()?; + let mut app = App::new(); + event_loop.run_app(&mut app)?; + + println!("Arrêt du moteur."); + Ok(()) +} diff --git a/src/math.rs b/src/math.rs new file mode 100644 index 0000000..bb37f9e --- /dev/null +++ b/src/math.rs @@ -0,0 +1,286 @@ +use std::ops::{Add, Div, Mul, Neg, Sub}; + +/// Vecteur 3D à virgule flottante 32 bits (f32). +/// Utilisé pour les positions, directions, normales et couleurs dans le monde 3D. +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C)] +pub struct Vec3 { + pub x: f32, + pub y: f32, + pub z: f32, +} + +impl Vec3 { + pub const fn new(x: f32, y: f32, z: f32) -> Self { + Self { x, y, z } + } + + pub const fn zero() -> Self { + Self::new(0.0, 0.0, 0.0) + } + + pub const fn one() -> Self { + Self::new(1.0, 1.0, 1.0) + } + + /// Produit scalaire (dot product). + /// Permet de mesurer l'alignement entre deux vecteurs ou pour l'éclairage diffus (Lambert). + pub fn dot(&self, other: Self) -> f32 { + self.x * other.x + self.y * other.y + self.z * other.z + } + + /// Produit vectoriel (cross product). + /// Donne un vecteur orthogonal aux deux opérandes (essentiel pour calculer normales et repères de caméra). + pub fn cross(&self, other: Self) -> Self { + Self { + x: self.y * other.z - self.z * other.y, + y: self.z * other.x - self.x * other.z, + z: self.x * other.y - self.y * other.x, + } + } + + /// Norme au carré (évite un appel coûteux à sqrt si seule une comparaison est nécessaire). + pub fn length_squared(&self) -> f32 { + self.dot(*self) + } + + /// Norme euclidienne du vecteur. + pub fn length(&self) -> f32 { + self.length_squared().sqrt() + } + + /// Normalise le vecteur pour que sa norme devienne 1.0. + /// Retourne un vecteur nul si la norme est 0 pour éviter une division par zéro. + pub fn normalize(&self) -> Self { + let len = self.length(); + if len > 0.00001 { + *self / len + } else { + Self::zero() + } + } +} + +impl Add for Vec3 { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) + } +} + +impl Sub for Vec3 { + type Output = Self; + fn sub(self, rhs: Self) -> Self::Output { + Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) + } +} + +impl Mul for Vec3 { + type Output = Self; + fn mul(self, rhs: f32) -> Self::Output { + Self::new(self.x * rhs, self.y * rhs, self.z * rhs) + } +} + +impl Mul for f32 { + type Output = Vec3; + fn mul(self, rhs: Vec3) -> Self::Output { + rhs * self + } +} + +impl Div for Vec3 { + type Output = Self; + fn div(self, rhs: f32) -> Self::Output { + Self::new(self.x / rhs, self.y / rhs, self.z / rhs) + } +} + +impl Neg for Vec3 { + type Output = Self; + fn neg(self) -> Self::Output { + Self::new(-self.x, -self.y, -self.z) + } +} + +/// Matrice 4x4 stockée en ordre 'column-major' (colonnes contiguës en mémoire). +/// +/// Alignement mémoire : +/// `cols[colonne][ligne]` +/// cols[0] = [m00, m10, m20, m30] (1ère colonne) +/// cols[1] = [m01, m11, m21, m31] (2ème colonne) +/// cols[2] = [m02, m12, m22, m32] (3ème colonne) +/// cols[3] = [m03, m13, m23, m33] (4ème colonne) +/// +/// Cet ordre correspond exactement à l'agencement mémoire attendu par GLSL / SPIR-V +/// lorsqu'on transmet la matrice via push constants ou uniform buffer. +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C)] +pub struct Mat4 { + pub cols: [[f32; 4]; 4], +} + +#[allow(dead_code)] +impl Mat4 { + /// Crée une matrice identité (diagonale = 1, le reste = 0). + pub const fn identity() -> Self { + Self { + cols: [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + } + } + + /// Crée une matrice nulle. + pub const fn zero() -> Self { + Self { + cols: [[0.0; 4]; 4], + } + } + + /// Crée une matrice de translation. + pub fn from_translation(t: Vec3) -> Self { + let mut m = Self::identity(); + m.cols[3][0] = t.x; + m.cols[3][1] = t.y; + m.cols[3][2] = t.z; + m + } + + /// Crée une matrice de mise à l'échelle (scale). + pub fn from_scale(s: Vec3) -> Self { + Self { + cols: [ + [s.x, 0.0, 0.0, 0.0], + [0.0, s.y, 0.0, 0.0], + [0.0, 0.0, s.z, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + } + } + + /// Crée une matrice de rotation autour de l'axe Y (angle en radians). + pub fn from_rotation_y(rad: f32) -> Self { + let cos = rad.cos(); + let sin = rad.sin(); + let mut m = Self::identity(); + m.cols[0][0] = cos; + m.cols[0][2] = -sin; + m.cols[2][0] = sin; + m.cols[2][2] = cos; + m + } + + /// Crée une matrice de rotation autour de l'axe X (angle en radians). + pub fn from_rotation_x(rad: f32) -> Self { + let cos = rad.cos(); + let sin = rad.sin(); + let mut m = Self::identity(); + m.cols[1][1] = cos; + m.cols[1][2] = sin; + m.cols[2][1] = -sin; + m.cols[2][2] = cos; + m + } + + /// Matrice de vue standard (Look At). + /// + /// Convention du repère : + /// - Monde : main droite, +Y vers le haut (Up), +X vers la droite, +Z vers l'observateur. + /// - Caméra : placée en `eye`, regarde en direction de `target`. + /// L'axe de visée de la caméra pointe le long de -Z (repère de vue standard). + pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self { + let forward = (target - eye).normalize(); + let right = forward.cross(up).normalize(); + let true_up = right.cross(forward); + + // La rotation amène le repère monde dans le repère caméra : + // Axe X = right + // Axe Y = true_up + // Axe Z = -forward + let mut m = Self::identity(); + m.cols[0][0] = right.x; + m.cols[1][0] = right.y; + m.cols[2][0] = right.z; + m.cols[3][0] = -right.dot(eye); + + m.cols[0][1] = true_up.x; + m.cols[1][1] = true_up.y; + m.cols[2][1] = true_up.z; + m.cols[3][1] = -true_up.dot(eye); + + m.cols[0][2] = -forward.x; + m.cols[1][2] = -forward.y; + m.cols[2][2] = -forward.z; + m.cols[3][2] = forward.dot(eye); + + m + } + + /// Matrice de projection perspective adaptée à Vulkan. + /// + /// Spécificités Vulkan vs OpenGL : + /// 1. Dans Vulkan, l'axe Y en coordonnées NDC (Normalized Device Coordinates) + /// va vers le BAS (le haut de l'écran est à -1, le bas à +1). Pour conserver + /// notre monde avec +Y vers le haut, nous inversons le signe de P[1][1] (-f). + /// 2. Dans Vulkan, la profondeur Z en coordonnées NDC varie de [0.0 (Near), 1.0 (Far)], + /// contrairement à OpenGL qui utilise [-1.0, 1.0]. + /// La projection mappe donc [near, far] sur [0, 1]. + pub fn perspective(fov_y_rad: f32, aspect: f32, near: f32, far: f32) -> Self { + let f = 1.0 / (fov_y_rad * 0.5).tan(); + let range_inv = 1.0 / (near - far); + + let mut m = Self::zero(); + m.cols[0][0] = f / aspect; + m.cols[1][1] = -f; // Inversion de Y pour le repère d'écran Vulkan + m.cols[2][2] = far * range_inv; + m.cols[2][3] = -1.0; + m.cols[3][2] = near * far * range_inv; + m + } +} + +impl Mul for Mat4 { + type Output = Self; + + /// Multiplication de matrices 4x4 : C = A * B + /// En ordre column-major, C[col][row] = sum_k (A[k][row] * B[col][k]) + fn mul(self, rhs: Self) -> Self::Output { + let mut res = Self::zero(); + for col in 0..4 { + for row in 0..4 { + res.cols[col][row] = self.cols[0][row] * rhs.cols[col][0] + + self.cols[1][row] * rhs.cols[col][1] + + self.cols[2][row] * rhs.cols[col][2] + + self.cols[3][row] * rhs.cols[col][3]; + } + } + res + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_vec3_operations() { + let a = Vec3::new(1.0, 2.0, 3.0); + let b = Vec3::new(4.0, 5.0, 6.0); + assert_eq!(a + b, Vec3::new(5.0, 7.0, 9.0)); + assert_eq!(b - a, Vec3::new(3.0, 3.0, 3.0)); + assert_eq!(a * 2.0, Vec3::new(2.0, 4.0, 6.0)); + assert_eq!(a.dot(b), 4.0 + 10.0 + 18.0); + } + + #[test] + fn test_mat4_identity_mul() { + let id = Mat4::identity(); + let m = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0)); + assert_eq!(id * m, m); + assert_eq!(m * id, m); + } +} diff --git a/src/physics.rs b/src/physics.rs new file mode 100644 index 0000000..c9313f2 --- /dev/null +++ b/src/physics.rs @@ -0,0 +1,463 @@ +use crate::camera::Camera; +use crate::math::Vec3; +use crate::world::World; + +/// Boîte englobante alignée sur les axes (Axis-Aligned Bounding Box). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AABB { + pub min: Vec3, + pub max: Vec3, +} + +impl AABB { + pub fn new(min: Vec3, max: Vec3) -> Self { + Self { min, max } + } + + /// Crée une AABB depuis la position des pieds du joueur et ses dimensions. + pub fn from_feet(feet: Vec3, width: f32, height: f32) -> Self { + let half_w = width * 0.5; + Self { + min: Vec3::new(feet.x - half_w, feet.y, feet.z - half_w), + max: Vec3::new(feet.x + half_w, feet.y + height, feet.z + half_w), + } + } + + /// Teste si deux boîtes AABB s'intersectent de manière stricte (chevauchement en volume). + #[inline(always)] + pub fn intersects(&self, other: &AABB) -> bool { + self.min.x < other.max.x + && self.max.x > other.min.x + && self.min.y < other.max.y + && self.max.y > other.min.y + && self.min.z < other.max.z + && self.max.z > other.min.z + } +} + +/// Gestion de l'entité Joueur, de sa physique (gravité, saut) et des collisions monde. +pub struct Player { + pub position: Vec3, // Position des pieds dans le monde + pub velocity: Vec3, // Vélocité en m/s + pub width: f32, // 0.6 bloc + pub height: f32, // 1.8 bloc + pub eye_height: f32,// 1.6 bloc (hauteur des yeux par rapport aux pieds) + pub is_grounded: bool, + pub flying: bool, // Mode vol activable par touche (F) +} + +impl Player { + pub const WIDTH: f32 = 0.6; + pub const HEIGHT: f32 = 1.8; + pub const EYE_HEIGHT: f32 = 1.6; + pub const GRAVITY: f32 = -26.0; // Accélération verticale en unités/s² + pub const JUMP_VELOCITY: f32 = 8.5; // Impulsion de saut permettant de franchir 1.2 bloc + pub const WALK_SPEED: f32 = 5.0; // Vitesse de marche normale + pub const FLY_SPEED: f32 = 16.0; // Vitesse en mode vol libre + + pub fn new(feet_pos: Vec3) -> Self { + Self { + position: feet_pos, + velocity: Vec3::zero(), + width: Self::WIDTH, + height: Self::HEIGHT, + eye_height: Self::EYE_HEIGHT, + is_grounded: false, + flying: false, + } + } + + /// Boîte englobante AABB actuelle du joueur. + #[inline(always)] + pub fn aabb(&self) -> AABB { + AABB::from_feet(self.position, self.width, self.height) + } + + /// Position des yeux pour la caméra de rendu et le raycasting. + #[inline(always)] + pub fn eye_position(&self) -> Vec3 { + Vec3::new( + self.position.x, + self.position.y + self.eye_height, + self.position.z, + ) + } + + /// Mise à jour physique du joueur pour un pas de temps delta-time (dt en secondes). + pub fn update(&mut self, dt: f32, camera: &Camera, world: &World) { + if self.flying { + // --- Mode vol libre (noclip / debug) --- + let fwd = camera.forward(); + let rgt = camera.right(); + let up = Vec3::new(0.0, 1.0, 0.0); + + let mut dir = Vec3::zero(); + if camera.move_forward { dir = dir + fwd; } + if camera.move_backward { dir = dir - fwd; } + if camera.move_right { dir = dir + rgt; } + if camera.move_left { dir = dir - rgt; } + if camera.move_up { dir = dir + up; } + if camera.move_down { dir = dir - up; } + + if dir.length_squared() > 0.0001 { + self.position = self.position + dir.normalize() * (Self::FLY_SPEED * dt); + } + self.velocity = Vec3::zero(); + self.is_grounded = false; + } else { + // --- Mode marche avec gravité et collisions AABB --- + // On subdivise les frames longues pour garantir l'intégrité anti-tunneling + let max_substep = 0.015; + let steps = (dt / max_substep).ceil() as usize; + let steps = steps.max(1); + let sub_dt = dt / steps as f32; + + for _ in 0..steps { + self.physics_step(sub_dt, camera, world); + } + } + } + + /// Exécute un sous-pas de physique avec résolution des collisions axe par axe. + fn physics_step(&mut self, dt: f32, camera: &Camera, world: &World) { + // 1. Calcul de la direction horizontale voulue par le joueur (plan XZ) + let yaw = camera.yaw; + let fwd = Vec3::new(yaw.sin(), 0.0, -yaw.cos()).normalize(); + let rgt = Vec3::new(yaw.cos(), 0.0, yaw.sin()).normalize(); + + let mut wish_dir = Vec3::zero(); + if camera.move_forward { wish_dir = wish_dir + fwd; } + if camera.move_backward { wish_dir = wish_dir - fwd; } + if camera.move_right { wish_dir = wish_dir + rgt; } + if camera.move_left { wish_dir = wish_dir - rgt; } + + if wish_dir.length_squared() > 0.0001 { + let move_vel = wish_dir.normalize() * Self::WALK_SPEED; + self.velocity.x = move_vel.x; + self.velocity.z = move_vel.z; + } else { + self.velocity.x = 0.0; + self.velocity.z = 0.0; + } + + // 2. Saut (impulsion verticale) uniquement si au sol + if camera.move_up && self.is_grounded { + self.velocity.y = Self::JUMP_VELOCITY; + self.is_grounded = false; + } + + // 3. Intégration de la gravité + self.velocity.y += Self::GRAVITY * dt; + // Vitesse terminale de chute (plafonnée à -35 m/s) + if self.velocity.y < -35.0 { + self.velocity.y = -35.0; + } + + // 4. Résolution des collisions AXE PAR AXE : X, puis Y, puis Z + self.resolve_axis_x(dt, world); + self.resolve_axis_y(dt, world); + self.resolve_axis_z(dt, world); + } + + /// Résolution des collisions sur l'axe X + fn resolve_axis_x(&mut self, dt: f32, world: &World) { + let dx = self.velocity.x * dt; + if dx.abs() < 1e-6 { + return; + } + + self.position.x += dx; + let half_w = self.width * 0.5; + let aabb = self.aabb(); + + let min_x = aabb.min.x.floor() as i32; + let max_x = aabb.max.x.floor() as i32; + let min_y = aabb.min.y.floor() as i32; + let max_y = aabb.max.y.floor() as i32; + let min_z = aabb.min.z.floor() as i32; + let max_z = aabb.max.z.floor() as i32; + + let mut collided = false; + let mut target_x = self.position.x; + + for y in min_y..=max_y { + for z in min_z..=max_z { + for x in min_x..=max_x { + if world.get_block(x, y, z).is_opaque() { + let block_aabb = AABB::new( + Vec3::new(x as f32, y as f32, z as f32), + Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32), + ); + if self.aabb().intersects(&block_aabb) { + collided = true; + if dx > 0.0 { + let limit = (x as f32) - half_w - 0.0001; + target_x = target_x.min(limit); + } else { + let limit = (x + 1) as f32 + half_w + 0.0001; + target_x = target_x.max(limit); + } + } + } + } + } + } + + if collided { + self.position.x = target_x; + self.velocity.x = 0.0; + } + } + + /// Résolution des collisions sur l'axe Y (chute / saut / détection du sol) + fn resolve_axis_y(&mut self, dt: f32, world: &World) { + let dy = self.velocity.y * dt; + self.position.y += dy; + + let aabb = self.aabb(); + let min_x = aabb.min.x.floor() as i32; + let max_x = aabb.max.x.floor() as i32; + let min_y = aabb.min.y.floor() as i32; + let max_y = aabb.max.y.floor() as i32; + let min_z = aabb.min.z.floor() as i32; + let max_z = aabb.max.z.floor() as i32; + + let mut collided = false; + let mut hit_ground = false; + let mut target_y = self.position.y; + + for y in min_y..=max_y { + for z in min_z..=max_z { + for x in min_x..=max_x { + if world.get_block(x, y, z).is_opaque() { + let block_aabb = AABB::new( + Vec3::new(x as f32, y as f32, z as f32), + Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32), + ); + if self.aabb().intersects(&block_aabb) { + collided = true; + if dy < 0.0 { + // Atterrissage sur le dessus d'un bloc plein + let limit = (y + 1) as f32; + target_y = target_y.max(limit); + hit_ground = true; + } else if dy > 0.0 { + // Choc contre le plafond + let limit = (y as f32) - self.height - 0.0001; + target_y = target_y.min(limit); + } + } + } + } + } + } + + if collided { + self.position.y = target_y; + self.velocity.y = 0.0; + if hit_ground { + self.is_grounded = true; + } + } else { + // Aucun contact au sol -> en chute ou en vol + self.is_grounded = false; + } + } + + /// Résolution des collisions sur l'axe Z + fn resolve_axis_z(&mut self, dt: f32, world: &World) { + let dz = self.velocity.z * dt; + if dz.abs() < 1e-6 { + return; + } + + self.position.z += dz; + let half_w = self.width * 0.5; + let aabb = self.aabb(); + + let min_x = aabb.min.x.floor() as i32; + let max_x = aabb.max.x.floor() as i32; + let min_y = aabb.min.y.floor() as i32; + let max_y = aabb.max.y.floor() as i32; + let min_z = aabb.min.z.floor() as i32; + let max_z = aabb.max.z.floor() as i32; + + let mut collided = false; + let mut target_z = self.position.z; + + for y in min_y..=max_y { + for z in min_z..=max_z { + for x in min_x..=max_x { + if world.get_block(x, y, z).is_opaque() { + let block_aabb = AABB::new( + Vec3::new(x as f32, y as f32, z as f32), + Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32), + ); + if self.aabb().intersects(&block_aabb) { + collided = true; + if dz > 0.0 { + let limit = (z as f32) - half_w - 0.0001; + target_z = target_z.min(limit); + } else { + let limit = (z + 1) as f32 + half_w + 0.0001; + target_z = target_z.max(limit); + } + } + } + } + } + } + + if collided { + self.position.z = target_z; + self.velocity.z = 0.0; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::world::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Z}; + + #[test] + fn test_aabb_intersection() { + let b1 = AABB::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)); + let b2 = AABB::new(Vec3::new(0.5, 0.5, 0.5), Vec3::new(1.5, 1.5, 1.5)); + let b3 = AABB::new(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 1.0, 1.0)); + + assert!(b1.intersects(&b2)); + assert!(!b1.intersects(&b3)); + } + + #[test] + fn test_gravity_and_ground_landing() { + let mut world = World::new(); + let mut chunk = Chunk::new_empty(0, 0); + // Crée un sol de pierre au niveau y = 2 + for x in 0..CHUNK_SIZE_X { + for z in 0..CHUNK_SIZE_Z { + chunk.set_block_local(x, 2, z, BlockType::Stone); + } + } + world.chunks.insert((0, 0), chunk); + + let camera = Camera::new(Vec3::new(2.0, 5.0, 2.0)); + let mut player = Player::new(Vec3::new(2.0, 5.0, 2.0)); + + // Intègre la physique sur plusieurs pas de temps + for _ in 0..60 { + player.update(0.016, &camera, &world); + } + + // Le joueur doit être posé sur le sol à y = 3.0 (y=2 est plein, le dessus est à y=3.0) + assert!((player.position.y - 3.0).abs() < 0.01, "Position Y: {}", player.position.y); + assert!(player.is_grounded, "Le joueur doit être au sol"); + assert_eq!(player.velocity.y, 0.0, "La vélocité verticale doit être nulle au repos"); + } + + #[test] + fn test_player_jump() { + let mut world = World::new(); + let mut chunk = Chunk::new_empty(0, 0); + for x in 0..CHUNK_SIZE_X { + for z in 0..CHUNK_SIZE_Z { + chunk.set_block_local(x, 2, z, BlockType::Stone); + } + } + world.chunks.insert((0, 0), chunk); + + let mut camera = Camera::new(Vec3::new(2.0, 3.0, 2.0)); + let mut player = Player::new(Vec3::new(2.0, 3.0, 2.0)); + player.is_grounded = true; + camera.move_up = true; // Demande de saut + + // Un pas physique avec saut + player.update(0.016, &camera, &world); + assert!(player.velocity.y > 0.0, "Le saut doit donner une vitesse vers le haut"); + assert!(!player.is_grounded, "Le joueur ne doit plus être au sol lors du saut"); + assert!(player.position.y > 3.0, "Le joueur doit avoir monté"); + } + + #[test] + fn test_wall_collision_x() { + let mut world = World::new(); + let mut chunk = Chunk::new_empty(0, 0); + // Sol à y = 0 + for x in 0..CHUNK_SIZE_X { + for z in 0..CHUNK_SIZE_Z { + chunk.set_block_local(x, 0, z, BlockType::Stone); + } + } + // Mur à x = 4, y = 1..=2, z = 0..CHUNK_SIZE_Z + for y in 1..=2 { + for z in 0..CHUNK_SIZE_Z { + chunk.set_block_local(4, y, z, BlockType::Stone); + } + } + world.chunks.insert((0, 0), chunk); + + let mut camera = Camera::new(Vec3::new(3.0, 1.0, 2.0)); + // Regarde vers +X (yaw = pi/2) + camera.yaw = std::f32::consts::FRAC_PI_2; + camera.move_forward = true; + + let mut player = Player::new(Vec3::new(3.0, 1.0, 2.0)); + player.is_grounded = true; + + for _ in 0..30 { + player.update(0.016, &camera, &world); + } + + // Le bord du joueur à x + 0.3 ne doit jamais pénétrer x = 4.0 + assert!(player.position.x + player.width * 0.5 <= 4.0001, "Position X: {}", player.position.x); + } + + #[test] + fn test_jump_and_land_on_chunk_boundary() { + let mut world = World::new(); + // Deux chunks côte à côte : (0, 0) et (1, 0) + // La frontière en X se situe exactement à x = 16.0 + let mut chunk0 = Chunk::new_empty(0, 0); + let mut chunk1 = Chunk::new_empty(1, 0); + + // Sol continu à y = 4 sur les deux chunks + for z in 0..CHUNK_SIZE_Z { + for x in 0..CHUNK_SIZE_X { + chunk0.set_block_local(x, 4, z, BlockType::Stone); + chunk1.set_block_local(x, 4, z, BlockType::Stone); + } + } + world.chunks.insert((0, 0), chunk0); + world.chunks.insert((1, 0), chunk1); + + // Joueur positionné exactement à la frontière : x = 16.0, z = 8.0, y = 8.0 + // Son AABB (largeur 0.6) s'étend de 15.7 (chunk 0) à 16.3 (chunk 1) + let mut player = Player::new(Vec3::new(16.0, 8.0, 8.0)); + let mut camera = Camera::new(player.eye_position()); + + // 1. Chute et atterrissage à cheval sur la frontière + for _ in 0..60 { + player.update(0.016, &camera, &world); + } + + assert!((player.position.y - 5.0).abs() < 0.01, "Y après atterrissage: {}", player.position.y); + assert!(player.is_grounded, "Le joueur doit être au sol sur la frontière"); + + // 2. Saut depuis la frontière + camera.move_up = true; + player.update(0.016, &camera, &world); + assert!(!player.is_grounded); + assert!(player.velocity.y > 0.0); + + // 3. Retombée et deuxième atterrissage sur la frontière + camera.move_up = false; + for _ in 0..60 { + player.update(0.016, &camera, &world); + } + + assert!((player.position.y - 5.0).abs() < 0.01, "Y après retombée: {}", player.position.y); + assert!(player.is_grounded, "Le joueur doit réatterrir de façon stable"); + assert!((player.position.x - 16.0).abs() < 0.01, "X doit rester aligné"); + } +} diff --git a/src/raycast.rs b/src/raycast.rs new file mode 100644 index 0000000..228734c --- /dev/null +++ b/src/raycast.rs @@ -0,0 +1,171 @@ +use crate::math::Vec3; +use crate::world::World; + +/// Résultat d'un raycast voxel traversant la grille du monde. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RaycastHit { + /// Coordonnées absolues (x, y, z) du bloc touché (à casser). + pub hit_pos: (i32, i32, i32), + /// Coordonnées absolues (x, y, z) du bloc adjacent vide sur la face d'impact (où poser un nouveau bloc). + pub place_pos: (i32, i32, i32), + /// Normale de la face touchée. + pub face_normal: (i32, i32, i32), +} + +/// Algorithme DDA 3D (Amanatides & Woo - "A Fast Voxel Traversal Algorithm for Ray Tracing"). +/// +/// Traverse de manière continue l'espace 3D du monde entier à travers de multiples chunks. +pub fn raycast_voxel( + origin: Vec3, + direction: Vec3, + max_distance: f32, + world: &World, +) -> Option { + let dir = direction.normalize(); + if dir.length_squared() < 0.0001 { + return None; + } + + // Coordonnées de la cellule voxel courante en coordonnées monde + let mut x = origin.x.floor() as i32; + let mut y = origin.y.floor() as i32; + let mut z = origin.z.floor() as i32; + + // Direction du pas sur chaque axe (+1 ou -1) + let step_x = if dir.x > 0.0 { 1 } else if dir.x < 0.0 { -1 } else { 0 }; + let step_y = if dir.y > 0.0 { 1 } else if dir.y < 0.0 { -1 } else { 0 }; + let step_z = if dir.z > 0.0 { 1 } else if dir.z < 0.0 { -1 } else { 0 }; + + // Distance le long du rayon pour traverser une cellule complète (1 unité) + let t_delta_x = if step_x != 0 { (1.0 / dir.x).abs() } else { f32::INFINITY }; + let t_delta_y = if step_y != 0 { (1.0 / dir.y).abs() } else { f32::INFINITY }; + let t_delta_z = if step_z != 0 { (1.0 / dir.z).abs() } else { f32::INFINITY }; + + // Distance initiale jusqu'à la première frontière de voxel + let mut t_max_x = if step_x > 0 { + ((x + 1) as f32 - origin.x) * t_delta_x + } else if step_x < 0 { + (origin.x - x as f32) * t_delta_x + } else { + f32::INFINITY + }; + + let mut t_max_y = if step_y > 0 { + ((y + 1) as f32 - origin.y) * t_delta_y + } else if step_y < 0 { + (origin.y - y as f32) * t_delta_y + } else { + f32::INFINITY + }; + + let mut t_max_z = if step_z > 0 { + ((z + 1) as f32 - origin.z) * t_delta_z + } else if step_z < 0 { + (origin.z - z as f32) * t_delta_z + } else { + f32::INFINITY + }; + + let mut current_dist = 0.0f32; + let mut normal; + + // Si la caméra est déjà dans un bloc solide dès le départ + if world.get_block(x, y, z).is_opaque() { + return Some(RaycastHit { + hit_pos: (x, y, z), + place_pos: (x, y, z), + face_normal: (0, 1, 0), + }); + } + + while current_dist <= max_distance { + // Avance vers la frontière de voxel la plus proche + if t_max_x < t_max_y { + if t_max_x < t_max_z { + current_dist = t_max_x; + t_max_x += t_delta_x; + x += step_x; + normal = (-step_x, 0, 0); + } else { + current_dist = t_max_z; + t_max_z += t_delta_z; + z += step_z; + normal = (0, 0, -step_z); + } + } else { + if t_max_y < t_max_z { + current_dist = t_max_y; + t_max_y += t_delta_y; + y += step_y; + normal = (0, -step_y, 0); + } else { + current_dist = t_max_z; + t_max_z += t_delta_z; + z += step_z; + normal = (0, 0, -step_z); + } + } + + if current_dist > max_distance { + break; + } + + // Test si la nouvelle cellule globale contient un bloc plein + if world.get_block(x, y, z).is_opaque() { + let place_pos = (x + normal.0, y + normal.1, z + normal.2); + return Some(RaycastHit { + hit_pos: (x, y, z), + place_pos, + face_normal: normal, + }); + } + } + + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::world::{BlockType, Chunk}; + + #[test] + fn test_raycast_hits_block_front() { + let mut world = World::new(); + let mut chunk = Chunk::new_empty(0, 0); + chunk.set_block_local(10, 10, 10, BlockType::Stone); + world.chunks.insert((0, 0), chunk); + + let origin = Vec3::new(10.5, 10.5, 15.0); + let dir = Vec3::new(0.0, 0.0, -1.0); + + let hit = raycast_voxel(origin, dir, 8.0, &world); + assert!(hit.is_some()); + let h = hit.unwrap(); + assert_eq!(h.hit_pos, (10, 10, 10)); + assert_eq!(h.face_normal, (0, 0, 1)); + assert_eq!(h.place_pos, (10, 10, 11)); + } + + #[test] + fn test_raycast_across_chunk_boundary() { + let mut world = World::new(); + // Chunk (0, 0) vide + world.chunks.insert((0, 0), Chunk::new_empty(0, 0)); + // Chunk (1, 0) contenant un bloc en local (0, 10, 8), soit en monde (16, 10, 8) + let mut chunk1 = Chunk::new_empty(1, 0); + chunk1.set_block_local(0, 10, 8, BlockType::Stone); + world.chunks.insert((1, 0), chunk1); + + // Rayon tiré depuis chunk 0 en (14.5, 10.5, 8.5) vers +X + let origin = Vec3::new(14.5, 10.5, 8.5); + let dir = Vec3::new(1.0, 0.0, 0.0); + + let hit = raycast_voxel(origin, dir, 8.0, &world); + assert!(hit.is_some()); + let h = hit.unwrap(); + assert_eq!(h.hit_pos, (16, 10, 8)); // Bloc dans le chunk voisin ! + assert_eq!(h.face_normal, (-1, 0, 0)); // Entrée par -X + assert_eq!(h.place_pos, (15, 10, 8)); // Poser dans le chunk 0 + } +} diff --git a/src/renderer/device.rs b/src/renderer/device.rs new file mode 100644 index 0000000..08d8fb4 --- /dev/null +++ b/src/renderer/device.rs @@ -0,0 +1,151 @@ +use winit::raw_window_handle::HasDisplayHandle; +use std::sync::Arc; +use vulkano::device::physical::{PhysicalDevice, PhysicalDeviceType}; +use vulkano::device::{Device, DeviceCreateInfo, DeviceExtensions, Queue, QueueCreateInfo, QueueFlags}; +use vulkano::instance::{Instance, InstanceCreateFlags, InstanceCreateInfo}; +use vulkano::swapchain::Surface; +use vulkano::VulkanLibrary; +use winit::window::Window; + +/// Structure regroupant le contexte initial du périphérique Vulkan. +pub struct DeviceContext { + pub instance: Arc, + pub surface: Arc, + pub device: Arc, + pub queue: Arc, +} + +/// Initialise l'instance Vulkan, crée la Surface liée à la fenêtre winit, +/// sélectionne le meilleur GPU physique disponible et crée le Logical Device. +pub fn init_device( + window: Arc, + display_handle: &impl HasDisplayHandle, +) -> Result> { + // 1. Chargement de la bibliothèque dynamique Vulkan installée sur l'OS (vulkan-1.dll / libvulkan.so) + let library = VulkanLibrary::new()?; + + // 2. Extensions d'instance requises pour afficher sur une fenêtre (Winit / OS surface) + // Surface::required_extensions interroge le display handle winit pour savoir quelles + // extensions WSI (Window System Integration) sont indispensables (ex: VK_KHR_win32_surface, VK_KHR_surface). + let required_extensions = Surface::required_extensions(display_handle)?; + + // 3. Création de l'instance Vulkan + // L'instance représente la connexion entre notre application et le runtime Vulkan. + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + )?; + + // 4. Création de la Surface Vulkan + // La Surface fait le pont entre le système de fenêtrage de l'OS (géré par winit) + // et l'instance Vulkan. Les images rendues par le GPU y seront présentées. + let surface = Surface::from_window(instance.clone(), window)?; + + // 5. Extensions requises au niveau du Device (GPU) + // La swapchain (VK_KHR_swapchain) est impérative pour pouvoir présenter des images à l'écran. + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + + // 6. Sélection du Physical Device (GPU) et de la Queue Family appropriée + // + // Pourquoi ce filtrage et ce choix : + // - On ne garde que les GPU supportant l'extension `khr_swapchain`. + // - On recherche une "Queue Family" qui supporte À LA FOIS : + // a) Les opérations graphiques (QueueFlags::GRAPHICS) pour le dessin de nos voxels. + // b) La présentation vers notre Surface (`surface_support(...) == true`). + // Avoir une queue unique combinant Graphique + Présentation évite d'avoir à gérer + // des transferts complexes d'images entre plusieurs files (Queue Family Ownership Transfers). + // - On priorise un GPU dédié (DiscreteGpu) par rapport à un GPU intégré (IntegratedGpu), + // puis virtuel ou logiciel. + let (physical_device, queue_family_index) = select_physical_device( + &instance, + &surface, + &device_extensions, + )?; + + println!( + "GPU sélectionné : {} (Type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type + ); + + // 7. Création du Logical Device et de la Queue graphique + // Le Logical Device est l'interface principale avec laquelle nous communiquerons avec le GPU. + // On alloue 1 queue avec une priorité standard (1.0). + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() + }, + )?; + + let queue = queues.next().expect("Aucune queue trouvée sur le device"); + + Ok(DeviceContext { + instance, + surface, + device, + queue, + }) +} + +/// Parcourt tous les GPU disponibles et choisit le plus adapté selon nos critères. +fn select_physical_device( + instance: &Arc, + surface: &Arc, + device_extensions: &DeviceExtensions, +) -> Result<(Arc, u32), Box> { + let mut candidates: Vec<(Arc, u32, u32)> = Vec::new(); + + for p in instance.enumerate_physical_devices()? { + // Le GPU doit supporter les extensions demandées (khr_swapchain) + if !p.supported_extensions().contains(device_extensions) { + continue; + } + + // On cherche une queue family supportant Graphique ET Présentation + let mut suitable_queue_family = None; + for (idx, q) in p.queue_family_properties().iter().enumerate() { + let index = idx as u32; + let supports_graphics = q.queue_flags.intersects(QueueFlags::GRAPHICS); + let supports_presentation = p.surface_support(index, surface).unwrap_or(false); + + if supports_graphics && supports_presentation { + suitable_queue_family = Some(index); + break; + } + } + + if let Some(q_idx) = suitable_queue_family { + // Score de priorité selon le type de périphérique + let score = match p.properties().device_type { + PhysicalDeviceType::DiscreteGpu => 0, + PhysicalDeviceType::IntegratedGpu => 1, + PhysicalDeviceType::VirtualGpu => 2, + PhysicalDeviceType::Cpu => 3, + _ => 4, + }; + candidates.push((p, q_idx, score)); + } + } + + // On trie par score croissant (0 = DiscreteGpu en priorité) + candidates.sort_by_key(|(_, _, score)| *score); + + if let Some((device, queue_family, _)) = candidates.into_iter().next() { + Ok((device, queue_family)) + } else { + Err("Aucun GPU compatible avec le rendu graphique et la présentation Vulkan n'a été trouvé.".into()) + } +} diff --git a/src/renderer/mesh.rs b/src/renderer/mesh.rs new file mode 100644 index 0000000..811c7d3 --- /dev/null +++ b/src/renderer/mesh.rs @@ -0,0 +1,234 @@ +use std::sync::Arc; +use vulkano::buffer::{Buffer, BufferContents, BufferCreateInfo, BufferUsage, Subbuffer}; +use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator}; +use vulkano::pipeline::graphics::vertex_input::Vertex; + +/// Format d'un sommet pour notre cube (et futurs chunks voxel). +/// +/// Alignement mémoire : +/// - `position` : coordonnées 3D (X, Y, Z) +/// - `color` : couleur RVB par sommet (permet une couleur unique par face ou teinte) +/// - `normal` : normale de la surface (pour un ombrage directionnel basique) +/// - `uv` : coordonnées de texture normalisées [0..1] dans l'atlas +#[derive(BufferContents, Vertex, Clone, Copy, Debug)] +#[repr(C)] +pub struct CubeVertex { + #[format(R32G32B32_SFLOAT)] + pub position: [f32; 3], + #[format(R32G32B32_SFLOAT)] + pub color: [f32; 3], + #[format(R32G32B32_SFLOAT)] + pub normal: [f32; 3], + #[format(R32G32_SFLOAT)] + pub uv: [f32; 2], +} + +/// Conteneur des buffers GPU d'un maillage. +pub struct MeshBuffers { + pub vertex_buffer: Subbuffer<[CubeVertex]>, + pub index_buffer: Subbuffer<[u32]>, + pub index_count: u32, +} + +/// Génère la géométrie d'un cube unitaire de côté 1.0 centré en (0, 0, 0). +/// +/// Pourquoi 24 sommets et non 8 ? +/// Un cube partagé avec 8 sommets forcerait les faces adjacentes à partager +/// leurs normales et leurs couleurs. En dupliquant les 4 sommets de chaque +/// face (6 faces * 4 = 24 sommets), chaque face dispose d'une normale plane +/// distincte (flat shading) et d'une couleur propre. +#[allow(dead_code)] +pub fn create_cube_mesh( + memory_allocator: Arc, +) -> Result> { + let mut vertices = Vec::with_capacity(24); + let mut indices = Vec::with_capacity(36); + + // Définition des 6 faces : (nom, normale, couleur, [p0, p1, p2, p3]) + // Ordre des sommets en Counter-Clockwise (sens trigonométrique vu de l'extérieur) + let faces = [ + // Face Dessus (+Y) - Vert Herbe + ( + [0.0, 1.0, 0.0], + [0.2, 0.8, 0.25], + [ + [-0.5, 0.5, 0.5], + [0.5, 0.5, 0.5], + [0.5, 0.5, -0.5], + [-0.5, 0.5, -0.5], + ], + ), + // Face Dessous (-Y) - Marron Terre + ( + [0.0, -1.0, 0.0], + [0.55, 0.35, 0.2], + [ + [-0.5, -0.5, -0.5], + [0.5, -0.5, -0.5], + [0.5, -0.5, 0.5], + [-0.5, -0.5, 0.5], + ], + ), + // Face Avant (+Z) - Bleu + ( + [0.0, 0.0, 1.0], + [0.2, 0.45, 0.9], + [ + [-0.5, -0.5, 0.5], + [0.5, -0.5, 0.5], + [0.5, 0.5, 0.5], + [-0.5, 0.5, 0.5], + ], + ), + // Face Arrière (-Z) - Cyan + ( + [0.0, 0.0, -1.0], + [0.2, 0.85, 0.85], + [ + [0.5, -0.5, -0.5], + [-0.5, -0.5, -0.5], + [-0.5, 0.5, -0.5], + [0.5, 0.5, -0.5], + ], + ), + // Face Droite (+X) - Rouge + ( + [1.0, 0.0, 0.0], + [0.9, 0.25, 0.25], + [ + [0.5, -0.5, 0.5], + [0.5, -0.5, -0.5], + [0.5, 0.5, -0.5], + [0.5, 0.5, 0.5], + ], + ), + // Face Gauche (-X) - Jaune + ( + [-1.0, 0.0, 0.0], + [0.9, 0.85, 0.2], + [ + [-0.5, -0.5, -0.5], + [-0.5, -0.5, 0.5], + [-0.5, 0.5, 0.5], + [-0.5, 0.5, -0.5], + ], + ), + ]; + + for (face_idx, (normal, color, quad)) in faces.iter().enumerate() { + let base_index = (face_idx * 4) as u32; + + for (i, pos) in quad.iter().enumerate() { + let uv = match i { + 0 => [0.0, 1.0], + 1 => [1.0, 1.0], + 2 => [1.0, 0.0], + _ => [0.0, 0.0], + }; + vertices.push(CubeVertex { + position: *pos, + color: *color, + normal: *normal, + uv, + }); + } + + // Deux triangles par quad : (0, 1, 2) et (2, 3, 0) + indices.push(base_index + 0); + indices.push(base_index + 1); + indices.push(base_index + 2); + indices.push(base_index + 2); + indices.push(base_index + 3); + indices.push(base_index + 0); + } + + MeshBuffers::from_data(memory_allocator, vertices, indices) +} + +impl MeshBuffers { + /// Alloue les Vertex et Index Buffers Vulkan à partir d'une liste de sommets et d'indices. + pub fn from_data( + memory_allocator: Arc, + vertices: Vec, + indices: Vec, + ) -> Result> { + let index_count = indices.len() as u32; + + let vertex_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + )?; + + let index_buffer = Buffer::from_iter( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::INDEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + indices, + )?; + + Ok(Self { + vertex_buffer, + index_buffer, + index_count, + }) + } +} + +/// Crée le maillage filaire (12 arêtes = 24 indices) d'un cube unitaire [0..1] +/// légèrement dilaté pour le contour de sélection visuelle. +pub fn create_wireframe_cube_mesh( + memory_allocator: Arc, +) -> Result> { + let s = 1.002f32; + let o = -0.001f32; + let color = [0.05f32, 0.05f32, 0.05f32]; // Noir / gris très sombre + let normal = [0.0f32, 1.0f32, 0.0f32]; + + let p = [ + [o, o, o], + [o + s, o, o], + [o + s, o, o + s], + [o, o, o + s], + [o, o + s, o], + [o + s, o + s, o], + [o + s, o + s, o + s], + [o, o + s, o + s], + ]; + + let vertices: Vec = p + .iter() + .map(|pos| CubeVertex { + position: *pos, + color, + normal, + uv: [0.0, 0.0], + }) + .collect(); + + let indices: Vec = vec![ + // Base inférieure + 0, 1, 1, 2, 2, 3, 3, 0, + // Base supérieure + 4, 5, 5, 6, 6, 7, 7, 4, + // Montants verticaux + 0, 4, 1, 5, 2, 6, 3, 7, + ]; + + MeshBuffers::from_data(memory_allocator, vertices, indices) +} diff --git a/src/renderer/mod.rs b/src/renderer/mod.rs new file mode 100644 index 0000000..880eaad --- /dev/null +++ b/src/renderer/mod.rs @@ -0,0 +1,390 @@ +pub mod device; +pub mod mesh; +pub mod pipeline; +pub mod render_pass; +pub mod swapchain; +pub mod texture; + +use std::collections::HashMap; +use std::sync::Arc; +use vulkano::command_buffer::allocator::StandardCommandBufferAllocator; +use vulkano::command_buffer::{ + AutoCommandBufferBuilder, CommandBufferUsage, RenderPassBeginInfo, SubpassBeginInfo, + SubpassContents, +}; +use vulkano::device::{Device, Queue}; +use vulkano::format::Format; +use vulkano::memory::allocator::StandardMemoryAllocator; +use vulkano::pipeline::graphics::viewport::Viewport; +use vulkano::pipeline::{GraphicsPipeline, Pipeline, PipelineBindPoint}; +use vulkano::render_pass::RenderPass; +use vulkano::swapchain::{acquire_next_image, SwapchainPresentInfo}; +use vulkano::sync::{self, GpuFuture}; +use vulkano::{Validated, VulkanError}; +use winit::raw_window_handle::HasDisplayHandle; +use winit::window::Window; + +use crate::math::Mat4; +use self::device::init_device; +use self::mesh::{create_wireframe_cube_mesh, MeshBuffers}; +use self::pipeline::{create_graphics_pipeline, create_line_pipeline, create_ui_pipeline, vs}; +use self::render_pass::create_render_pass; +use self::swapchain::{create_swapchain_bundle, recreate_swapchain_bundle, SwapchainBundle}; +use self::texture::{create_texture_atlas_bundle, VulkanTexture}; + +/// Le gestionnaire principal du moteur de rendu Vulkan. +pub struct VulkanRenderer { + _instance: Arc, + device: Arc, + queue: Arc, + render_pass: Arc, + pipeline: Arc, + line_pipeline: Arc, + ui_pipeline: Arc, + texture: VulkanTexture, + chunk_meshes: HashMap<(i32, i32), MeshBuffers>, + wireframe_mesh: MeshBuffers, + memory_allocator: Arc, + swapchain_bundle: SwapchainBundle, + command_buffer_allocator: Arc, + previous_frame_end: Option>, + recreate_swapchain: bool, +} + +impl VulkanRenderer { + /// Initialise tous les composants Vulkan nécessaires au rendu 3D. + pub fn new( + window: Arc, + display_handle: &impl HasDisplayHandle, + ) -> Result> { + let dimensions = window.inner_size().into(); + + // 1. Initialisation de l'instance, de la surface et du GPU + let dev_ctx = init_device(window, display_handle)?; + + // 2. Allocateur de mémoire GPU standard + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(dev_ctx.device.clone())); + + // 3. Détection des formats (couleur sRGB et profondeur D32_SFLOAT) + let surface_formats = dev_ctx + .device + .physical_device() + .surface_formats(&dev_ctx.surface, Default::default())?; + let (color_format, _) = surface_formats + .iter() + .cloned() + .find(|(format, _)| { + *format == Format::B8G8R8A8_SRGB || *format == Format::R8G8B8A8_SRGB + }) + .unwrap_or_else(|| surface_formats[0]); + + // Format de profondeur standard optimal + let depth_format = Format::D32_SFLOAT; + + // 4. Création de la RenderPass avec Color + Depth Buffer + let render_pass = create_render_pass(dev_ctx.device.clone(), color_format, depth_format)?; + + // 5. Création de la Swapchain et des Framebuffers + let swapchain_bundle = create_swapchain_bundle( + dev_ctx.device.clone(), + memory_allocator.clone(), + dev_ctx.surface.clone(), + dimensions, + render_pass.clone(), + depth_format, + )?; + + // 6. Création des pipelines graphiques (3D opaque, wireframe de sélection et 2D UI hotbar) + let subpass = render_pass.clone().first_subpass(); + let pipeline = create_graphics_pipeline(dev_ctx.device.clone(), subpass.clone())?; + let line_pipeline = create_line_pipeline(dev_ctx.device.clone(), subpass.clone())?; + let ui_pipeline = create_ui_pipeline(dev_ctx.device.clone(), subpass)?; + + // 7. Génération du maillage filaire pour la sélection + let wireframe_mesh = create_wireframe_cube_mesh(memory_allocator.clone())?; + + // 8. Allocateur de Command Buffers + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + dev_ctx.device.clone(), + Default::default(), + )); + + // 9. Génération et upload de l'atlas de textures procédurales (Nearest Sampler, Set 0 Binding 0) + let texture = create_texture_atlas_bundle( + memory_allocator.clone(), + command_buffer_allocator.clone(), + dev_ctx.device.clone(), + dev_ctx.queue.clone(), + pipeline.layout().clone(), + )?; + + // 10. Initialisation de la synchronisation GPU + let previous_frame_end = Some(sync::now(dev_ctx.device.clone()).boxed()); + + Ok(Self { + _instance: dev_ctx.instance, + device: dev_ctx.device, + queue: dev_ctx.queue, + render_pass, + pipeline, + line_pipeline, + ui_pipeline, + texture, + chunk_meshes: HashMap::new(), + wireframe_mesh, + memory_allocator, + swapchain_bundle, + command_buffer_allocator, + previous_frame_end, + recreate_swapchain: false, + }) + } + + /// Met à jour ou insère les buffers GPU d'un chunk spécifique. + pub fn set_chunk_mesh( + &mut self, + chunk_pos: (i32, i32), + data: crate::world::ChunkMeshData, + ) -> Result<(), Box> { + let buffers = MeshBuffers::from_data( + self.memory_allocator.clone(), + data.vertices, + data.indices, + )?; + self.chunk_meshes.insert(chunk_pos, buffers); + Ok(()) + } + + /// Supprime le maillage GPU d'un chunk déchargé. + #[allow(dead_code)] + pub fn remove_chunk_mesh(&mut self, chunk_pos: &(i32, i32)) { + self.chunk_meshes.remove(chunk_pos); + } + + /// Signale que la fenêtre a été redimensionnée. + pub fn notify_resized(&mut self) { + self.recreate_swapchain = true; + } + + /// Exécute une frame complète de rendu : chunks 3D, contour de sélection et 2D Hotbar d'inventaire. + pub fn render( + &mut self, + window_dimensions: [u32; 2], + view_matrix: Mat4, + selected_block: Option<(i32, i32, i32)>, + ui_mesh: Option<(Vec, Vec)>, + ) { + if window_dimensions[0] == 0 || window_dimensions[1] == 0 { + return; + } + + // Nettoyage régulier des ressources désallouées sur le GPU + if let Some(future) = &mut self.previous_frame_end { + future.cleanup_finished(); + } + + // Recréation de la swapchain et du depth buffer lors d'un resize + if self.recreate_swapchain { + if let Err(err) = recreate_swapchain_bundle( + &mut self.swapchain_bundle, + self.memory_allocator.clone(), + window_dimensions, + self.render_pass.clone(), + ) { + eprintln!("Erreur lors de la recréation de la swapchain : {err}"); + return; + } + self.recreate_swapchain = false; + } + + // Calcul de la matrice MVP (Model-View-Projection) + let aspect = window_dimensions[0] as f32 / window_dimensions[1] as f32; + let fov = 60.0f32.to_radians(); + let projection = Mat4::perspective(fov, aspect, 0.1, 100.0); + let model = Mat4::identity(); // Le cube est positionné à l'origine (0, 0, 0) + let mvp = projection * view_matrix * model; + + // 1. Acquisition de la prochaine image de la swapchain + let (image_index, suboptimal, acquire_future) = match acquire_next_image( + self.swapchain_bundle.swapchain.clone(), + None, + ) + .map_err(Validated::unwrap) + { + Ok(r) => r, + Err(VulkanError::OutOfDate) => { + self.recreate_swapchain = true; + return; + } + Err(e) => { + eprintln!("Échec de l'acquisition de l'image suivante : {e}"); + return; + } + }; + + if suboptimal { + self.recreate_swapchain = true; + } + + // 2. Enregistrement des commandes GPU + let mut builder = AutoCommandBufferBuilder::primary( + self.command_buffer_allocator.clone(), + self.queue.queue_family_index(), + CommandBufferUsage::OneTimeSubmit, + ) + .expect("Échec de la création du command buffer builder"); + + // Fond bleu ciel et effacement du depth buffer à 1.0 + let clear_color = [0.25f32, 0.50f32, 0.85f32, 1.0f32]; + let clear_depth = 1.0f32; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: [window_dimensions[0] as f32, window_dimensions[1] as f32], + depth_range: 0.0..=1.0, + }; + + let push_constants = vs::PushConstants { mvp: mvp.cols }; + + builder + .begin_render_pass( + RenderPassBeginInfo { + clear_values: vec![Some(clear_color.into()), Some(clear_depth.into())], + ..RenderPassBeginInfo::framebuffer( + self.swapchain_bundle.framebuffers[image_index as usize].clone(), + ) + }, + SubpassBeginInfo { + contents: SubpassContents::Inline, + ..Default::default() + }, + ) + .expect("Échec du début de la render pass") + .bind_pipeline_graphics(self.pipeline.clone()) + .expect("Échec du bind pipeline") + .bind_descriptor_sets( + PipelineBindPoint::Graphics, + self.pipeline.layout().clone(), + 0, + self.texture.descriptor_set.clone(), + ) + .expect("Échec du bind descriptor set") + .set_viewport(0, [viewport].into_iter().collect()) + .expect("Échec du set viewport") + .push_constants(self.pipeline.layout().clone(), 0, push_constants) + .expect("Échec de l'envoi des push constants"); + + // Rendu de chaque chunk du monde (1 draw call par chunk) + for mesh in self.chunk_meshes.values() { + if mesh.index_count > 0 { + builder + .bind_vertex_buffers(0, mesh.vertex_buffer.clone()) + .expect("Échec du bind vertex buffer") + .bind_index_buffer(mesh.index_buffer.clone()) + .expect("Échec du bind index buffer"); + + unsafe { + builder + .draw_indexed(mesh.index_count, 1, 0, 0, 0) + .expect("Échec du draw_indexed"); + } + } + } + + // 2.bis Rendu du contour filaire (wireframe) autour du bloc visé + if let Some((bx, by, bz)) = selected_block { + let wireframe_model = Mat4::from_translation(crate::math::Vec3::new( + bx as f32, by as f32, bz as f32, + )); + let wireframe_mvp = projection * view_matrix * wireframe_model; + + builder + .bind_pipeline_graphics(self.line_pipeline.clone()) + .expect("Échec du bind line pipeline") + .bind_vertex_buffers(0, self.wireframe_mesh.vertex_buffer.clone()) + .expect("Échec du bind wireframe vertex buffer") + .bind_index_buffer(self.wireframe_mesh.index_buffer.clone()) + .expect("Échec du bind wireframe index buffer") + .push_constants( + self.line_pipeline.layout().clone(), + 0, + vs::PushConstants { + mvp: wireframe_mvp.cols, + }, + ) + .expect("Échec de l'envoi des push constants wireframe"); + + unsafe { + builder + .draw_indexed(self.wireframe_mesh.index_count, 1, 0, 0, 0) + .expect("Échec du draw_indexed wireframe"); + } + } + + // 2.ter Rendu de l'interface 2D (Hotbar d'inventaire) + if let Some((ui_vertices, ui_indices)) = ui_mesh { + if !ui_indices.is_empty() { + if let Ok(ui_buf) = MeshBuffers::from_data( + self.memory_allocator.clone(), + ui_vertices, + ui_indices, + ) { + builder + .bind_pipeline_graphics(self.ui_pipeline.clone()) + .expect("Échec du bind UI pipeline") + .bind_vertex_buffers(0, ui_buf.vertex_buffer.clone()) + .expect("Échec du bind UI vertex buffer") + .bind_index_buffer(ui_buf.index_buffer.clone()) + .expect("Échec du bind UI index buffer"); + + unsafe { + builder + .draw_indexed(ui_buf.index_count, 1, 0, 0, 0) + .expect("Échec du draw_indexed UI"); + } + } + } + } + + builder + .end_render_pass(Default::default()) + .expect("Échec de la fin de la render pass"); + + let command_buffer = builder + .build() + .expect("Échec de la construction du command buffer"); + + // 3. Soumission et présentation + let prev_future = self + .previous_frame_end + .take() + .unwrap_or_else(|| sync::now(self.device.clone()).boxed()); + + let execution = prev_future + .join(acquire_future) + .then_execute(self.queue.clone(), command_buffer) + .expect("Échec de la soumission du command buffer") + .then_swapchain_present( + self.queue.clone(), + SwapchainPresentInfo::swapchain_image_index( + self.swapchain_bundle.swapchain.clone(), + image_index, + ), + ) + .then_signal_fence_and_flush(); + + match execution.map_err(Validated::unwrap) { + Ok(future) => { + self.previous_frame_end = Some(future.boxed()); + } + Err(VulkanError::OutOfDate) => { + self.recreate_swapchain = true; + self.previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + } + Err(e) => { + eprintln!("Erreur lors de la synchronisation GPU/présentation : {e}"); + self.previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + } + } + } +} diff --git a/src/renderer/pipeline.rs b/src/renderer/pipeline.rs new file mode 100644 index 0000000..7e0caf9 --- /dev/null +++ b/src/renderer/pipeline.rs @@ -0,0 +1,275 @@ +use std::sync::Arc; +use vulkano::device::Device; +use vulkano::pipeline::graphics::color_blend::{ColorBlendAttachmentState, ColorBlendState}; +use vulkano::pipeline::graphics::depth_stencil::{CompareOp, DepthState, DepthStencilState}; +use vulkano::pipeline::graphics::input_assembly::{InputAssemblyState, PrimitiveTopology}; +use vulkano::pipeline::graphics::multisample::MultisampleState; +use vulkano::pipeline::graphics::rasterization::{CullMode, FrontFace, RasterizationState}; +use vulkano::pipeline::graphics::vertex_input::{Vertex, VertexDefinition}; +use vulkano::pipeline::graphics::viewport::ViewportState; +use vulkano::pipeline::graphics::GraphicsPipelineCreateInfo; +use vulkano::pipeline::layout::PipelineDescriptorSetLayoutCreateInfo; +use vulkano::pipeline::{DynamicState, GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo}; +use vulkano::render_pass::Subpass; + +use super::mesh::CubeVertex; + +pub mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 + layout(location = 0) in vec3 position; + layout(location = 1) in vec3 color; + layout(location = 2) in vec3 normal; + layout(location = 3) in vec2 uv; + + layout(push_constant) uniform PushConstants { + mat4 mvp; + } pc; + + layout(location = 0) out vec3 v_color; + layout(location = 1) out vec3 v_normal; + layout(location = 2) out vec2 v_uv; + + void main() { + gl_Position = pc.mvp * vec4(position, 1.0); + v_color = color; + v_normal = normal; + v_uv = uv; + } + ", + } +} + +pub mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 + layout(location = 0) in vec3 v_color; + layout(location = 1) in vec3 v_normal; + layout(location = 2) in vec2 v_uv; + + layout(set = 0, binding = 0) uniform sampler2D tex_sampler; + + layout(location = 0) out vec4 f_color; + + void main() { + // Éclairage diffus direct (type soleil de Minecraft) + vec3 light_dir = normalize(vec3(0.4, 0.9, 0.3)); + float diff = max(dot(normalize(v_normal), light_dir), 0.35); + vec4 tex_color = texture(tex_sampler, v_uv); + f_color = vec4(tex_color.rgb * v_color * diff, tex_color.a); + } + ", + } +} + +pub mod line_fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 + layout(location = 0) in vec3 v_color; + layout(location = 1) in vec3 v_normal; + layout(location = 2) in vec2 v_uv; + + layout(location = 0) out vec4 f_color; + + void main() { + // Rendu de la couleur directe sans ombrage pour le wireframe + f_color = vec4(v_color, 1.0); + } + ", + } +} + +/// Crée le pipeline graphique 3D avec Depth Testing, Culling et Push Constants. +pub fn create_graphics_pipeline( + device: Arc, + subpass: Subpass, +) -> Result, Box> { + let vs = vs::load(device.clone())?.entry_point("main").unwrap(); + let fs = fs::load(device.clone())?.entry_point("main").unwrap(); + + let vertex_input_state = [CubeVertex::per_vertex()] + .definition(&vs)?; + + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + + let layout = PipelineLayout::new( + device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(device.clone())?, + )?; + + let pipeline = GraphicsPipeline::new( + device, + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState { + cull_mode: CullMode::Back, + front_face: FrontFace::Clockwise, + ..Default::default() + }), + depth_stencil_state: Some(DepthStencilState { + depth: Some(DepthState::simple()), + ..Default::default() + }), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + )?; + + Ok(pipeline) +} + +/// Crée le pipeline graphique dédié au rendu des lignes du cadre de sélection (Wireframe). +pub fn create_line_pipeline( + device: Arc, + subpass: Subpass, +) -> Result, Box> { + let vs = vs::load(device.clone())?.entry_point("main").unwrap(); + let fs = line_fs::load(device.clone())?.entry_point("main").unwrap(); + + let vertex_input_state = [CubeVertex::per_vertex()] + .definition(&vs)?; + + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + + let layout = PipelineLayout::new( + device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(device.clone())?, + )?; + + let pipeline = GraphicsPipeline::new( + device, + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + // Topologie LineList pour dessiner les arêtes du cube + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::LineList, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState { + cull_mode: CullMode::None, + ..Default::default() + }), + // CompareOp::LessOrEqual sans écriture dans le depth buffer pour un contour net + depth_stencil_state: Some(DepthStencilState { + depth: Some(DepthState { + compare_op: CompareOp::LessOrEqual, + write_enable: false, + }), + ..Default::default() + }), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + )?; + + Ok(pipeline) +} + +pub mod ui_vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 + layout(location = 0) in vec3 position; + layout(location = 1) in vec3 color; + layout(location = 2) in vec3 normal; + layout(location = 3) in vec2 uv; + + layout(location = 0) out vec3 v_color; + + void main() { + // Coordonnées 2D écran directes en NDC [-1..1] + gl_Position = vec4(position.xy, 0.0, 1.0); + v_color = color; + } + ", + } +} + +/// Crée le pipeline graphique dédié à l'interface 2D (Hotbar d'inventaire). +pub fn create_ui_pipeline( + device: Arc, + subpass: Subpass, +) -> Result, Box> { + let vs = ui_vs::load(device.clone())?.entry_point("main").unwrap(); + let fs = line_fs::load(device.clone())?.entry_point("main").unwrap(); + + let vertex_input_state = [CubeVertex::per_vertex()].definition(&vs)?; + + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + + let layout = PipelineLayout::new( + device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(device.clone())?, + )?; + + let pipeline = GraphicsPipeline::new( + device, + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState { + cull_mode: CullMode::None, + ..Default::default() + }), + // Depth test désactivé : l'UI s'affiche toujours au premier plan + depth_stencil_state: Some(DepthStencilState { + depth: Some(DepthState { + compare_op: CompareOp::Always, + write_enable: false, + }), + ..Default::default() + }), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + )?; + + Ok(pipeline) +} diff --git a/src/renderer/render_pass.rs b/src/renderer/render_pass.rs new file mode 100644 index 0000000..d9092a1 --- /dev/null +++ b/src/renderer/render_pass.rs @@ -0,0 +1,45 @@ +use std::sync::Arc; +use vulkano::device::Device; +use vulkano::format::Format; +use vulkano::render_pass::RenderPass; +use vulkano::single_pass_renderpass; + +/// Crée une RenderPass 3D avec attachement couleur et attachement de profondeur (Depth Buffer). +/// +/// Détails des choix Vulkan : +/// - Couleur : +/// * `load_op: Clear` : Au début de la passe, le GPU efface l'écran avec la couleur de fond choisie. +/// * `store_op: Store` : Le résultat rendu est conservé pour être présenté sur la fenêtre. +/// - Profondeur : +/// * `load_op: Clear` : Réinitialise le depth buffer à 1.0 (distance maximale). +/// * `store_op: DontCare` : Une fois la passe terminée, les données de profondeur n'ont plus besoin +/// d'être conservées en mémoire vidéo principale (économie de bande passante mémoire). +pub fn create_render_pass( + device: Arc, + color_format: Format, + depth_format: Format, +) -> Result, Box> { + let render_pass = single_pass_renderpass!( + device, + attachments: { + color: { + format: color_format, + samples: 1, + load_op: Clear, + store_op: Store, + }, + depth: { + format: depth_format, + samples: 1, + load_op: Clear, + store_op: DontCare, + }, + }, + pass: { + color: [color], + depth_stencil: {depth}, + }, + )?; + + Ok(render_pass) +} diff --git a/src/renderer/swapchain.rs b/src/renderer/swapchain.rs new file mode 100644 index 0000000..e8f1b56 --- /dev/null +++ b/src/renderer/swapchain.rs @@ -0,0 +1,170 @@ +use std::sync::Arc; +use vulkano::device::Device; +use vulkano::format::Format; +use vulkano::image::view::ImageView; +use vulkano::image::{Image, ImageCreateInfo, ImageType, ImageUsage}; +use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator}; +use vulkano::render_pass::{Framebuffer, FramebufferCreateInfo, RenderPass}; +use vulkano::swapchain::{ + CompositeAlpha, PresentMode, Surface, Swapchain, SwapchainCreateInfo, +}; + +/// Regroupe la swapchain et les ressources dérivées (images, buffer de profondeur et framebuffers). +pub struct SwapchainBundle { + pub swapchain: Arc, + pub images: Vec>, + #[allow(dead_code)] + pub image_format: Format, + pub depth_format: Format, + pub framebuffers: Vec>, +} + +/// Crée la Swapchain, l'image de profondeur (Z-Buffer) et les Framebuffers initiaux. +pub fn create_swapchain_bundle( + device: Arc, + memory_allocator: Arc, + surface: Arc, + dimensions: [u32; 2], + render_pass: Arc, + depth_format: Format, +) -> Result> { + let surface_capabilities = device + .physical_device() + .surface_capabilities(&surface, Default::default())?; + + // 1. Choix du format de couleur : + // On privilégie un format sRGB (B8G8R8A8_SRGB ou R8G8B8A8_SRGB) + // car le rendu sRGB permet une correction gamma automatique par le matériel. + let surface_formats = device + .physical_device() + .surface_formats(&surface, Default::default())?; + + let (image_format, _) = surface_formats + .iter() + .cloned() + .find(|(format, _)| { + *format == Format::B8G8R8A8_SRGB || *format == Format::R8G8B8A8_SRGB + }) + .unwrap_or_else(|| surface_formats[0]); + + // 2. Nombre d'images dans la swapchain (Triple Buffering si supporté) + let max_images = surface_capabilities.max_image_count.unwrap_or(u32::MAX); + let min_image_count = (surface_capabilities.min_image_count + 1).min(max_images); + + // 3. Mode de composition alpha : Opaque pour éviter la transparence avec le bureau + let composite_alpha = surface_capabilities + .supported_composite_alpha + .into_iter() + .find(|&c| c == CompositeAlpha::Opaque) + .unwrap_or_else(|| { + surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap_or(CompositeAlpha::Opaque) + }); + + // 4. Mode de présentation : Fifo = V-Sync garanti sans tearing + let present_mode = PresentMode::Fifo; + + // 5. Création de la Swapchain + let (swapchain, images) = Swapchain::new( + device, + surface, + SwapchainCreateInfo { + min_image_count, + image_format, + image_extent: dimensions, + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha, + present_mode, + ..Default::default() + }, + )?; + + // 6. Création de l'image de profondeur (Z-Buffer) et des Framebuffers + let framebuffers = create_framebuffers( + &images, + memory_allocator, + dimensions, + depth_format, + render_pass, + )?; + + Ok(SwapchainBundle { + swapchain, + images, + image_format, + depth_format, + framebuffers, + }) +} + +/// Crée un Framebuffer pour chaque image de la Swapchain en attachant la vue couleur +/// et la vue de profondeur (Depth Buffer). +pub fn create_framebuffers( + images: &[Arc], + memory_allocator: Arc, + dimensions: [u32; 2], + depth_format: Format, + render_pass: Arc, +) -> Result>, Box> { + // Création de l'image de profondeur aux dimensions de la fenêtre + let depth_image = Image::new( + memory_allocator, + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: depth_format, + extent: [dimensions[0], dimensions[1], 1], + usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT | ImageUsage::TRANSIENT_ATTACHMENT, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE, + ..Default::default() + }, + )?; + let depth_view = ImageView::new_default(depth_image)?; + + images + .iter() + .map(|image| { + let color_view = ImageView::new_default(image.clone())?; + let framebuffer = Framebuffer::new( + render_pass.clone(), + FramebufferCreateInfo { + attachments: vec![color_view, depth_view.clone()], + ..Default::default() + }, + )?; + Ok(framebuffer) + }) + .collect() +} + +/// Recrée la Swapchain et ses Framebuffers (avec un nouveau depth buffer adapté) lors d'un resize. +pub fn recreate_swapchain_bundle( + bundle: &mut SwapchainBundle, + memory_allocator: Arc, + new_dimensions: [u32; 2], + render_pass: Arc, +) -> Result<(), Box> { + let (new_swapchain, new_images) = bundle.swapchain.recreate(SwapchainCreateInfo { + image_extent: new_dimensions, + ..bundle.swapchain.create_info() + })?; + + let new_framebuffers = create_framebuffers( + &new_images, + memory_allocator, + new_dimensions, + bundle.depth_format, + render_pass, + )?; + + bundle.swapchain = new_swapchain; + bundle.images = new_images; + bundle.framebuffers = new_framebuffers; + + Ok(()) +} diff --git a/src/renderer/texture.rs b/src/renderer/texture.rs new file mode 100644 index 0000000..9f15190 --- /dev/null +++ b/src/renderer/texture.rs @@ -0,0 +1,268 @@ +use std::sync::Arc; +use vulkano::buffer::{Buffer, BufferCreateInfo, BufferUsage}; +use vulkano::command_buffer::allocator::StandardCommandBufferAllocator; +use vulkano::command_buffer::{ + AutoCommandBufferBuilder, CommandBufferUsage, CopyBufferToImageInfo, + PrimaryCommandBufferAbstract, +}; +use vulkano::descriptor_set::allocator::StandardDescriptorSetAllocator; +use vulkano::descriptor_set::{DescriptorSet, WriteDescriptorSet}; +use vulkano::device::{Device, Queue}; +use vulkano::format::Format; +use vulkano::image::sampler::{Filter, Sampler, SamplerAddressMode, SamplerCreateInfo}; +use vulkano::image::view::ImageView; +use vulkano::image::{Image, ImageCreateInfo, ImageType, ImageUsage}; +use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator}; +use vulkano::pipeline::PipelineLayout; +use vulkano::sync::GpuFuture; + +pub const ATLAS_WIDTH: u32 = 128; +pub const ATLAS_HEIGHT: u32 = 128; +pub const TILE_SIZE: u32 = 16; +#[allow(dead_code)] +pub const TILES_PER_ROW: u32 = ATLAS_WIDTH / TILE_SIZE; // 8 + +/// Conteneur des ressources GPU pour la texture atlas et son DescriptorSet. +#[allow(dead_code)] +pub struct VulkanTexture { + pub image: Arc, + pub view: Arc, + pub sampler: Arc, + pub descriptor_set: Arc, +} + +/// Générateur pseudo-aléatoire déterministe simple (hachage LCG sans crate externe). +#[inline(always)] +fn hash_pixel(x: u32, y: u32, seed: u32) -> u32 { + let mut h = seed + .wrapping_add(x.wrapping_mul(374761393)) + .wrapping_add(y.wrapping_mul(668265263)); + h = (h ^ (h >> 13)).wrapping_mul(1274126177); + h ^ (h >> 16) +} + +/// Génère une variation entière signée dans [-range, range]. +#[inline(always)] +fn noise_variation(x: u32, y: u32, seed: u32, range: i32) -> i32 { + let span = (range * 2 + 1) as u32; + let r = (hash_pixel(x, y, seed) % span) as i32; + r - range +} + +/// Écrit un pixel RGBA aux coordonnées locales de la tuile. +#[inline(always)] +fn put_pixel( + pixels: &mut [u8], + tile_col: u32, + tile_row: u32, + px: u32, + py: u32, + r: u8, + g: u8, + b: u8, + a: u8, +) { + let gx = tile_col * TILE_SIZE + px; + let gy = tile_row * TILE_SIZE + py; + let idx = ((gy * ATLAS_WIDTH + gx) * 4) as usize; + pixels[idx] = r; + pixels[idx + 1] = g; + pixels[idx + 2] = b; + pixels[idx + 3] = a; +} + +/// Génère l'atlas procédural de textures 128x128 en mémoire (8x8 tuiles de 16x16 pixels). +pub fn generate_texture_atlas() -> Vec { + let mut pixels = vec![255u8; (ATLAS_WIDTH * ATLAS_HEIGHT * 4) as usize]; + + for py in 0..TILE_SIZE { + for px in 0..TILE_SIZE { + // --- Tuile 0 : Dessus d'Herbe (Grass Top) --- + let n_grass = noise_variation(px, py, 101, 16); + let r_gt = (88 + n_grass).clamp(0, 255) as u8; + let g_gt = (168 + n_grass * 2).clamp(0, 255) as u8; + let b_gt = (68 + n_grass).clamp(0, 255) as u8; + put_pixel(&mut pixels, 0, 0, px, py, r_gt, g_gt, b_gt, 255); + + // --- Tuile 2 : Terre (Dirt) --- + let n_dirt = noise_variation(px, py, 202, 14); + let is_pebble = hash_pixel(px, py, 999) % 13 == 0; + let (r_d, g_d, b_d) = if is_pebble { + (90, 65, 52) + } else { + ( + (134 + n_dirt).clamp(0, 255) as u8, + (96 + n_dirt).clamp(0, 255) as u8, + (67 + n_dirt).clamp(0, 255) as u8, + ) + }; + put_pixel(&mut pixels, 2, 0, px, py, r_d, g_d, b_d, 255); + + // --- Tuile 1 : Côté d'Herbe (Grass Side) --- + // Le tiers supérieur est de l'herbe festonnée, le reste est de la terre + let grass_cutoff = 3 + (hash_pixel(px, 0, 303) % 3); + if py <= grass_cutoff { + let r = (88 + n_grass).clamp(0, 255) as u8; + let g = (168 + n_grass * 2).clamp(0, 255) as u8; + let b = (68 + n_grass).clamp(0, 255) as u8; + put_pixel(&mut pixels, 1, 0, px, py, r, g, b, 255); + } else { + put_pixel(&mut pixels, 1, 0, px, py, r_d, g_d, b_d, 255); + } + + // --- Tuile 3 : Pierre (Stone) --- + let n_stone = noise_variation(px, py, 404, 18); + let is_dark_crack = hash_pixel(px, py, 777) % 9 == 0; + let (r_s, g_s, b_s) = if is_dark_crack { + (95, 95, 100) + } else { + let v = (138 + n_stone).clamp(0, 255) as u8; + (v, v, (v as i32 + 3).min(255) as u8) + }; + put_pixel(&mut pixels, 3, 0, px, py, r_s, g_s, b_s, 255); + + // --- Tuile 4 : Côté de Tronc d'Arbre / Bois (Wood Log Side) --- + let n_bark = noise_variation(px, py, 505, 8); + let is_bark_groove = px % 4 == 0 || (px + py) % 7 == 0; + let (r_w, g_w, b_w) = if is_bark_groove { + (80, 54, 40) + } else { + ( + (115 + n_bark).clamp(0, 255) as u8, + (82 + n_bark).clamp(0, 255) as u8, + (58 + n_bark).clamp(0, 255) as u8, + ) + }; + put_pixel(&mut pixels, 4, 0, px, py, r_w, g_w, b_w, 255); + + // --- Tuile 5 : Extrémité de Tronc d'Arbre (Wood Log Top/Bottom - Cernes) --- + let c_dist = (((px as f32 - 7.5).powi(2) + (py as f32 - 7.5).powi(2)).sqrt()).round() as i32; + let (r_wt, g_wt, b_wt) = if c_dist >= 7 { + (80, 54, 40) // Écorce extérieure + } else if c_dist % 2 == 0 { + (160, 120, 80) // Cerne sombre + } else { + (185, 145, 100) // Cœur de bois clair + }; + put_pixel(&mut pixels, 5, 0, px, py, r_wt, g_wt, b_wt, 255); + + // --- Tuile 6 : Feuilles (Leaves) --- + let n_leaf = noise_variation(px, py, 606, 22); + let leaf_type = hash_pixel(px, py, 888) % 3; + let (r_l, g_l, b_l) = match leaf_type { + 0 => (42, 105, 38), // Ombre + 1 => (72, 160, 60), // Normal + _ => ( + (58 + n_leaf).clamp(0, 255) as u8, + (135 + n_leaf * 2).clamp(0, 255) as u8, + (45 + n_leaf).clamp(0, 255) as u8, + ), + }; + put_pixel(&mut pixels, 6, 0, px, py, r_l, g_l, b_l, 255); + + // --- Tuile 7 : Sable (Sand) --- + let n_sand = noise_variation(px, py, 707, 10); + let r_sa = (220 + n_sand).clamp(0, 255) as u8; + let g_sa = (205 + n_sand).clamp(0, 255) as u8; + let b_sa = (150 + n_sand).clamp(0, 255) as u8; + put_pixel(&mut pixels, 7, 0, px, py, r_sa, g_sa, b_sa, 255); + } + } + + pixels +} + +/// Crée la texture atlas sur le GPU, son image view, son sampler Nearest, et alloue son DescriptorSet. +pub fn create_texture_atlas_bundle( + memory_allocator: Arc, + command_buffer_allocator: Arc, + device: Arc, + queue: Arc, + pipeline_layout: Arc, +) -> Result> { + let pixels = generate_texture_atlas(); + + // 1. Buffer de transit hôte (Staging Buffer) + let staging_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + pixels, + )?; + + // 2. Image GPU (Device Local) + let image = Image::new( + memory_allocator, + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: Format::R8G8B8A8_SRGB, + extent: [ATLAS_WIDTH, ATLAS_HEIGHT, 1], + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE, + ..Default::default() + }, + )?; + + // 3. Commande de copie du buffer vers l'image GPU + let mut builder = AutoCommandBufferBuilder::primary( + command_buffer_allocator, + queue.queue_family_index(), + CommandBufferUsage::OneTimeSubmit, + )?; + + let copy_info = CopyBufferToImageInfo::buffer_image(staging_buffer, image.clone()); + builder.copy_buffer_to_image(copy_info)?; + + let command_buffer = builder.build()?; + command_buffer + .execute(queue)? + .then_signal_fence_and_flush()? + .wait(None)?; + + // 4. ImageView et Sampler configuré en Filter::Nearest (Pixel art net sans flou) + let view = ImageView::new_default(image.clone())?; + let sampler = Sampler::new( + device.clone(), + SamplerCreateInfo { + mag_filter: Filter::Nearest, + min_filter: Filter::Nearest, + address_mode: [SamplerAddressMode::Repeat; 3], + ..Default::default() + }, + )?; + + // 5. DescriptorSet (Set 0, Binding 0) + let desc_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device, + Default::default(), + )); + let set_layout = pipeline_layout + .set_layouts() + .get(0) + .ok_or("Le layout de pipeline ne contient pas le descriptor set 0")? + .clone(); + + let descriptor_set = DescriptorSet::new( + desc_allocator, + set_layout, + [WriteDescriptorSet::image_view_sampler(0, view.clone(), sampler.clone())], + [], + )?; + + Ok(VulkanTexture { + image, + view, + sampler, + descriptor_set, + }) +} diff --git a/src/window.rs b/src/window.rs new file mode 100644 index 0000000..2a3c4d2 --- /dev/null +++ b/src/window.rs @@ -0,0 +1,405 @@ +use std::sync::Arc; +use std::time::Instant; +use winit::application::ApplicationHandler; +use winit::dpi::LogicalSize; +use winit::event::{DeviceEvent, DeviceId, ElementState, MouseButton, WindowEvent}; +use winit::event_loop::ActiveEventLoop; +use winit::keyboard::{KeyCode, PhysicalKey}; +use winit::window::{CursorGrabMode, Window, WindowId}; + +use crate::camera::Camera; +use crate::inventory::Inventory; +use crate::math::Vec3; +use crate::physics::Player; +use crate::raycast::{raycast_voxel, RaycastHit}; +use crate::renderer::VulkanRenderer; +use crate::world::{build_chunk_mesh_world, BlockType, World, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z}; + +/// Structure principale de l'application gérant la fenêtre, la caméra et le monde multi-chunks. +pub struct App { + window: Option>, + renderer: Option, + camera: Camera, + player: Player, + inventory: Inventory, + cursor_captured: bool, + last_frame_time: Instant, + world: World, + render_radius: i32, + last_player_chunk: (i32, i32), + targeted_block: Option, +} + +impl App { + pub fn new() -> Self { + // Le joueur apparaît au-dessus du relief à (0.5, 20.0, 0.5) + let player = Player::new(Vec3::new(0.5, 20.0, 0.5)); + let mut camera = Camera::new(player.eye_position()); + camera.pitch = -0.2; + camera.speed = 18.0; + + Self { + window: None, + renderer: None, + camera, + player, + inventory: Inventory::new(), + cursor_captured: false, + last_frame_time: Instant::now(), + world: World::new(), + render_radius: 3, // Rayon de 3 chunks = grille 7x7 = 49 chunks (112x112 blocs) + last_player_chunk: (i32::MAX, i32::MAX), + targeted_block: None, + } + } + + /// Active ou désactive la capture du curseur souris dans la fenêtre + fn set_cursor_grab(&mut self, grab: bool) { + if let Some(window) = &self.window { + self.cursor_captured = grab; + let _ = window.set_cursor_grab(if grab { + CursorGrabMode::Locked + } else { + CursorGrabMode::None + }) + .or_else(|_| { + window.set_cursor_grab(if grab { + CursorGrabMode::Confined + } else { + CursorGrabMode::None + }) + }); + window.set_cursor_visible(!grab); + } + } + + /// Régénère et upload vers le GPU uniquement les maillages des chunks marqués `dirty_mesh = true`. + fn update_dirty_meshes(&mut self) { + if let Some(renderer) = &mut self.renderer { + let dirty_positions: Vec<(i32, i32)> = self + .world + .chunks + .iter() + .filter(|(_, chunk)| chunk.dirty_mesh) + .map(|(pos, _)| *pos) + .collect(); + + for pos in dirty_positions { + if let Some(chunk) = self.world.chunks.get(&pos) { + // Construction avec culling aux frontières via le World global + let mesh_data = build_chunk_mesh_world(chunk, &self.world); + let _ = renderer.set_chunk_mesh(pos, mesh_data); + } + if let Some(chunk) = self.world.chunks.get_mut(&pos) { + chunk.dirty_mesh = false; + } + } + } + } + + /// Sélectionne un slot de la hotbar et affiche l'état. + fn select_slot(&mut self, slot: usize) { + self.inventory.select_slot(slot); + println!( + "Hotbar [{}] : {:?} (Disponible : {})", + self.inventory.selected_slot + 1, + self.inventory.selected_block(), + self.inventory.selected_count() + ); + } + + /// Casse le bloc actuellement visé, l'ajoute à l'inventaire et régénère les maillages. + fn break_targeted_block(&mut self) { + if let Some(hit) = self.targeted_block { + let (x, y, z) = hit.hit_pos; + let target_block = self.world.get_block(x, y, z); + if target_block != BlockType::Air && self.world.set_block(x, y, z, BlockType::Air) { + self.inventory.add_block(target_block); + self.update_dirty_meshes(); + println!( + "+1 {:?} récolté en ({x}, {y}, {z}) (Total inventaire : {})", + target_block, + self.inventory.selected_count() + ); + } + } + } + + /// Pose un bloc depuis le slot d'inventaire actif sur la face ciblée. + fn place_block_on_target(&mut self) { + if let Some(hit) = self.targeted_block { + let (x, y, z) = hit.place_pos; + + // Protection anti-collision joueur : ne pas poser à l'intérieur du corps du joueur + let block_aabb = crate::physics::AABB::new( + Vec3::new(x as f32, y as f32, z as f32), + Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32), + ); + if self.player.aabb().intersects(&block_aabb) { + println!("Impossible de poser un bloc à l'intérieur du joueur !"); + return; + } + + // Consomme 1 bloc du stock du slot actif (refus silencieux si 0) + if let Some(block_to_place) = self.inventory.consume_selected() { + if self.world.set_block(x, y, z, block_to_place) { + self.update_dirty_meshes(); + println!( + "-1 {:?} posé en ({x}, {y}, {z}) (Restant : {})", + block_to_place, + self.inventory.selected_count() + ); + } else { + // Remboursement si pose refusée (ex: hors des limites du monde) + self.inventory.add_block(block_to_place); + } + } else { + println!("Slot vide ! (0 bloc disponible)"); + } + } + } +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_none() { + let window_attributes = Window::default_attributes() + .with_title("Moteur Voxel - Monde Multi-Chunks & Chargement Dynamique") + .with_inner_size(LogicalSize::new(1280.0, 720.0)); + + let window = match event_loop.create_window(window_attributes) { + Ok(w) => Arc::new(w), + Err(err) => { + eprintln!("Impossible de créer la fenêtre : {err}"); + event_loop.exit(); + return; + } + }; + + let renderer = match VulkanRenderer::new(window.clone(), event_loop) { + Ok(r) => r, + Err(err) => { + eprintln!("Erreur lors de l'initialisation du moteur Vulkan : {err}"); + event_loop.exit(); + return; + } + }; + + self.window = Some(window); + self.renderer = Some(renderer); + self.last_frame_time = Instant::now(); + + // 1. Initialisation des chunks autour du joueur + let player_chunk_x = (self.camera.position.x.floor() as i32).div_euclid(CHUNK_SIZE_X as i32); + let player_chunk_z = (self.camera.position.z.floor() as i32).div_euclid(CHUNK_SIZE_Z as i32); + self.last_player_chunk = (player_chunk_x, player_chunk_z); + + let (generated_count, gen_time) = self.world.update_chunks_around( + self.camera.position.x, + self.camera.position.z, + self.render_radius, + ); + + // 2. Maillage initial et upload GPU + let mesh_start = Instant::now(); + self.update_dirty_meshes(); + let mesh_time = mesh_start.elapsed().as_secs_f32() * 1000.0; + + let total_chunks = self.world.chunks.len(); + let total_voxels = total_chunks * CHUNK_SIZE_X * CHUNK_SIZE_Y * CHUNK_SIZE_Z; + + println!(); + println!("============================================================"); + println!(" INITIALISATION DU MONDE MULTI-CHUNKS "); + println!("============================================================"); + println!(" - Chunks actifs : {total_chunks} (Rayon : {} chunks)", self.render_radius); + println!(" - Grille couverte : {} x {} blocs", (self.render_radius * 2 + 1) * CHUNK_SIZE_X as i32, (self.render_radius * 2 + 1) * CHUNK_SIZE_Z as i32); + println!(" - Voxels totaux en mémoire : {total_voxels}"); + println!(" - Nouveaux chunks générés : {generated_count}"); + println!(" - Temps de génération relief : {gen_time:.2} ms"); + println!(" - Temps de maillage & upload : {mesh_time:.2} ms"); + println!("============================================================"); + println!(); + + self.set_cursor_grab(true); + } + } + + /// Mouvements relatifs de la souris (orientation caméra) + fn device_event( + &mut self, + _event_loop: &ActiveEventLoop, + _device_id: DeviceId, + event: DeviceEvent, + ) { + if self.cursor_captured { + if let DeviceEvent::MouseMotion { delta } = event { + self.camera.rotate(delta.0 as f32, delta.1 as f32); + } + } + } + + /// Événements de fenêtre et entrées utilisateur + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + match event { + // Fermeture de la fenêtre + WindowEvent::CloseRequested => { + event_loop.exit(); + } + + // Redimensionnement de la fenêtre + WindowEvent::Resized(physical_size) => { + if physical_size.width > 0 && physical_size.height > 0 { + if let Some(renderer) = &mut self.renderer { + renderer.notify_resized(); + } + } + } + + // Clics souris pour casser ou poser des blocs + WindowEvent::MouseInput { state, button, .. } => { + if state == ElementState::Pressed { + if !self.cursor_captured { + self.set_cursor_grab(true); + } else { + match button { + MouseButton::Left => { + self.break_targeted_block(); + } + MouseButton::Right => { + self.place_block_on_target(); + } + _ => (), + } + } + } + } + + // Molette de souris pour faire défiler la hotbar d'inventaire + WindowEvent::MouseWheel { delta, .. } => { + let scroll_y = match delta { + winit::event::MouseScrollDelta::LineDelta(_, y) => y, + winit::event::MouseScrollDelta::PixelDelta(pos) => pos.y as f32, + }; + if scroll_y > 0.1 { + self.inventory.cycle_slot(-1); + println!( + "Hotbar [{}] : {:?} (Disponible : {})", + self.inventory.selected_slot + 1, + self.inventory.selected_block(), + self.inventory.selected_count() + ); + } else if scroll_y < -0.1 { + self.inventory.cycle_slot(1); + println!( + "Hotbar [{}] : {:?} (Disponible : {})", + self.inventory.selected_slot + 1, + self.inventory.selected_block(), + self.inventory.selected_count() + ); + } + } + + // Touches du clavier + WindowEvent::KeyboardInput { event, .. } => { + let is_pressed = event.state.is_pressed(); + + if let PhysicalKey::Code(key_code) = event.physical_key { + match key_code { + KeyCode::KeyW | KeyCode::KeyZ => self.camera.move_forward = is_pressed, + KeyCode::KeyS => self.camera.move_backward = is_pressed, + KeyCode::KeyA | KeyCode::KeyQ => self.camera.move_left = is_pressed, + KeyCode::KeyD => self.camera.move_right = is_pressed, + KeyCode::Space => self.camera.move_up = is_pressed, + KeyCode::ShiftLeft | KeyCode::ShiftRight => { + self.camera.move_down = is_pressed + } + KeyCode::Digit1 => { if is_pressed { self.select_slot(0); } } + KeyCode::Digit2 => { if is_pressed { self.select_slot(1); } } + KeyCode::Digit3 => { if is_pressed { self.select_slot(2); } } + KeyCode::Digit4 => { if is_pressed { self.select_slot(3); } } + KeyCode::Digit5 => { if is_pressed { self.select_slot(4); } } + KeyCode::Digit6 => { if is_pressed { self.select_slot(5); } } + KeyCode::KeyF => { + if is_pressed { + self.player.flying = !self.player.flying; + self.player.velocity = Vec3::zero(); + println!( + "Mode de déplacement : {}", + if self.player.flying { + "VOL LIBRE (noclip/rapide)" + } else { + "MARCHE & GRAVITÉ" + } + ); + } + } + KeyCode::Escape => { + if is_pressed { + let new_grab = !self.cursor_captured; + self.set_cursor_grab(new_grab); + } + } + _ => (), + } + } + } + + // Rafraîchissement / Rendu de chaque frame + WindowEvent::RedrawRequested => { + let now = Instant::now(); + let dt = (now - self.last_frame_time).as_secs_f32().min(0.05); + self.last_frame_time = now; + + // Mise à jour de la physique du joueur (marche/gravité ou vol libre) + self.player.update(dt, &self.camera, &self.world); + self.camera.position = self.player.eye_position(); + + // Chargement dynamique des chunks lors du déplacement du joueur + let player_chunk_x = (self.camera.position.x.floor() as i32).div_euclid(CHUNK_SIZE_X as i32); + let player_chunk_z = (self.camera.position.z.floor() as i32).div_euclid(CHUNK_SIZE_Z as i32); + if (player_chunk_x, player_chunk_z) != self.last_player_chunk { + self.last_player_chunk = (player_chunk_x, player_chunk_z); + let (new_chunks, elapsed) = self.world.update_chunks_around( + self.camera.position.x, + self.camera.position.z, + self.render_radius, + ); + if new_chunks > 0 { + println!("Monde : {new_chunks} nouveaux chunks générés en {elapsed:.2} ms"); + self.update_dirty_meshes(); + } + } + + // Raycasting voxel multi-chunks (portée 7.0 blocs) + self.targeted_block = raycast_voxel( + self.camera.position, + self.camera.forward(), + 7.0, + &self.world, + ); + + if let (Some(renderer), Some(window)) = (&mut self.renderer, &self.window) { + let dimensions: [u32; 2] = window.inner_size().into(); + let view_matrix = self.camera.view_matrix(); + let selected_pos = self.targeted_block.map(|h| h.hit_pos); + + // Génération du maillage 2D de la hotbar pour l'aspect ratio de la fenêtre + let aspect_ratio = dimensions[0] as f32 / dimensions[1] as f32; + let ui_mesh = self.inventory.generate_ui_mesh(aspect_ratio); + + renderer.render(dimensions, view_matrix, selected_pos, Some(ui_mesh)); + + window.request_redraw(); + } + } + + _ => (), + } + } +} diff --git a/src/world/chunk.rs b/src/world/chunk.rs new file mode 100644 index 0000000..adb7660 --- /dev/null +++ b/src/world/chunk.rs @@ -0,0 +1,230 @@ +/// Dimensions d'un chunk voxel (16x32x16 = 8 192 blocs). +/// Ce format colonne 16x16 standard permet une génération et régénération incrémentale ultra-rapide. +pub const CHUNK_SIZE_X: usize = 16; +pub const CHUNK_SIZE_Y: usize = 32; +pub const CHUNK_SIZE_Z: usize = 16; + +/// Type de bloc voxel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum BlockType { + Air = 0, + Grass = 1, + Dirt = 2, + Stone = 3, + Wood = 4, + Leaves = 5, + Sand = 6, +} + +impl BlockType { + /// Indique si le bloc est opaque (solide pour le culling des faces et les collisions). + #[inline(always)] + pub fn is_opaque(&self) -> bool { + *self != BlockType::Air + } +} + +/// Structure représentant un Chunk 3D de voxels dans le monde. +pub struct Chunk { + pub chunk_x: i32, + pub chunk_z: i32, + pub voxels: Vec, + pub dirty_mesh: bool, +} + +impl Chunk { + /// Crée un chunk vide aux coordonnées (chunk_x, chunk_z). + pub fn new_empty(chunk_x: i32, chunk_z: i32) -> Self { + Self { + chunk_x, + chunk_z, + voxels: vec![BlockType::Air; CHUNK_SIZE_X * CHUNK_SIZE_Y * CHUNK_SIZE_Z], + dirty_mesh: true, + } + } + + /// Index 1D linéaire correspondant aux coordonnées locales 3D (x, y, z). + #[inline(always)] + fn index(x: usize, y: usize, z: usize) -> usize { + x + z * CHUNK_SIZE_X + y * CHUNK_SIZE_X * CHUNK_SIZE_Z + } + + /// Récupère le type de bloc aux coordonnées locales (x, y, z). + /// Retourne Air si les coordonnées sont en dehors du chunk local. + #[inline(always)] + pub fn get_block_local(&self, x: i32, y: i32, z: i32) -> BlockType { + if x < 0 + || x >= CHUNK_SIZE_X as i32 + || y < 0 + || y >= CHUNK_SIZE_Y as i32 + || z < 0 + || z >= CHUNK_SIZE_Z as i32 + { + BlockType::Air + } else { + self.voxels[Self::index(x as usize, y as usize, z as usize)] + } + } + + /// Modifie le bloc aux coordonnées locales (x, y, z). + pub fn set_block_local(&mut self, x: usize, y: usize, z: usize, block: BlockType) { + if x < CHUNK_SIZE_X && y < CHUNK_SIZE_Y && z < CHUNK_SIZE_Z { + let idx = Self::index(x, y, z); + self.voxels[idx] = block; + self.dirty_mesh = true; + } + } + + /// Génère un terrain procédural ondulé et continu basé sur les coordonnées mondes absolues. + /// Cela garantit une transition parfaitement continue et sans jointure entre les chunks adjacents. + pub fn generate_terrain(chunk_x: i32, chunk_z: i32) -> Self { + let mut chunk = Self::new_empty(chunk_x, chunk_z); + let world_base_x = chunk_x * CHUNK_SIZE_X as i32; + let world_base_z = chunk_z * CHUNK_SIZE_Z as i32; + + for lx in 0..CHUNK_SIZE_X { + let gx = (world_base_x + lx as i32) as f32; + + for lz in 0..CHUNK_SIZE_Z { + let gz = (world_base_z + lz as i32) as f32; + + // Fonction de hauteur continue en coordonnées globales + let wave1 = (gx * 0.07).sin() * (gz * 0.07).cos() * 5.0; + let wave2 = ((gx + gz) * 0.035).sin() * 3.5; + let wave3 = (gx * 0.15 - gz * 0.12).cos() * 1.5; + + let height = (14.0 + wave1 + wave2 + wave3).round() as i32; + let height = height.clamp(1, (CHUNK_SIZE_Y - 7) as i32); + + for ly in 0..CHUNK_SIZE_Y as i32 { + if height <= 10 { + // Plages de sable à basse altitude + if ly == height { + chunk.set_block_local(lx, ly as usize, lz, BlockType::Sand); + } else if ly >= height - 2 && ly < height { + chunk.set_block_local(lx, ly as usize, lz, BlockType::Sand); + } else if ly < height - 2 { + chunk.set_block_local(lx, ly as usize, lz, BlockType::Stone); + } + } else { + // Collines herbues + if ly == height { + chunk.set_block_local(lx, ly as usize, lz, BlockType::Grass); + } else if ly >= height - 3 && ly < height { + chunk.set_block_local(lx, ly as usize, lz, BlockType::Dirt); + } else if ly < height - 3 { + chunk.set_block_local(lx, ly as usize, lz, BlockType::Stone); + } + } + } + } + } + + // Dispersion déterministe d'arbres (Bois + Feuilles) sur les zones d'herbe + let tree_spots = [(4, 4), (11, 11), (4, 11), (11, 4)]; + for &(tx, tz) in &tree_spots { + let mut h = (chunk_x as u32) + .wrapping_mul(374761393) + ^ (chunk_z as u32).wrapping_mul(668265263) + ^ ((tx as u32) << 4) + ^ (tz as u32); + h = (h ^ (h >> 13)).wrapping_mul(1274126177); + + // Densité modérée : ~25% de chance par spot (en moyenne ~1 arbre par chunk) + if h % 4 == 0 { + let mut surface_y = -1; + for y in (1..CHUNK_SIZE_Y as i32).rev() { + if chunk.get_block_local(tx as i32, y, tz as i32) == BlockType::Grass { + surface_y = y; + break; + } + } + + if surface_y > 0 && surface_y + 6 < CHUNK_SIZE_Y as i32 { + // Le bloc sous le tronc devient de la terre + chunk.set_block_local(tx, surface_y as usize, tz, BlockType::Dirt); + + // Tronc en bois (hauteur 3 blocs) + let trunk_h = 3; + for ty in 1..=trunk_h { + chunk.set_block_local(tx, (surface_y + ty) as usize, tz, BlockType::Wood); + } + + // Feuillage (Leaves) + let leaf_base = surface_y + trunk_h; + // Étage inférieur et médian (3x3) + for dy in 0..=1 { + for dx in -1..=1 { + for dz in -1..=1 { + if dy == 0 && dx == 0 && dz == 0 { + continue; // Emplacement du sommet du tronc + } + let lx = (tx as i32 + dx) as usize; + let lz = (tz as i32 + dz) as usize; + chunk.set_block_local( + lx, + (leaf_base + dy) as usize, + lz, + BlockType::Leaves, + ); + } + } + } + + // Étage sommital en croix (5 blocs) + for (dx, dz) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] { + let lx = (tx as i32 + dx) as usize; + let lz = (tz as i32 + dz) as usize; + chunk.set_block_local( + lx, + (leaf_base + 2) as usize, + lz, + BlockType::Leaves, + ); + } + } + } + } + + chunk.dirty_mesh = true; + chunk + } + + /// Compte le nombre total de blocs pleins (solides) dans le chunk. + #[allow(dead_code)] + pub fn count_solid_blocks(&self) -> usize { + self.voxels.iter().filter(|b| b.is_opaque()).count() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tree_generation_present() { + // En scannant plusieurs chunks, au moins certains contiennent des arbres (Bois + Feuilles) + let mut total_wood = 0; + let mut total_leaves = 0; + let mut total_sand = 0; + + for cx in 0..4 { + for cz in 0..4 { + let chunk = Chunk::generate_terrain(cx, cz); + for &b in &chunk.voxels { + match b { + BlockType::Wood => total_wood += 1, + BlockType::Leaves => total_leaves += 1, + BlockType::Sand => total_sand += 1, + _ => (), + } + } + } + } + + assert!(total_wood > 0, "Le monde doit générer des troncs de bois"); + assert!(total_leaves > 0, "Le monde doit générer des feuilles d'arbres"); + assert!(total_sand > 0, "Le monde doit générer des zones de sable"); + } +} diff --git a/src/world/mesh_builder.rs b/src/world/mesh_builder.rs new file mode 100644 index 0000000..6074143 --- /dev/null +++ b/src/world/mesh_builder.rs @@ -0,0 +1,303 @@ +use crate::renderer::mesh::CubeVertex; +use super::chunk::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z}; + +/// Données géométriques brutes générées pour le maillage du chunk. +pub struct ChunkMeshData { + pub vertices: Vec, + pub indices: Vec, + #[allow(dead_code)] + pub faces_count: usize, +} + +/// Énumération des 6 directions de faces d'un voxel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Direction { + PosY, // Haut (Top) + NegY, // Bas (Bottom) + PosZ, // Avant (Front) + NegZ, // Arrière (Back) + PosX, // Droite (Right) + NegX, // Gauche (Left) +} + +impl Direction { + const ALL: [Direction; 6] = [ + Direction::PosY, + Direction::NegY, + Direction::PosZ, + Direction::NegZ, + Direction::PosX, + Direction::NegX, + ]; + + #[inline(always)] + fn offset(&self) -> (i32, i32, i32) { + match self { + Direction::PosY => (0, 1, 0), + Direction::NegY => (0, -1, 0), + Direction::PosZ => (0, 0, 1), + Direction::NegZ => (0, 0, -1), + Direction::PosX => (1, 0, 0), + Direction::NegX => (-1, 0, 0), + } + } + + #[inline(always)] + fn normal(&self) -> [f32; 3] { + match self { + Direction::PosY => [0.0, 1.0, 0.0], + Direction::NegY => [0.0, -1.0, 0.0], + Direction::PosZ => [0.0, 0.0, 1.0], + Direction::NegZ => [0.0, 0.0, -1.0], + Direction::PosX => [1.0, 0.0, 0.0], + Direction::NegX => [-1.0, 0.0, 0.0], + } + } +} + +/// Retourne l'index de tuile dans l'atlas (8x8 tuiles) selon le type de bloc et la face. +pub fn get_face_tile_id(block: BlockType, dir: Direction) -> u32 { + match block { + BlockType::Grass => match dir { + Direction::PosY => 0, // Herbe dessus + Direction::NegY => 2, // Terre (dessous) + _ => 1, // Herbe côté + }, + BlockType::Dirt => 2, + BlockType::Stone => 3, + BlockType::Wood => match dir { + Direction::PosY | Direction::NegY => 5, // Cernes du bois + _ => 4, // Écorce + }, + BlockType::Leaves => 6, + BlockType::Sand => 7, + BlockType::Air => 0, + } +} + +use super::world::World; + +/// Construit le maillage optimisé d'un chunk avec Culling inter-chunks via le World global. +/// +/// CRITIQUE : Aux frontières du chunk, cette fonction interroge le bloc dans le chunk voisin +/// via `world.get_block(gx + dx, gy + dy, gz + dz)`. Cela élimine les faces fantômes et les +/// trous aux jonctions entre chunks adjacents. +/// Les positions des sommets sont directement générées en coordonnées monde absolues. +pub fn build_chunk_mesh_world(chunk: &Chunk, world: &World) -> ChunkMeshData { + let mut vertices = Vec::new(); + let mut indices = Vec::new(); + let mut faces_count = 0; + + let world_base_x = chunk.chunk_x * CHUNK_SIZE_X as i32; + let world_base_z = chunk.chunk_z * CHUNK_SIZE_Z as i32; + + for lx in 0..CHUNK_SIZE_X { + let gx = world_base_x + lx as i32; + let fx = gx as f32; + + for ly in 0..CHUNK_SIZE_Y { + let gy = ly as i32; + let fy = gy as f32; + + for lz in 0..CHUNK_SIZE_Z { + let gz = world_base_z + lz as i32; + let fz = gz as f32; + + let block = chunk.get_block_local(lx as i32, gy, lz as i32); + if !block.is_opaque() { + continue; + } + + for dir in Direction::ALL { + let (dx, dy, dz) = dir.offset(); + // Interrogation globale dans le monde (traverse les chunks voisins) + let neighbor = world.get_block(gx + dx, gy + dy, gz + dz); + + // Si le voisin immédiat est opaque, la face est masquée : culling ! + if neighbor.is_opaque() { + continue; + } + + faces_count += 1; + let base_index = vertices.len() as u32; + let normal = dir.normal(); + + // Coordonnées de texture dans l'atlas 8x8 tuiles + let tile_id = get_face_tile_id(block, dir); + let tile_u = (tile_id % 8) as f32; + let tile_v = (tile_id / 8) as f32; + let tile_size = 1.0 / 8.0; + + let u_min = tile_u * tile_size; + let u_max = (tile_u + 1.0) * tile_size; + let v_min = tile_v * tile_size; + let v_max = (tile_v + 1.0) * tile_size; + + let uvs = [ + [u_min, v_max], + [u_max, v_max], + [u_max, v_min], + [u_min, v_min], + ]; + + let quad = match dir { + Direction::PosY => [ + [fx, fy + 1.0, fz + 1.0], + [fx + 1.0, fy + 1.0, fz + 1.0], + [fx + 1.0, fy + 1.0, fz], + [fx, fy + 1.0, fz], + ], + Direction::NegY => [ + [fx, fy, fz], + [fx + 1.0, fy, fz], + [fx + 1.0, fy, fz + 1.0], + [fx, fy, fz + 1.0], + ], + Direction::PosZ => [ + [fx, fy, fz + 1.0], + [fx + 1.0, fy, fz + 1.0], + [fx + 1.0, fy + 1.0, fz + 1.0], + [fx, fy + 1.0, fz + 1.0], + ], + Direction::NegZ => [ + [fx + 1.0, fy, fz], + [fx, fy, fz], + [fx, fy + 1.0, fz], + [fx + 1.0, fy + 1.0, fz], + ], + Direction::PosX => [ + [fx + 1.0, fy, fz + 1.0], + [fx + 1.0, fy, fz], + [fx + 1.0, fy + 1.0, fz], + [fx + 1.0, fy + 1.0, fz + 1.0], + ], + Direction::NegX => [ + [fx, fy, fz], + [fx, fy, fz + 1.0], + [fx, fy + 1.0, fz + 1.0], + [fx, fy + 1.0, fz], + ], + }; + + for (i, pos) in quad.into_iter().enumerate() { + vertices.push(CubeVertex { + position: pos, + color: [1.0, 1.0, 1.0], + normal, + uv: uvs[i], + }); + } + + // 2 triangles par face : (0, 1, 2) et (2, 3, 0) + indices.push(base_index + 0); + indices.push(base_index + 1); + indices.push(base_index + 2); + indices.push(base_index + 2); + indices.push(base_index + 3); + indices.push(base_index + 0); + } + } + } + } + + ChunkMeshData { + vertices, + indices, + faces_count, + } +} + +/// Construit le maillage d'un chunk isolé (utile pour les tests unitaires). +#[allow(dead_code)] +pub fn build_chunk_mesh(chunk: &Chunk) -> ChunkMeshData { + let mut world = World::new(); + world.chunks.insert((chunk.chunk_x, chunk.chunk_z), Chunk { + chunk_x: chunk.chunk_x, + chunk_z: chunk.chunk_z, + voxels: chunk.voxels.clone(), + dirty_mesh: false, + }); + build_chunk_mesh_world(chunk, &world) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_isolated_block_has_6_faces() { + let mut chunk = Chunk::new_empty(0, 0); + chunk.set_block_local(5, 5, 5, BlockType::Stone); + let mesh = build_chunk_mesh(&chunk); + assert_eq!(mesh.faces_count, 6); + assert_eq!(mesh.indices.len(), 36); + } + + #[test] + fn test_adjacent_blocks_cull_shared_faces() { + let mut chunk = Chunk::new_empty(0, 0); + // Deux blocs adjacents en X : (5, 5, 5) et (6, 5, 5) + // Sans culling : 2 * 6 = 12 faces. + // Avec culling : la face droite de l'un et la face gauche de l'autre sont masquées -> 10 faces ! + chunk.set_block_local(5, 5, 5, BlockType::Stone); + chunk.set_block_local(6, 5, 5, BlockType::Stone); + let mesh = build_chunk_mesh(&chunk); + assert_eq!(mesh.faces_count, 10); + assert_eq!(mesh.indices.len(), 60); + } + + #[test] + fn test_2x2x2_cube_culling() { + let mut chunk = Chunk::new_empty(0, 0); + // 8 blocs formant un cube 2x2x2 + // Sans culling : 8 * 6 = 48 faces. + // Avec culling : seules les faces extérieures du macro-cube restent -> 6 faces * 4 = 24 faces ! + for x in 0..2 { + for y in 0..2 { + for z in 0..2 { + chunk.set_block_local(x, y, z, BlockType::Dirt); + } + } + } + let mesh = build_chunk_mesh(&chunk); + assert_eq!(mesh.faces_count, 24); + assert_eq!(mesh.indices.len(), 144); + } + + #[test] + fn test_cross_chunk_boundary_culling() { + let mut world = World::new(); + + // Chunk (0, 0) avec un bloc sur sa bordure maximale en X (15, 10, 8) + let mut chunk0 = Chunk::new_empty(0, 0); + chunk0.set_block_local(CHUNK_SIZE_X - 1, 10, 8, BlockType::Stone); + world.chunks.insert((0, 0), chunk0); + + // Chunk (1, 0) avec un bloc sur sa bordure minimale en X (0, 10, 8) + // Les deux blocs se touchent à la frontière entre les chunks ! + let mut chunk1 = Chunk::new_empty(1, 0); + chunk1.set_block_local(0, 10, 8, BlockType::Stone); + world.chunks.insert((1, 0), chunk1); + + // Sans culling inter-chunk : chaque bloc aurait 6 faces (12 au total) + // Avec culling inter-chunk : les 2 faces qui se touchent à la frontière sont masquées ! + let mesh0 = build_chunk_mesh_world(world.chunks.get(&(0, 0)).unwrap(), &world); + let mesh1 = build_chunk_mesh_world(world.chunks.get(&(1, 0)).unwrap(), &world); + + assert_eq!(mesh0.faces_count, 5); // 6 - 1 = 5 + assert_eq!(mesh1.faces_count, 5); // 6 - 1 = 5 + } + + #[test] + fn test_terrain_culling_stats() { + let chunk = Chunk::generate_terrain(0, 0); + let solid = chunk.count_solid_blocks(); + let theoretical = solid * 6; + let mesh = build_chunk_mesh(&chunk); + let reduction = (1.0 - (mesh.faces_count as f64 / theoretical as f64)) * 100.0; + println!("\n[TEST] Terrain chunk : {} blocs solides, {} faces théoriques -> {} faces générées (-{:.2}%)", + solid, theoretical, mesh.faces_count, reduction); + assert!(mesh.faces_count < theoretical); + assert!(reduction > 80.0); + } +} diff --git a/src/world/mod.rs b/src/world/mod.rs new file mode 100644 index 0000000..2573a91 --- /dev/null +++ b/src/world/mod.rs @@ -0,0 +1,9 @@ +pub mod chunk; +pub mod mesh_builder; +pub mod world; + +#[allow(unused_imports)] +pub use chunk::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z}; +#[allow(unused_imports)] +pub use mesh_builder::{build_chunk_mesh, build_chunk_mesh_world, ChunkMeshData}; +pub use world::World; diff --git a/src/world/world.rs b/src/world/world.rs new file mode 100644 index 0000000..8e73c0a --- /dev/null +++ b/src/world/world.rs @@ -0,0 +1,183 @@ +use std::collections::HashMap; +use std::time::Instant; + +use super::chunk::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z}; + +/// Structure gérant l'ensemble des Chunks du monde voxel. +pub struct World { + pub chunks: HashMap<(i32, i32), Chunk>, +} + +impl World { + pub fn new() -> Self { + Self { + chunks: HashMap::new(), + } + } + + /// Convertit des coordonnées absolues de bloc (X, Y, Z) en coordonnées de Chunk et coordonnées locales. + /// Utilise la division euclidienne pour gérer correctement les coordonnées négatives. + #[inline(always)] + pub fn world_to_chunk_and_local(x: i32, y: i32, z: i32) -> ((i32, i32), (usize, i32, usize)) { + let chunk_x = x.div_euclid(CHUNK_SIZE_X as i32); + let chunk_z = z.div_euclid(CHUNK_SIZE_Z as i32); + let local_x = x.rem_euclid(CHUNK_SIZE_X as i32) as usize; + let local_z = z.rem_euclid(CHUNK_SIZE_Z as i32) as usize; + ((chunk_x, chunk_z), (local_x, y, local_z)) + } + + /// Récupère le type de bloc aux coordonnées globales (x, y, z). + /// Traverse de manière transparente les frontières de chunks. + #[inline(always)] + pub fn get_block(&self, x: i32, y: i32, z: i32) -> BlockType { + if y < 0 || y >= CHUNK_SIZE_Y as i32 { + return BlockType::Air; + } + + let ((cx, cz), (lx, ly, lz)) = Self::world_to_chunk_and_local(x, y, z); + if let Some(chunk) = self.chunks.get(&(cx, cz)) { + chunk.get_block_local(lx as i32, ly, lz as i32) + } else { + BlockType::Air + } + } + + /// Modifie un bloc aux coordonnées globales (x, y, z). + /// Si le bloc modifié est sur une frontière de chunk, le chunk voisin est également + /// marqué comme `dirty_mesh = true` pour mettre à jour le culling des faces à la frontière. + pub fn set_block(&mut self, x: i32, y: i32, z: i32, block: BlockType) -> bool { + if y < 0 || y >= CHUNK_SIZE_Y as i32 { + return false; + } + + let ((cx, cz), (lx, ly, lz)) = Self::world_to_chunk_and_local(x, y, z); + + if let Some(chunk) = self.chunks.get_mut(&(cx, cz)) { + chunk.set_block_local(lx, ly as usize, lz, block); + + // Détection des bords de chunk pour marquer les voisins affectés + let on_min_x = lx == 0; + let on_max_x = lx == CHUNK_SIZE_X - 1; + let on_min_z = lz == 0; + let on_max_z = lz == CHUNK_SIZE_Z - 1; + + if on_min_x { + if let Some(neighbor) = self.chunks.get_mut(&(cx - 1, cz)) { + neighbor.dirty_mesh = true; + } + } + if on_max_x { + if let Some(neighbor) = self.chunks.get_mut(&(cx + 1, cz)) { + neighbor.dirty_mesh = true; + } + } + if on_min_z { + if let Some(neighbor) = self.chunks.get_mut(&(cx, cz - 1)) { + neighbor.dirty_mesh = true; + } + } + if on_max_z { + if let Some(neighbor) = self.chunks.get_mut(&(cx, cz + 1)) { + neighbor.dirty_mesh = true; + } + } + + true + } else { + false + } + } + + /// Charge/Génère dynamiquement les chunks dans un rayon donné autour de la position du joueur. + /// Retourne le nombre de nouveaux chunks générés et le temps pris en millisecondes. + pub fn update_chunks_around(&mut self, player_x: f32, player_z: f32, radius: i32) -> (usize, f32) { + let start = Instant::now(); + let player_chunk_x = (player_x.floor() as i32).div_euclid(CHUNK_SIZE_X as i32); + let player_chunk_z = (player_z.floor() as i32).div_euclid(CHUNK_SIZE_Z as i32); + + let mut generated_count = 0; + + for dx in -radius..=radius { + for dz in -radius..=radius { + let cx = player_chunk_x + dx; + let cz = player_chunk_z + dz; + + if !self.chunks.contains_key(&(cx, cz)) { + let chunk = Chunk::generate_terrain(cx, cz); + self.chunks.insert((cx, cz), chunk); + generated_count += 1; + + // Si on génère un nouveau chunk, les voisins déjà existants + // doivent recalculer leur frontière commune pour le culling ! + if let Some(neighbor) = self.chunks.get_mut(&(cx - 1, cz)) { + neighbor.dirty_mesh = true; + } + if let Some(neighbor) = self.chunks.get_mut(&(cx + 1, cz)) { + neighbor.dirty_mesh = true; + } + if let Some(neighbor) = self.chunks.get_mut(&(cx, cz - 1)) { + neighbor.dirty_mesh = true; + } + if let Some(neighbor) = self.chunks.get_mut(&(cx, cz + 1)) { + neighbor.dirty_mesh = true; + } + } + } + } + + let elapsed_ms = start.elapsed().as_secs_f32() * 1000.0; + (generated_count, elapsed_ms) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_break_block_at_extreme_negative_coordinate() { + let mut world = World::new(); + let x = -1000; + let y = 12; + let z = -2500; + + let ((cx, cz), (lx, ly, lz)) = World::world_to_chunk_and_local(x, y, z); + assert_eq!(cx, (-1000i32).div_euclid(CHUNK_SIZE_X as i32)); + assert_eq!(cz, (-2500i32).div_euclid(CHUNK_SIZE_Z as i32)); + assert!(lx < CHUNK_SIZE_X); + assert!(lz < CHUNK_SIZE_Z); + assert_eq!(ly, 12); + + // Crée le chunk cible à ces coordonnées lointaines + let mut chunk = Chunk::new_empty(cx, cz); + chunk.set_block_local(lx, ly as usize, lz, BlockType::Stone); + world.chunks.insert((cx, cz), chunk); + + // Vérifie la présence du bloc + assert_eq!(world.get_block(x, y, z), BlockType::Stone); + + // Casse le bloc à cette coordonnée extrême + let broken = world.set_block(x, y, z, BlockType::Air); + assert!(broken, "Le bloc doit être cassé avec succès"); + assert_eq!(world.get_block(x, y, z), BlockType::Air); + + // Tenter de casser un bloc dans un chunk inexistant à x = -999999 ne doit pas crasher + let non_existent = world.set_block(-999999, 10, -999999, BlockType::Air); + assert!(!non_existent, "Casser dans un chunk non chargé renvoie false sans paniquer"); + } + + #[test] + fn test_resize_during_chunk_generation() { + let mut world = World::new(); + // Simule une génération dynamique autour d'un joueur qui bouge rapidement + let positions = [(0.0, 0.0), (100.0, 100.0), (-50.0, -80.0), (200.0, -150.0)]; + + for (px, pz) in positions { + let (new_count, elapsed) = world.update_chunks_around(px, pz, 2); + assert!(elapsed >= 0.0); + assert!(new_count <= 25); + } + + assert!(world.chunks.len() >= 25); + } +}