diff --git a/Cargo.lock b/Cargo.lock index 3f0756271..5fa7f57e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -43,6 +43,28 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "alsa" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43" +dependencies = [ + "alsa-sys", + "bitflags 2.13.2", + "cfg-if", + "libc", +] + +[[package]] +name = "alsa-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "android-activity" version = "0.6.1" @@ -52,7 +74,7 @@ dependencies = [ "android-properties", "bitflags 2.13.2", "cc", - "jni", + "jni 0.22.4", "libc", "log", "ndk", @@ -231,6 +253,12 @@ dependencies = [ "shlex", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cfg-if" version = "1.0.5" @@ -311,6 +339,52 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "coreaudio-rs" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aae284fbaf7d27aa0e292f7677dfbe26503b0d555026f702940805a630eac17" +dependencies = [ + "bitflags 1.3.2", + "libc", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "cpal" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd307f43cc2a697e2d1f8bc7a1d824b5269e052209e28883e5bc04d095aaa3f" +dependencies = [ + "alsa", + "coreaudio-rs", + "dasp_sample", + "jni 0.21.1", + "js-sys", + "libc", + "mach2", + "ndk", + "ndk-context", + "num-derive", + "num-traits", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows 0.54.0", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -338,6 +412,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "dasp_sample" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" + [[package]] name = "dispatch" version = "0.2.0" @@ -384,6 +464,20 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -533,7 +627,7 @@ dependencies = [ "log", "presser", "thiserror 2.0.21", - "windows", + "windows 0.62.2", ] [[package]] @@ -588,6 +682,7 @@ name = "horizon-client" version = "0.1.0" dependencies = [ "bytemuck", + "cpal", "glam", "horizon-assets", "horizon-core", @@ -595,6 +690,7 @@ dependencies = [ "png", "pollster", "serde_json", + "symphonia", "wgpu", "winit", ] @@ -631,6 +727,22 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + [[package]] name = "jni" version = "0.22.4" @@ -710,6 +822,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.190" @@ -783,6 +901,15 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + [[package]] name = "memchr" version = "2.8.3" @@ -818,6 +945,12 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" @@ -886,6 +1019,17 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -959,6 +1103,21 @@ dependencies = [ "objc2-quartz-core 0.2.2", ] +[[package]] +name = "objc2-audio-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08" +dependencies = [ + "bitflags 2.13.2", + "libc", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-cloud-kit" version = "0.2.2" @@ -983,6 +1142,28 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + [[package]] name = "objc2-core-data" version = "0.2.2" @@ -1691,6 +1872,77 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-ogg", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" +dependencies = [ + "log", + "symphonia-core", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "syn" version = "2.0.119" @@ -2194,8 +2446,8 @@ dependencies = [ "thiserror 2.0.21", "wgpu-naga-bridge", "wgpu-types", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -2233,6 +2485,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "windows" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49" +dependencies = [ + "windows-core 0.54.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows" version = "0.62.2" @@ -2240,7 +2502,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ "windows-collections", - "windows-core", + "windows-core 0.62.2", "windows-future", "windows-numerics", ] @@ -2251,7 +2513,17 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core", + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65" +dependencies = [ + "windows-result 0.1.2", + "windows-targets 0.52.6", ] [[package]] @@ -2263,7 +2535,7 @@ dependencies = [ "windows-implement", "windows-interface", "windows-link", - "windows-result", + "windows-result 0.4.1", "windows-strings", ] @@ -2273,7 +2545,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core", + "windows-core 0.62.2", "windows-link", "windows-threading", ] @@ -2312,10 +2584,19 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core", + "windows-core 0.62.2", "windows-link", ] +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -2334,13 +2615,22 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -2349,7 +2639,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -2361,20 +2651,35 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + [[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_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -2386,18 +2691,36 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -2410,24 +2733,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index 70cf54aba..aca7bb21d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,3 +10,10 @@ rust-version = "1.85" [profile.release] lto = "thin" codegen-units = 1 + +# Optimized but quick-to-link builds for iteration: cargo build --profile fast +[profile.fast] +inherits = "release" +lto = false +codegen-units = 16 +incremental = true diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 4bf34c0f5..f9b002548 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -17,3 +17,5 @@ bytemuck = { version = "1.24", features = ["derive"] } glam = "0.30" png = "0.18" serde_json = { version = "1.0.151", features = ["raw_value"] } +cpal = "0.16" +symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index 40ae1a335..633c3009c 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -60,6 +60,8 @@ pub struct Assets { pub model_placements: Vec<(horizon_core::position::BlockPos, BlockStateId)>, pub model_gallery: Vec, pub animations: Vec, + pub sprite_layers: std::collections::BTreeMap, + pub translucent_layers: Vec, } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) @@ -177,6 +179,14 @@ impl Assets { sprites.insert(root, &format!("minecraft:block/{name}"))?; } let models = crate::models::prepare(root, ®istry, &mut sprites)?; + // Fluids are drawn by the fluid renderer, not block models; breaking + // progress uses the destroy-stage overlays. + for name in ["water_still", "water_flow", "water_overlay", "lava_still", "lava_flow"] { + sprites.insert(root, &format!("minecraft:block/{name}"))?; + } + for stage in 0..10 { + sprites.insert(root, &format!("minecraft:block/destroy_stage_{stage}"))?; + } Ok(Self { registry, properties, @@ -188,6 +198,8 @@ impl Assets { model_placements: models.placements, model_gallery: models.states, animations: sprites.animations, + sprite_layers: sprites.layers, + translucent_layers: sprites.translucent, }) } } diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs new file mode 100644 index 000000000..e332e863b --- /dev/null +++ b/crates/horizon-client/src/audio.rs @@ -0,0 +1,247 @@ +//! Sound playback: `sounds.json` events with weighted variants, Ogg/Vorbis +//! decoding, and a small mixer with vanilla's linear distance attenuation +//! (`SoundInstance.Attenuation.LINEAR`, default range 16 blocks) and stereo panning. +use crate::Result; +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use serde_json::Value; +use std::{ + collections::HashMap, + fs, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +#[derive(Clone, Debug)] +struct Variant { + name: String, + volume: f32, + pitch: f32, + weight: u32, + attenuation: f32, + is_event: bool, +} +struct Voice { + samples: Arc>, + position: f64, + step: f64, + left: f32, + right: f32, +} +#[derive(Default)] +struct Mixer { + voices: Vec, +} +pub struct Audio { + _stream: Option, + mixer: Arc>, + rate: u32, + root: PathBuf, + events: HashMap>, + cache: HashMap>, u32)>>, + seed: u64, + pub listener: [f64; 3], + pub listener_yaw: f32, + pub master: f32, +} +fn decode(path: &Path) -> Option<(Vec, u32)> { + use symphonia::core::{ + audio::SampleBuffer, codecs::DecoderOptions, formats::FormatOptions, io::MediaSourceStream, + meta::MetadataOptions, probe::Hint, + }; + let file = fs::File::open(path).ok()?; + let stream = MediaSourceStream::new(Box::new(file), Default::default()); + let mut hint = Hint::new(); + hint.with_extension("ogg"); + let probed = symphonia::default::get_probe() + .format(&hint, stream, &FormatOptions::default(), &MetadataOptions::default()) + .ok()?; + let mut format = probed.format; + let track = format.default_track()?; + let id = track.id; + let rate = track.codec_params.sample_rate?; + let mut decoder = symphonia::default::get_codecs() + .make(&track.codec_params, &DecoderOptions::default()) + .ok()?; + let mut mono = Vec::new(); + while let Ok(packet) = format.next_packet() { + if packet.track_id() != id { + continue; + } + let Ok(buffer) = decoder.decode(&packet) else { continue }; + let spec = *buffer.spec(); + let channels = spec.channels.count().max(1); + let mut samples = SampleBuffer::::new(buffer.capacity() as u64, spec); + samples.copy_interleaved_ref(buffer); + for frame in samples.samples().chunks(channels) { + mono.push(frame.iter().sum::() / channels as f32); + } + } + Some((mono, rate)) +} +impl Audio { + pub fn new(root: &Path) -> Self { + let mut events = HashMap::new(); + if let Ok(text) = fs::read(root.join("assets/minecraft/sounds.json")) + && let Ok(Value::Object(map)) = serde_json::from_slice::(&text) + { + for (name, def) in map { + let variants = def["sounds"] + .as_array() + .into_iter() + .flatten() + .map(|s| match s { + Value::String(n) => Variant { + name: n.clone(), + volume: 1.0, + pitch: 1.0, + weight: 1, + attenuation: 16.0, + is_event: false, + }, + _ => Variant { + name: s["name"].as_str().unwrap_or("").to_owned(), + volume: s["volume"].as_f64().unwrap_or(1.0) as f32, + pitch: s["pitch"].as_f64().unwrap_or(1.0) as f32, + weight: s["weight"].as_u64().unwrap_or(1) as u32, + attenuation: s["attenuation_distance"].as_f64().unwrap_or(16.0) as f32, + is_event: s["type"].as_str() == Some("event"), + }, + }) + .collect::>(); + events.insert(format!("minecraft:{name}"), variants); + } + } + let mixer = Arc::new(Mutex::new(Mixer::default())); + let (stream, rate) = match Self::open(mixer.clone()) { + Ok(v) => (Some(v.0), v.1), + Err(e) => { + eprintln!("Horizon: audio unavailable: {e}"); + (None, 48_000) + } + }; + Self { + _stream: stream, + mixer, + rate, + root: root.to_owned(), + events, + cache: HashMap::new(), + seed: 0x5DEE_CE66, + listener: [0.0; 3], + listener_yaw: 0.0, + master: 1.0, + } + } + fn open(mixer: Arc>) -> Result<(cpal::Stream, u32)> { + let host = cpal::default_host(); + let device = host.default_output_device().ok_or("no audio output device")?; + let config = device.default_output_config()?; + let rate = config.sample_rate().0; + let channels = config.channels() as usize; + let stream = device.build_output_stream( + &config.into(), + move |data: &mut [f32], _| { + data.fill(0.0); + let Ok(mut mixer) = mixer.lock() else { return }; + for frame in data.chunks_mut(channels) { + let (mut l, mut r) = (0.0f32, 0.0f32); + for v in mixer.voices.iter_mut() { + let i = v.position as usize; + if i + 1 >= v.samples.len() { + continue; + } + let t = (v.position - i as f64) as f32; + let s = v.samples[i] * (1.0 - t) + v.samples[i + 1] * t; + l += s * v.left; + r += s * v.right; + v.position += v.step; + } + if channels >= 2 { + frame[0] = l.clamp(-1.0, 1.0); + frame[1] = r.clamp(-1.0, 1.0); + } else { + frame[0] = ((l + r) / 2.0).clamp(-1.0, 1.0); + } + } + mixer.voices.retain(|v| (v.position as usize) + 1 < v.samples.len()); + }, + |e| eprintln!("Horizon: audio stream error: {e}"), + None, + )?; + stream.play()?; + Ok((stream, rate)) + } + fn random(&mut self) -> u64 { + self.seed ^= self.seed << 13; + self.seed ^= self.seed >> 7; + self.seed ^= self.seed << 17; + self.seed + } + fn resolve(&mut self, event: &str, depth: u32) -> Option { + let variants = self.events.get(event)?.clone(); + let total: u32 = variants.iter().map(|v| v.weight).sum(); + if total == 0 { + return None; + } + let mut pick = (self.random() % u64::from(total)) as u32; + let chosen = variants.into_iter().find(|v| { + if pick < v.weight { + true + } else { + pick -= v.weight; + false + } + })?; + if chosen.is_event && depth < 4 { + let name = if chosen.name.contains(':') { chosen.name.clone() } else { format!("minecraft:{}", chosen.name) }; + let mut inner = self.resolve(&name, depth + 1)?; + inner.volume *= chosen.volume; + inner.pitch *= chosen.pitch; + return Some(inner); + } + Some(chosen) + } + /// Play a sound event at a world position (None = non-positional UI sound). + pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) { + if self._stream.is_none() { + return; + } + let Some(variant) = self.resolve(event, 0) else { return }; + let file = variant.name.trim_start_matches("minecraft:").to_owned(); + let entry = self.cache.entry(file.clone()).or_insert_with(|| { + decode(&self.root.join(format!("assets/minecraft/sounds/{file}.ogg"))).map(|(s, r)| (Arc::new(s), r)) + }); + let Some((samples, rate)) = entry.clone() else { return }; + let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master; + let pitch = (pitch * variant.pitch).clamp(0.5, 2.0); + let (mut left, mut right) = (volume, volume); + if let Some(p) = at { + let d = [p[0] - self.listener[0], p[1] - self.listener[1], p[2] - self.listener[2]]; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; + let range = variant.attenuation * volume.max(1.0); + let gain = (1.0 - distance / range).clamp(0.0, 1.0); + if gain <= 0.0 { + return; + } + let yaw = self.listener_yaw.to_radians(); + // Right vector of a Minecraft yaw. + let side = (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001); + let pan = side.clamp(-1.0, 1.0); + left = volume * gain * (1.0 - pan.max(0.0) * 0.6); + right = volume * gain * (1.0 + pan.min(0.0) * 0.6); + } + let step = f64::from(rate) / f64::from(self.rate) * f64::from(pitch); + if let Ok(mut m) = self.mixer.lock() { + if m.voices.len() > 64 { + m.voices.remove(0); + } + m.voices.push(Voice { + samples, + position: 0.0, + step, + left, + right, + }); + } + } +} diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs new file mode 100644 index 000000000..3096d6d4c --- /dev/null +++ b/crates/horizon-client/src/biome.rs @@ -0,0 +1,153 @@ +//! Biome colours from the pinned biome definitions and colormaps +//! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`). +use crate::Result; +use horizon_core::{noise::SimplexNoise, random::LegacyRandom}; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GrassModifier { + None, + DarkForest, + Swamp, +} +#[derive(Clone, Debug)] +pub struct BiomeInfo { + pub name: String, + pub temperature: f32, + pub downfall: f32, + pub precipitation: bool, + pub grass: u32, + pub modifier: GrassModifier, + pub foliage: u32, + pub dry_foliage: u32, + pub water: u32, + pub sky: u32, + pub fog: u32, + pub water_fog: u32, +} +pub struct Biomes { + pub list: Vec, + pub index: HashMap, + info_noise: SimplexNoise, +} +fn color(v: &Value) -> Option { + match v { + Value::String(s) => u32::from_str_radix(s.trim_start_matches('#'), 16) + .ok() + .map(|c| c & 0xFF_FFFF), + Value::Number(n) => n.as_i64().map(|c| c as u32 & 0xFF_FFFF), + _ => None, + } +} +fn colormap(root: &Path, name: &str) -> Result> { + let path = root.join(format!("assets/minecraft/textures/colormap/{name}.png")); + let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?)); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); + let mut reader = decoder.read_info()?; + let mut bytes = vec![0; reader.output_buffer_size().ok_or("colormap too large")?]; + let info = reader.next_frame(&mut bytes)?; + let channels = info.color_type.samples(); + Ok(bytes[..info.buffer_size()] + .chunks_exact(channels) + .map(|p| u32::from(p[0]) << 16 | u32::from(p[1]) << 8 | u32::from(p[2])) + .collect()) +} +/// `GrassColor.get`/`FoliageColor.get`: temperature and downfall index a 256x256 map. +fn sample(map: &[u32], temperature: f32, downfall: f32, fallback: u32) -> u32 { + let temperature = f64::from(temperature.clamp(0.0, 1.0)); + let downfall = f64::from(downfall.clamp(0.0, 1.0)) * temperature; + let x = ((1.0 - temperature) * 255.0) as i32; + let y = ((1.0 - downfall) * 255.0) as i32; + let index = (y << 8 | x) as usize; + map.get(index).copied().unwrap_or(fallback) +} +impl Biomes { + pub fn load(root: &Path) -> Result { + let grass = colormap(root, "grass")?; + let foliage = colormap(root, "foliage")?; + let dry = colormap(root, "dry_foliage")?; + let dimension: Value = serde_json::from_slice(&fs::read( + root.join("data/minecraft/dimension_type/overworld.json"), + )?)?; + let default_fog = color(&dimension["attributes"]["minecraft:visual/fog_color"]) + .unwrap_or(0xC0D8FF); + let default_sky = color(&dimension["attributes"]["minecraft:visual/sky_color"]) + .unwrap_or(0x78A7FF); + let mut list = Vec::new(); + let mut names: Vec<_> = fs::read_dir(root.join("data/minecraft/worldgen/biome"))? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + names.sort(); + for path in names { + let name = format!( + "minecraft:{}", + path.file_stem().and_then(|s| s.to_str()).ok_or("bad biome")? + ); + let v: Value = serde_json::from_slice(&fs::read(&path)?)?; + let effects = &v["effects"]; + let attributes = &v["attributes"]; + let temperature = v["temperature"].as_f64().unwrap_or(0.5) as f32; + let downfall = v["downfall"].as_f64().unwrap_or(0.5) as f32; + let modifier = match effects["grass_color_modifier"].as_str() { + Some("dark_forest") => GrassModifier::DarkForest, + Some("swamp") => GrassModifier::Swamp, + _ => GrassModifier::None, + }; + list.push(BiomeInfo { + temperature, + downfall, + precipitation: v["has_precipitation"].as_bool().unwrap_or(true), + grass: color(&effects["grass_color"]) + .unwrap_or_else(|| sample(&grass, temperature, downfall, 0xFF00FF)), + modifier, + foliage: color(&effects["foliage_color"]) + .unwrap_or_else(|| sample(&foliage, temperature, downfall, 0x48B518)), + dry_foliage: color(&effects["dry_foliage_color"]) + .unwrap_or_else(|| sample(&dry, temperature, downfall, 0x5D4930)), + water: color(&effects["water_color"]).unwrap_or(0x3F76E4), + sky: color(&attributes["minecraft:visual/sky_color"]).unwrap_or(default_sky), + fog: color(&attributes["minecraft:visual/fog_color"]).unwrap_or(default_fog), + water_fog: color(&attributes["minecraft:visual/water_fog_color"]) + .unwrap_or(0x050533), + name, + }); + } + let index = list + .iter() + .enumerate() + .map(|(i, b)| (b.name.clone(), i as u16)) + .collect(); + Ok(Self { + list, + index, + info_noise: SimplexNoise::with_skipped_offsets(&mut LegacyRandom::new(2345), true), + }) + } + pub fn id(&self, name: &str) -> u16 { + self.index + .get(name) + .or_else(|| self.index.get("minecraft:plains")) + .copied() + .unwrap_or(0) + } + pub fn get(&self, id: u16) -> &BiomeInfo { + &self.list[usize::from(id).min(self.list.len() - 1)] + } + pub fn grass(&self, id: u16, x: f64, z: f64) -> u32 { + let b = self.get(id); + match b.modifier { + GrassModifier::None => b.grass, + GrassModifier::DarkForest => ((b.grass & 0xFE_FEFE) + 0x28_340A) >> 1, + GrassModifier::Swamp => { + if f64::from(self.info_noise.get2(x * 0.0225, z * 0.0225)) < -0.1 { + 0x4C_763C + } else { + 0x6A_7039 + } + } + } + } +} diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs new file mode 100644 index 000000000..b67529ece --- /dev/null +++ b/crates/horizon-client/src/blocks.rs @@ -0,0 +1,164 @@ +//! Per-state gameplay facts exported from vanilla's own block-state accessors +//! (`gameplay-facts.json`), indexed by registry state ID. +use crate::Result; +use horizon_world::registry::{BlockRegistry, BlockStateId}; +use serde_json::Value; +use std::{collections::HashMap, fs::File, io::BufReader, path::Path, sync::Arc}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RenderShape { + Model, + Invisible, + Animated, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fluid { + None, + Water, + Lava, +} +#[derive(Clone, Debug)] +pub struct Sounds { + pub volume: f32, + pub pitch: f32, + pub break_sound: Arc, + pub step: Arc, + pub place: Arc, + pub hit: Arc, + pub fall: Arc, +} +#[derive(Clone, Debug)] +pub struct StateFacts { + pub name: Arc, + pub emission: u8, + pub dampening: u8, + pub skylight_down: bool, + pub shape_occlusion: bool, + pub can_occlude: bool, + pub solid_render: bool, + pub hardness: f32, + pub requires_tool: bool, + pub replaceable: bool, + pub random_ticks: bool, + pub block_entity: bool, + pub render_shape: RenderShape, + pub full_collision: bool, + pub friction: f32, + pub explosion_resistance: f32, + pub item: Arc, + pub sounds: Sounds, + pub fluid: Fluid, + /// Fluid amount 1..=8 (8 = source/falling surface), 0 when there is no fluid. + pub fluid_level: u8, + pub fluid_falling: bool, + pub waterlogged: bool, +} +pub struct BlockFacts { + pub states: Vec, + pub air: BlockStateId, +} +impl BlockFacts { + pub fn load(root: &Path, registry: &BlockRegistry) -> Result { + let raw: Value = + serde_json::from_reader(BufReader::new(File::open(root.join("gameplay-facts.json"))?))?; + let entries = raw["states"] + .as_array() + .ok_or("missing gameplay state facts")?; + if entries.len() != registry.len() { + return Err("gameplay facts do not match the block registry".into()); + } + let mut names: HashMap> = HashMap::new(); + let mut intern = |s: &str| -> Arc { + names + .entry(s.to_owned()) + .or_insert_with(|| Arc::from(s)) + .clone() + }; + let mut states = Vec::with_capacity(entries.len()); + for (index, entry) in entries.iter().enumerate() { + let id = BlockStateId(index as u32); + if entry["id"].as_u64() != Some(index as u64) { + return Err("gameplay facts are not in registry order".into()); + } + let state = registry.state(id).ok_or("missing registry state")?; + let num = |k: &str| entry[k].as_f64().unwrap_or(0.0); + let flag = |k: &str| entry[k].as_bool().unwrap_or(false); + let sound = &entry["sound"]; + let sound_id = |k: &str| sound[k]["id"].as_str().unwrap_or("").to_owned(); + let prop = |k: &str| state.properties.get(k).map(String::as_str); + let (fluid, fluid_level, fluid_falling) = match state.name.as_str() { + "minecraft:water" | "minecraft:lava" => { + let level: u8 = prop("level").and_then(|v| v.parse().ok()).unwrap_or(0); + let kind = if state.name == "minecraft:water" { + Fluid::Water + } else { + Fluid::Lava + }; + // LiquidBlock: level 0 is the source; 1..7 flowing; >=8 falling. + if level == 0 { + (kind, 8, false) + } else if level >= 8 { + (kind, 8, true) + } else { + (kind, 8 - level, false) + } + } + "minecraft:bubble_column" | "minecraft:kelp" | "minecraft:kelp_plant" + | "minecraft:seagrass" | "minecraft:tall_seagrass" => (Fluid::Water, 8, false), + _ if prop("waterlogged") == Some("true") => (Fluid::Water, 8, false), + _ => (Fluid::None, 0, false), + }; + states.push(StateFacts { + name: intern(&state.name), + emission: num("emission") as u8, + dampening: num("dampening") as u8, + skylight_down: flag("skylight_down"), + shape_occlusion: flag("shape_occlusion"), + can_occlude: flag("can_occlude"), + solid_render: flag("solid_render"), + hardness: num("hardness") as f32, + requires_tool: flag("requires_tool"), + replaceable: flag("replaceable"), + random_ticks: flag("random_ticks"), + block_entity: flag("block_entity"), + render_shape: match entry["render_shape"].as_str() { + Some("INVISIBLE") => RenderShape::Invisible, + Some("ENTITYBLOCK_ANIMATED") => RenderShape::Animated, + _ => RenderShape::Model, + }, + full_collision: flag("full_collision"), + friction: num("friction") as f32, + explosion_resistance: num("explosion_resistance") as f32, + item: intern(entry["item"].as_str().unwrap_or("minecraft:air")), + sounds: Sounds { + volume: sound["volume"].as_f64().unwrap_or(1.0) as f32, + pitch: sound["pitch"].as_f64().unwrap_or(1.0) as f32, + break_sound: intern(&sound_id("break")), + step: intern(&sound_id("step")), + place: intern(&sound_id("place")), + hit: intern(&sound_id("hit")), + fall: intern(&sound_id("fall")), + }, + fluid, + fluid_level, + fluid_falling, + waterlogged: prop("waterlogged") == Some("true"), + }); + } + Ok(Self { + states, + air: registry + .default_state("minecraft:air") + .ok_or("missing air")?, + }) + } + pub fn get(&self, id: BlockStateId) -> &StateFacts { + &self.states[id.0 as usize] + } + pub fn is_air(&self, id: BlockStateId) -> bool { + matches!( + &*self.states[id.0 as usize].name, + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ) + } +} diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs deleted file mode 100644 index 468030e8a..000000000 --- a/crates/horizon-client/src/camera.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! Free inspection camera, deliberately separate from future player simulation. -use glam::{DVec3, Mat4, Vec3}; -use std::collections::HashSet; -use winit::keyboard::KeyCode; -pub struct Camera { - pub position: DVec3, - pub yaw: f64, - pub pitch: f64, -} -impl Default for Camera { - fn default() -> Self { - Self { - position: DVec3::new(25.0, 18.0, 25.0), - yaw: -135_f64.to_radians(), - pitch: -22_f64.to_radians(), - } - } -} -impl Camera { - /// A standing-sized inspection volume, not a simulated player entity. - pub fn collision_bounds(&self) -> horizon_core::geometry::Aabb { - use horizon_core::geometry::{Aabb, Vec3}; - let half_width = f64::from(0.6_f32 / 2.0); - let feet = self.position.y - f64::from(1.62_f32); - Aabb::new( - Vec3::new( - self.position.x - half_width, - feet, - self.position.z - half_width, - ), - Vec3::new( - self.position.x + half_width, - feet + f64::from(1.8_f32), - self.position.z + half_width, - ), - ) - } - pub fn look(&mut self, x: f64, y: f64) { - self.yaw -= x * 0.002; - self.pitch = (self.pitch - y * 0.002).clamp(-1.55, 1.55); - } - pub fn update(&mut self, keys: &HashSet, seconds: f64) { - self.turn(keys, seconds); - let held = |key| f64::from(u8::from(keys.contains(&key))); - let forward = DVec3::new(self.yaw.sin(), 0.0, self.yaw.cos()); - let right = DVec3::new(-self.yaw.cos(), 0.0, self.yaw.sin()); - let movement = forward * (held(KeyCode::KeyW) - held(KeyCode::KeyS)) - + right * (held(KeyCode::KeyD) - held(KeyCode::KeyA)) - + DVec3::Y - * (held(KeyCode::Space) - held(KeyCode::ShiftLeft) - held(KeyCode::ShiftRight)); - if movement.length_squared() > 0.0 { - self.position += movement.normalize() - * seconds - * if keys.contains(&KeyCode::ControlLeft) || keys.contains(&KeyCode::ControlRight) { - 40.0 - } else { - 12.0 - }; - } - } - pub fn turn(&mut self, keys: &HashSet, seconds: f64) { - let held = |key| f64::from(u8::from(keys.contains(&key))); - self.yaw += (held(KeyCode::ArrowLeft) - held(KeyCode::ArrowRight)) * seconds * 1.5; - self.pitch = (self.pitch - + (held(KeyCode::ArrowUp) - held(KeyCode::ArrowDown)) * seconds * 1.5) - .clamp(-1.55, 1.55); - } - pub fn matrix(&self, aspect: f32) -> Mat4 { - let forward = Vec3::new( - (self.yaw.sin() * self.pitch.cos()) as f32, - self.pitch.sin() as f32, - (self.yaw.cos() * self.pitch.cos()) as f32, - ); - Mat4::perspective_rh(70_f32.to_radians(), aspect, 0.05, 1024.0) - * Mat4::look_to_rh(self.position.as_vec3(), forward, Vec3::Y) - } -} diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs new file mode 100644 index 000000000..056f88f84 --- /dev/null +++ b/crates/horizon-client/src/chunk.rs @@ -0,0 +1,144 @@ +//! Resident client chunk storage. Sections are reference-counted so worker +//! threads can mesh and light immutable snapshots while the game thread edits +//! (copy-on-write through `Arc::make_mut`). +use horizon_world::registry::BlockStateId; +use std::sync::Arc; + +pub const MIN_Y: i32 = -64; +pub const HEIGHT: i32 = 384; +pub const SECTIONS: usize = (HEIGHT / 16) as usize; + +#[derive(Clone)] +pub enum Blocks { + Uniform(u16), + Full(Box<[u16; 4096]>), +} +/// Packed light per block: sky light in the high nibble, block light in the low one. +#[derive(Clone)] +pub enum Light { + Uniform(u8), + Full(Box<[u8; 4096]>), +} +#[inline] +pub fn index(x: i32, y: i32, z: i32) -> usize { + ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize +} +#[derive(Clone)] +pub struct Section { + pub blocks: Blocks, + pub light: Light, +} +impl Default for Section { + fn default() -> Self { + Self { + blocks: Blocks::Uniform(0), + light: Light::Uniform(0xF0), + } + } +} +impl Section { + #[inline] + pub fn get(&self, i: usize) -> u16 { + match &self.blocks { + Blocks::Uniform(v) => *v, + Blocks::Full(a) => a[i], + } + } + pub fn set(&mut self, i: usize, v: u16) -> u16 { + match &mut self.blocks { + Blocks::Uniform(u) if *u == v => v, + Blocks::Uniform(u) => { + let old = *u; + let mut a = Box::new([old; 4096]); + a[i] = v; + self.blocks = Blocks::Full(a); + old + } + Blocks::Full(a) => std::mem::replace(&mut a[i], v), + } + } + #[inline] + pub fn light(&self, i: usize) -> u8 { + match &self.light { + Light::Uniform(v) => *v, + Light::Full(a) => a[i], + } + } + pub fn is_uniform(&self, v: u16) -> bool { + match &self.blocks { + Blocks::Uniform(u) => *u == v, + Blocks::Full(a) => a.iter().all(|&b| b == v), + } + } + /// Collapse storage that became uniform. + pub fn compact(&mut self) { + if let Blocks::Full(a) = &self.blocks + && a.iter().all(|&b| b == a[0]) + { + self.blocks = Blocks::Uniform(a[0]); + } + if let Light::Full(a) = &self.light + && a.iter().all(|&b| b == a[0]) + { + self.light = Light::Uniform(a[0]); + } + } +} +#[derive(Clone)] +pub struct Chunk { + pub x: i32, + pub z: i32, + pub sections: Vec>, + /// Biome index per 4x4x4 cell (x,z in 0..4, y in 0..96) into `Biomes`. + pub biomes: Arc>, + /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. + pub heights: Arc<[i16; 256]>, + pub lit: bool, +} +impl Chunk { + pub fn empty(x: i32, z: i32) -> Self { + Self { + x, + z, + sections: (0..SECTIONS).map(|_| Arc::new(Section::default())).collect(), + biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]), + heights: Arc::new([MIN_Y as i16; 256]), + lit: false, + } + } + #[inline] + pub fn get(&self, x: i32, y: i32, z: i32) -> u16 { + let s = (y - MIN_Y) >> 4; + if !(0..SECTIONS as i32).contains(&s) { + return 0; + } + self.sections[s as usize].get(index(x, y, z)) + } + #[inline] + pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { + BlockStateId(u32::from(self.get(x, y, z))) + } + pub fn set(&mut self, x: i32, y: i32, z: i32, v: u16) -> u16 { + let s = (y - MIN_Y) >> 4; + if !(0..SECTIONS as i32).contains(&s) { + return v; + } + Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v) + } + #[inline] + pub fn light(&self, x: i32, y: i32, z: i32) -> u8 { + let s = (y - MIN_Y) >> 4; + if s < 0 { + return 0; + } + if s >= SECTIONS as i32 { + return 0xF0; + } + self.sections[s as usize].light(index(x, y, z)) + } + #[inline] + pub fn biome(&self, x: i32, y: i32, z: i32) -> u16 { + let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1); + self.biomes[(qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize] + } +} diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 3fe979b5b..f5cd36704 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -1,7 +1,7 @@ //! Collision queries against the same resident chunks used by the renderer. //! The development scene has no entities, block entities or world border. //! Entity-dependent block rules fail explicitly until an entity runtime exists. -use crate::{Result, world::TestWorld}; +use crate::{Result, world::World}; use horizon_core::{ geometry::{Aabb, Vec3, VoxelShape}, position::{BlockPos, ChunkPos}, @@ -40,7 +40,7 @@ pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result { - pub world: &'w TestWorld<'r>, + pub world: &'w World, pub binding: &'w BlockCollisionRegistry<'r>, } impl SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs new file mode 100644 index 000000000..7cc2e8854 --- /dev/null +++ b/crates/horizon-client/src/crafting.rs @@ -0,0 +1,203 @@ +//! Crafting and cooking recipes from the pinned data pack: shaped patterns +//! (placed anywhere in the grid, optionally mirrored as in +//! `ShapedRecipePattern.matches`), shapeless ingredient sets, and furnace-type +//! cooking lookups. +use crate::{Result, items::{ItemStack, Items}}; +use serde_json::Value; +use std::{collections::HashSet, fs, path::Path, sync::Arc}; + +/// A set of accepted items (expanded from an item, list or tag). +#[derive(Clone, Debug)] +pub struct Ingredient(pub HashSet); +impl Ingredient { + fn parse(v: &Value, items: &Items) -> Option { + let mut set = HashSet::new(); + let mut add = |s: &str| { + if let Some(tag) = s.strip_prefix('#') { + set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()); + } else { + set.insert(s.to_owned()); + } + }; + match v { + Value::String(s) => add(s), + Value::Array(a) => a.iter().filter_map(Value::as_str).for_each(&mut add), + Value::Object(o) => { + if let Some(s) = o.get("item").and_then(Value::as_str) { + add(s); + } + if let Some(t) = o.get("tag").and_then(Value::as_str) { + add(&format!("#{t}")); + } + } + _ => return None, + } + (!set.is_empty()).then_some(Self(set)) + } + pub fn test(&self, stack: &ItemStack) -> bool { + self.0.contains(&*stack.item) + } +} +#[derive(Clone, Debug)] +pub enum Recipe { + Shaped { + width: usize, + height: usize, + cells: Vec>, + result: ItemStack, + }, + Shapeless { + ingredients: Vec, + result: ItemStack, + }, +} +#[derive(Clone, Debug)] +pub struct Cooking { + pub kind: String, + pub ingredient: Ingredient, + pub result: ItemStack, + pub experience: f32, + pub time: u32, +} +pub struct Recipes { + pub crafting: Vec<(String, Recipe)>, + pub cooking: Vec, +} +fn result(v: &Value) -> Option { + Some(ItemStack { + item: Arc::from(v["id"].as_str()?), + count: v["count"].as_u64().unwrap_or(1) as u32, + damage: 0, + }) +} +impl Recipes { + pub fn load(root: &Path, items: &Items) -> Result { + let mut crafting = Vec::new(); + let mut cooking = Vec::new(); + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))? + .flatten() + .map(|e| e.path()) + .collect(); + files.sort(); + for path in files { + let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_owned(); + let v: Value = serde_json::from_slice(&fs::read(&path)?)?; + match v["type"].as_str().unwrap_or("") { + "minecraft:crafting_shaped" => { + let pattern: Vec> = v["pattern"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r.as_str().map(|s| s.chars().collect())) + .collect(); + let height = pattern.len(); + let width = pattern.iter().map(Vec::len).max().unwrap_or(0); + let mut cells = Vec::with_capacity(width * height); + let mut ok = true; + for row in &pattern { + for x in 0..width { + let c = row.get(x).copied().unwrap_or(' '); + if c == ' ' { + cells.push(None); + } else { + match Ingredient::parse(&v["key"][c.to_string()], items) { + Some(i) => cells.push(Some(i)), + None => ok = false, + } + } + } + } + if let (true, Some(result)) = (ok, result(&v["result"])) { + crafting.push((name, Recipe::Shaped { width, height, cells, result })); + } + } + "minecraft:crafting_shapeless" => { + let ingredients: Option> = v["ingredients"] + .as_array() + .into_iter() + .flatten() + .map(|i| Ingredient::parse(i, items)) + .collect(); + if let (Some(ingredients), Some(result)) = (ingredients, result(&v["result"])) { + crafting.push((name, Recipe::Shapeless { ingredients, result })); + } + } + kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" | "minecraft:campfire_cooking") => { + if let (Some(ingredient), Some(result)) = (Ingredient::parse(&v["ingredient"], items), result(&v["result"])) { + cooking.push(Cooking { + kind: kind.to_owned(), + ingredient, + result, + experience: v["experience"].as_f64().unwrap_or(0.0) as f32, + time: v["cookingtime"].as_u64().unwrap_or(200) as u32, + }); + } + } + _ => {} + } + } + Ok(Self { crafting, cooking }) + } + /// Match a `size`x`size` grid (row-major) against the crafting recipes. + pub fn craft(&self, grid: &[Option], size: usize) -> Option { + // Trim to the occupied bounding box. + let occupied: Vec<(usize, usize)> = (0..size * size) + .filter(|&i| grid[i].is_some()) + .map(|i| (i % size, i / size)) + .collect(); + if occupied.is_empty() { + return None; + } + let (x0, x1) = (occupied.iter().map(|p| p.0).min()?, occupied.iter().map(|p| p.0).max()?); + let (y0, y1) = (occupied.iter().map(|p| p.1).min()?, occupied.iter().map(|p| p.1).max()?); + let (w, h) = (x1 - x0 + 1, y1 - y0 + 1); + let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); + for (_, recipe) in &self.crafting { + match recipe { + Recipe::Shaped { width, height, cells, result } => { + if *width != w || *height != h { + continue; + } + let matches = |mirror: bool| { + (0..h).all(|y| { + (0..w).all(|x| { + let rx = if mirror { w - 1 - x } else { x }; + match (&cells[y * w + rx], cell(x, y)) { + (None, None) => true, + (Some(i), Some(s)) => i.test(s), + _ => false, + } + }) + }) + }; + if matches(false) || matches(true) { + return Some(result.clone()); + } + } + Recipe::Shapeless { ingredients, result } => { + let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); + if stacks.len() != ingredients.len() { + continue; + } + // Greedy bipartite matching is sufficient for vanilla's ingredient sets. + let mut used = vec![false; stacks.len()]; + let ok = ingredients.iter().all(|ingredient| { + if let Some(i) = (0..stacks.len()).find(|&i| !used[i] && ingredient.test(stacks[i])) { + used[i] = true; + true + } else { + false + } + }); + if ok { + return Some(result.clone()); + } + } + } + } + None + } + pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { + self.cooking.iter().find(|c| c.kind == kind && c.ingredient.test(input)) + } +} diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs new file mode 100644 index 000000000..bf8f0ebb6 --- /dev/null +++ b/crates/horizon-client/src/entities.rs @@ -0,0 +1,100 @@ +//! Non-player entities simulated on the client world. Dropped items follow +//! `ItemEntity.tick`: gravity 0.04, 0.98 drag (block friction on the ground), +//! a ground bounce of -0.5, water buoyancy, pickup delay and 6000-tick despawn. +use crate::{ + blocks::{BlockFacts, Fluid}, + collisions::SceneCollisions, + items::ItemStack, + world::World, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::block_collision::BlockCollisionRegistry; + +#[derive(Clone, Debug)] +pub struct ItemEntity { + pub id: u32, + pub stack: ItemStack, + pub position: Vec3, + pub previous: Vec3, + pub velocity: Vec3, + pub on_ground: bool, + pub age: u32, + pub pickup_delay: u32, + pub bob_offset: f32, +} +impl ItemEntity { + pub const WIDTH: f64 = 0.25; + pub fn bounds(&self) -> Aabb { + let h = Self::WIDTH / 2.0; + Aabb::new( + Vec3::new(self.position.x - h, self.position.y, self.position.z - h), + Vec3::new(self.position.x + h, self.position.y + Self::WIDTH, self.position.z + h), + ) + } + /// Returns false when the item should be removed. + pub fn tick( + &mut self, + world: &World, + facts: &BlockFacts, + collision: &BlockCollisionRegistry<'_>, + ) -> bool { + self.previous = self.position; + if self.pickup_delay > 0 && self.pickup_delay != u32::MAX { + self.pickup_delay -= 1; + } + let eye = world.block( + self.position.x.floor() as i32, + (self.position.y + 0.1).floor() as i32, + self.position.z.floor() as i32, + ); + let in_water = facts.get(eye).fluid == Fluid::Water; + if in_water { + // ItemEntity.setUnderwaterMovement + self.velocity = Vec3::new( + self.velocity.x * 0.99, + self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 }, + self.velocity.z * 0.99, + ); + } else { + self.velocity.y -= 0.04; + } + let horizontal = self.velocity.x * self.velocity.x + self.velocity.z * self.velocity.z; + if !self.on_ground || horizontal > 1.0e-5 || (self.age + self.id) % 4 == 0 { + let mut scene = SceneCollisions { world, binding: collision }; + let wanted = self.velocity; + let moved = scene + .resolve(self.bounds(), wanted, 0.0, self.on_ground) + .unwrap_or(Vec3::ZERO); + self.position = Vec3::new( + self.position.x + moved.x, + self.position.y + moved.y, + self.position.z + moved.z, + ); + self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + if moved.x != wanted.x { + self.velocity.x = 0.0; + } + if moved.z != wanted.z { + self.velocity.z = 0.0; + } + if moved.y != wanted.y { + self.velocity.y = 0.0; + } + let mut friction = 0.98; + if self.on_ground { + let below = world.block( + self.position.x.floor() as i32, + (self.position.y - 0.999_999).floor() as i32, + self.position.z.floor() as i32, + ); + friction = f64::from(facts.get(below).friction) * 0.98; + } + self.velocity = Vec3::new(self.velocity.x * friction, self.velocity.y * 0.98, self.velocity.z * friction); + if self.on_ground && self.velocity.y < 0.0 { + self.velocity.y *= -0.5; + } + } + self.age += 1; + self.age < 6000 && self.position.y > -128.0 + } +} diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl new file mode 100644 index 000000000..269c6a80c --- /dev/null +++ b/crates/horizon-client/src/entity.wgsl @@ -0,0 +1,52 @@ +// Entities, dropped items and particles: camera-relative vertices textured +// from the shared 2D atlas, lit through the same lightmap as terrain. +struct Globals { + view_proj: mat4x4, + fog_color: vec4, + fog: vec4, + sky_color: vec4, + misc: vec4, + inverse_view: mat4x4, + sunrise: vec4, + sun: vec4, +} +@group(0) @binding(0) var globals: Globals; +@group(0) @binding(1) var atlas: texture_2d; +@group(0) @binding(2) var atlas_sampler: sampler; +@group(0) @binding(3) var lightmap: texture_2d; +@group(0) @binding(4) var lightmap_sampler: sampler; +struct Out { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) color: vec4, + @location(2) spherical: f32, + @location(3) cylindrical: f32, +} +@vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4) -> Out { + var out: Out; + out.clip = globals.view_proj * vec4(position, 1.0); + out.uv = uv; + let l = vec2(f32(light.y), f32(light.x)); + let lm = textureSampleLevel(lightmap, lightmap_sampler, + clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); + var c = color * lm; + // Hurt overlay (OverlayTexture red tint). + if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); } + out.color = c; + out.spherical = length(position); + out.cylindrical = max(length(position.xz), abs(position.y)); + return out; +} +fn linear_fog(d: f32, start: f32, end: f32) -> f32 { + if d <= start { return 0.0; } + if d >= end { return 1.0; } + return (d - start) / (end - start); +} +@fragment fn fs_entity(in: Out) -> @location(0) vec4 { + let color = textureSample(atlas, atlas_sampler, in.uv) * in.color; + if color.a < 0.1 { discard; } + let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), + linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); + return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); +} diff --git a/crates/horizon-client/src/environment.rs b/crates/horizon-client/src/environment.rs new file mode 100644 index 000000000..c9275126a --- /dev/null +++ b/crates/horizon-client/src/environment.rs @@ -0,0 +1,263 @@ +//! Data-driven environment attributes sampled from the pinned timelines +//! (`KeyframeTrackSampler`, `EasingType`): sky/fog colours, sky light factor, +//! celestial angles and star brightness for the overworld day cycle. +use crate::Result; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +#[derive(Clone, Copy, Debug)] +enum Easing { + Linear, + Constant, + Bezier([f32; 4]), +} +impl Easing { + fn apply(self, x: f32) -> f32 { + match self { + Self::Linear => x, + Self::Constant => 0.0, + Self::Bezier([x1, y1, x2, y2]) => { + let curve = |c1: f32, c2: f32| (3.0 * c1 - 3.0 * c2 + 1.0, -6.0 * c1 + 3.0 * c2, 3.0 * c1); + let (ax, bx, cx) = curve(x1, x2); + let (ay, by, cy) = curve(y1, y2); + let sample = |(a, b, c): (f32, f32, f32), t: f32| ((a * t + b) * t + c) * t; + let gradient = |t: f32| (3.0 * ax * t + 2.0 * bx) * t + cx; + let mut t = x; + let mut solved = false; + for _ in 0..4 { + let error = sample((ax, bx, cx), t) - x; + if error.abs() < 1e-5 { + solved = true; + break; + } + let g = gradient(t); + if g < 1e-5 { + break; + } + t -= (error / g).clamp(-0.25, 0.25); + } + if !solved { + let (mut t0, mut t1) = (0.0f32, 1.0f32); + while t0 < t1 { + let error = sample((ax, bx, cx), t) - x; + if error.abs() < 1e-5 { + break; + } + if error < 0.0 { + t0 = t; + } else { + t1 = t; + } + let next = (t0 + t1) / 2.0; + if next == t { + break; + } + t = next; + } + } + sample((ay, by, cy), t) + } + } + } +} +#[derive(Clone, Debug)] +struct Track { + keyframes: Vec<(i64, [f32; 4])>, + easing: Easing, + multiply: bool, +} +fn parse_value(v: &Value) -> Option<[f32; 4]> { + match v { + Value::Number(n) => n.as_f64().map(|f| [f as f32, 0.0, 0.0, 0.0]), + Value::Bool(b) => Some([f32::from(u8::from(*b)), 0.0, 0.0, 0.0]), + Value::String(s) => { + let hex = s.trim_start_matches('#'); + let c = u32::from_str_radix(hex, 16).ok()?; + let f = |shift: u32| (c >> shift & 255) as f32 / 255.0; + Some(if hex.len() == 8 { + [f(16), f(8), f(0), f(24)] + } else { + [f(16), f(8), f(0), 1.0] + }) + } + _ => None, + } +} +impl Track { + fn sample(&self, ticks: i64, period: i64) -> [f32; 4] { + let k = &self.keyframes; + if k.len() == 1 { + return k[0].1; + } + let t = ticks.rem_euclid(period); + let (first, last) = (k[0], k[k.len() - 1]); + let mut segments = vec![(last.1, last.0 - period, first.1, first.0)]; + for pair in k.windows(2) { + segments.push((pair[0].1, pair[0].0, pair[1].1, pair[1].0)); + } + segments.push((last.1, last.0, first.1, first.0 + period)); + let segment = segments + .iter() + .find(|s| t < s.3) + .copied() + .unwrap_or(segments[segments.len() - 1]); + let (from, from_t, to, to_t) = segment; + if t <= from_t { + return from; + } + if t >= to_t { + return to; + } + let alpha = self.easing.apply((t - from_t) as f32 / (to_t - from_t) as f32); + std::array::from_fn(|i| from[i] + (to[i] - from[i]) * alpha) + } +} +pub struct Environment { + period: i64, + tracks: HashMap, + base: HashMap, +} +#[derive(Clone, Copy, Debug, Default)] +pub struct Sky { + pub sky_color: [f32; 3], + pub fog_color: [f32; 3], + pub sky_light_factor: f32, + pub sky_light_color: [f32; 3], + pub block_light_tint: [f32; 3], + pub ambient_light_color: [f32; 3], + pub sun_angle: f32, + pub moon_angle: f32, + pub star_angle: f32, + pub star_brightness: f32, + pub sunrise_color: [f32; 4], + pub cloud_color: [f32; 4], + /// `gameplay/sky_light_level`, the server-side sky darkening. + pub sky_light_level: f32, +} +impl Environment { + pub fn load(root: &Path) -> Result { + let timeline: Value = + serde_json::from_slice(&fs::read(root.join("data/minecraft/timeline/day.json"))?)?; + let dimension: Value = serde_json::from_slice(&fs::read( + root.join("data/minecraft/dimension_type/overworld.json"), + )?)?; + let mut tracks = HashMap::new(); + for (name, track) in timeline["tracks"].as_object().ok_or("invalid timeline")? { + let easing = match &track["ease"] { + Value::String(s) if s == "constant" => Easing::Constant, + Value::Object(o) => match o.get("cubic_bezier").and_then(Value::as_array) { + Some(a) if a.len() == 4 => Easing::Bezier(std::array::from_fn(|i| { + a[i].as_f64().unwrap_or(0.0) as f32 + })), + _ => Easing::Linear, + }, + _ => Easing::Linear, + }; + let keyframes: Vec<_> = track["keyframes"] + .as_array() + .into_iter() + .flatten() + .filter_map(|k| Some((k["ticks"].as_i64()?, parse_value(&k["value"])?))) + .collect(); + if keyframes.is_empty() { + continue; + } + tracks.insert( + name.clone(), + Track { + keyframes, + easing, + multiply: track["modifier"].as_str() == Some("multiply"), + }, + ); + } + let mut base: HashMap = [ + ("minecraft:visual/block_light_tint", "#ffd88c"), + ("minecraft:visual/sky_light_color", "#ffffff"), + ("minecraft:visual/ambient_light_color", "#000000"), + ] + .into_iter() + .filter_map(|(k, v)| Some((k.to_owned(), parse_value(&Value::String(v.into()))?))) + .collect(); + base.insert("minecraft:visual/sky_light_factor".into(), [1.0, 0.0, 0.0, 0.0]); + base.insert("minecraft:gameplay/sky_light_level".into(), [1.0, 0.0, 0.0, 0.0]); + for (k, v) in dimension["attributes"].as_object().into_iter().flatten() { + if let Some(v) = parse_value(v) { + base.insert(k.clone(), v); + } + } + Ok(Self { + period: timeline["period_ticks"].as_i64().unwrap_or(24000), + tracks, + base, + }) + } + fn value(&self, name: &str, base: [f32; 4], ticks: i64) -> [f32; 4] { + match self.tracks.get(name) { + Some(track) => { + let v = track.sample(ticks, self.period); + if track.multiply { + std::array::from_fn(|i| base[i] * v[i]) + } else { + v + } + } + None => base, + } + } + fn base(&self, name: &str) -> [f32; 4] { + self.base.get(name).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]) + } + /// Sky state for a time of day, with the biome's sky and fog colours as base values. + pub fn sample(&self, ticks: i64, biome_sky: u32, biome_fog: u32) -> Sky { + let rgb = |c: u32| { + [ + (c >> 16 & 255) as f32 / 255.0, + (c >> 8 & 255) as f32 / 255.0, + (c & 255) as f32 / 255.0, + 1.0, + ] + }; + let v = |name: &str, base: [f32; 4]| self.value(name, base, ticks); + let three = |a: [f32; 4]| [a[0], a[1], a[2]]; + let scalar = |name: &str| { + let b = self.base(name); + let b = if self.base.contains_key(name) { b } else { [1.0, 0.0, 0.0, 0.0] }; + let t = self.tracks.get(name); + match t { + Some(t) if t.multiply => b[0] * t.sample(ticks, self.period)[0], + Some(t) => t.sample(ticks, self.period)[0], + None => b[0], + } + }; + let angle = |name: &str| { + self.tracks + .get(name) + .map_or(0.0, |t| t.sample(ticks, self.period)[0]) + }; + Sky { + sky_color: three(v("minecraft:visual/sky_color", rgb(biome_sky))), + fog_color: three(v("minecraft:visual/fog_color", rgb(biome_fog))), + sky_light_factor: scalar("minecraft:visual/sky_light_factor"), + sky_light_color: three(v( + "minecraft:visual/sky_light_color", + self.base("minecraft:visual/sky_light_color"), + )), + block_light_tint: three(self.base("minecraft:visual/block_light_tint")), + ambient_light_color: three(self.base("minecraft:visual/ambient_light_color")), + sun_angle: angle("minecraft:visual/sun_angle"), + moon_angle: angle("minecraft:visual/moon_angle"), + star_angle: angle("minecraft:visual/star_angle"), + star_brightness: angle("minecraft:visual/star_brightness"), + sunrise_color: self + .tracks + .get("minecraft:visual/sunrise_sunset_color") + .map_or([0.0; 4], |t| t.sample(ticks, self.period)), + cloud_color: v( + "minecraft:visual/cloud_color", + self.base("minecraft:visual/cloud_color"), + ), + sky_light_level: scalar("minecraft:gameplay/sky_light_level"), + } + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs new file mode 100644 index 000000000..f4defd23d --- /dev/null +++ b/crates/horizon-client/src/game.rs @@ -0,0 +1,1999 @@ +//! The playable game loop: streaming world, player simulation at 20 ticks/s, +//! block interaction, inventory and HUD. +use horizon_client::{ + Result, + assets::Assets, + audio::Audio, + biome::Biomes, + blocks::{BlockFacts, Fluid}, + chunk::{HEIGHT, MIN_Y}, + clock::FixedStep, + entities::ItemEntity, + particles::Particle, + crafting::Recipes, + collisions, + environment::Environment, + gfx::{Frame, Renderer}, + hud::{HudAtlas, HudBatch, rgba}, + items::{ItemStack, Items}, + light::LightTables, + mesher::{MeshTables, Vertex}, + models, + motion::{MotionEvent, MotionResources, MotionWorld, PlayerMotion}, + sprint::Keys, + streaming::{Streaming, WorkerContext}, + save::{Level, Persistent, SaveDir}, + testgen::TestTerrain, + world::World, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_world::{block_collision::BlockCollisionRegistry, chunk::BlockState, registry::BlockStateId}; +use std::{ + collections::{HashMap, HashSet}, + path::PathBuf, + sync::Arc, + time::{Duration, Instant}, +}; +use winit::{ + application::ApplicationHandler, + event::{DeviceEvent, DeviceId, ElementState, MouseButton, MouseScrollDelta, WindowEvent}, + event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, + keyboard::{KeyCode, PhysicalKey}, + window::{CursorGrabMode, Window, WindowId}, +}; + +struct Options { + resources: PathBuf, + distance: i32, + seed: i64, + creative: bool, + test_terrain: bool, + frames: Option, + screenshot_after: Option, + timeout: Duration, + report: Option, + world: String, +} +impl Options { + fn read() -> Result> { + let sibling = std::env::current_exe()? + .parent() + .ok_or("missing executable directory")? + .join("resources"); + let mut o = Self { + resources: if sibling.join("horizon-resources.json").exists() { + sibling + } else { + PathBuf::from(".local/horizon-client/26.3") + }, + distance: 12, + seed: 0, + creative: false, + test_terrain: false, + frames: None, + screenshot_after: None, + timeout: Duration::from_secs(120), + report: None, + world: "New World".into(), + }; + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "--help" | "-h" => { + println!( + "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." + ); + return Ok(None); + } + "--creative" => o.creative = true, + "--test-terrain" => o.test_terrain = true, + _ => { + let value = args.next().ok_or_else(|| format!("missing value after {arg}"))?; + match arg.as_str() { + "--resources" => o.resources = value.into(), + "--render-distance" | "--radius" => { + o.distance = value.parse()?; + if !(2..=64).contains(&o.distance) { + return Err("render distance must be 2..64".into()); + } + } + "--seed" => { + o.seed = value.parse().unwrap_or_else(|_| { + // Text seeds hash like String.hashCode. + value + .encode_utf16() + .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c))) + .into() + }) + } + "--frames" => o.frames = Some(value.parse()?), + "--timeout-seconds" => o.timeout = Duration::from_secs(value.parse()?), + "--smoke-report" => o.report = Some(value.into()), + "--screenshot-after" => o.screenshot_after = Some(value.parse()?), + "--world" => o.world = value, + _ => return Err(format!("unknown option {arg}").into()), + } + } + } + } + Ok(Some(o)) + } +} +#[derive(Clone, Copy, PartialEq, Eq)] +enum Screen { + Playing, + Paused, + Inventory, + Dead, +} +#[derive(Clone)] +enum Icon { + Flat(String), + Cube { top: String, left: String, right: String, tint: u32 }, +} +struct Mining { + pos: [i32; 3], + progress: f32, + ticks: u32, +} +struct Hit { + pos: [i32; 3], + face: [i32; 3], + point: [f64; 3], +} +pub struct Resources { + assets: Arc, + facts: BlockFacts, + items: Items, + recipes: Recipes, + biomes: Arc, + environment: Environment, + atlas: HudAtlas, + icons: HashMap>, + layer_names: HashMap, +} +struct Game<'a> { + res: &'a mut Resources, + collision: &'a BlockCollisionRegistry<'a>, + motion: &'a MotionResources, + world: World, + streaming: Streaming, + options: Options, + player: Option, + spawn: Option, + clock: FixedStep, + previous_position: Vec3, + eye: f32, + previous_eye: f32, + yaw: f32, + pitch: f32, + inventory: Vec>, + selected: usize, + carried: Option, + craft_grid: Vec>, + craft_size: usize, + mining: Option, + destroy_delay: u32, + use_delay: u32, + creative: bool, + keys: HashSet, + left: bool, + right: bool, + cursor: (f32, f32), + captured: bool, + focused: bool, + debug: bool, + screen: Screen, + window: Option>, + renderer: Option, + started: Instant, + previous: Instant, + frames: u64, + fps: f32, + fps_frames: u64, + fps_at: Instant, + ticks: u64, + error: Option, + message: Option<(String, Instant)>, + save: Arc, + level: Level, + audio: Audio, + dropped: Vec, + next_entity: u32, + particles: Vec, +} +fn view_vector(yaw: f32, pitch: f32) -> [f64; 3] { + let (y, p) = (f64::from(yaw).to_radians(), f64::from(pitch).to_radians()); + [-y.sin() * p.cos(), -p.sin(), y.cos() * p.cos()] +} +impl Game<'_> { + fn eye_position(&self) -> Option<[f64; 3]> { + let p = self.player.as_ref()?; + Some([p.position.x, p.position.y + f64::from(p.dimensions.eye_height), p.position.z]) + } + fn reach(&self) -> f64 { + if self.creative { 5.0 } else { 4.5 } + } + /// Voxel traversal against non-air, non-fluid blocks (outline = full cube). + fn pick(&self) -> Option { + let origin = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach = self.reach(); + let mut pos = origin.map(|v| v.floor() as i32); + let step = dir.map(|d| if d > 0.0 { 1 } else { -1 }); + let delta = dir.map(|d| if d == 0.0 { f64::INFINITY } else { (1.0 / d).abs() }); + let mut t_max = [0.0; 3]; + for i in 0..3 { + let boundary = if dir[i] > 0.0 { f64::from(pos[i]) + 1.0 } else { f64::from(pos[i]) }; + t_max[i] = if dir[i] == 0.0 { f64::INFINITY } else { (boundary - origin[i]) / dir[i] }; + } + let mut face = [0; 3]; + let mut t = 0.0; + while t <= reach { + let state = self.world.block(pos[0], pos[1], pos[2]); + let f = self.res.facts.get(state); + if !self.res.facts.is_air(state) + && !(f.fluid != Fluid::None && !f.waterlogged && &*f.name != "minecraft:kelp" && f.render_shape != horizon_client::blocks::RenderShape::Model) + && !matches!(&*f.name, "minecraft:water" | "minecraft:lava" | "minecraft:bubble_column") + { + return Some(Hit { + pos, + face, + point: [origin[0] + dir[0] * t, origin[1] + dir[1] * t, origin[2] + dir[2] * t], + }); + } + let axis = if t_max[0] < t_max[1] { + if t_max[0] < t_max[2] { 0 } else { 2 } + } else if t_max[1] < t_max[2] { + 1 + } else { + 2 + }; + t = t_max[axis]; + t_max[axis] += delta[axis]; + pos[axis] += step[axis]; + face = [0; 3]; + face[axis] = -step[axis]; + } + None + } + fn held(&self) -> Option<&ItemStack> { + self.inventory[self.selected].as_ref() + } + /// Inventory.add: returns the stack that did not fit. + fn give(&mut self, mut stack: ItemStack) -> Option { + let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); + // Prefer the selected slot, then the hotbar, then the main inventory. + let order: Vec = std::iter::once(self.selected).chain((0..36).filter(|&i| i != self.selected)).collect(); + for &i in &order { + if let Some(slot) = &mut self.inventory[i] + && slot.item == stack.item + && slot.damage == stack.damage + && slot.count < max + { + let moved = (max - slot.count).min(stack.count); + slot.count += moved; + stack.count -= moved; + if stack.count == 0 { + return None; + } + } + } + for i in 0..36 { + if self.inventory[i].is_none() { + let moved = stack.count.min(max); + self.inventory[i] = Some(ItemStack { count: moved, ..stack.clone() }); + stack.count -= moved; + if stack.count == 0 { + return None; + } + } + } + Some(stack) + } + /// The block's particle texture (approximated by its first model face) and tint. + fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { + let models = self.res.assets.model_catalog.collect(state, horizon_core::position::BlockPos::new(0, 0, 0)).ok()?; + let face = models.iter().flat_map(|(_, m)| m.faces.iter()).find(|f| f.quad.facing == horizon_assets::model::Direction::Up) + .or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next())?; + let name = self.res.layer_names.get(&face.layer)?.clone(); + let tint = if face.quad.tint_index >= 0 { + let n = &self.res.facts.get(state).name; + if n.contains("leaves") || n.contains("vine") { 0x48B518 } else { 0x91BD59 } + } else { + 0xFFFFFF + }; + Some((name, tint)) + } + /// ParticleEngine.destroy: a 4x4x4 burst. + fn destroy_particles(&mut self, pos: [i32; 3], state: BlockStateId) { + let Some((sprite, tint)) = self.particle_sprite(state) else { return }; + for x in 0..4 { + for y in 0..4 { + for z in 0..4 { + let d = |i: i32| (f64::from(i) + 0.5) / 4.0; + let p = [f64::from(pos[0]) + d(x), f64::from(pos[1]) + d(y), f64::from(pos[2]) + d(z)]; + let v = [d(x) - 0.5, d(y) - 0.5, d(z) - 0.5]; + let particle = Particle::terrain(&mut self.world.random, p, v, sprite.clone(), tint); + self.particles.push(particle); + } + } + } + } + /// ParticleEngine.crack: one crumb on the face being mined. + fn crack_particle(&mut self, pos: [i32; 3], face: [i32; 3], state: BlockStateId) { + let Some((sprite, tint)) = self.particle_sprite(state) else { return }; + let r = &mut self.world.random; + let mut p = [0.0; 3]; + for i in 0..3 { + let base = f64::from(pos[i]); + p[i] = match face[i] { + 1 => base + 1.0 + 0.1, + -1 => base - 0.1, + _ => base + 0.1 + r.next_double() * 0.8, + }; + } + let mut particle = Particle::terrain(r, p, [0.0; 3], sprite, tint); + for c in &mut particle.velocity { + *c *= 0.2; + } + particle.velocity[1] = (particle.velocity[1] - 0.1) * 0.2 + 0.1; + particle.size *= 0.6; + self.particles.push(particle); + } + fn spawn_item(&mut self, stack: ItemStack, position: [f64; 3], velocity: [f64; 3], pickup_delay: u32) { + self.next_entity += 1; + let p = Vec3::new(position[0], position[1], position[2]); + let bob = self.world.random.next_float() * std::f32::consts::PI * 2.0; + self.dropped.push(ItemEntity { + id: self.next_entity, + stack, + position: p, + previous: p, + velocity: Vec3::new(velocity[0], velocity[1], velocity[2]), + on_ground: false, + age: 0, + pickup_delay, + bob_offset: bob, + }); + } + /// Block.popResource + fn pop_resource(&mut self, pos: [i32; 3], stack: ItemStack) { + let r = &mut self.world.random; + let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25; + let p = [ + f64::from(pos[0]) + 0.5 + offset(), + f64::from(pos[1]) + 0.5 + offset() - 0.125, + f64::from(pos[2]) + 0.5 + offset(), + ]; + let v = [r.next_double() * 0.2 - 0.1, 0.2, r.next_double() * 0.2 - 0.1]; + self.spawn_item(stack, p, v, 10); + } + /// Player.drop: thrown from the eyes along the view direction. + fn drop_held(&mut self, all: bool) { + let Some(eye) = self.eye_position() else { return }; + let Some(stack) = self.inventory[self.selected].as_mut() else { return }; + let count = if all { stack.count } else { 1 }; + let thrown = ItemStack { count, ..stack.clone() }; + stack.count -= count; + if stack.count == 0 { + self.inventory[self.selected] = None; + } + let (yaw, pitch) = (f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians()); + let r = &mut self.world.random; + let spread = f64::from(r.next_float()) * std::f64::consts::TAU; + let strength = 0.02 * f64::from(r.next_float()); + let v = [ + -yaw.sin() * pitch.cos() * 0.3 + spread.cos() * strength, + -pitch.sin() * 0.3 + 0.1 + f64::from(r.next_float() - r.next_float()) * 0.1, + yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength, + ]; + self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40); + } + fn tick_items(&mut self) { + let mut items = std::mem::take(&mut self.dropped); + items.retain_mut(|item| item.tick(&self.world, &self.res.facts, self.collision)); + let Some(p) = self.player.as_ref() else { + self.dropped = items; + return; + }; + if p.health.dead_or_dying() { + self.dropped = items; + return; + } + let w = f64::from(p.dimensions.width) / 2.0; + let (min, max) = ( + [p.position.x - w - 1.0, p.position.y - 0.5, p.position.z - w - 1.0], + [p.position.x + w + 1.0, p.position.y + f64::from(p.dimensions.height) + 0.5, p.position.z + w + 1.0], + ); + let feet = [p.position.x, p.position.y, p.position.z]; + let mut kept = Vec::with_capacity(items.len()); + for mut item in items { + let b = item.bounds(); + let touching = b.min_position().x < max[0] && b.max_position().x > min[0] + && b.min_position().y < max[1] && b.max_position().y > min[1] + && b.min_position().z < max[2] && b.max_position().z > min[2]; + if touching && item.pickup_delay == 0 { + let before = item.stack.count; + match self.give(item.stack.clone()) { + None => { + let pitch = ((self.world.random.next_float() - self.world.random.next_float()) * 0.7 + 1.0) * 2.0; + self.audio.play("minecraft:entity.item.pickup", Some(feet), 0.2, pitch); + continue; + } + Some(rest) => { + if rest.count < before { + self.audio.play("minecraft:entity.item.pickup", Some(feet), 0.2, 1.0); + } + item.stack = rest; + } + } + } + kept.push(item); + } + self.dropped = kept; + } + fn break_block(&mut self, pos: [i32; 3]) -> Result<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + let facts = self.res.facts.get(state).clone(); + if !self.creative { + let held = self.held().cloned(); + let harvest = !facts.requires_tool + || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + if harvest { + let drops = self.res.items.block_drops( + &self.res.assets.registry, + state, + held.as_ref(), + &mut self.world.random, + ); + for d in drops { + if &*d.item != "minecraft:air" { + self.pop_resource(pos, d); + } + } + } + // Tools lose durability on blocks with nonzero hardness. + if facts.hardness > 0.0 + && let Some(stack) = self.inventory[self.selected].as_mut() + && let Some(info) = self.res.items.get(&stack.item) + && info.max_damage > 0 + && !info.tool.is_empty() + { + stack.damage += 1; + if stack.damage >= info.max_damage { + self.inventory[self.selected] = None; + } + } + } + let replacement = if facts.waterlogged { + self.res.assets.registry.default_state("minecraft:water") + } else { + None + } + .unwrap_or(self.world.air); + self.world.set(pos[0], pos[1], pos[2], replacement)?; + self.destroy_particles(pos, state); + let center = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(&facts.sounds.break_sound, Some(center), (facts.sounds.volume + 1.0) / 2.0, facts.sounds.pitch * 0.8); + // Two-block plants and doors break their other half. + if let Some(props) = self.res.assets.registry.state(state).map(|s| s.properties.clone()) + && let Some(half) = props.get("half") + { + let other = match half.as_str() { + "upper" => Some(pos[1] - 1), + "lower" => Some(pos[1] + 1), + _ => None, + }; + if let Some(y) = other { + let o = self.world.block(pos[0], y, pos[2]); + if self.res.facts.get(o).name == facts.name { + self.world.set(pos[0], y, pos[2], self.world.air)?; + } + } + } + // Unsupported plants above fall (snow, flowers, grass): simple support rule. + let above = self.world.block(pos[0], pos[1] + 1, pos[2]); + let af = self.res.facts.get(above); + if !self.res.facts.is_air(above) && af.hardness == 0.0 && !af.full_collision && af.fluid == Fluid::None { + self.break_block([pos[0], pos[1] + 1, pos[2]])?; + } + Ok(()) + } + /// `BlockItem.getPlacementState` for the common placement properties. + fn placement_state(&self, block: BlockStateId, hit: &Hit) -> BlockStateId { + let registry = &self.res.assets.registry; + let Some(state) = registry.state(block) else { return block }; + let mut s = state.clone(); + let yaw = self.yaw.rem_euclid(360.0); + let facing = match ((yaw + 45.0) / 90.0) as i32 % 4 { + 0 => "south", + 1 => "west", + 2 => "north", + _ => "east", + }; + let opposite = |d: &str| match d { + "north" => "south", + "south" => "north", + "east" => "west", + "west" => "east", + "up" => "down", + _ => "up", + }; + let clicked = match hit.face { + [0, 1, 0] => "up", + [0, -1, 0] => "down", + [0, 0, -1] => "north", + [0, 0, 1] => "south", + [-1, 0, 0] => "west", + _ => "east", + }; + let frac_y = hit.point[1] - hit.point[1].floor(); + let top_half = hit.face == [0, -1, 0] || (hit.face[1] == 0 && frac_y > 0.5); + let name = s.name.clone(); + let props = &mut s.properties; + if props.contains_key("axis") { + let axis = match hit.face { + [_, 0, 0] if hit.face[0] != 0 => "x", + [0, _, 0] if hit.face[1] != 0 => "y", + _ => "z", + }; + if props.get("axis").is_some() { + props.insert("axis".into(), axis.into()); + } + } + if let Some(f) = props.get("facing").cloned() { + let wants = if name.ends_with("_stairs") || name.contains("fence_gate") || name.ends_with("_door") || name.ends_with("_trapdoor") { + facing.to_owned() + } else if name.ends_with("torch") || name.ends_with("ladder") || name.contains("wall_") { + clicked.to_owned() + } else if name.contains("piston") || name.contains("observer") || name.contains("dispenser") || name.contains("dropper") || name.ends_with("rod") || name.contains("amethyst") { + clicked.to_owned() + } else { + opposite(facing).to_owned() + }; + props.insert("facing".into(), wants); + let mut probe = BlockState { name: name.clone(), properties: props.clone() }; + if registry.resolve(&probe).is_err() { + probe.properties.insert("facing".into(), f); + *props = probe.properties; + } + } + if name.ends_with("_slab") { + props.insert("type".into(), if top_half { "top" } else { "bottom" }.into()); + } + if (name.ends_with("_stairs") || name.ends_with("_trapdoor")) && props.contains_key("half") { + props.insert("half".into(), if top_half { "top" } else { "bottom" }.into()); + } + // Torches on walls become wall torches. + if name.ends_with("torch") && hit.face[1] == 0 { + let wall = name.replace("torch", "wall_torch"); + if let Some(wall_state) = registry.default_state(&wall) + && let Some(ws) = registry.state(wall_state) + { + let mut w = ws.clone(); + w.properties.insert("facing".into(), clicked.into()); + if let Ok(id) = registry.resolve(&w) { + return id; + } + } + } + if let Some(w) = props.get_mut("waterlogged") { + let target = [hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2]]; + let existing = self.world.block(target[0], target[1], target[2]); + let f = self.res.facts.get(existing); + *w = (f.fluid == Fluid::Water && f.fluid_level == 8 && !f.fluid_falling).to_string(); + } + registry.resolve(&s).unwrap_or(block) + } + fn use_item(&mut self) -> Result<()> { + let sneaking = self.keys.contains(&KeyCode::ShiftLeft); + if !sneaking + && let Some(hit) = self.pick() + { + let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if &*self.res.facts.get(clicked).name == "minecraft:crafting_table" { + self.craft_size = 3; + self.screen = Screen::Inventory; + self.capture(false); + self.right = false; + return Ok(()); + } + } + let Some(stack) = self.held().cloned() else { return Ok(()) }; + let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()) }; + if let Some((nutrition, saturation)) = info.food + && let Some(p) = self.player.as_mut() + && (p.health.food.food < 20 || self.creative) + { + let food = &mut p.health.food; + food.food = (food.food + nutrition as i32).min(20); + food.saturation = (food.saturation + saturation).min(food.food as f32); + self.consume_held(); + return Ok(()); + } + let Some(hit) = self.pick() else { return Ok(()) }; + let Some(block) = info.block else { return Ok(()) }; + let clicked_state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let target = if self.res.facts.get(clicked_state).replaceable { + hit.pos + } else { + [hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2]] + }; + if target[1] < MIN_Y || target[1] >= MIN_Y + HEIGHT || !self.world.loaded(target[0], target[2]) { + return Ok(()); + } + let existing = self.world.block(target[0], target[1], target[2]); + if !self.res.facts.get(existing).replaceable { + return Ok(()); + } + let state = self.placement_state(block, &hit); + // Do not place collidable blocks inside the player. + if self.res.facts.get(state).full_collision + && let Some(p) = &self.player + { + let w = f64::from(p.dimensions.width) / 2.0; + let (min, max) = ( + [p.position.x - w, p.position.y, p.position.z - w], + [p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w], + ); + let overlaps = (0..3).all(|i| { + f64::from(target[i]) < max[i] - 1e-7 && f64::from(target[i]) + 1.0 > min[i] + 1e-7 + }); + if overlaps { + return Ok(()); + } + } + self.world.set(target[0], target[1], target[2], state)?; + let sounds = self.res.facts.get(state).sounds.clone(); + let center = [f64::from(target[0]) + 0.5, f64::from(target[1]) + 0.5, f64::from(target[2]) + 0.5]; + self.audio.play(&sounds.place, Some(center), (sounds.volume + 1.0) / 2.0, sounds.pitch * 0.8); + // Two-block items place their upper half. + if let Some(s) = self.res.assets.registry.state(state) + && s.properties.get("half").map(String::as_str) == Some("lower") + { + let mut upper = s.clone(); + upper.properties.insert("half".into(), "upper".into()); + if let Ok(u) = self.res.assets.registry.resolve(&upper) + && self.res.facts.get(self.world.block(target[0], target[1] + 1, target[2])).replaceable + { + self.world.set(target[0], target[1] + 1, target[2], u)?; + } + } + self.consume_held(); + Ok(()) + } + fn consume_held(&mut self) { + if self.creative { + return; + } + if let Some(s) = self.inventory[self.selected].as_mut() { + s.count -= 1; + if s.count == 0 { + self.inventory[self.selected] = None; + } + } + } + fn tick_mining(&mut self) -> Result<()> { + if self.destroy_delay > 0 { + self.destroy_delay -= 1; + } + if !self.left || self.screen != Screen::Playing { + self.mining = None; + return Ok(()); + } + let Some(hit) = self.pick() else { + self.mining = None; + return Ok(()); + }; + if self.creative { + if self.destroy_delay == 0 { + self.break_block(hit.pos)?; + self.destroy_delay = 5; + } + return Ok(()); + } + if self.destroy_delay > 0 { + return Ok(()); + } + if self.mining.as_ref().is_none_or(|m| m.pos != hit.pos) { + self.mining = Some(Mining { pos: hit.pos, progress: 0.0, ticks: 0 }); + } + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let facts = self.res.facts.get(state); + if facts.hardness < 0.0 { + return Ok(()); + } + // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. + let held = self.held(); + let mut speed = self.res.items.mining_speed(held, &facts.name); + let player = self.player.as_ref().ok_or("no player")?; + if !player.ground.on_ground { + speed /= 5.0; + } + let eye = self.eye_position().unwrap_or_default(); + if self.res.facts.get(self.world.block(eye[0].floor() as i32, eye[1].floor() as i32, eye[2].floor() as i32)).fluid == Fluid::Water { + speed /= 5.0; + } + let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); + let progress = if facts.hardness == 0.0 { + 1.0 + } else { + speed / facts.hardness / if harvest { 30.0 } else { 100.0 } + }; + let hit_sound = facts.sounds.clone(); + let m = self.mining.as_mut().ok_or("mining")?; + m.progress += progress; + m.ticks += 1; + let crack = (m.pos, hit.face); + if m.ticks % 4 == 1 { + let c = [f64::from(m.pos[0]) + 0.5, f64::from(m.pos[1]) + 0.5, f64::from(m.pos[2]) + 0.5]; + self.audio.play(&hit_sound.hit, Some(c), (hit_sound.volume + 1.0) / 8.0, hit_sound.pitch * 0.5); + } + self.crack_particle(crack.0, crack.1, state); + let m = self.mining.as_mut().ok_or("mining")?; + if m.progress >= 1.0 { + let pos = m.pos; + self.mining = None; + self.break_block(pos)?; + self.destroy_delay = 5; + } + Ok(()) + } + fn spawn_player(&mut self) -> Result<()> { + if self.player.is_some() { + return Ok(()); + } + let (sx, sz) = (0, 0); + if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(dx, dz))) { + return Ok(()); + } + let saved = self.level.position.take().map(|p| Vec3::new(p[0], p[1], p[2])); + if saved.is_some() && self.spawn.is_none() { + self.spawn = self.level.spawn.map(|s| Vec3::new(s[0] + 0.5, s[1], s[2] + 0.5)); + } + let feet = match saved.or(self.spawn) { + Some(s) => s, + None => { + let mut y = MIN_Y + HEIGHT - 1; + while y > MIN_Y { + let s = self.world.block(sx, y, sz); + let f = self.res.facts.get(s); + if !self.res.facts.is_air(s) && (f.full_collision || f.fluid != Fluid::None) { + break; + } + y -= 1; + } + let spawn = Vec3::new(f64::from(sx) + 0.5, f64::from(y + 1), f64::from(sz) + 0.5); + self.spawn = Some(spawn); + spawn + } + }; + let mut player = PlayerMotion::new(self.motion, feet)?; + player.yaw = self.yaw; + if self.level.health > 0.0 && self.ticks < 2 { + player.set_health(self.level.health, false)?; + player.health.food.food = self.level.food; + player.health.food.saturation = self.level.saturation; + } + self.previous_position = feet; + self.player = Some(player); + self.eye = 1.62; + self.previous_eye = 1.62; + self.clock.reset(); + Ok(()) + } + fn tick(&mut self) -> Result<()> { + self.ticks += 1; + self.world.game_time += 1; + if self.ticks % 6000 == 0 { + self.save_game()?; + } + self.world.day_time += 1; + if self.use_delay > 0 { + self.use_delay -= 1; + } + let Some(player) = self.player.as_mut() else { return Ok(()) }; + // Hold position until the surrounding terrain exists. + let (cx, cz) = ((player.position.x.floor() as i32) >> 4, (player.position.z.floor() as i32) >> 4); + if !self.streaming.is_lit(cx, cz) { + return Ok(()); + } + let playing = self.screen == Screen::Playing; + let held = |k| playing && self.keys.contains(&k); + let keys = Keys { + forward: held(KeyCode::KeyW), + backward: held(KeyCode::KeyS), + left: held(KeyCode::KeyA), + right: held(KeyCode::KeyD), + jump: held(KeyCode::Space), + shift: held(KeyCode::ShiftLeft), + sprint: held(KeyCode::ControlLeft), + }; + self.previous_position = player.position; + player.yaw = self.yaw; + MotionWorld { + player, + scene: &mut self.world, + assets: &self.res.assets, + collision_binding: self.collision, + resources: self.motion, + } + .controlled_simulation_tick(keys)?; + let events = std::mem::take(&mut player.events); + let feet = [player.position.x, player.position.y, player.position.z]; + self.previous_eye = self.eye; + self.eye += (player.dimensions.eye_height - self.eye) * 0.5; + let crouching = player.pose == horizon_client::pose::Pose::Crouching; + for event in events { + match event { + MotionEvent::Emission { position, state, .. } if !crouching => { + // Entity.playStepSound: the block's step sound at 0.15 volume. + let sounds = self.res.facts.get(state).sounds.clone(); + self.audio.play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); + let _ = position; + } + MotionEvent::Fall(horizon_client::landing::FallEvent::Sound { sound, volume, pitch, .. }) => { + let name = match sound { + horizon_client::landing::SceneSound::BigFall => "minecraft:entity.player.big_fall", + horizon_client::landing::SceneSound::SmallFall => "minecraft:entity.player.small_fall", + _ => continue, + }; + self.audio.play(name, Some(feet), volume, pitch); + } + MotionEvent::Fall(horizon_client::landing::FallEvent::Damage { .. }) => { + self.audio.play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0); + } + _ => {} + } + } + let Some(player) = self.player.as_mut() else { return Ok(()) }; + if player.position.y < f64::from(MIN_Y - 64) { + // Out of the world. + let _ = player.set_health(0.0, false); + } + if player.health.dead_or_dying() && self.screen != Screen::Dead { + self.screen = Screen::Dead; + self.capture(false); + } + self.tick_mining()?; + self.tick_items(); + let facts = &self.res.facts; + let world = &self.world; + self.particles.retain_mut(|p| p.tick(world, |id| facts.states[id as usize].full_collision)); + if self.particles.len() > 4000 { + let excess = self.particles.len() - 4000; + self.particles.drain(..excess); + } + if self.right && self.use_delay == 0 && self.screen == Screen::Playing { + self.use_item()?; + self.use_delay = 4; + } + Ok(()) + } + fn capture(&mut self, capture: bool) { + let Some(window) = &self.window else { return }; + if capture { + self.captured = window + .set_cursor_grab(CursorGrabMode::Locked) + .or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined)) + .is_ok(); + } else { + let _ = window.set_cursor_grab(CursorGrabMode::None); + self.captured = false; + } + window.set_cursor_visible(!self.captured); + } + fn icon(&mut self, item: &str) -> Option { + if let Some(icon) = self.res.icons.get(item) { + return icon.clone(); + } + let icon = self.resolve_icon(item); + self.res.icons.insert(item.to_owned(), icon.clone()); + icon + } + fn resolve_icon(&self, item: &str) -> Option { + let root = &self.options.resources; + let name = item.trim_start_matches("minecraft:"); + let info = self.res.items.get(item); + let model_name = info.map_or(name.to_owned(), |i| i.model.trim_start_matches("minecraft:").to_owned()); + let def: serde_json::Value = serde_json::from_slice( + &std::fs::read(root.join(format!("assets/minecraft/items/{model_name}.json"))).ok()?, + ) + .ok()?; + // Find the first plain model reference in the item model definition. + fn first_model(v: &serde_json::Value) -> Option { + match v { + serde_json::Value::Object(o) => { + if o.get("type").and_then(|t| t.as_str()) == Some("minecraft:model") { + return o.get("model").and_then(|m| m.as_str()).map(str::to_owned); + } + for key in ["model", "fallback", "on_false", "on_true", "cases", "entries", "tints"] { + if let Some(m) = o.get(key).and_then(first_model) { + return Some(m); + } + } + o.values().find_map(first_model) + } + serde_json::Value::Array(a) => a.iter().find_map(first_model), + _ => None, + } + } + let model = first_model(&def["model"])?; + let path = model.trim_start_matches("minecraft:").to_owned(); + let mut current = path.clone(); + let mut textures = serde_json::Map::new(); + for _ in 0..16 { + let text = std::fs::read(root.join(format!("assets/minecraft/models/{current}.json"))).ok()?; + let m: serde_json::Value = serde_json::from_slice(&text).ok()?; + if let Some(t) = m["textures"].as_object() { + for (k, v) in t { + textures.entry(k.clone()).or_insert(v.clone()); + } + } + match m["parent"].as_str() { + Some(p) if p.ends_with("item/generated") || p.ends_with("item/handheld") || p.contains("handheld") => { + let layer = textures.get("layer0")?.as_str()?; + return Some(Icon::Flat(layer.trim_start_matches("minecraft:").to_owned())); + } + Some(p) => current = p.trim_start_matches("minecraft:").to_owned(), + None => break, + } + } + if path.starts_with("block/") { + let block = self.res.assets.registry.default_state(&format!("minecraft:{name}")) + .or_else(|| info.and_then(|i| i.block))?; + let models = self.res.assets.model_catalog.collect(block, horizon_core::position::BlockPos::new(0, 0, 0)).ok()?; + let mut faces: HashMap = HashMap::new(); + for (_, m) in &models { + for f in &m.faces { + faces.entry(f.quad.facing as usize).or_insert((f.layer, f.quad.tint_index)); + } + } + use horizon_assets::model::Direction as D; + let get = |d: D| faces.get(&(d as usize)).and_then(|(l, _)| self.res.layer_names.get(l)).cloned(); + let top = get(D::Up)?; + let tinted = faces.get(&(D::Up as usize)).is_some_and(|(_, t)| *t >= 0); + let tint = if tinted { + if name.contains("leaves") || name == "vine" { 0x48B518 } else { 0x91BD59 } + } else { + 0xFFFFFF + }; + return Some(Icon::Cube { + left: get(D::South).unwrap_or(top.clone()), + right: get(D::East).unwrap_or(top.clone()), + top, + tint, + }); + } + textures + .get("layer0") + .or_else(|| textures.get("all")) + .or_else(|| textures.get("texture")) + .and_then(|t| t.as_str()) + .map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned())) + } + fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { + let icon = self.icon(&stack.item); + let atlas = &self.res.atlas; + match icon { + Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX), + Some(Icon::Cube { top, left, right, tint }) => { + let color = |b: f32| { + let c = |s: u32| (((tint >> s) & 255) as f32 * b) as u8; + rgba(c(16), c(8), c(0), 255) + }; + let (cx, top_y) = (x + 8.0, y + 1.0); + let quad = |batch: &mut HudBatch, name: &str, p: [[f32; 2]; 4], c: u32| { + if let Some(r) = atlas.sprites.get(name).copied() { + batch.quad(p, [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]], c); + } + }; + let (w, h) = (7.0, 3.6); + quad(batch, &top, [[cx, top_y], [cx + w, top_y + h], [cx, top_y + 2.0 * h], [cx - w, top_y + h]], color(1.0)); + let side = 8.0; + quad(batch, &left, [[cx - w, top_y + h], [cx, top_y + 2.0 * h], [cx, top_y + 2.0 * h + side], [cx - w, top_y + h + side]], color(0.8)); + quad(batch, &right, [[cx, top_y + 2.0 * h], [cx + w, top_y + h], [cx + w, top_y + h + side], [cx, top_y + 2.0 * h + side]], color(0.6)); + } + None => batch.fill(atlas, x + 2.0, y + 2.0, 12.0, 12.0, rgba(200, 0, 200, 255)), + } + if stack.count > 1 { + let text = stack.count.to_string(); + let w = HudBatch::text_width(atlas, &text); + batch.text(atlas, &text, x + 17.0 - w, y + 9.0, u32::MAX, true); + } + if let Some(info) = self.res.items.get(&stack.item) + && info.max_damage > 0 + && stack.damage > 0 + { + let f = 1.0 - stack.damage as f32 / info.max_damage as f32; + let width = (13.0 * f).round(); + let hue = f / 3.0; + let (r, g) = ((255.0 * (1.0 - hue * 3.0).clamp(0.0, 1.0)) as u8, (255.0 * (hue * 3.0).clamp(0.0, 1.0)) as u8); + batch.fill(atlas, x + 2.0, y + 13.0, 13.0, 2.0, rgba(0, 0, 0, 255)); + batch.fill(atlas, x + 2.0, y + 13.0, width, 1.0, rgba(r, g, 0, 255)); + } + } + fn hud(&mut self, size: [u32; 2]) -> HudBatch { + let mut batch = HudBatch::new(size); + let (w, h) = (batch.width, batch.height); + let atlas_ptr: *const HudAtlas = &self.res.atlas; + let _ = atlas_ptr; + if self.player.is_none() { + let text = "Loading terrain..."; + let atlas = &self.res.atlas; + let tw = HudBatch::text_width(atlas, text); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); + batch.text(atlas, text, (w - tw) / 2.0, h / 2.0 - 4.0, u32::MAX, true); + return batch; + } + { + let atlas = &self.res.atlas; + // Crosshair. + batch.sprite(atlas, "gui/sprites/hud/crosshair", (w - 15.0) / 2.0, (h - 15.0) / 2.0); + // Hotbar. + batch.sprite(atlas, "gui/sprites/hud/hotbar", w / 2.0 - 91.0, h - 22.0); + batch.sprite(atlas, "gui/sprites/hud/hotbar_selection", w / 2.0 - 91.0 - 1.0 + self.selected as f32 * 20.0, h - 23.0); + } + for i in 0..9 { + if let Some(stack) = self.inventory[i].clone() { + self.draw_item(&mut batch, &stack, w / 2.0 - 90.0 + i as f32 * 20.0 + 2.0, h - 19.0); + } + } + let atlas = &self.res.atlas; + if !self.creative + && let Some(p) = &self.player + { + // Experience bar and hearts/food (Gui.renderPlayerHealth). + batch.sprite(atlas, "gui/sprites/hud/experience_bar_background", w / 2.0 - 91.0, h - 29.0); + let health = p.health.health().ceil() as i32; + let top = h - 39.0; + for i in 0..10 { + let x = w / 2.0 - 91.0 + i as f32 * 8.0; + let y = if health <= 4 { top + ((self.ticks + i as u64 * 7) % 3) as f32 - 1.0 } else { top }; + batch.sprite(atlas, "gui/sprites/hud/heart/container", x, y); + let v = health - i * 2; + if v >= 2 { + batch.sprite(atlas, "gui/sprites/hud/heart/full", x, y); + } else if v == 1 { + batch.sprite(atlas, "gui/sprites/hud/heart/half", x, y); + } + } + let food = p.health.food.food; + for i in 0..10 { + let x = w / 2.0 + 91.0 - i as f32 * 8.0 - 9.0; + batch.sprite(atlas, "gui/sprites/hud/food_empty", x, top); + let v = food - i * 2; + if v >= 2 { + batch.sprite(atlas, "gui/sprites/hud/food_full", x, top); + } else if v == 1 { + batch.sprite(atlas, "gui/sprites/hud/food_half", x, top); + } + } + } + if self.debug { + let p = self.player.as_ref().map(|p| p.position).unwrap_or(Vec3::ZERO); + let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + let biome = self + .world + .chunks + .get(&(block[0] >> 4, block[2] >> 4)) + .map(|c| self.res.biomes.get(c.biome(block[0], block[1], block[2])).name.clone()) + .unwrap_or_default(); + let light = self.world.light(block[0], block[1], block[2]); + let facing = match ((self.yaw.rem_euclid(360.0) + 45.0) / 90.0) as i32 % 4 { + 0 => "south (Towards positive Z)", + 1 => "west (Towards negative X)", + 2 => "north (Towards negative Z)", + _ => "east (Towards positive X)", + }; + let lines = [ + format!("Horizon 26.3 (Rust) {:.0} fps", self.fps), + format!("C: {} chunks, {} sections drawn / {}", self.world.chunks.len(), self.renderer.as_ref().map_or(0, |r| r.drawn_sections), self.renderer.as_ref().map_or(0, |r| r.section_count())), + format!("Pending jobs: {}", self.streaming.pending()), + String::new(), + format!("XYZ: {:.3} / {:.5} / {:.3}", p.x, p.y, p.z), + format!("Block: {} {} {}", block[0], block[1], block[2]), + format!("Chunk: {} {} {} in {} {} {}", block[0] & 15, block[1] & 15, block[2] & 15, block[0] >> 4, block[1] >> 4, block[2] >> 4), + format!("Facing: {facing} ({:.1} / {:.1})", self.yaw.rem_euclid(360.0) - if self.yaw.rem_euclid(360.0) > 180.0 { 360.0 } else { 0.0 }, self.pitch), + format!("Light: {} (sky {}, block {})", (light >> 4).max(light & 15), light >> 4, light & 15), + format!("Biome: {biome}"), + format!("Day {} time {}", self.world.day_time / 24000, self.world.day_time % 24000), + ]; + for (i, line) in lines.iter().enumerate() { + if line.is_empty() { + continue; + } + let tw = HudBatch::text_width(atlas, line); + batch.fill(atlas, 1.0, 2.0 + i as f32 * 9.0 - 1.0, tw + 2.0, 9.0, rgba(80, 80, 80, 144)); + batch.text(atlas, line, 2.0, 2.0 + i as f32 * 9.0, rgba(224, 224, 224, 255), false); + } + } + if let Some((text, at)) = &self.message + && at.elapsed() < Duration::from_secs(3) + { + let tw = HudBatch::text_width(atlas, text); + batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true); + } + match self.screen { + Screen::Paused => { + batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); + let title = "Game Menu"; + let tw = HudBatch::text_width(atlas, title); + batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); + for (i, label) in ["Back to Game", "Save and Quit to Title"].iter().enumerate() { + let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 24.0 + i as f32 * 24.0 + 16.0); + let hover = self.cursor.0 >= bx && self.cursor.0 < bx + 200.0 && self.cursor.1 >= by && self.cursor.1 < by + 20.0; + let sprite = if hover { "gui/sprites/widget/button_highlighted" } else { "gui/sprites/widget/button" }; + batch.sprite_scaled(atlas, sprite, bx, by, 200.0, 20.0, u32::MAX); + let tw = HudBatch::text_width(atlas, label); + batch.text(atlas, label, bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true); + } + } + Screen::Dead => { + batch.fill(atlas, 0.0, 0.0, w, h, rgba(80, 0, 0, 120)); + let title = "You Died!"; + let tw = HudBatch::text_width(atlas, title); + batch.text(atlas, title, (w - tw) / 2.0, 60.0, u32::MAX, true); + let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 72.0); + batch.sprite_scaled(atlas, "gui/sprites/widget/button", bx, by, 200.0, 20.0, u32::MAX); + let label = "Respawn"; + let tw = HudBatch::text_width(atlas, label); + batch.text(atlas, label, bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true); + } + Screen::Inventory => { + self.draw_inventory(&mut batch); + } + Screen::Playing => {} + } + batch + } + fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { + ((batch.width - 176.0) / 2.0, (batch.height - 166.0) / 2.0) + } + /// Slot ids: 0..36 player inventory, 100..109 crafting grid, 200 result. + fn slots(&self) -> Vec { + let mut v: Vec = (0..36).collect(); + v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); + v.push(200); + v + } + /// InventoryMenu / CraftingMenu slot layouts. + fn slot_position(&self, i: usize) -> (f32, f32) { + let table = self.craft_size == 3; + match i { + 0..9 => (8.0 + i as f32 * 18.0, 142.0), + 9..36 => (8.0 + ((i - 9) % 9) as f32 * 18.0, 84.0 + ((i - 9) / 9) as f32 * 18.0), + 200 => if table { (124.0, 35.0) } else { (154.0, 28.0) }, + _ => { + let g = i - 100; + let (r, c) = (g / self.craft_size, g % self.craft_size); + if table { + (30.0 + c as f32 * 18.0, 17.0 + r as f32 * 18.0) + } else { + (98.0 + c as f32 * 18.0, 18.0 + r as f32 * 18.0) + } + } + } + } + fn slot_at(&self, batch: &HudBatch, x: f32, y: f32) -> Option { + let (ox, oy) = self.inventory_origin(batch); + self.slots().into_iter().find(|&i| { + let (sx, sy) = self.slot_position(i); + x >= ox + sx && x < ox + sx + 16.0 && y >= oy + sy && y < oy + sy + 16.0 + }) + } + fn slot_mut(&mut self, i: usize) -> &mut Option { + if i >= 100 && i < 109 { + &mut self.craft_grid[i - 100] + } else { + &mut self.inventory[i] + } + } + fn craft_result(&self) -> Option { + let n = self.craft_size; + let grid: Vec> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect(); + self.res.recipes.craft(&grid, n) + } + fn draw_inventory(&mut self, batch: &mut HudBatch) { + let (ox, oy) = self.inventory_origin(batch); + { + let atlas = &self.res.atlas; + batch.fill(atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160)); + let texture = if self.craft_size == 3 { "gui/container/crafting_table" } else { "gui/container/inventory" }; + if let Some(r) = atlas.sprites.get(texture).copied() { + // Container textures are 256x256 with the screen in the top-left 176x166. + let mut r = r; + r.u1 = r.u0 + (r.u1 - r.u0) * 176.0 / r.w as f32; + r.v1 = r.v0 + (r.v1 - r.v0) * 166.0 / r.h as f32; + batch.rect_uv(ox, oy, 176.0, 166.0, r, u32::MAX); + } + let (title, tx) = if self.craft_size == 3 { ("Crafting", 29.0) } else { ("Crafting", 97.0) }; + batch.text(atlas, title, ox + tx, oy + if self.craft_size == 3 { 6.0 } else { 8.0 }, rgba(64, 64, 64, 255), false); + batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, rgba(64, 64, 64, 255), false); + } + for i in self.slots() { + let (sx, sy) = self.slot_position(i); + let stack = if i == 200 { self.craft_result() } else { self.slot_mut(i).clone() }; + if let Some(stack) = stack { + self.draw_item(batch, &stack, ox + sx, oy + sy); + } + } + if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { + let (sx, sy) = self.slot_position(slot); + batch.fill(&self.res.atlas, ox + sx, oy + sy, 16.0, 16.0, rgba(255, 255, 255, 128)); + } + if let Some(stack) = self.carried.clone() { + self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0); + } + } + fn close_container(&mut self) { + let mut returned: Vec = self.carried.take().into_iter().collect(); + returned.extend(self.craft_grid.iter_mut().filter_map(Option::take)); + for stack in returned { + if let Some(rest) = self.give(stack) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + } + } + self.craft_size = 2; + } + fn click_inventory(&mut self, right: bool) { + let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; + let batch = HudBatch::new(size); + let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return }; + let max = |items: &Items, s: &ItemStack| items.get(&s.item).map_or(64, |i| i.max_stack); + let shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + if slot == 200 { + // ResultSlot: take the crafted stack and consume one of each ingredient. + let mut crafted = 0; + while let Some(result) = self.craft_result() { + if shift { + if self.give(result).is_some() { + break; + } + } else { + match &mut self.carried { + None => self.carried = Some(result), + Some(c) if c.item == result.item && c.count + result.count <= max(&self.res.items, c) => c.count += result.count, + _ => return, + } + } + for cell in self.craft_grid.iter_mut() { + if let Some(s) = cell { + s.count -= 1; + if s.count == 0 { + *cell = None; + } + } + } + crafted += 1; + if !shift || crafted >= 64 { + break; + } + } + return; + } + if shift && slot < 36 { + // Quick move between hotbar and main inventory. + if let Some(stack) = self.inventory[slot].take() { + let range = if slot < 9 { 9..36 } else { 0..9 }; + let mut stack = stack; + for i in range.clone() { + if let Some(s) = &mut self.inventory[i] + && s.item == stack.item + && s.damage == stack.damage + { + let moved = max(&self.res.items, s).saturating_sub(s.count).min(stack.count); + s.count += moved; + stack.count -= moved; + } + } + if stack.count > 0 + && let Some(i) = range.clone().find(|&i| self.inventory[i].is_none()) + { + self.inventory[i] = Some(stack); + stack = ItemStack { count: 0, ..self.inventory[i].clone().unwrap() }; + } + if stack.count > 0 { + self.inventory[slot] = Some(stack); + } + } + return; + } + let carried = self.carried.take(); + let current = self.slot_mut(slot).take(); + let items = &self.res.items; + let (new_slot, new_carried) = match (carried, current) { + (None, Some(mut s)) if right => { + let half = s.count.div_ceil(2); + s.count -= half; + let taken = ItemStack { count: half, ..s.clone() }; + ((s.count > 0).then_some(s), Some(taken)) + } + (None, s) => (None, s), + (Some(mut c), None) if right => { + let one = ItemStack { count: 1, ..c.clone() }; + c.count -= 1; + (Some(one), (c.count > 0).then_some(c)) + } + (Some(c), None) => (Some(c), None), + (Some(mut c), Some(mut s)) if c.item == s.item && c.damage == s.damage => { + let room = max(items, &s).saturating_sub(s.count); + let moved = if right { 1.min(room).min(c.count) } else { room.min(c.count) }; + s.count += moved; + c.count -= moved; + (Some(s), (c.count > 0).then_some(c)) + } + (Some(c), Some(s)) => (Some(c), Some(s)), + }; + *self.slot_mut(slot) = new_slot; + self.carried = new_carried; + } + /// ItemEntityRenderer: items bob and spin; blocks render as small cubes. + fn entity_geometry(&mut self, camera: glam::DVec3, alpha: f64) -> Vec { + let mut out = Vec::new(); + let items = self.dropped.clone(); + for item in &items { + let p = item.previous; + let q = item.position; + let pos = glam::DVec3::new( + p.x + (q.x - p.x) * alpha, + p.y + (q.y - p.y) * alpha, + p.z + (q.z - p.z) * alpha, + ) - camera; + if pos.length_squared() > 64.0 * 64.0 { + continue; + } + let age = item.age as f32 + alpha as f32; + let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1; + let spin = age / 20.0 + item.bob_offset; + let light = self.world.light(q.x.floor() as i32, (q.y + 0.1).floor() as i32, q.z.floor() as i32); + let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; + let center = pos.as_vec3() + glam::Vec3::new(0.0, bob + 0.125, 0.0); + let rot = glam::Mat3::from_rotation_y(spin); + let icon = self.icon(&item.stack.item); + let atlas = &self.res.atlas; + let mut quad = |corners: [glam::Vec3; 4], name: &str, shade: f32, tint: u32| { + let Some(r) = atlas.sprites.get(name).copied() else { return }; + let uv = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; + let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32; + let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16); + for (corner, uv) in corners.iter().zip(uv) { + let v = center + rot * *corner; + out.push(Vertex { pos: v.to_array(), uv, layer: 0, color, light: packed }); + } + }; + let copies = match item.stack.count { + 0..=1 => 1, + 2..=16 => 2, + 17..=32 => 3, + _ => 4, + }; + for k in 0..copies { + let o = glam::Vec3::new(k as f32 * 0.03, k as f32 * 0.03, k as f32 * 0.05); + match &icon { + Some(Icon::Cube { top, left, right, tint }) => { + let h = 0.125; + let v = |x: f32, y: f32, z: f32| glam::Vec3::new(x * h, y * h, z * h) + o; + quad([v(-1., 1., 1.), v(1., 1., 1.), v(1., 1., -1.), v(-1., 1., -1.)], top, 1.0, *tint); + quad([v(-1., -1., -1.), v(1., -1., -1.), v(1., -1., 1.), v(-1., -1., 1.)], top, 0.5, *tint); + quad([v(-1., -1., 1.), v(1., -1., 1.), v(1., 1., 1.), v(-1., 1., 1.)], left, 0.8, 0xFFFFFF); + quad([v(1., -1., -1.), v(-1., -1., -1.), v(-1., 1., -1.), v(1., 1., -1.)], left, 0.8, 0xFFFFFF); + quad([v(1., -1., 1.), v(1., -1., -1.), v(1., 1., -1.), v(1., 1., 1.)], right, 0.6, 0xFFFFFF); + quad([v(-1., -1., -1.), v(-1., -1., 1.), v(-1., 1., 1.), v(-1., 1., -1.)], right, 0.6, 0xFFFFFF); + } + Some(Icon::Flat(name)) => { + let h = 0.25; + let v = |x: f32, y: f32| glam::Vec3::new(x * h, y * h + 0.125, 0.0) + o; + quad([v(-1., -1.), v(1., -1.), v(1., 1.), v(-1., 1.)], name, 1.0, 0xFFFFFF); + } + None => {} + } + } + } + // Camera-facing particle quads. + let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); + let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); + let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); + let up = right.cross(forward).normalize_or_zero(); + let atlas = &self.res.atlas; + for p in &self.particles { + let Some(r) = atlas.sprites.get(&p.sprite).copied() else { continue }; + let a = alpha; + let pos = glam::DVec3::new( + p.previous[0] + (p.position[0] - p.previous[0]) * a, + p.previous[1] + (p.position[1] - p.previous[1]) * a, + p.previous[2] + (p.position[2] - p.previous[2]) * a, + ) - camera; + let c = pos.as_vec3(); + let light = self.world.light(p.position[0].floor() as i32, p.position[1].floor() as i32, p.position[2].floor() as i32); + let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; + // TerrainParticle colour: 0.6 base brightness times the block tint. + let ch = |sft: u32| (((p.tint >> sft) & 255) as f32 * 0.6) as u32; + let color = 0xFF00_0000 | ch(0) << 16 | ch(8) << 8 | ch(16); + let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0); + let (u0, v0, u1, v1) = (r.u0 + du * p.uv[0], r.v0 + dv * p.uv[1], r.u0 + du * p.uv[2], r.v0 + dv * p.uv[3]); + let s = p.size; + for (k, uv) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].iter().zip([[u0, v1], [u1, v1], [u1, v0], [u0, v0]]) { + let v = c + right * (k.0 * s) + up * (k.1 * s); + out.push(Vertex { pos: v.to_array(), uv, layer: 0, color, light: packed }); + } + } + // Breaking progress overlay (destroy_stage_0..9). + if let Some(m) = &self.mining + && m.progress > 0.0 + { + let stage = ((m.progress * 10.0) as u32).min(9); + if let Some(r) = atlas.sprites.get(&format!("block/destroy_stage_{stage}")).copied() { + let o = (glam::DVec3::new(f64::from(m.pos[0]), f64::from(m.pos[1]), f64::from(m.pos[2])) - camera).as_vec3(); + let e = 0.002; + let corner = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x * (1.0 + 2.0 * e) - e, y * (1.0 + 2.0 * e) - e, z * (1.0 + 2.0 * e) - e); + let faces = [ + [corner(0., 1., 0.), corner(1., 1., 0.), corner(1., 1., 1.), corner(0., 1., 1.)], + [corner(0., 0., 1.), corner(1., 0., 1.), corner(1., 0., 0.), corner(0., 0., 0.)], + [corner(0., 0., 0.), corner(1., 0., 0.), corner(1., 1., 0.), corner(0., 1., 0.)], + [corner(1., 0., 1.), corner(0., 0., 1.), corner(0., 1., 1.), corner(1., 1., 1.)], + [corner(0., 0., 1.), corner(0., 0., 0.), corner(0., 1., 0.), corner(0., 1., 1.)], + [corner(1., 0., 0.), corner(1., 0., 1.), corner(1., 1., 1.), corner(1., 1., 0.)], + ]; + for f in faces { + for (v, uv) in f.iter().zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) { + out.push(Vertex { pos: v.to_array(), uv, layer: 0, color: 0xB4FF_FFFF, light: 15 * 16 | (15 * 16) << 8 }); + } + } + } + } + out + } + fn save_game(&mut self) -> Result<()> { + let chunks: Vec<_> = self + .world + .modified + .drain() + .filter_map(|k| self.world.chunks.get(&k).cloned()) + .collect(); + self.save.save(&chunks, &self.res.assets.registry, &self.res.biomes)?; + let level = &mut self.level; + level.creative = self.creative; + level.time = self.world.game_time; + level.day_time = self.world.day_time; + level.spawn = self.spawn.map(|s| [s.x, s.y, s.z]); + level.rotation = [self.yaw, self.pitch]; + if let Some(p) = &self.player { + level.position = Some([p.position.x, p.position.y, p.position.z]); + level.health = p.health.health(); + level.food = p.health.food.food; + level.saturation = p.health.food.saturation; + } + level.inventory = self + .inventory + .iter() + .enumerate() + .filter_map(|(i, s)| s.as_ref().map(|s| (i as u8, s.item.to_string(), s.count, s.damage))) + .collect(); + level.write(&self.save.root)?; + self.message = Some(("Saved the game".into(), Instant::now())); + Ok(()) + } + fn render(&mut self) -> Result { + let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { + return Ok(false); + }; + let alpha = self.clock.fraction(); + let (camera, underwater) = match &self.player { + Some(p) => { + let (a, b) = (self.previous_position, p.position); + let eye = self.previous_eye + alpha as f32 * (self.eye - self.previous_eye); + let c = glam::DVec3::new( + a.x + (b.x - a.x) * alpha, + a.y + (b.y - a.y) * alpha + f64::from(eye), + a.z + (b.z - a.z) * alpha, + ); + let s = self.world.block(c.x.floor() as i32, c.y.floor() as i32, c.z.floor() as i32); + (c, self.res.facts.get(s).fluid == Fluid::Water) + } + None => (glam::DVec3::new(0.5, 100.0, 0.5), false), + }; + self.audio.listener = [camera.x, camera.y, camera.z]; + self.audio.listener_yaw = self.yaw; + let block = [camera.x.floor() as i32, camera.y.floor() as i32, camera.z.floor() as i32]; + let biome = self + .world + .chunks + .get(&(block[0] >> 4, block[2] >> 4)) + .map(|c| c.biome(block[0], block[1], block[2])) + .unwrap_or(0); + let info = self.res.biomes.get(biome).clone(); + let sky = self.res.environment.sample(self.world.day_time, info.sky, info.fog); + let outline = if self.screen == Screen::Playing { + self.pick().map(|h| { + let p = h.pos.map(f64::from); + [p[0], p[1], p[2], p[0] + 1.0, p[1] + 1.0, p[2] + 1.0] + }) + } else { + None + }; + let hud = self.hud(size); + let entities = self.entity_geometry(camera, alpha); + let water_fog = { + let c = info.water_fog; + [(c >> 16 & 255) as f32 / 255.0, (c >> 8 & 255) as f32 / 255.0, (c & 255) as f32 / 255.0] + }; + let frame = Frame { + camera, + yaw: self.yaw, + pitch: self.pitch, + fov_degrees: 70.0, + sky, + distance: (self.streaming.radius * 16) as f32, + underwater, + water_fog, + outline, + hud: &hud, + entities: &entities, + game_time: self.world.game_time as f32, + ticks: self.ticks, + }; + self.renderer.as_mut().ok_or("renderer")?.render(&frame) + } + fn update_world(&mut self) { + if let Some(p) = &self.player { + self.streaming.center = ((p.position.x.floor() as i32) >> 4, (p.position.z.floor() as i32) >> 4); + } + let (uploads, unloaded) = self.streaming.update(&mut self.world); + let modified: Vec<_> = unloaded + .iter() + .filter(|c| self.world.modified.remove(&(c.x, c.z))) + .cloned() + .collect(); + if !modified.is_empty() + && let Err(e) = self.save.save(&modified, &self.res.assets.registry, &self.res.biomes) + { + eprintln!("Horizon: failed to save unloaded chunks: {e}"); + } + if let Some(renderer) = self.renderer.as_mut() { + for (key, mesh) in uploads { + renderer.upload(key, &mesh); + } + for c in unloaded { + for sy in 0..(HEIGHT / 16) { + renderer.remove((c.x, sy, c.z)); + } + } + } + } +} +impl ApplicationHandler for Game<'_> { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_some() { + return; + } + let window = match event_loop.create_window( + Window::default_attributes() + .with_title("Horizon") + .with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0)), + ) { + Ok(w) => Arc::new(w), + Err(e) => { + self.error = Some(e.to_string()); + event_loop.exit(); + return; + } + }; + let assets = &self.res.assets; + match pollster::block_on(Renderer::new( + window.clone(), + &assets.pixels, + assets.sprite_size, + assets.texture_layers, + &assets.animations, + (&self.res.atlas.pixels, self.res.atlas.width, self.res.atlas.height), + )) { + Ok(r) => self.renderer = Some(r), + Err(e) => { + self.error = Some(e.to_string()); + event_loop.exit(); + return; + } + } + self.window = Some(window); + self.previous = Instant::now(); + } + fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + if self.window.as_ref().is_none_or(|w| w.id() != id) { + return; + } + let result: Result<()> = (|| { + match event { + WindowEvent::CloseRequested => { + self.save_game()?; + event_loop.exit(); + } + WindowEvent::Resized(size) => { + if let Some(r) = &mut self.renderer { + r.resize(size.width, size.height); + } + } + WindowEvent::Focused(focused) => { + self.focused = focused; + if !focused { + self.keys.clear(); + self.left = false; + self.right = false; + self.capture(false); + if self.screen == Screen::Playing && self.player.is_some() { + self.screen = Screen::Paused; + } + } + } + WindowEvent::CursorMoved { position, .. } => { + if let Some(r) = &self.renderer { + let scale = HudBatch::new([r.config.width, r.config.height]).scale; + self.cursor = (position.x as f32 / scale, position.y as f32 / scale); + } + } + WindowEvent::MouseWheel { delta, .. } => { + let d = match delta { + MouseScrollDelta::LineDelta(_, y) => y, + MouseScrollDelta::PixelDelta(p) => p.y as f32, + }; + if self.screen == Screen::Playing && d != 0.0 { + self.selected = (self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize; + } + } + WindowEvent::MouseInput { state, button, .. } => { + let pressed = state == ElementState::Pressed; + match self.screen { + Screen::Playing => { + if pressed && !self.captured { + self.capture(true); + return Ok(()); + } + match button { + MouseButton::Left => { + self.left = pressed; + if pressed { + self.destroy_delay = 0; + } + } + MouseButton::Right => { + self.right = pressed; + if pressed { + self.use_item()?; + self.use_delay = 4; + } + } + MouseButton::Middle if pressed && self.creative => { + if let Some(hit) = self.pick() { + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let item = self.res.facts.get(state).item.clone(); + if &*item != "minecraft:air" { + self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0 }); + } + } + } + _ => {} + } + } + Screen::Inventory if pressed => { + self.click_inventory(button == MouseButton::Right); + } + Screen::Paused if pressed => { + let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); + let b = HudBatch::new(size); + for i in 0..2 { + let (bx, by) = (b.width / 2.0 - 100.0, b.height / 4.0 + 24.0 + i as f32 * 24.0 + 16.0); + if self.cursor.0 >= bx && self.cursor.0 < bx + 200.0 && self.cursor.1 >= by && self.cursor.1 < by + 20.0 { + if i == 0 { + self.screen = Screen::Playing; + self.capture(true); + } else { + self.save_game()?; + event_loop.exit(); + } + } + } + } + Screen::Dead if pressed => { + self.player = None; + self.screen = Screen::Playing; + if !self.creative { + self.inventory.iter_mut().for_each(|s| *s = None); + } + self.spawn_player()?; + self.capture(true); + } + _ => {} + } + } + WindowEvent::KeyboardInput { event, .. } => { + let PhysicalKey::Code(key) = event.physical_key else { return Ok(()) }; + if event.state != ElementState::Pressed { + self.keys.remove(&key); + return Ok(()); + } + self.keys.insert(key); + if event.repeat { + return Ok(()); + } + match key { + KeyCode::Escape => match self.screen { + Screen::Playing => { + self.screen = Screen::Paused; + self.capture(false); + } + Screen::Paused | Screen::Inventory => { + self.close_container(); + self.screen = Screen::Playing; + self.capture(true); + } + Screen::Dead => {} + }, + KeyCode::KeyE => match self.screen { + Screen::Playing => { + self.screen = Screen::Inventory; + self.capture(false); + } + Screen::Inventory => { + self.close_container(); + self.screen = Screen::Playing; + self.capture(true); + } + _ => {} + }, + KeyCode::F3 => self.debug = !self.debug, + KeyCode::KeyQ if self.screen == Screen::Playing => { + let all = self.keys.contains(&KeyCode::ControlLeft); + self.drop_held(all); + } + KeyCode::Digit1 | KeyCode::Digit2 | KeyCode::Digit3 | KeyCode::Digit4 | KeyCode::Digit5 | KeyCode::Digit6 | KeyCode::Digit7 | KeyCode::Digit8 | KeyCode::Digit9 => { + self.selected = match key { + KeyCode::Digit1 => 0, + KeyCode::Digit2 => 1, + KeyCode::Digit3 => 2, + KeyCode::Digit4 => 3, + KeyCode::Digit5 => 4, + KeyCode::Digit6 => 5, + KeyCode::Digit7 => 6, + KeyCode::Digit8 => 7, + _ => 8, + }; + } + _ => {} + } + } + WindowEvent::RedrawRequested => { + let now = Instant::now(); + let elapsed = now.duration_since(self.previous); + self.previous = now; + // Arrow keys turn the camera (accessibility / scripted testing). + let turn = |k| f32::from(u8::from(self.keys.contains(&k))); + let secs = elapsed.as_secs_f32().min(0.1); + self.yaw += (turn(KeyCode::ArrowRight) - turn(KeyCode::ArrowLeft)) * 90.0 * secs; + self.pitch = (self.pitch + (turn(KeyCode::ArrowDown) - turn(KeyCode::ArrowUp)) * 90.0 * secs).clamp(-90.0, 90.0); + self.update_world(); + self.spawn_player()?; + let steps = self.clock.advance(elapsed); + for _ in 0..steps { + self.tick()?; + } + if self.render()? { + self.frames += 1; + self.fps_frames += 1; + if self.fps_at.elapsed() >= Duration::from_secs(1) { + self.fps = self.fps_frames as f32 / self.fps_at.elapsed().as_secs_f32(); + self.fps_frames = 0; + self.fps_at = Instant::now(); + } + if self.options.frames.is_some_and(|f| self.frames >= f) { + event_loop.exit(); + } + } + } + _ => {} + } + Ok(()) + })(); + if let Err(e) = result { + self.error = Some(e.to_string()); + event_loop.exit(); + } + } + fn device_event(&mut self, _: &ActiveEventLoop, _: DeviceId, event: DeviceEvent) { + if self.captured + && self.focused + && self.screen == Screen::Playing + && let DeviceEvent::MouseMotion { delta: (x, y) } = event + { + // MouseHandler.turnPlayer at default sensitivity 0.5: 0.15 degrees per count. + let s = 0.5_f64 * 0.6 + 0.2; + let f = s * s * s * 8.0; + self.yaw += (x * f * 0.15) as f32; + self.pitch = (self.pitch + (y * f * 0.15) as f32).clamp(-90.0, 90.0); + } + } + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout { + self.error = Some("frame-limited run timed out".into()); + event_loop.exit(); + return; + } + if let Some(w) = &self.window { + w.request_redraw(); + } + event_loop.set_control_flow(ControlFlow::Poll); + } +} +struct Generators { + test: Option>, +} +pub fn run() -> Result<()> { + let Some(options) = Options::read()? else { return Ok(()) }; + let started = Instant::now(); + let root = options.resources.clone(); + let assets = Arc::new(Assets::load(&root).map_err(|e| { + format!("{e}\nPrepare resources with: python3 tools/prepare_native_client.py --prepare") + })?); + eprintln!("load assets: {:.2}s", started.elapsed().as_secs_f32()); + let facts = BlockFacts::load(&root, &assets.registry)?; + eprintln!("load facts: {:.2}s", started.elapsed().as_secs_f32()); + let items = Items::load(&root, &assets.registry, &facts)?; + eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32()); + let recipes = Recipes::load(&root, &items)?; + let biomes = Arc::new(Biomes::load(&root)?); + let environment = Environment::load(&root)?; + eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); + let visibility = models::load_visibility(&root, &assets.registry)?; + eprintln!("load visibility: {:.2}s", started.elapsed().as_secs_f32()); + let tables = Arc::new(MeshTables::new(&assets, &facts, visibility)?); + let light = Arc::new(LightTables::new(&facts)); + eprintln!("load tables: {:.2}s", started.elapsed().as_secs_f32()); + let atlas = HudAtlas::build(&root)?; + eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); + let layer_names = assets + .sprite_layers + .iter() + .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) + .collect(); + let registry_owner = assets.clone(); + let collision = collisions::load(&root, ®istry_owner.registry)?; + let motion = MotionResources::load(&root, ®istry_owner)?; + eprintln!("load collision+motion: {:.2}s", started.elapsed().as_secs_f32()); + let context = Arc::new(WorkerContext { + assets: assets.clone(), + tables, + biomes: biomes.clone(), + light, + }); + let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).saturating_sub(1).max(1); + let generators = Generators { + test: Some(Arc::new(TestTerrain::new(&assets.registry, &biomes)?)), + }; + let _ = options.test_terrain; + let save_root = std::env::current_dir()?.join("saves").join(&options.world); + let level = Level::read(&save_root).unwrap_or_else(|| Level { + name: options.world.clone(), + seed: options.seed, + creative: options.creative, + day_time: 1000, + health: 20.0, + food: 20, + saturation: 5.0, + ..Level::default() + }); + let save = Arc::new(SaveDir::new(save_root)); + let generator = Arc::new(Persistent { + inner: generators.test.clone().ok_or("generator")?, + save: save.clone(), + registry: assets.clone(), + biomes: biomes.clone(), + }); + let mut streaming = Streaming::new(generator, context, threads); + streaming.radius = options.distance; + eprintln!( + "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", + started.elapsed().as_secs_f32(), + facts.states.len(), + items.items.len(), + biomes.list.len(), + threads + ); + let audio = Audio::new(&root); + let mut world = World::new(facts.air, level.seed); + world.game_time = level.time; + world.day_time = level.day_time; + let creative = level.creative || options.creative; + let mut resources = Resources { + assets, + facts, + items, + recipes, + biomes, + environment, + atlas, + icons: HashMap::new(), + layer_names, + }; + let mut inventory = vec![None; 36]; + for (slot, id, count, damage) in &level.inventory { + if let Some(cell) = inventory.get_mut(usize::from(*slot)) { + *cell = Some(ItemStack { item: Arc::from(id.as_str()), count: *count, damage: *damage }); + } + } + let fresh = level.inventory.is_empty() && level.position.is_none(); + if creative && fresh { + for (i, name) in ["minecraft:grass_block", "minecraft:stone", "minecraft:oak_planks", "minecraft:glass", "minecraft:torch", "minecraft:oak_log", "minecraft:cobblestone", "minecraft:water_bucket", "minecraft:diamond_pickaxe"].iter().enumerate() { + inventory[i] = Some(ItemStack { item: Arc::from(*name), count: 1, damage: 0 }); + } + } + let now = Instant::now(); + let mut game = Game { + res: &mut resources, + collision: &collision, + motion: &motion, + world, + streaming, + options, + player: None, + spawn: None, + clock: FixedStep::default(), + previous_position: Vec3::ZERO, + eye: 1.62, + previous_eye: 1.62, + yaw: level.rotation[0], + pitch: level.rotation[1], + inventory, + selected: 0, + carried: None, + craft_grid: vec![None; 9], + craft_size: 2, + mining: None, + destroy_delay: 0, + use_delay: 0, + creative, + keys: HashSet::new(), + left: false, + right: false, + cursor: (0.0, 0.0), + captured: false, + focused: true, + debug: false, + screen: Screen::Playing, + window: None, + renderer: None, + started: now, + previous: now, + frames: 0, + fps: 0.0, + fps_frames: 0, + fps_at: now, + ticks: 0, + error: None, + message: None, + save, + level, + audio, + dropped: Vec::new(), + next_entity: 0, + particles: Vec::new(), + }; + EventLoop::new()?.run_app(&mut game)?; + if let Some(path) = &game.options.report { + let report = serde_json::json!({ + "frames": game.frames, + "elapsed_seconds": game.started.elapsed().as_secs_f64(), + "chunks": game.world.chunks.len(), + "generated": game.streaming.generated_total, + "meshed_sections": game.streaming.meshed_total, + "player": game.player.as_ref().map(|p| [p.position.x, p.position.y, p.position.z]), + "error": game.error, + }); + std::fs::write(path, serde_json::to_vec_pretty(&report)?)?; + } + if let Some(e) = game.error { + return Err(e.into()); + } + Ok(()) +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs new file mode 100644 index 000000000..694747527 --- /dev/null +++ b/crates/horizon-client/src/gfx.rs @@ -0,0 +1,1061 @@ +//! GPU renderer for streamed terrain sections, sky, block outline and HUD. +//! Section origins are supplied relative to the camera each frame so large +//! world coordinates keep full precision. +use crate::{ + Result, + environment::Sky, + hud::{HudBatch, HudRenderer}, + mesher::{SectionMesh, Vertex}, + sprites::SpriteAnimation, +}; +use glam::{DVec3, Mat4, Vec3, Vec4}; +use std::{collections::HashMap, sync::Arc, time::Instant}; +use wgpu::util::DeviceExt; +use winit::window::Window; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Globals { + view_proj: [[f32; 4]; 4], + fog_color: [f32; 4], + fog: [f32; 4], + sky_color: [f32; 4], + misc: [f32; 4], + inverse_view: [[f32; 4]; 4], + sunrise: [f32; 4], + sun: [f32; 4], +} +pub type SectionKey = (i32, i32, i32); +struct SectionGpu { + buffer: wgpu::Buffer, + solid: u32, + translucent: u32, +} +pub struct Frame<'a> { + pub camera: DVec3, + pub yaw: f32, + pub pitch: f32, + pub fov_degrees: f32, + pub sky: Sky, + /// Render distance in blocks (fog end). + pub distance: f32, + pub underwater: bool, + pub water_fog: [f32; 3], + pub outline: Option<[f64; 6]>, + pub hud: &'a HudBatch, + /// Camera-relative entity geometry textured from the shared atlas. + pub entities: &'a [Vertex], + pub game_time: f32, + pub ticks: u64, +} +pub struct Renderer { + instance: wgpu::Instance, + surface: wgpu::Surface<'static>, + window: Arc, + pub device: wgpu::Device, + pub queue: wgpu::Queue, + pub config: wgpu::SurfaceConfiguration, + solid: wgpu::RenderPipeline, + translucent: wgpu::RenderPipeline, + sky: wgpu::RenderPipeline, + lines: wgpu::RenderPipeline, + entity_pipeline: wgpu::RenderPipeline, + entity_group: wgpu::BindGroup, + entity_buffer: wgpu::Buffer, + entity_capacity: u64, + group: wgpu::BindGroup, + globals: wgpu::Buffer, + lightmap: wgpu::Texture, + sprite_texture: wgpu::Texture, + mip_levels: u32, + animations: Vec<(SpriteAnimation, usize)>, + indices: wgpu::Buffer, + index_quads: u32, + instances: wgpu::Buffer, + instance_capacity: u64, + outline: wgpu::Buffer, + depth: wgpu::TextureView, + sections: HashMap, + pub hud: HudRenderer, + pub info: wgpu::AdapterInfo, + pub suspended: bool, + pub drawn_sections: usize, + pub uploaded_bytes: u64, + started: Instant, +} +fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec, u32) { + let levels = size.trailing_zeros() + 1; + let mut out = Vec::new(); + for layer in 0..layers as usize { + let base = &pixels[layer * (size * size * 4) as usize..(layer + 1) * (size * size * 4) as usize]; + let mut level = base.to_vec(); + let mut s = size as usize; + out.extend_from_slice(&level); + for _ in 1..levels { + let n = s / 2; + let mut next = vec![0u8; n * n * 4]; + for y in 0..n { + for x in 0..n { + let mut acc = [0u32; 4]; + let mut weight = 0u32; + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let p = &level[((y * 2 + dy) * s + x * 2 + dx) * 4..][..4]; + let a = u32::from(p[3]); + for c in 0..3 { + acc[c] += u32::from(p[c]) * a; + } + acc[3] += a; + weight += a; + } + let o = &mut next[(y * n + x) * 4..][..4]; + for c in 0..3 { + o[c] = if weight > 0 { (acc[c] / weight) as u8 } else { 0 }; + } + o[3] = (acc[3] / 4) as u8; + } + } + out.extend_from_slice(&next); + level = next; + s = n; + } + } + (out, levels) +} +impl Renderer { + pub async fn new( + window: Arc, + sprite_pixels: &[u8], + sprite_size: u32, + layers: u32, + animations: &[SpriteAnimation], + hud_atlas: (&[u8], u32, u32), + ) -> Result { + let instance = + wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let surface = instance.create_surface(window.clone())?; + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + compatible_surface: Some(&surface), + force_fallback_adapter: false, + ..Default::default() + }) + .await?; + let info = adapter.get_info(); + eprintln!( + "Horizon renderer: {} ({:?}, {:?})", + info.name, info.backend, info.device_type + ); + let limits = adapter.limits(); + if limits.max_texture_array_layers < layers { + return Err(format!( + "GPU supports {} texture layers; {layers} required", + limits.max_texture_array_layers + ) + .into()); + } + let (device, queue) = adapter + .request_device(&wgpu::DeviceDescriptor { + label: Some("Horizon device"), + required_limits: limits.clone(), + ..Default::default() + }) + .await?; + let size = window.inner_size(); + let mut config = surface + .get_default_config(&adapter, size.width.max(1), size.height.max(1)) + .ok_or("surface has no supported configuration")?; + let caps = surface.get_capabilities(&adapter); + // Vanilla blends and tints in gamma space: use a non-sRGB target. + config.format = caps + .formats + .iter() + .copied() + .find(|f| !f.is_srgb()) + .unwrap_or(config.format); + config.view_formats = vec![config.format.remove_srgb_suffix()]; + config.present_mode = if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) { + wgpu::PresentMode::Mailbox + } else { + wgpu::PresentMode::Fifo + }; + surface.configure(&device, &config); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon terrain"), + source: wgpu::ShaderSource::Wgsl(include_str!("terrain.wgsl").into()), + }); + let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry { + binding, + visibility, + ty, + count: None, + }; + let vf = wgpu::ShaderStages::VERTEX_FRAGMENT; + let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Horizon terrain bindings"), + entries: &[ + entry( + 0, + vf, + wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + ), + entry( + 1, + vf, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2Array, + multisampled: false, + }, + ), + entry(1 + 1, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + entry( + 3, + vf, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + ), + entry(4, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Horizon terrain layout"), + bind_group_layouts: &[Some(&bindings)], + ..Default::default() + }); + let vertex_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4]; + let instance_attributes = wgpu::vertex_attr_array![5=>Float32x4]; + let terrain_buffers = [ + Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &vertex_attributes, + }), + Some(wgpu::VertexBufferLayout { + array_stride: 16, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &instance_attributes, + }), + ]; + let line_attributes = wgpu::vertex_attr_array![0=>Float32x3]; + let line_buffers = [Some(wgpu::VertexBufferLayout { + array_stride: 12, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &line_attributes, + })]; + let alpha_blend = wgpu::BlendState::ALPHA_BLENDING; + let pipeline = |label: &str, + vertex: &str, + fragment: &str, + buffers: &[Option>], + topology: wgpu::PrimitiveTopology, + cull: Option, + depth_write: bool, + depth_test: bool, + blend: Option| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some(vertex), + compilation_options: Default::default(), + buffers, + }, + primitive: wgpu::PrimitiveState { + topology, + cull_mode: cull, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(depth_write), + depth_compare: Some(if depth_test { + wgpu::CompareFunction::LessEqual + } else { + wgpu::CompareFunction::Always + }), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(fragment), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; + let tri = wgpu::PrimitiveTopology::TriangleList; + let solid = pipeline( + "Terrain solid", + "vs_terrain", + "fs_solid", + &terrain_buffers, + tri, + Some(wgpu::Face::Back), + true, + true, + None, + ); + let translucent = pipeline( + "Terrain translucent", + "vs_terrain", + "fs_translucent", + &terrain_buffers, + tri, + Some(wgpu::Face::Back), + false, + true, + Some(alpha_blend), + ); + let sky = pipeline("Sky", "vs_sky", "fs_sky", &[], tri, None, false, false, None); + let lines = pipeline( + "Block outline", + "vs_line", + "fs_line", + &line_buffers, + wgpu::PrimitiveTopology::LineList, + None, + false, + true, + Some(alpha_blend), + ); + let globals = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Horizon globals"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, layers); + let sprite_texture = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: Some("Block sprites"), + size: wgpu::Extent3d { + width: sprite_size, + height: sprite_size, + depth_or_array_layers: layers, + }, + mip_level_count: mip_levels, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &mips, + ); + let sprite_view = sprite_texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + ..Default::default() + }); + let sprite_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Block sprites"), + address_mode_u: wgpu::AddressMode::Repeat, + address_mode_v: wgpu::AddressMode::Repeat, + mag_filter: wgpu::FilterMode::Nearest, + min_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }); + let lightmap = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Lightmap"), + size: wgpu::Extent3d { + width: 16, + height: 16, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let lightmap_view = lightmap.create_view(&Default::default()); + let lightmap_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Lightmap"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Horizon terrain resources"), + layout: &bindings, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: globals.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&sprite_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sprite_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&lightmap_view), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&lightmap_sampler), + }, + ], + }); + let index_quads = 1 << 16; + let indices = Self::quad_indices(&device, index_quads); + let instance_capacity = 4096; + let instances = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Section origins"), + size: instance_capacity * 16, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let outline = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Outline"), + size: 24 * 12, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let depth = Self::depth(&device, &config); + let (atlas_pixels, atlas_width, atlas_height) = hud_atlas; + let atlas = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: Some("Shared atlas"), + size: wgpu::Extent3d { + width: atlas_width, + height: atlas_height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + atlas_pixels, + ); + let atlas_view = atlas.create_view(&Default::default()); + let hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?; + let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon entities"), + source: wgpu::ShaderSource::Wgsl(include_str!("entity.wgsl").into()), + }); + let entity_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Entity bindings"), + entries: &[ + entry( + 0, + vf, + wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + ), + entry( + 1, + vf, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + ), + entry(2, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + entry( + 3, + vf, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + ), + entry(4, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + ], + }); + let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Atlas"), + ..Default::default() + }); + let entity_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Entity resources"), + layout: &entity_bindings, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: globals.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&atlas_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&atlas_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&lightmap_view), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&lightmap_sampler), + }, + ], + }); + let entity_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Entity layout"), + bind_group_layouts: &[Some(&entity_bindings)], + ..Default::default() + }); + let entity_vertex = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &vertex_attributes, + })]; + let entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Entities"), + layout: Some(&entity_layout), + vertex: wgpu::VertexState { + module: &entity_shader, + entry_point: Some("vs_entity"), + compilation_options: Default::default(), + buffers: &entity_vertex, + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &entity_shader, + entry_point: Some("fs_entity"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend: Some(alpha_blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + let entity_capacity = 1 << 14; + let entity_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Entity vertices"), + size: entity_capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Ok(Self { + instance, + surface, + window, + device, + queue, + config, + solid, + translucent, + sky, + lines, + entity_pipeline, + entity_group, + entity_buffer, + entity_capacity, + group, + globals, + lightmap, + sprite_texture, + mip_levels, + animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(), + indices, + index_quads, + instances, + instance_capacity, + outline, + depth, + sections: HashMap::new(), + hud, + info, + suspended: size.width == 0 || size.height == 0, + drawn_sections: 0, + uploaded_bytes: 0, + started: Instant::now(), + }) + } + fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { + let indices: Vec = (0..quads) + .flat_map(|q| { + let b = q * 4; + [b, b + 1, b + 2, b, b + 2, b + 3] + }) + .collect(); + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Quad indices"), + contents: bytemuck::cast_slice(&indices), + usage: wgpu::BufferUsages::INDEX, + }) + } + fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some("Horizon depth"), + size: wgpu::Extent3d { + width: config.width, + height: config.height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }) + .create_view(&Default::default()) + } + pub fn resize(&mut self, width: u32, height: u32) { + self.suspended = width == 0 || height == 0; + if self.suspended { + return; + } + self.config.width = width; + self.config.height = height; + self.surface.configure(&self.device, &self.config); + self.depth = Self::depth(&self.device, &self.config); + } + pub fn section_count(&self) -> usize { + self.sections.len() + } + pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { + let solid = (mesh.solid.len() / 4) as u32; + let translucent = (mesh.translucent.len() / 4) as u32; + if solid + translucent == 0 { + self.sections.remove(&key); + return; + } + let max = solid.max(translucent); + if max > self.index_quads { + self.index_quads = max.next_power_of_two(); + self.indices = Self::quad_indices(&self.device, self.index_quads); + } + let mut data = Vec::with_capacity(mesh.solid.len() + mesh.translucent.len()); + data.extend_from_slice(&mesh.solid); + data.extend_from_slice(&mesh.translucent); + let bytes: &[u8] = bytemuck::cast_slice(&data); + self.uploaded_bytes += bytes.len() as u64; + let buffer = self + .device + .create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Section mesh"), + contents: bytes, + usage: wgpu::BufferUsages::VERTEX, + }); + self.sections.insert( + key, + SectionGpu { + buffer, + solid, + translucent, + }, + ); + } + pub fn remove(&mut self, key: SectionKey) { + self.sections.remove(&key); + } + pub fn view_projection(&self, frame: &Frame) -> Mat4 { + let aspect = self.config.width as f32 / self.config.height.max(1) as f32; + let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); + // Minecraft yaw: 0 = +Z (south), 90 = -X (west); pitch positive looks down. + let forward = Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); + let far = (frame.distance * 4.0).max(1024.0); + Mat4::perspective_rh(frame.fov_degrees.to_radians(), aspect, 0.05, far) + * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) + } + fn update_lightmap(&self, sky: &Sky, darkness: f32, gamma: f32) { + // lightmap.fsh: per (block, sky) level. + let brightness = |level: f32| level / (4.0 - 3.0 * level); + let mut pixels = [0u8; 16 * 16 * 4]; + for s in 0..16 { + for b in 0..16 { + let block_level = b as f32 / 15.0; + let sky_level = s as f32 / 15.0; + let block_brightness = brightness(block_level) * 1.4; + let sky_brightness = brightness(sky_level) * sky.sky_light_factor; + let mut color = Vec3::from(sky.ambient_light_color); + color += Vec3::from(sky.sky_light_color) * sky_brightness; + let parabolic = (2.0 * block_level - 1.0).powi(2); + let block_color = Vec3::from(sky.block_light_tint).lerp(Vec3::ONE, 0.9 * parabolic); + color += block_color * block_brightness; + color -= Vec3::splat(darkness); + color = color.clamp(Vec3::ZERO, Vec3::ONE); + let max = color.max_element().max(1e-6); + let inverted = 1.0 - max; + let scaled = 1.0 - inverted.powi(4); + let not_gamma = color * (scaled / max); + color = color.lerp(not_gamma, gamma); + let i = (s * 16 + b) * 4; + pixels[i] = (color.x * 255.0) as u8; + pixels[i + 1] = (color.y * 255.0) as u8; + pixels[i + 2] = (color.z * 255.0) as u8; + pixels[i + 3] = 255; + } + } + self.queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &self.lightmap, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + &pixels, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(64), + rows_per_image: Some(16), + }, + wgpu::Extent3d { + width: 16, + height: 16, + depth_or_array_layers: 1, + }, + ); + } + fn animate(&mut self, tick: u64) { + for (animation, previous) in &mut self.animations { + let frame = animation.frame(tick); + if frame == *previous { + continue; + } + *previous = frame; + let (mips, levels) = mip_chain(animation.pixels(frame), 16, 1); + let mut offset = 0; + for level in 0..levels.min(self.mip_levels) { + let size = 16 >> level; + let bytes = (size * size * 4) as usize; + self.queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &self.sprite_texture, + mip_level: level, + origin: wgpu::Origin3d { + x: 0, + y: 0, + z: animation.layer, + }, + aspect: wgpu::TextureAspect::All, + }, + &mips[offset..offset + bytes], + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(size * 4), + rows_per_image: Some(size), + }, + wgpu::Extent3d { + width: size, + height: size, + depth_or_array_layers: 1, + }, + ); + offset += bytes; + } + } + } + pub fn render(&mut self, frame: &Frame) -> Result { + if self.suspended { + return Ok(false); + } + let (surface_frame, reconfigure) = match self.surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(f) => (f, false), + wgpu::CurrentSurfaceTexture::Suboptimal(f) => (f, true), + wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => { + return Ok(false); + } + wgpu::CurrentSurfaceTexture::Outdated => { + self.surface.configure(&self.device, &self.config); + return Ok(false); + } + wgpu::CurrentSurfaceTexture::Lost => { + self.surface = self.instance.create_surface(self.window.clone())?; + self.surface.configure(&self.device, &self.config); + return Ok(false); + } + wgpu::CurrentSurfaceTexture::Validation => { + return Err("surface acquisition failed validation".into()); + } + }; + self.animate(frame.ticks); + self.update_lightmap(&frame.sky, 0.0, 0.5); + let view_proj = self.view_projection(frame); + let aspect = self.config.width as f32 / self.config.height.max(1) as f32; + let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); + let forward = Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); + let view = Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y); + let sun_angle = frame.sky.sun_angle.to_radians(); + // Celestial bodies rotate around the X axis; angle 0 = noon. + let sun = Vec3::new(0.0, sun_angle.cos(), -sun_angle.sin()); + let (fog_color, fog) = if frame.underwater { + ( + [frame.water_fog[0], frame.water_fog[1], frame.water_fog[2], 1.0], + [-8.0, 96.0, -8.0, 96.0], + ) + } else { + let d = frame.distance; + ( + [frame.sky.fog_color[0], frame.sky.fog_color[1], frame.sky.fog_color[2], 1.0], + // FogRenderer: render-distance fog starts at max(d - 16, 0)... d. + [f32::MAX, f32::MAX, (d - d.min(64.0) * 0.25).max(0.0), d], + ) + }; + let globals = Globals { + view_proj: view_proj.to_cols_array_2d(), + fog_color, + fog, + sky_color: [frame.sky.sky_color[0], frame.sky.sky_color[1], frame.sky.sky_color[2], 1.0], + misc: [ + 1.0 - frame.sky.sky_light_factor, + frame.game_time, + aspect, + (frame.fov_degrees.to_radians() / 2.0).tan(), + ], + inverse_view: view.inverse().to_cols_array_2d(), + sunrise: frame.sky.sunrise_color, + sun: [sun.x, sun.y, sun.z, frame.sky.star_brightness], + }; + self.queue + .write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals)); + // Frustum culling and camera-relative origins. + let planes = frustum(view_proj); + let camera = frame.camera; + let mut visible: Vec<(SectionKey, f64, [f32; 3])> = self + .sections + .keys() + .filter_map(|&(sx, sy, sz)| { + let origin = DVec3::new( + f64::from(sx * 16), + f64::from(crate::chunk::MIN_Y + sy * 16), + f64::from(sz * 16), + ) - camera; + let center = origin + DVec3::splat(8.0); + let horizontal = (center.x * center.x + center.z * center.z).sqrt(); + if horizontal > f64::from(frame.distance) + 24.0 { + return None; + } + let min = origin.as_vec3(); + let max = min + Vec3::splat(16.0); + if planes.iter().any(|p| { + let v = Vec3::new( + if p.x >= 0.0 { max.x } else { min.x }, + if p.y >= 0.0 { max.y } else { min.y }, + if p.z >= 0.0 { max.z } else { min.z }, + ); + p.truncate().dot(v) + p.w < 0.0 + }) { + return None; + } + Some(((sx, sy, sz), center.length_squared(), origin.as_vec3().to_array())) + }) + .collect(); + visible.sort_by(|a, b| a.1.total_cmp(&b.1)); + self.drawn_sections = visible.len(); + if visible.len() as u64 > self.instance_capacity { + self.instance_capacity = (visible.len() as u64).next_power_of_two(); + self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Section origins"), + size: self.instance_capacity * 16, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + let origins: Vec<[f32; 4]> = visible + .iter() + .map(|(_, _, o)| [o[0], o[1], o[2], 0.0]) + .collect(); + if !origins.is_empty() { + self.queue + .write_buffer(&self.instances, 0, bytemuck::cast_slice(&origins)); + } + if let Some(b) = frame.outline { + let o = [ + (b[0] - camera.x) as f32 - 0.002, + (b[1] - camera.y) as f32 - 0.002, + (b[2] - camera.z) as f32 - 0.002, + ]; + let e = [ + (b[3] - camera.x) as f32 + 0.002, + (b[4] - camera.y) as f32 + 0.002, + (b[5] - camera.z) as f32 + 0.002, + ]; + let c = |i: usize| -> [f32; 3] { + [ + if i & 1 == 0 { o[0] } else { e[0] }, + if i & 2 == 0 { o[1] } else { e[1] }, + if i & 4 == 0 { o[2] } else { e[2] }, + ] + }; + let edges = [ + (0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7), + ]; + let lines: Vec<[f32; 3]> = edges.iter().flat_map(|&(a, b)| [c(a), c(b)]).collect(); + self.queue + .write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines)); + } + let entity_vertices = frame.entities.len() as u64; + if entity_vertices > self.entity_capacity { + self.entity_capacity = entity_vertices.next_power_of_two(); + self.entity_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Entity vertices"), + size: self.entity_capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + if entity_vertices > 0 { + self.queue + .write_buffer(&self.entity_buffer, 0, bytemuck::cast_slice(frame.entities)); + } + let entity_quads = (entity_vertices / 4) as u32; + if entity_quads > self.index_quads { + self.index_quads = entity_quads.next_power_of_two(); + self.indices = Self::quad_indices(&self.device, self.index_quads); + } + let view_target = surface_frame.texture.create_view(&wgpu::TextureViewDescriptor { + format: Some(self.config.format.remove_srgb_suffix()), + ..Default::default() + }); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Horizon frame"), + }); + { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: &view_target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: f64::from(fog_color[0]), + g: f64::from(fog_color[1]), + b: f64::from(fog_color[2]), + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon world"), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_bind_group(0, &self.group, &[]); + if !frame.underwater { + pass.set_pipeline(&self.sky); + pass.draw(0..3, 0..1); + } + pass.set_pipeline(&self.solid); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + for (i, (key, _, _)) in visible.iter().enumerate() { + let s = &self.sections[key]; + if s.solid == 0 { + continue; + } + pass.set_vertex_buffer(0, s.buffer.slice(..)); + pass.draw_indexed(0..s.solid * 6, 0, i as u32..i as u32 + 1); + } + if entity_quads > 0 { + pass.set_pipeline(&self.entity_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed(0..entity_quads * 6, 0, 0..1); + pass.set_bind_group(0, &self.group, &[]); + } + if frame.outline.is_some() { + pass.set_pipeline(&self.lines); + pass.set_vertex_buffer(0, self.outline.slice(..)); + pass.draw(0..24, 0..1); + } + pass.set_pipeline(&self.translucent); + pass.set_vertex_buffer(1, self.instances.slice(..)); + for (i, (key, _, _)) in visible.iter().enumerate().rev() { + let s = &self.sections[key]; + if s.translucent == 0 { + continue; + } + pass.set_vertex_buffer(0, s.buffer.slice(..)); + pass.draw_indexed( + 0..s.translucent * 6, + (s.solid * 4) as i32, + i as u32..i as u32 + 1, + ); + } + } + self.hud.draw( + &self.device, + &self.queue, + &mut encoder, + &view_target, + frame.hud, + [self.config.width, self.config.height], + ); + self.queue.submit([encoder.finish()]); + self.window.pre_present_notify(); + self.queue.present(surface_frame); + if reconfigure { + self.surface.configure(&self.device, &self.config); + } + let _ = self.started; + Ok(true) + } +} +fn frustum(m: Mat4) -> [Vec4; 6] { + let r = |i| m.row(i); + let planes = [ + r(3) + r(0), + r(3) - r(0), + r(3) + r(1), + r(3) - r(1), + r(2), + r(3) - r(2), + ]; + planes.map(|p| p / p.truncate().length()) +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs new file mode 100644 index 000000000..187b0b365 --- /dev/null +++ b/crates/horizon-client/src/hud.rs @@ -0,0 +1,508 @@ +//! 2D overlay: one atlas holding GUI sprites, the bitmap font, item and block +//! textures, and a batch of textured quads in GUI pixels (vanilla's automatic +//! GUI scale is applied when drawing). +use crate::Result; +use std::{ + collections::HashMap, + fs, + path::{Path, PathBuf}, +}; +use wgpu::util::DeviceExt; + +#[derive(Clone, Copy, Debug)] +pub struct Rect { + pub u0: f32, + pub v0: f32, + pub u1: f32, + pub v1: f32, + pub w: u32, + pub h: u32, +} +#[derive(Clone, Copy)] +struct Glyph { + rect: Rect, + advance: f32, +} +pub struct HudAtlas { + pub pixels: Vec, + pub width: u32, + pub height: u32, + pub sprites: HashMap, + glyphs: HashMap, + white: Rect, +} +fn decode(path: &Path) -> Result<(u32, u32, Vec)> { + let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?)); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); + let mut reader = decoder.read_info()?; + let mut bytes = vec![0; reader.output_buffer_size().ok_or("image too large")?]; + let info = reader.next_frame(&mut bytes)?; + let channels = info.color_type.samples(); + let mut rgba = Vec::with_capacity((info.width * info.height * 4) as usize); + for p in bytes[..info.buffer_size()].chunks_exact(channels) { + rgba.extend(match channels { + 4 => [p[0], p[1], p[2], p[3]], + 3 => [p[0], p[1], p[2], 255], + 2 => [p[0], p[0], p[0], p[1]], + _ => [p[0], p[0], p[0], 255], + }); + } + Ok((info.width, info.height, rgba)) +} +fn walk(dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, out); + } else if path.extension().is_some_and(|e| e == "png") { + out.push(path); + } + } +} +impl HudAtlas { + pub fn build(root: &Path) -> Result { + let textures = root.join("assets/minecraft/textures"); + let mut files = Vec::new(); + walk(&textures.join("gui"), &mut files); + walk(&textures.join("item"), &mut files); + walk(&textures.join("block"), &mut files); + walk(&textures.join("font"), &mut files); + walk(&textures.join("environment"), &mut files); + walk(&textures.join("misc"), &mut files); + walk(&textures.join("entity"), &mut files); + walk(&textures.join("particle"), &mut files); + files.retain(|p| { + let s = p.to_string_lossy(); + !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") + }); + let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec)> { + let name = path + .strip_prefix(&textures) + .ok()? + .with_extension("") + .to_string_lossy() + .replace('\\', "/"); + let (w, mut h, pixels) = decode(path).ok()?; + let is_frame_strip = (name.starts_with("block/") || name.starts_with("item/")) && h > w; + let pixels = if is_frame_strip { + h = w; + pixels[..(w * w * 4) as usize].to_vec() + } else { + pixels + }; + (w <= 512 && h <= 512).then_some((name, w, h, pixels)) + }; + let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); + let chunk = files.len().div_ceil(threads).max(1); + let mut images: Vec<_> = std::thread::scope(|scope| { + let handles: Vec<_> = files + .chunks(chunk) + .map(|part| scope.spawn(move || part.iter().filter_map(decode_one).collect::>())) + .collect(); + handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect() + }); + images.push(("horizon/white".into(), 4, 4, vec![255; 64])); + images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); + let width = 4096u32; + let mut placements = Vec::with_capacity(images.len()); + let (mut x, mut y, mut row) = (0u32, 0u32, 0u32); + for (_, w, h, _) in &images { + if x + w + 1 > width { + x = 0; + y += row + 1; + row = 0; + } + placements.push((x, y)); + x += w + 1; + row = row.max(*h); + } + let height = (y + row + 1).next_power_of_two(); + let mut pixels = vec![0u8; (width * height * 4) as usize]; + let mut sprites = HashMap::new(); + for ((name, w, h, data), (px, py)) in images.iter().zip(placements) { + for row in 0..*h { + let src = &data[(row * w * 4) as usize..((row + 1) * w * 4) as usize]; + let dst = (((py + row) * width + px) * 4) as usize; + pixels[dst..dst + (w * 4) as usize].copy_from_slice(src); + } + sprites.insert( + name.clone(), + Rect { + u0: px as f32 / width as f32, + v0: py as f32 / height as f32, + u1: (px + w) as f32 / width as f32, + v1: (py + h) as f32 / height as f32, + w: *w, + h: *h, + }, + ); + } + let white = sprites["horizon/white"]; + let mut atlas = Self { + pixels, + width, + height, + sprites, + glyphs: HashMap::new(), + white, + }; + atlas.load_font(root)?; + Ok(atlas) + } + fn load_font(&mut self, root: &Path) -> Result<()> { + let text = fs::read_to_string(root.join("assets/minecraft/font/include/default.json"))?; + let value: serde_json::Value = serde_json::from_str(&text)?; + for provider in value["providers"].as_array().into_iter().flatten() { + if provider["type"] != "bitmap" { + continue; + } + let file = provider["file"].as_str().unwrap_or(""); + let name = file + .trim_start_matches("minecraft:") + .trim_end_matches(".png") + .to_owned(); + let Some(rect) = self.sprites.get(&name).copied() else { + continue; + }; + let rows: Vec> = provider["chars"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r.as_str().map(|s| s.chars().collect())) + .collect(); + if rows.is_empty() { + continue; + } + let columns = rows[0].len() as u32; + let cell_w = rect.w / columns; + let cell_h = rect.h / rows.len() as u32; + let height = provider["height"].as_f64().unwrap_or(8.0) as f32; + let scale = height / cell_h as f32; + let (ax, ay) = ( + (rect.u0 * self.width as f32) as u32, + (rect.v0 * self.height as f32) as u32, + ); + for (r, row) in rows.iter().enumerate() { + for (c, ch) in row.iter().enumerate() { + if *ch == '\0' || self.glyphs.contains_key(ch) { + continue; + } + let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h); + // Glyph width: rightmost column containing an opaque pixel. + let mut used = 0; + for x in (0..cell_w).rev() { + if (0..cell_h).any(|y| { + self.pixels[(((cy + y) * self.width + cx + x) * 4 + 3) as usize] != 0 + }) { + used = x + 1; + break; + } + } + self.glyphs.insert( + *ch, + Glyph { + rect: Rect { + u0: cx as f32 / self.width as f32, + v0: cy as f32 / self.height as f32, + u1: (cx + cell_w) as f32 / self.width as f32, + v1: (cy + cell_h) as f32 / self.height as f32, + w: cell_w, + h: cell_h, + }, + advance: (used as f32 * scale + 0.5).floor() + 1.0, + }, + ); + } + } + } + self.glyphs.insert( + ' ', + Glyph { + rect: self.white, + advance: 4.0, + }, + ); + Ok(()) + } +} +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +pub struct HudVertex { + pub pos: [f32; 2], + pub uv: [f32; 2], + pub color: u32, +} +/// One frame of overlay geometry in GUI pixels. +pub struct HudBatch { + pub vertices: Vec, + pub scale: f32, + pub width: f32, + pub height: f32, +} +pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 { + u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r) +} +impl HudBatch { + /// Vanilla's automatic GUI scale: the largest scale keeping >= 320x240 GUI pixels. + pub fn new(window: [u32; 2]) -> Self { + let mut scale = 1; + while window[0] / (scale + 1) >= 320 && window[1] / (scale + 1) >= 240 { + scale += 1; + } + Self { + vertices: Vec::new(), + scale: scale as f32, + width: (window[0] as f32 / scale as f32).ceil(), + height: (window[1] as f32 / scale as f32).ceil(), + } + } + pub fn quad(&mut self, p: [[f32; 2]; 4], uv: [[f32; 2]; 4], color: u32) { + for i in [0, 1, 2, 0, 2, 3] { + self.vertices.push(HudVertex { + pos: p[i], + uv: uv[i], + color, + }); + } + } + pub fn rect_uv(&mut self, x: f32, y: f32, w: f32, h: f32, r: Rect, color: u32) { + self.quad( + [[x, y], [x + w, y], [x + w, y + h], [x, y + h]], + [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]], + color, + ); + } + pub fn sprite(&mut self, atlas: &HudAtlas, name: &str, x: f32, y: f32) { + if let Some(r) = atlas.sprites.get(name).copied() { + self.rect_uv(x, y, r.w as f32, r.h as f32, r, u32::MAX); + } + } + pub fn sprite_scaled(&mut self, atlas: &HudAtlas, name: &str, x: f32, y: f32, w: f32, h: f32, color: u32) { + if let Some(r) = atlas.sprites.get(name).copied() { + self.rect_uv(x, y, w, h, r, color); + } + } + /// Draw part of a sprite, `fraction` of its width from the left. + pub fn sprite_part(&mut self, atlas: &HudAtlas, name: &str, x: f32, y: f32, fraction: f32) { + if let Some(mut r) = atlas.sprites.get(name).copied() { + let w = r.w as f32 * fraction; + r.u1 = r.u0 + (r.u1 - r.u0) * fraction; + self.rect_uv(x, y, w, r.h as f32, r, u32::MAX); + } + } + pub fn fill(&mut self, atlas: &HudAtlas, x: f32, y: f32, w: f32, h: f32, color: u32) { + let mut r = atlas.white; + let (cu, cv) = ((r.u0 + r.u1) / 2.0, (r.v0 + r.v1) / 2.0); + r.u0 = cu; + r.u1 = cu; + r.v0 = cv; + r.v1 = cv; + self.rect_uv(x, y, w, h, r, color); + } + pub fn text_width(atlas: &HudAtlas, text: &str) -> f32 { + text.chars() + .map(|c| atlas.glyphs.get(&c).map_or(6.0, |g| g.advance)) + .sum() + } + pub fn text(&mut self, atlas: &HudAtlas, text: &str, x: f32, y: f32, color: u32, shadow: bool) -> f32 { + if shadow { + let c = color.to_le_bytes(); + let dark = rgba(c[0] / 4, c[1] / 4, c[2] / 4, c[3]); + self.text(atlas, text, x + 1.0, y + 1.0, dark, false); + } + let mut cursor = x; + for ch in text.chars() { + let Some(g) = atlas.glyphs.get(&ch).copied() else { + cursor += 6.0; + continue; + }; + if ch != ' ' { + self.rect_uv(cursor, y, 8.0, 8.0, g.rect, color); + } + cursor += g.advance; + } + cursor - x + } +} +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct HudUniform { + size: [f32; 4], +} +pub struct HudRenderer { + pipeline: wgpu::RenderPipeline, + group: wgpu::BindGroup, + uniform: wgpu::Buffer, + buffer: wgpu::Buffer, + capacity: u64, +} +impl HudRenderer { + pub fn new( + device: &wgpu::Device, + format: wgpu::TextureFormat, + view: &wgpu::TextureView, + ) -> Result { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon HUD"), + source: wgpu::ShaderSource::Wgsl(include_str!("hud.wgsl").into()), + }); + + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("HUD"), + ..Default::default() + }); + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("HUD size"), + contents: bytemuck::bytes_of(&HudUniform { size: [1.0; 4] }), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("HUD bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("HUD resources"), + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("HUD layout"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4]; + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("HUD"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &attributes, + })], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + let capacity = 1 << 16; + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("HUD vertices"), + size: capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Ok(Self { + pipeline, + group, + uniform, + buffer, + capacity, + }) + } + pub fn draw( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + batch: &HudBatch, + size: [u32; 2], + ) { + if batch.vertices.is_empty() { + return; + } + let count = batch.vertices.len() as u64; + if count > self.capacity { + self.capacity = count.next_power_of_two(); + self.buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("HUD vertices"), + size: self.capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&batch.vertices)); + queue.write_buffer( + &self.uniform, + 0, + bytemuck::bytes_of(&HudUniform { + size: [size[0] as f32, size[1] as f32, batch.scale, 0.0], + }), + ); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("HUD"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &self.group, &[]); + pass.set_vertex_buffer(0, self.buffer.slice(..)); + pass.draw(0..count as u32, 0..1); + } +} diff --git a/crates/horizon-client/src/hud.wgsl b/crates/horizon-client/src/hud.wgsl new file mode 100644 index 000000000..d455db179 --- /dev/null +++ b/crates/horizon-client/src/hud.wgsl @@ -0,0 +1,22 @@ +struct Hud { size: vec4 } +@group(0) @binding(0) var hud: Hud; +@group(0) @binding(1) var atlas: texture_2d; +@group(0) @binding(2) var atlas_sampler: sampler; +struct Out { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) color: vec4, +} +@vertex fn vs_main(@location(0) pos: vec2, @location(1) uv: vec2, @location(2) color: vec4) -> Out { + let pixels = pos * hud.size.z; + var out: Out; + out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, 0.0, 1.0); + out.uv = uv; + out.color = color; + return out; +} +@fragment fn fs_main(in: Out) -> @location(0) vec4 { + let c = textureSample(atlas, atlas_sampler, in.uv) * in.color; + if c.a < 0.004 { discard; } + return c; +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs new file mode 100644 index 000000000..8c914d8e4 --- /dev/null +++ b/crates/horizon-client/src/items.rs @@ -0,0 +1,458 @@ +//! Items from vanilla's default-component reports, block<->item mapping, +//! tool mining rules and block loot tables (`LootTable`/`LootPool` semantics +//! for the condition, entry and modifier types used by block drops). +use crate::{Result, blocks::BlockFacts}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::registry::{BlockRegistry, BlockStateId}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + fs, + path::Path, + sync::Arc, +}; + +#[derive(Clone, Debug)] +pub struct ToolRule { + pub blocks: Vec, + pub speed: Option, + pub correct: Option, +} +#[derive(Clone, Debug)] +pub struct ItemInfo { + pub id: Arc, + pub max_stack: u32, + pub max_damage: u32, + pub block: Option, + pub tool: Vec, + pub tool_default_speed: f32, + pub food: Option<(u32, f32)>, + pub model: String, +} +#[derive(Clone, Debug, PartialEq)] +pub struct ItemStack { + pub item: Arc, + pub count: u32, + pub damage: u32, +} +pub struct Items { + pub items: HashMap, ItemInfo>, + pub order: Vec>, + /// Block tag name (without '#') -> member block names. + pub block_tags: HashMap>, + pub item_tags: HashMap>, + loot: HashMap, +} +fn load_tags(root: &Path, kind: &str) -> Result>> { + let dir = root.join(format!("data/minecraft/tags/{kind}")); + let mut raw: HashMap> = HashMap::new(); + fn walk(dir: &Path, base: &Path, raw: &mut HashMap>) -> Result<()> { + for entry in fs::read_dir(dir)?.flatten() { + let p = entry.path(); + if p.is_dir() { + walk(&p, base, raw)?; + } else if p.extension().is_some_and(|e| e == "json") { + let name = format!( + "minecraft:{}", + p.strip_prefix(base)?.with_extension("").to_string_lossy().replace('\\', "/") + ); + let v: Value = serde_json::from_slice(&fs::read(&p)?)?; + let values = v["values"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned)) + .collect(); + raw.insert(name, values); + } + } + Ok(()) + } + if dir.exists() { + walk(&dir, &dir, &mut raw)?; + } + fn resolve(name: &str, raw: &HashMap>, out: &mut HashSet, depth: u32) { + if depth > 32 { + return; + } + for v in raw.get(name).into_iter().flatten() { + if let Some(tag) = v.strip_prefix('#') { + resolve(tag, raw, out, depth + 1); + } else { + out.insert(v.clone()); + } + } + } + Ok(raw + .keys() + .map(|k| { + let mut set = HashSet::new(); + resolve(k, &raw, &mut set, 0); + (k.clone(), set) + }) + .collect()) +} +impl Items { + pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result { + let raw: BTreeMap = + serde_json::from_slice(&fs::read(root.join("items.json"))?)?; + let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new(); + for (i, s) in facts.states.iter().enumerate() { + let default = registry.default_state(&s.name); + if default == Some(BlockStateId(i as u32)) && &*s.item != "minecraft:air" { + block_for_item.entry(&s.item).or_insert(BlockStateId(i as u32)); + } + } + let mut items = HashMap::new(); + let mut order = Vec::new(); + for (name, c) in &raw { + let id: Arc = Arc::from(name.as_str()); + let tool = c["minecraft:tool"]["rules"] + .as_array() + .into_iter() + .flatten() + .map(|r| ToolRule { + blocks: match &r["blocks"] { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(), + _ => vec![], + }, + speed: r["speed"].as_f64().map(|v| v as f32), + correct: r["correct_for_drops"].as_bool(), + }) + .collect(); + let food = c.get("minecraft:food").map(|f| { + ( + f["nutrition"].as_u64().unwrap_or(0) as u32, + f["saturation"].as_f64().unwrap_or(0.0) as f32, + ) + }); + items.insert( + id.clone(), + ItemInfo { + id: id.clone(), + max_stack: c["minecraft:max_stack_size"].as_u64().unwrap_or(64) as u32, + max_damage: c["minecraft:max_damage"].as_u64().unwrap_or(0) as u32, + block: block_for_item.get(name.as_str()).copied(), + tool, + tool_default_speed: c["minecraft:tool"]["default_mining_speed"] + .as_f64() + .unwrap_or(1.0) as f32, + food, + model: c["minecraft:item_model"].as_str().unwrap_or(name).to_owned(), + }, + ); + order.push(id); + } + let mut loot = HashMap::new(); + let dir = root.join("data/minecraft/loot_table/blocks"); + for entry in fs::read_dir(&dir)?.flatten() { + let p = entry.path(); + if let Some(stem) = p.file_stem().and_then(|s| s.to_str()) { + loot.insert(format!("minecraft:blocks/{stem}"), serde_json::from_slice(&fs::read(&p)?)?); + } + } + Ok(Self { + items, + order, + block_tags: load_tags(root, "block")?, + item_tags: load_tags(root, "item")?, + loot, + }) + } + pub fn get(&self, id: &str) -> Option<&ItemInfo> { + self.items.get(id) + } + fn block_matches(&self, spec: &str, block: &str) -> bool { + match spec.strip_prefix('#') { + Some(tag) => self.block_tags.get(tag).is_some_and(|s| s.contains(block)), + None => spec == block, + } + } + /// `Tool.getMiningSpeed` for the held item (1.0 without a tool component). + pub fn mining_speed(&self, held: Option<&ItemStack>, block: &str) -> f32 { + let Some(info) = held.and_then(|s| self.get(&s.item)) else { + return 1.0; + }; + for rule in &info.tool { + if let Some(speed) = rule.speed + && rule.blocks.iter().any(|b| self.block_matches(b, block)) + { + return speed; + } + } + if info.tool.is_empty() { + 1.0 + } else { + info.tool_default_speed + } + } + /// `Tool.isCorrectForDrops`. + pub fn correct_for_drops(&self, held: Option<&ItemStack>, block: &str) -> bool { + let Some(info) = held.and_then(|s| self.get(&s.item)) else { + return false; + }; + for rule in &info.tool { + if let Some(correct) = rule.correct + && rule.blocks.iter().any(|b| self.block_matches(b, block)) + { + return correct; + } + } + false + } + /// Evaluate the block's loot table for a player break without explosions. + pub fn block_drops( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + random: &mut LegacyRandom, + ) -> Vec { + let Some(block) = registry.state(state) else { + return vec![]; + }; + let name = block.name.trim_start_matches("minecraft:"); + let Some(table) = self.loot.get(&format!("minecraft:blocks/{name}")) else { + return vec![]; + }; + let ctx = LootContext { + items: self, + block: &block.name, + properties: &block.properties, + held, + }; + let mut out = Vec::new(); + for pool in table["pools"].as_array().into_iter().flatten() { + if !ctx.conditions(pool, random) { + continue; + } + let rolls = ctx.number(&pool["rolls"], random).max(0.0) as u32; + for _ in 0..rolls { + let mut produced = Vec::new(); + ctx.choose(pool["entries"].as_array().map_or(&[][..], Vec::as_slice), random, &mut produced); + for mut stack in produced { + ctx.modifiers(&pool["modifier"], &mut stack, random); + ctx.modifiers(&table["modifier"], &mut stack, random); + if stack.count > 0 { + out.push(stack); + } + } + } + } + out + } +} +struct LootContext<'a> { + items: &'a Items, + block: &'a str, + properties: &'a BTreeMap, + held: Option<&'a ItemStack>, +} +impl LootContext<'_> { + fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 { + match v { + Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, + Value::Object(o) => match o.get("type").and_then(Value::as_str).unwrap_or("minecraft:uniform") { + "minecraft:constant" => o.get("value").and_then(Value::as_f64).unwrap_or(0.0) as f32, + "minecraft:uniform" => { + let min = self.number(o.get("min").unwrap_or(&Value::Null), random); + let max = self.number(o.get("max").unwrap_or(&Value::Null), random); + // UniformGenerator.getFloat / getInt (Mth.nextInt) differ; use int for counts. + if max <= min { + min + } else { + min + random.next_float() * (max - min) + } + } + "minecraft:binomial" => { + let n = self.number(o.get("n").unwrap_or(&Value::Null), random) as u32; + let p = self.number(o.get("p").unwrap_or(&Value::Null), random); + (0..n).filter(|_| random.next_float() < p).count() as f32 + } + _ => 1.0, + }, + _ => 1.0, + } + } + fn int_number(&self, v: &Value, random: &mut LegacyRandom) -> i32 { + if let Value::Object(o) = v + && o.get("type").and_then(Value::as_str).unwrap_or("minecraft:uniform") == "minecraft:uniform" + { + let min = self.int_number(o.get("min").unwrap_or(&Value::Null), random); + let max = self.int_number(o.get("max").unwrap_or(&Value::Null), random); + return if max <= min { + min + } else { + min + random.next_int_bound(max - min + 1).unwrap_or(0) + }; + } + self.number(v, random).round() as i32 + } + fn condition(&self, c: &Value, random: &mut LegacyRandom) -> bool { + let (kind, c) = match c { + Value::String(s) => (s.as_str(), &Value::Null), + Value::Object(o) => (o.get("type").and_then(Value::as_str).unwrap_or(""), c), + _ => return true, + }; + match kind { + "minecraft:survives_explosion" => true, + "minecraft:tool/can_silk_touch" => false, + "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), + "minecraft:inverted" => !self.condition(&c["term"], random), + "minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, random)), + "minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, random)), + "minecraft:random_chance" => random.next_float() < self.number(&c["chance"], random), + "minecraft:table_bonus" => { + let chance = c["chances"][0].as_f64().unwrap_or(0.0) as f32; + random.next_float() < chance + } + "minecraft:match_block" | "minecraft:block_state_property" => { + let blocks_ok = match &c["blocks"].as_str().or(c["block"].as_str()) { + Some(spec) => self.items.block_matches(spec, self.block), + None => true, + }; + blocks_ok + && c["state"].as_object().into_iter().flatten().chain(c["properties"].as_object().into_iter().flatten()).all(|(k, v)| { + let have = self.properties.get(k).map(String::as_str); + match v { + Value::String(s) => have == Some(s.as_str()), + Value::Object(r) => { + let have: i64 = have.and_then(|h| h.parse().ok()).unwrap_or(0); + r.get("min").and_then(Value::as_i64).is_none_or(|m| have >= m) + && r.get("max").and_then(Value::as_i64).is_none_or(|m| have <= m) + } + _ => true, + } + }) + } + "minecraft:match_tool" => { + let items = &c["predicate"]["items"]; + match (self.held, items) { + (Some(h), Value::String(s)) => match s.strip_prefix('#') { + Some(tag) => self.items.item_tags.get(tag).is_some_and(|t| t.contains(&*h.item)), + None => **s == *h.item, + }, + _ => false, + } + } + "minecraft:entity_properties" => true, + _ => true, + } + } + fn conditions(&self, o: &Value, random: &mut LegacyRandom) -> bool { + if let Some(c) = o.get("condition") + && !self.condition(c, random) + { + return false; + } + o.get("conditions") + .and_then(Value::as_array) + .into_iter() + .flatten() + .all(|c| self.condition(c, random)) + } + /// Expand entries; returns whether an entry succeeded (for alternatives). + fn expand(&self, e: &Value, random: &mut LegacyRandom, out: &mut Vec<(i32, ItemStack, Value)>) -> bool { + if !self.conditions(e, random) { + return false; + } + match e["type"].as_str().unwrap_or("") { + "minecraft:item" => { + out.push(( + e["weight"].as_i64().unwrap_or(1) as i32, + ItemStack { + item: Arc::from(e["name"].as_str().unwrap_or("minecraft:air")), + count: 1, + damage: 0, + }, + e["modifier"].clone(), + )); + true + } + "minecraft:alternatives" => { + for child in e["children"].as_array().into_iter().flatten() { + if self.expand(child, random, out) { + return true; + } + } + false + } + "minecraft:group" => { + for child in e["children"].as_array().into_iter().flatten() { + self.expand(child, random, out); + } + true + } + "minecraft:sequence" => { + for child in e["children"].as_array().into_iter().flatten() { + if !self.expand(child, random, out) { + break; + } + } + true + } + "minecraft:empty" => { + out.push((e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from("minecraft:air"), count: 0, damage: 0 }, Value::Null)); + true + } + _ => false, + } + } + fn choose(&self, entries: &[Value], random: &mut LegacyRandom, produced: &mut Vec) { + let mut candidates = Vec::new(); + for e in entries { + self.expand(e, random, &mut candidates); + } + if candidates.is_empty() { + return; + } + let pick = if candidates.len() == 1 { + 0 + } else { + let total: i32 = candidates.iter().map(|c| c.0.max(0)).sum(); + let mut r = random.next_int_bound(total.max(1)).unwrap_or(0); + let mut chosen = 0; + for (i, c) in candidates.iter().enumerate() { + r -= c.0.max(0); + if r < 0 { + chosen = i; + break; + } + } + chosen + }; + let (_, mut stack, modifiers) = candidates.swap_remove(pick); + self.modifiers(&modifiers, &mut stack, random); + produced.push(stack); + } + fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut LegacyRandom) { + let list: Vec<&Value> = match m { + Value::Array(a) => a.iter().collect(), + Value::Object(_) => vec![m], + _ => return, + }; + for f in list { + if !self.conditions(f, random) { + continue; + } + match f["type"].as_str().or(f["function"].as_str()).unwrap_or("") { + "minecraft:set_count" => { + let n = self.int_number(&f["count"], random); + let base = if f["add"].as_bool() == Some(true) { stack.count as i32 } else { 0 }; + stack.count = (base + n).max(0) as u32; + } + "minecraft:limit_count" => { + let limit = &f["limit"]; + if let Some(min) = limit["min"].as_i64() { + stack.count = stack.count.max(min as u32); + } + if let Some(max) = limit["max"].as_i64() { + stack.count = stack.count.min(max as u32); + } + } + _ => {} + } + } + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 9c487c254..c7ef9bba4 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -1,17 +1,34 @@ -//! Shared resident-scene loading and queries for the native development client. +//! Horizon native client: resources, world streaming, rendering and the +//! bindings between the validated simulation pieces and the game loop. #![forbid(unsafe_code)] pub mod assets; pub mod attribute_updates; +pub mod audio; +pub mod biome; +pub mod blocks; +pub mod chunk; pub mod clock; +pub mod crafting; pub mod collisions; +pub mod entities; +pub mod environment; +pub mod gfx; pub mod health; +pub mod hud; pub mod hunger; pub mod input; +pub mod items; pub mod landing; +pub mod light; +pub mod mesher; pub mod models; pub mod motion; +pub mod particles; pub mod pose; +pub mod save; pub mod sprint; pub mod sprites; +pub mod streaming; +pub mod testgen; pub mod world; pub type Result = std::result::Result>; diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs new file mode 100644 index 000000000..61d808ad3 --- /dev/null +++ b/crates/horizon-client/src/light.rs @@ -0,0 +1,184 @@ +//! Sky and block light for one chunk, flood-filled over its 3x3 neighbourhood +//! with vanilla's rules: sky sources run down each column until an edge is +//! occluded (`ChunkSkyLightSources`), and light then spreads losing +//! `max(1, dampening)` per step (`LightEngine.getOpacity`). Light can travel at +//! most 15 blocks, so the 48-wide region determines the centre exactly, apart +//! from face-shape occlusion of partial blocks (slabs, stairs), which is not +//! modelled yet. +use crate::{ + blocks::BlockFacts, + chunk::{Chunk, HEIGHT, Light, SECTIONS, Section, index}, +}; +use std::{collections::VecDeque, sync::Arc}; + +const W: usize = 48; +#[derive(Clone, Copy)] +struct Cell { + dampening: u8, + emission: u8, +} +pub struct LightTables { + cells: Vec, +} +impl LightTables { + pub fn new(facts: &BlockFacts) -> Self { + Self { + cells: facts + .states + .iter() + .map(|s| Cell { + dampening: s.dampening.min(15), + emission: s.emission.min(15), + }) + .collect(), + } + } +} +/// `region[dz][dx]` holds the chunks around the centre (index 1,1). +pub fn light_chunk(region: &[[Option<&Chunk>; 3]; 3], tables: &LightTables) -> Vec> { + let center = region[1][1].expect("centre chunk"); + // Highest occupied section in the region bounds the work. + let mut top_section = 0; + for chunk in region.iter().flatten().flatten() { + for (i, s) in chunk.sections.iter().enumerate().rev() { + if !s.is_uniform(0) { + top_section = top_section.max(i + 1); + break; + } + } + } + let h = (top_section * 16 + 1).min(HEIGHT as usize); + let at = |x: usize, y: usize, z: usize| (y * W + z) * W + x; + let mut damp = vec![0u8; W * W * h]; + let mut sky = vec![0u8; W * W * h]; + let mut block = vec![0u8; W * W * h]; + let mut queue = VecDeque::new(); + let mut sky_queue = VecDeque::new(); + for (dz, row) in region.iter().enumerate() { + for (dx, chunk) in row.iter().enumerate() { + let Some(chunk) = chunk else { continue }; + for (si, section) in chunk.sections.iter().enumerate().take(top_section) { + if section.is_uniform(0) { + continue; + } + for i in 0..4096 { + let id = section.get(i) as usize; + let cell = tables.cells[id]; + let (lx, lz, ly) = (i & 15, (i >> 4) & 15, i >> 8); + let p = at(dx * 16 + lx, si * 16 + ly, dz * 16 + lz); + damp[p] = cell.dampening; + if cell.emission > 0 { + block[p] = cell.emission; + queue.push_back(p as u32); + } + } + } + } + } + // Columns of missing neighbour chunks contribute no light. + let present = |x: usize, z: usize| region[z / 16][x / 16].is_some(); + let mut lowest = vec![h as i32; W * W]; + for z in 0..W { + for x in 0..W { + if !present(x, z) { + continue; + } + let mut y = h as i32 - 1; + // The top layer (above the occupied range) is always open sky. + while y >= 0 && damp[at(x, y as usize, z)] == 0 { + sky[at(x, y as usize, z)] = 15; + y -= 1; + } + lowest[z * W + x] = y + 1; + } + } + for z in 0..W { + for x in 0..W { + if !present(x, z) { + continue; + } + let own = lowest[z * W + x]; + let mut deepest = own; + for (nx, nz) in [(x.wrapping_sub(1), z), (x + 1, z), (x, z.wrapping_sub(1)), (x, z + 1)] { + if nx < W && nz < W && present(nx, nz) { + deepest = deepest.max(lowest[nz * W + nx]); + } + } + // Seed propagation from the source cells that border darker cells. + let from = own.max(0) as usize; + let to = (deepest as usize).min(h - 1); + for y in from..=to { + if sky[at(x, y, z)] == 15 { + sky_queue.push_back(at(x, y, z) as u32); + } + } + } + } + let spread = |light: &mut [u8], queue: &mut VecDeque| { + while let Some(p) = queue.pop_front() { + let p = p as usize; + let level = light[p]; + if level <= 1 { + continue; + } + let x = p % W; + let z = (p / W) % W; + let y = p / (W * W); + let mut visit = |q: usize| { + let next = level.saturating_sub(damp[q].max(1)); + if next > light[q] { + light[q] = next; + queue.push_back(q as u32); + } + }; + if x > 0 { + visit(p - 1); + } + if x + 1 < W { + visit(p + 1); + } + if z > 0 { + visit(p - W); + } + if z + 1 < W { + visit(p + W); + } + if y > 0 { + visit(p - W * W); + } + if y + 1 < h { + visit(p + W * W); + } + } + }; + spread(&mut sky, &mut sky_queue); + spread(&mut block, &mut queue); + let mut sections = Vec::with_capacity(SECTIONS); + for (si, section) in center.sections.iter().enumerate() { + let mut out = (**section).clone(); + if si * 16 >= h { + out.light = Light::Uniform(0xF0); + } else { + let mut data = Box::new([0u8; 4096]); + for ly in 0..16 { + let y = si * 16 + ly; + if y >= h { + for i in 0..256 { + data[ly << 8 | i] = 0xF0; + } + continue; + } + for lz in 0..16 { + for lx in 0..16 { + let p = at(16 + lx, y, 16 + lz); + data[index(lx as i32, ly as i32, lz as i32)] = sky[p] << 4 | block[p]; + } + } + } + out.light = Light::Full(data); + } + out.compact(); + sections.push(Arc::new(out)); + } + sections +} diff --git a/crates/horizon-client/src/main.rs b/crates/horizon-client/src/main.rs index e165c7d77..a9fb16aa8 100644 --- a/crates/horizon-client/src/main.rs +++ b/crates/horizon-client/src/main.rs @@ -1,649 +1,9 @@ -//! Native Horizon development client. The scene and free camera are rendering -//! tools; they do not replace the authoritative gameplay implementation. +//! Horizon: native Rust client for Minecraft Java Edition 26.3 gameplay. #![forbid(unsafe_code)] -mod camera; -mod mesh; -mod render; -use assets::Assets; -use camera::Camera; -use horizon_client::{assets, collisions, models, sprites, world}; -use horizon_client::{ - clock::FixedStep, - motion::{MotionResources, MotionWorld, PlayerMotion}, - sprint::Keys, -}; -use horizon_core::geometry::Vec3; -use mesh::Mesh; -use render::Renderer; -use std::{ - collections::HashSet, - fs, - path::PathBuf, - sync::Arc, - time::{Duration, Instant}, -}; -use winit::{ - application::ApplicationHandler, - event::{DeviceEvent, DeviceId, ElementState, MouseButton, WindowEvent}, - event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, - keyboard::{KeyCode, PhysicalKey}, - window::{CursorGrabMode, Window, WindowId}, -}; -use world::TestWorld; -type Result = std::result::Result>; -struct Options { - resources: PathBuf, - radius: i32, - frames: Option, - report: Option, - timeout: Duration, - trace_input: bool, -} -impl Options { - fn read() -> Result> { - let sibling = std::env::current_exe()? - .parent() - .ok_or("missing executable directory")? - .join("resources"); - let mut options = Self { - resources: if sibling.join("horizon-resources.json").exists() { - sibling - } else { - PathBuf::from(".local/horizon-client/26.3") - }, - radius: 4, - frames: None, - report: None, - timeout: Duration::from_secs(90), - trace_input: false, - }; - let mut args = std::env::args().skip(1); - while let Some(argument) = args.next() { - if argument == "--trace-input" { - options.trace_input = true; - continue; - } - if argument == "--help" || argument == "-h" { - println!( - "Horizon native development client\n\n --resources PATH Prepared pinned resources\n --radius CHUNKS Controlled scene radius, 1..16 (default 4)\n --frames COUNT Exit after this many presented frames\n --smoke-report PATH Write a runtime report on exit\n --timeout-seconds N Deadline for a frame-limited run (default 90)\n --trace-input Log received keyboard, mouse-button and focus events\n\nControls: click to capture mouse; WASD move; Space/Shift rise/descend;\nCtrl boosts speed; arrow keys rotate; Esc releases mouse; Ctrl+Q quits; F3 shows diagnostics; F4 toggles camera collisions; F5 toggles walking test.\nWalking test: WASD move; Space jumps; Left Shift crouches; Left Ctrl or double-tap W starts sprinting; gravity and collisions at 20 ticks/s.\n\nThis is a controlled development scene. Walking includes landing damage, stored health, hunger and regeneration. Full death/respawn, interaction, saving and complete gameplay remain unfinished." - ); - return Ok(None); - } - let value = args - .next() - .ok_or_else(|| format!("missing value after {argument}"))?; - match argument.as_str() { - "--resources" => options.resources = value.into(), - "--radius" => { - options.radius = value.parse()?; - if !(1..=16).contains(&options.radius) { - return Err("radius must be 1..16 chunks".into()); - } - } - "--frames" => { - let frames = value.parse()?; - if frames == 0 { - return Err("frame count must be positive".into()); - } - options.frames = Some(frames); - } - "--smoke-report" => options.report = Some(value.into()), - "--timeout-seconds" => { - let seconds: u64 = value.parse()?; - if seconds == 0 { - return Err("timeout must be positive".into()); - } - options.timeout = Duration::from_secs(seconds); - } - _ => return Err(format!("unknown option {argument}").into()), - } - } - Ok(Some(options)) - } -} -struct App<'a> { - assets: &'a Assets, - world: TestWorld<'a>, - collision_binding: &'a horizon_world::block_collision::BlockCollisionRegistry<'a>, - collision_camera: bool, - motion_resources: &'a MotionResources, - player: Option, - motion_clock: FixedStep, - previous_player_position: Vec3, - eye_height: f32, - previous_eye_height: f32, - crouch_ticks: u64, - crouch_distance_cm: u64, - movement_ticks: u64, - sprint_ticks: u64, - sprint_distance_cm: u64, - walk_distance_cm: u64, - fall_damage_requests: u64, - last_requested_fall_damage: Option, - visibility: horizon_world::block_render::FaceVisibility, - mesh_revision: u64, - mesh: Mesh, - options: Options, - window: Option>, - renderer: Option, - camera: Camera, - keys: HashSet, - captured: bool, - focused: bool, - diagnostics: bool, - started: Instant, - previous: Instant, - next_redraw: Instant, - title_at: Instant, - title_frames: u64, - frames: u64, - error: Option, -} -impl App<'_> { - fn toggle_walking(&mut self) -> Result<()> { - if self.player.is_some() { - self.player = None; - } else { - let mut collision = collisions::SceneCollisions { - world: &self.world, - binding: self.collision_binding, - }; - if !collision.unobstructed(self.camera.collision_bounds())? { - eprintln!( - "Horizon: move the inspection camera to an unobstructed position before walking." - ); - return Ok(()); - } - let p = self.camera.position; - let feet = Vec3::new(p.x, p.y - f64::from(1.62_f32), p.z); - self.player = Some(PlayerMotion::new(self.motion_resources, feet)?); - self.previous_player_position = feet; - self.eye_height = 1.62; - self.previous_eye_height = self.eye_height; - self.collision_camera = false; - } - self.motion_clock.reset(); - self.previous = Instant::now(); - eprintln!("Horizon walking test: {}", self.player.is_some()); - Ok(()) - } - fn move_player(&mut self, elapsed: Duration) -> Result<()> { - let player = self.player.as_mut().ok_or("missing movement actor")?; - let keys = Keys { - forward: self.keys.contains(&KeyCode::KeyW), - backward: self.keys.contains(&KeyCode::KeyS), - left: self.keys.contains(&KeyCode::KeyA), - right: self.keys.contains(&KeyCode::KeyD), - jump: self.keys.contains(&KeyCode::Space), - shift: self.keys.contains(&KeyCode::ShiftLeft), - sprint: self.keys.contains(&KeyCode::ControlLeft), - }; - for _ in 0..self.motion_clock.advance(elapsed) { - self.previous_player_position = player.position; - player.yaw = (-self.camera.yaw.to_degrees()) as f32; - MotionWorld { - player, - scene: &mut self.world, - assets: self.assets, - collision_binding: self.collision_binding, - resources: self.motion_resources, - } - .controlled_simulation_tick(keys)?; - // Health is already updated synchronously during landing. These - // counters expose incoming requests; delivery consumers remain pending. - for event in player.events.drain(..) { - match event { - horizon_client::motion::MotionEvent::Fall( - horizon_client::landing::FallEvent::Damage { amount, .. }, - ) => { - self.fall_damage_requests += 1; - self.last_requested_fall_damage = Some(amount); - } - horizon_client::motion::MotionEvent::Health( - horizon_client::health::HealthEvent::Statistic { name, amount }, - ) => match name { - "sprint_one_cm" => self.sprint_distance_cm += amount as u64, - "walk_one_cm" => self.walk_distance_cm += amount as u64, - "crouch_one_cm" => self.crouch_distance_cm += amount as u64, - _ => {} - }, - _ => {} - } - } - // Camera.tick keeps float eye-height smoothing separate from physics. - self.previous_eye_height = self.eye_height; - self.eye_height += (player.dimensions.eye_height - self.eye_height) * 0.5; - self.crouch_ticks += u64::from(player.pose == horizon_client::pose::Pose::Crouching); - self.movement_ticks += 1; - self.sprint_ticks += u64::from(player.sprinting); - } - let from = self.previous_player_position; - let to = player.position; - let alpha = self.motion_clock.fraction(); - let eye = self.previous_eye_height - + (alpha as f32) * (self.eye_height - self.previous_eye_height); - self.camera.position = glam::DVec3::new( - from.x + (to.x - from.x) * alpha, - from.y + (to.y - from.y) * alpha + f64::from(eye), - from.z + (to.z - from.z) * alpha, - ); - if self.mesh_revision != self.world.revision { - let mesh = mesh::build(&self.world, self.assets, &mut self.visibility)?; - self.renderer - .as_mut() - .ok_or("missing renderer")? - .replace_mesh(&mesh.cubes, &mesh.models)?; - self.mesh = mesh; - self.mesh_revision = self.world.revision; - } - Ok(()) - } - fn fail(&mut self, event_loop: &ActiveEventLoop, error: impl ToString) { - self.error = Some(error.to_string()); - event_loop.exit(); - } - fn capture(&mut self, capture: bool) { - let Some(window) = &self.window else { - return; - }; - if capture { - self.captured = window - .set_cursor_grab(CursorGrabMode::Locked) - .or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined)) - .is_ok(); - } else { - let _ = window.set_cursor_grab(CursorGrabMode::None); - self.captured = false; - } - window.set_cursor_visible(!self.captured); - } - fn write_report(&self) -> Result<()> { - let Some(path) = &self.options.report else { - return Ok(()); - }; - let renderer = self.renderer.as_ref(); - let adapter = renderer.map(|r| { - serde_json::json!({ - "name": r.info.name, - "backend": format!("{:?}", r.info.backend), - "device_type": format!("{:?}", r.info.device_type), - "vendor": r.info.vendor, - "device": r.info.device, - }) - }); - let size = self.window.as_ref().map(|window| { - let size = window.inner_size(); - [size.width, size.height] - }); - let mut report = serde_json::json!({ - "schema": 1, - "project": "Horizon", - "scope": "Native resident-scene renderer with inspection camera and optional fixed-rate dry walking test; full gameplay remains unfinished", - "os": std::env::consts::OS, - "arch": std::env::consts::ARCH, - "adapter": adapter, - "window_size": size, - "presented_frames": self.frames, - "elapsed_seconds": self.started.elapsed().as_secs_f64(), - "resident_chunks": self.world.chunks.len(), - "merged_quads": self.mesh.cubes.len(), - "model_quads": self.mesh.models.len(), - "visible_model_faces": self.mesh.visible_faces, - "culled_model_faces": self.mesh.culled_faces, - "model_blocks": self.mesh.model_blocks, - "model_gallery": self.assets.model_gallery, - "sprite_layers": self.assets.texture_layers, - "animated_sprites": self.assets.animations.len(), - "animation_uploads": self.renderer.as_ref().map_or(0, |r| r.animation_uploads), - "camera_position": self.camera.position.to_array(), - "camera_yaw": self.camera.yaw, - "camera_pitch": self.camera.pitch, - "collision_camera": self.collision_camera, - "walking": self.player.is_some(), - "movement_ticks": self.movement_ticks, - "player_position": self.player.as_ref().map(|p| [p.position.x,p.position.y,p.position.z]), - "player_velocity": self.player.as_ref().map(|p| [p.velocity.x,p.velocity.y,p.velocity.z]), - "player_on_ground": self.player.as_ref().map(|p| p.ground.on_ground), - "player_health": self.player.as_ref().map(|p| p.health.health()), - "player_absorption": self.player.as_ref().map(|p| p.health.absorption()), - "player_dead": self.player.as_ref().map(|p| p.health.dead), - "player_hurt_cooldown": self.player.as_ref().map(|p| p.health.hurt.cooldown), - "player_fall_distance": self.player.as_ref().map(|p| p.fall_distance), - "fall_damage_requests": self.fall_damage_requests, - "last_requested_fall_damage": self.last_requested_fall_damage, - "world_revision": self.world.revision, - "mesh_revision": self.mesh_revision, - "error": self.error, - }); - if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - fs::create_dir_all(parent)?; - } - report["player_food"] = serde_json::json!(self.player.as_ref().map(|p| p.health.food.food)); - report["player_saturation"] = - serde_json::json!(self.player.as_ref().map(|p| p.health.food.saturation)); - report["player_exhaustion"] = - serde_json::json!(self.player.as_ref().map(|p| p.health.food.exhaustion)); - report["player_food_timer"] = - serde_json::json!(self.player.as_ref().map(|p| p.health.food.timer)); - report["player_sprinting"] = serde_json::json!(self.player.as_ref().map(|p| p.sprinting)); - report["player_sprint_trigger"] = - serde_json::json!(self.player.as_ref().map(|p| p.sprint_input.trigger_time)); - report["player_pose"] = serde_json::json!(self.player.as_ref().map(|p| p.pose.name())); - report["player_local_crouching"] = - serde_json::json!(self.player.as_ref().map(|p| p.local_crouching)); - report["player_shift"] = serde_json::json!(self.player.as_ref().map(|p| p.shift_key_down)); - report["player_dimensions"] = serde_json::json!(self.player.as_ref().map(|p| [ - p.dimensions.width, - p.dimensions.height, - p.dimensions.eye_height - ])); - report["camera_eye_height"] = serde_json::json!(self.eye_height); - report["crouch_ticks"] = serde_json::json!(self.crouch_ticks); - report["crouch_distance_cm"] = serde_json::json!(self.crouch_distance_cm); - report["sprint_ticks"] = serde_json::json!(self.sprint_ticks); - report["sprint_distance_cm"] = serde_json::json!(self.sprint_distance_cm); - report["walk_distance_cm"] = serde_json::json!(self.walk_distance_cm); - fs::write(path, serde_json::to_vec_pretty(&report)?)?; - Ok(()) - } -} -impl ApplicationHandler for App<'_> { - fn resumed(&mut self, event_loop: &ActiveEventLoop) { - if self.window.is_some() { - return; - } - let window = match event_loop.create_window( - Window::default_attributes() - .with_title("Horizon — Development Client") - .with_inner_size(winit::dpi::LogicalSize::new(1280.0, 800.0)), - ) { - Ok(window) => Arc::new(window), - Err(error) => { - self.fail(event_loop, error); - return; - } - }; - match pollster::block_on(Renderer::new( - window.clone(), - self.assets, - &self.mesh.cubes, - &self.mesh.models, - ((self.options.radius + 1) * 16) as f32, - )) { - Ok(renderer) => self.renderer = Some(renderer), - Err(error) => { - self.fail(event_loop, error); - return; - } - } - self.window = Some(window); - self.previous = Instant::now(); - self.next_redraw = self.previous; - self.title_at = self.previous; - } - fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { - if self.options.trace_input - && matches!( - event, - WindowEvent::Focused(_) - | WindowEvent::KeyboardInput { .. } - | WindowEvent::MouseInput { .. } - ) - { - eprintln!("Horizon input: {event:?}"); - } - if self.window.as_ref().is_none_or(|window| window.id() != id) { - return; - } - match event { - WindowEvent::CloseRequested => event_loop.exit(), - WindowEvent::Resized(size) => { - if let Some(renderer) = &mut self.renderer { - renderer.resize(size.width, size.height); - } - self.next_redraw = Instant::now(); - } - WindowEvent::Focused(focused) => { - self.focused = focused; - if !focused { - self.keys.clear(); - self.capture(false); - } - self.previous = Instant::now(); - self.motion_clock.reset(); - } - WindowEvent::MouseInput { - state: ElementState::Pressed, - button: MouseButton::Left, - .. - } => self.capture(true), - WindowEvent::KeyboardInput { event, .. } => { - if let PhysicalKey::Code(key) = event.physical_key { - if event.state == ElementState::Pressed { - self.keys.insert(key); - if key == KeyCode::Escape { - self.capture(false); - } - if key == KeyCode::F5 - && !event.repeat - && let Err(error) = self.toggle_walking() - { - self.fail(event_loop, error); - } - if key == KeyCode::F4 && !event.repeat && self.player.is_none() { - if self.collision_camera { - self.collision_camera = false; - } else { - let mut collision = collisions::SceneCollisions { - world: &self.world, - binding: self.collision_binding, - }; - match collision.unobstructed(self.camera.collision_bounds()) { - Ok(clear) => self.collision_camera = clear, - Err(error) => self.fail(event_loop, error), - } - } - eprintln!( - "Horizon inspection camera collisions: {}", - self.collision_camera - ); - } - if key == KeyCode::F3 && !event.repeat { - self.diagnostics = !self.diagnostics; - if !self.diagnostics { - self.window - .as_ref() - .unwrap() - .set_title("Horizon — Development Client"); - } - } - if key == KeyCode::KeyQ - && (self.keys.contains(&KeyCode::ControlLeft) - || self.keys.contains(&KeyCode::ControlRight)) - { - event_loop.exit(); - } - } else { - self.keys.remove(&key); - } - } - } - WindowEvent::RedrawRequested => { - let now = Instant::now(); - let elapsed = now.duration_since(self.previous); - let seconds = elapsed.as_secs_f64().min(0.1); - self.previous = now; - if self.focused && self.player.is_some() { - self.camera.turn(&self.keys, seconds); - if let Err(error) = self.move_player(elapsed) { - self.fail(event_loop, error); - return; - } - } else if self.focused { - let from = self.camera.position; - let bounds = self.camera.collision_bounds(); - self.camera.update(&self.keys, seconds); - if self.collision_camera { - let delta = self.camera.position - from; - let mut collision = collisions::SceneCollisions { - world: &self.world, - binding: self.collision_binding, - }; - match collision.resolve( - bounds, - horizon_core::geometry::Vec3::new(delta.x, delta.y, delta.z), - 0.0, - false, - ) { - Ok(movement) => { - self.camera.position = - from + glam::DVec3::new(movement.x, movement.y, movement.z) - } - Err(error) => { - self.fail(event_loop, error); - return; - } - } - } - } - let result = self.renderer.as_mut().unwrap().render(&self.camera); - match result { - Ok(true) => { - self.frames += 1; - self.next_redraw = Instant::now(); - if self - .options - .frames - .is_some_and(|target| self.frames >= target) - { - event_loop.exit(); - } - if self.diagnostics && self.title_at.elapsed() >= Duration::from_secs(1) { - let fps = (self.frames - self.title_frames) as f64 - / self.title_at.elapsed().as_secs_f64(); - let health = self.player.as_ref().map_or_else(String::new, |p| { - format!( - " | Health {} | Food {} | Sprint {} | Pose {}{}", - p.health.health(), - p.health.food.food, - p.sprinting, - p.pose.name(), - if p.health.dead_or_dying() { - " (dead)" - } else { - "" - } - ) - }); - self.window.as_ref().unwrap().set_title(&format!( - "Horizon — Development | {fps:.0} FPS | {} chunks | {} quads{health}", - self.world.chunks.len(), - self.mesh.cubes.len() - )); - self.title_at = Instant::now(); - self.title_frames = self.frames; - } - } - Ok(false) => self.next_redraw = Instant::now() + Duration::from_millis(100), - Err(error) => self.fail(event_loop, error), - } - } - _ => {} - } - } - fn device_event(&mut self, _: &ActiveEventLoop, _: DeviceId, event: DeviceEvent) { - if self.captured - && self.focused - && let DeviceEvent::MouseMotion { delta: (x, y) } = event - { - self.camera.look(x, y); - } - } - fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { - if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout { - self.fail(event_loop, "frame-limited client run timed out"); - return; - } - if Instant::now() >= self.next_redraw { - if let Some(window) = &self.window { - window.request_redraw(); - } - event_loop.set_control_flow(if self.options.frames.is_some() { - ControlFlow::WaitUntil(self.started + self.options.timeout) - } else { - ControlFlow::Wait - }); - } else { - event_loop.set_control_flow(ControlFlow::WaitUntil(self.next_redraw)); - } - } -} -fn run() -> Result<()> { - let Some(options) = Options::read()? else { - return Ok(()); - }; - let assets = Assets::load(&options.resources).map_err(|error| { - format!("{error}\nPrepare pinned resources with: python3 tools/prepare_native_client.py") - })?; - let world = TestWorld::new(&assets, options.radius)?; - let collision_binding = collisions::load(&options.resources, &assets.registry)?; - let motion_resources = MotionResources::load(&options.resources, &assets)?; - let mut visibility = models::load_visibility(&options.resources, &assets.registry)?; - let mesh = mesh::build(&world, &assets, &mut visibility)?; - eprintln!( - "Horizon development scene: {} resident chunks, {} merged cube faces, {} baked model faces.\nClick to capture mouse; WASD/Space/Shift move; arrows rotate; F4 toggles camera collisions; F5 toggles walking test; Esc releases; Ctrl+Q quits.", - world.chunks.len(), - mesh.cubes.len(), - mesh.models.len() - ); - let now = Instant::now(); - let mut app = App { - assets: &assets, - world, - collision_binding: &collision_binding, - collision_camera: false, - motion_resources: &motion_resources, - player: None, - motion_clock: FixedStep::default(), - previous_player_position: Vec3::ZERO, - eye_height: 1.62, - previous_eye_height: 1.62, - crouch_ticks: 0, - crouch_distance_cm: 0, - movement_ticks: 0, - sprint_ticks: 0, - sprint_distance_cm: 0, - walk_distance_cm: 0, - fall_damage_requests: 0, - last_requested_fall_damage: None, - visibility, - mesh_revision: 0, - mesh, - options, - window: None, - renderer: None, - camera: Camera::default(), - keys: HashSet::new(), - captured: false, - focused: true, - diagnostics: false, - started: now, - previous: now, - next_redraw: now, - title_at: now, - title_frames: 0, - frames: 0, - error: None, - }; - EventLoop::new()?.run_app(&mut app)?; - app.write_report()?; - if let Some(error) = app.error { - return Err(error.into()); - } - Ok(()) -} +mod game; + fn main() { - if let Err(error) = run() { + if let Err(error) = game::run() { eprintln!("Horizon: {error}"); std::process::exit(1); } diff --git a/crates/horizon-client/src/mesh.rs b/crates/horizon-client/src/mesh.rs deleted file mode 100644 index 37213bf29..000000000 --- a/crates/horizon-client/src/mesh.rs +++ /dev/null @@ -1,377 +0,0 @@ -//! Resident blockstate model meshing. Greedy rectangles preserve the texture -//! and signed UV basis of eligible unit-cube faces; other geometry stays baked. -use crate::{ - Result, - assets::Assets, - models::{self, CubeStyle, ModelInstance}, - world::TestWorld, -}; -use horizon_core::{geometry::Direction, position::BlockPos}; -use horizon_world::block_render::FaceVisibility; - -#[repr(C)] -#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] -pub struct Quad { - pub origin: [f32; 3], - pub extent: [f32; 2], - pub face: u32, - pub layer: u32, - pub uv_origin: [f32; 2], - pub uv_u: [f32; 2], - pub uv_v: [f32; 2], - pub shade: f32, -} -pub struct Mesh { - pub cubes: Vec, - pub models: Vec, - pub visible_faces: usize, - pub culled_faces: usize, - pub model_blocks: usize, -} -fn position(face: usize, plane: usize, u: usize, v: usize) -> [usize; 3] { - match face { - 0 | 1 => [u, plane, v], - 2 | 3 => [u, v, plane], - _ => [plane, v, u], - } -} -pub fn build( - world: &TestWorld<'_>, - assets: &Assets, - visibility: &mut FaceVisibility, -) -> Result { - let mut mesh = Mesh { - cubes: Vec::new(), - models: Vec::new(), - visible_faces: 0, - culled_faces: 0, - model_blocks: 0, - }; - for &(cx, cz) in world.chunks.keys() { - let mut masks = vec![[None; 256]; 6 * 16]; - for y in 0..16 { - for z in 0..16 { - for x in 0..16 { - let pos = BlockPos::new(cx * 16 + x, y, cz * 16 + z); - let state = world.block(pos.x, pos.y, pos.z); - if world.is_air(state) { - continue; - } - mesh.model_blocks += 1; - let selected = assets.model_catalog.collect(state, pos)?; - let mut visible = [false; 6]; - for direction in Direction::ALL { - let [dx, dy, dz] = direction.normal(); - let neighbor = world.block(pos.x + dx, pos.y + dy, pos.z + dz); - visible[direction as usize] = - visibility.should_render_face(state, neighbor, direction, true)?; - } - if selected.len() == 1 - && let Some(styles) = selected[0].1.cube - { - for (face, style) in styles.into_iter().enumerate() { - if !visible[face] { - mesh.culled_faces += 1; - continue; - } - mesh.visible_faces += 1; - let (plane, u, v) = match face { - 0 | 1 => (y, x, z), - 2 | 3 => (z, x, y), - _ => (x, z, y), - }; - masks[face * 16 + plane as usize][(u + 16 * v) as usize] = Some(style); - } - } else { - for (_, model) in selected { - for face in &model.faces { - if face.quad.cull.is_some_and(|d| !visible[d as usize]) { - mesh.culled_faces += 1; - continue; - } - mesh.visible_faces += 1; - mesh.models.push(models::instance(face, pos)); - } - } - } - } - } - } - for (index, mask) in masks.iter_mut().enumerate() { - merge(mask, index / 16, index % 16, cx, cz, &mut mesh.cubes); - } - } - Ok(mesh) -} -fn merge( - mask: &mut [Option; 256], - face: usize, - plane: usize, - cx: i32, - cz: i32, - quads: &mut Vec, -) { - for v in 0..16 { - let mut u = 0; - while u < 16 { - let Some(style) = mask[u + v * 16] else { - u += 1; - continue; - }; - let mut width = 1; - while u + width < 16 && mask[u + width + v * 16] == Some(style) { - width += 1; - } - let mut height = 1; - while v + height < 16 - && (u..u + width).all(|x| mask[x + (v + height) * 16] == Some(style)) - { - height += 1; - } - for y in v..v + height { - for x in u..u + width { - mask[x + y * 16] = None; - } - } - let p = position(face, plane + usize::from(face % 2 == 1), u, v); - let [a, b, c, d, e, f] = style.uv.map(f32::from); - quads.push(Quad { - origin: [ - (cx * 16 + p[0] as i32) as f32, - p[1] as f32, - (cz * 16 + p[2] as i32) as f32, - ], - extent: [width as f32, height as f32], - face: face as u32, - layer: style.layer, - uv_origin: [a, b], - uv_u: [c, d], - uv_v: [e, f], - shade: f32::from_bits(style.shade_bits), - }); - u += width; - } - } -} - -#[cfg(test)] -fn index(x: usize, y: usize, z: usize) -> usize { - x + 18 * (z + 18 * y) -} -#[cfg(test)] -fn mesh_chunk(cells: &[i32; 18 * 18 * 18], cx: i32, cz: i32, quads: &mut Vec) { - for face in 0..6 { - for plane in 0..16 { - let mut mask = [None; 256]; - for v in 0..16 { - for u in 0..16 { - let p = position(face, plane + 1, u + 1, v + 1); - let mut adjacent = p; - let axis = match face { - 0 | 1 => 1, - 2 | 3 => 2, - _ => 0, - }; - if face % 2 == 0 { - adjacent[axis] -= 1; - } else { - adjacent[axis] += 1; - } - let layer = cells[index(p[0], p[1], p[2])]; - if layer >= 0 && cells[index(adjacent[0], adjacent[1], adjacent[2])] < 0 { - mask[u + 16 * v] = Some(CubeStyle { - layer: layer as u32, - uv: [0, 1, 1, 0, 0, -1], - shade_bits: 1f32.to_bits(), - }); - } - } - } - merge(&mut mask, face, plane, cx, cz, quads); - } - } -} -#[cfg(test)] -mod tests { - use super::*; - use std::collections::BTreeSet; - - // Compare rectangles expanded to unit faces against direct voxel adjacency. - // The reference does not use the mesher's plane masks or coordinate helper. - fn verify(cells: &[i32; 18 * 18 * 18], cx: i32, cz: i32) -> Vec { - let mut expected = BTreeSet::new(); - let directions = [ - [0, -1, 0], - [0, 1, 0], - [0, 0, -1], - [0, 0, 1], - [-1, 0, 0], - [1, 0, 0], - ]; - for y in 1..=16 { - for z in 1..=16 { - for x in 1..=16 { - let layer = cells[index(x, y, z)]; - if layer < 0 { - continue; - } - for (face, [dx, dy, dz]) in directions.iter().enumerate() { - let neighbor = [ - (x as i32 + dx) as usize, - (y as i32 + dy) as usize, - (z as i32 + dz) as usize, - ]; - if cells[index(neighbor[0], neighbor[1], neighbor[2])] < 0 { - expected.insert(( - x as i32 - 1 + cx * 16, - y as i32 - 1, - z as i32 - 1 + cz * 16, - face as u32, - layer as u32, - )); - } - } - } - } - } - let mut quads = Vec::new(); - mesh_chunk(cells, cx, cz, &mut quads); - let mut actual = BTreeSet::new(); - for quad in &quads { - assert!( - quad.extent - .iter() - .all(|&e| (1.0..=16.0).contains(&e) && e.fract() == 0.0) - ); - for v in 0..quad.extent[1] as i32 { - for u in 0..quad.extent[0] as i32 { - let [x, y, z] = quad.origin.map(|n| n as i32); - let (x, y, z) = match quad.face { - 0 => (x + u, y, z + v), - 1 => (x + u, y - 1, z + v), - 2 => (x + u, y + v, z), - 3 => (x + u, y + v, z - 1), - 4 => (x, y + v, z + u), - 5 => (x - 1, y + v, z + u), - _ => panic!("invalid face"), - }; - assert!( - actual.insert((x, y, z, quad.face, quad.layer)), - "overlapping faces" - ); - } - } - } - assert_eq!(actual, expected); - quads - } - - #[test] - fn merging_preserves_rotation_mirroring_shade_and_texture() { - let bases = [ - [0, 0, 1, 0, 0, 1], - [1, 0, 0, 1, -1, 0], - [1, 1, -1, 0, 0, -1], - [0, 1, 0, -1, 1, 0], - [1, 0, -1, 0, 0, 1], - [0, 1, 1, 0, 0, -1], - [0, 0, 0, 1, 1, 0], - [1, 1, 0, -1, -1, 0], - ]; - let original: [Option; 256] = std::array::from_fn(|i| { - (i % 17 != 0).then_some(CubeStyle { - layer: (i / 64) as u32, - uv: bases[(i / 4) % 8], - shade_bits: if i % 5 == 0 { 0.5f32 } else { 1f32 }.to_bits(), - }) - }); - for face in 0..6 { - let mut mask = original; - let mut quads = Vec::new(); - merge(&mut mask, face, 4, -2, 3, &mut quads); - let mut covered = [false; 256]; - for q in quads { - let p = [q.origin[0] + 32.0, q.origin[1], q.origin[2] - 48.0]; - let (u0, v0) = match face { - 0 | 1 => (p[0] as usize, p[2] as usize), - 2 | 3 => (p[0] as usize, p[1] as usize), - _ => (p[2] as usize, p[1] as usize), - }; - for dv in 0..q.extent[1] as usize { - for du in 0..q.extent[0] as usize { - let index = u0 + du + 16 * (v0 + dv); - assert!(!covered[index]); - covered[index] = true; - let style = original[index].unwrap(); - assert_eq!(q.layer, style.layer); - assert_eq!(q.shade.to_bits(), style.shade_bits); - let [a, b, c, d, e, f] = style.uv.map(f32::from); - let local = [a + c * 0.25 + e * 0.75, b + d * 0.25 + f * 0.75]; - let merged: [f32; 2] = std::array::from_fn(|axis| { - q.uv_origin[axis] - + q.uv_u[axis] * (du as f32 + 0.25) - + q.uv_v[axis] * (dv as f32 + 0.75) - }); - assert_eq!( - local.map(|v| v.rem_euclid(1.0)), - merged.map(|v| v.rem_euclid(1.0)) - ); - } - } - } - assert_eq!(covered, original.map(|v| v.is_some())); - } - } - - #[test] - fn empty_solid_and_neighbor_seams() { - let mut cells = [-1; 18 * 18 * 18]; - assert!(verify(&cells, 0, 0).is_empty()); - for y in 1..=16 { - for z in 1..=16 { - for x in 1..=16 { - cells[index(x, y, z)] = 3; - } - } - } - assert_eq!(verify(&cells, -3, 2).len(), 6); - // A solid neighbor removes only the shared boundary, including corners. - for y in 1..=16 { - for z in 1..=16 { - cells[index(17, y, z)] = 4; - } - } - assert_eq!(verify(&cells, -3, 2).len(), 5); - cells.fill(3); - assert!(verify(&cells, 1, -2).is_empty()); - } - - #[test] - fn cavities_material_boundaries_and_random_neighbors() { - let mut state = 0x183d_994e_058b_9432_u64; - for pattern in 0..12 { - let mut cells = [-1; 18 * 18 * 18]; - for y in 0..18 { - for z in 0..18 { - for x in 0..18 { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - cells[index(x, y, z)] = match pattern { - 0 => { - if x == 8 && y == 8 && z == 8 { - -1 - } else { - 0 - } - } - 1 => ((x + y + z) % 3) as i32, - _ => (state % 7) as i32 - 1, - }; - } - } - } - verify(&cells, pattern - 6, 3 - pattern); - } - } -} diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs new file mode 100644 index 000000000..04421b208 --- /dev/null +++ b/crates/horizon-client/src/mesher.rs @@ -0,0 +1,671 @@ +//! Section meshing on worker threads. Faces follow the baked blockstate models +//! with vanilla's neighbour culling; vertex lighting follows +//! `ModelBlockRenderer`'s smooth-lighting blend (four samples per corner, zero +//! samples replaced by the centre) and ambient-occlusion shade brightness. +//! Fluids follow `FluidRenderer` (corner heights, still/flowing sprites). +use crate::{ + assets::Assets, + biome::Biomes, + blocks::{BlockFacts, Fluid, RenderShape}, + chunk::{Chunk, MIN_Y}, + models::catalog::BakedFace, +}; +use horizon_core::{geometry::Direction, position::BlockPos}; +use horizon_world::{block_render::FaceVisibility, registry::BlockStateId}; +use std::sync::Arc; + +#[repr(C)] +#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Vertex { + /// Section-relative position. + pub pos: [f32; 3], + pub uv: [f32; 2], + pub layer: u32, + /// RGBA8: tint multiplied by directional shade and ambient occlusion. + pub color: u32, + /// Smooth light, 16x fixed point: sky in bits 0..8, block in bits 8..16. + pub light: u32, +} +#[derive(Default)] +pub struct SectionMesh { + pub solid: Vec, + pub translucent: Vec, +} +#[derive(Clone, Copy, PartialEq, Eq)] +enum Tint { + None, + Grass, + TallGrassUpper, + Foliage, + DryFoliage, + Water, + Constant(u32), + Redstone(u8), + Stem(u8), +} +/// Per-state data the mesher needs on every block, flattened for speed. +#[derive(Clone, Copy)] +struct Info { + solid: bool, + /// `isCollisionShapeFullBlock` drives the 0.2 AO shade brightness. + full: bool, + /// Side blocks that are transparent let the AO corner sample through. + translucent: bool, + emission: u8, + fluid: Fluid, + level: u8, + model: bool, + tints: [Tint; 2], +} +pub struct MeshTables { + info: Vec, + pub visibility: FaceVisibility, + water_still: u32, + water_flow: u32, + lava_still: u32, + lava_flow: u32, +} +fn redstone_color(power: u8) -> u32 { + // RedstoneWireBlock.COLORS + let f = f32::from(power) / 15.0; + let r = f * 0.6 + if f > 0.0 { 0.4 } else { 0.3 }; + let g = (f * f * 0.7 - 0.5).clamp(0.0, 1.0); + let b = (f * f * 0.6 - 0.7).clamp(0.0, 1.0); + ((r * 255.0) as u32) << 16 | ((g * 255.0) as u32) << 8 | (b * 255.0) as u32 +} +impl MeshTables { + pub fn new( + assets: &Assets, + facts: &BlockFacts, + visibility: FaceVisibility, + ) -> crate::Result { + let layer = |name: &str| -> crate::Result { + assets + .sprite_layers + .get(name) + .copied() + .ok_or_else(|| format!("missing fluid sprite {name}").into()) + }; + let info = facts + .states + .iter() + .enumerate() + .map(|(id, s)| { + let props = assets + .registry + .state(BlockStateId(id as u32)) + .map(|s| &s.properties); + let prop = |k: &str| -> u8 { + props + .and_then(|p| p.get(k)) + .and_then(|v| v.parse().ok()) + .unwrap_or(0) + }; + let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name); + let tints = match name { + "large_fern" | "tall_grass" => { + if props.and_then(|p| p.get("half")).map(String::as_str) == Some("upper") { + [Tint::TallGrassUpper; 2] + } else { + [Tint::Grass; 2] + } + } + "fern" | "short_grass" | "potted_fern" | "bush" | "grass_block" + | "sugar_cane" => [Tint::Grass; 2], + "pink_petals" | "wildflowers" => [Tint::None, Tint::Grass], + "spruce_leaves" => [Tint::Constant(0x61_9961); 2], + "birch_leaves" => [Tint::Constant(0x80_A755); 2], + "oak_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" + | "vine" | "mangrove_leaves" => [Tint::Foliage; 2], + "leaf_litter" => [Tint::DryFoliage; 2], + "water_cauldron" | "water" | "bubble_column" => [Tint::Water; 2], + "redstone_wire" => [Tint::Redstone(prop("power")); 2], + "attached_melon_stem" | "attached_pumpkin_stem" => { + [Tint::Constant(0xE0_C71C); 2] + } + "melon_stem" | "pumpkin_stem" => [Tint::Stem(prop("age")); 2], + "lily_pad" => [Tint::Constant(0x20_8030); 2], + _ => [Tint::None; 2], + }; + Info { + solid: s.solid_render, + full: s.full_collision, + translucent: !s.solid_render || s.dampening == 0, + emission: s.emission, + fluid: s.fluid, + level: s.fluid_level, + model: s.render_shape == RenderShape::Model, + tints, + } + }) + .collect(); + Ok(Self { + info, + visibility, + water_still: layer("minecraft:block/water_still")?, + water_flow: layer("minecraft:block/water_flow")?, + lava_still: layer("minecraft:block/lava_still")?, + lava_flow: layer("minecraft:block/lava_flow")?, + }) + } +} +const P: usize = 18; +#[inline] +fn pi(x: i32, y: i32, z: i32) -> usize { + ((y + 1) as usize * P + (z + 1) as usize) * P + (x + 1) as usize +} +/// Blocks and light of one section plus a one-block border. +struct Padded { + blocks: Vec, + light: Vec, +} +impl Padded { + fn new(region: &[[Option<&Chunk>; 3]; 3], sy: i32) -> Self { + let mut blocks = vec![0u16; P * P * P]; + let mut light = vec![0u8; P * P * P]; + let base_y = MIN_Y + sy * 16; + for y in -1..17 { + let wy = base_y + y; + for z in -1..17i32 { + for x in -1..17i32 { + let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize]; + let i = pi(x, y, z); + if let Some(c) = chunk { + blocks[i] = c.get(x & 15, wy, z & 15); + light[i] = c.light(x & 15, wy, z & 15); + } else { + light[i] = 0xF0; + } + } + } + } + Self { blocks, light } + } +} +#[derive(Clone, Copy)] +struct Colors { + grass: [u32; 256], + tall_upper: [u32; 256], + foliage: [u32; 256], + dry: [u32; 256], + water: [u32; 256], +} +fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y: i32) -> Colors { + // Vanilla blends over a (2r+1)^2 area; r = 2 is the default option. + const R: i32 = 2; + let biome_at = |x: i32, z: i32| -> u16 { + region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize] + .map_or(0, |c| c.biome(x & 15, y, z & 15)) + }; + let mut colors = Colors { + grass: [0; 256], + tall_upper: [0; 256], + foliage: [0; 256], + dry: [0; 256], + water: [0; 256], + }; + let avg = |f: &dyn Fn(u16, i32, i32) -> u32, x: i32, z: i32| -> u32 { + let (mut r, mut g, mut b) = (0, 0, 0); + for dz in -R..=R { + for dx in -R..=R { + let c = f(biome_at(x + dx, z + dz), x + dx, z + dz); + r += c >> 16 & 255; + g += c >> 8 & 255; + b += c & 255; + } + } + let n = ((2 * R + 1) * (2 * R + 1)) as u32; + (r / n) << 16 | (g / n) << 8 | b / n + }; + for z in 0..16 { + for x in 0..16 { + let i = (z * 16 + x) as usize; + let (wx, wz) = (cx * 16 + x, cz * 16 + z); + colors.grass[i] = avg( + &|b, dx, dz| biomes.grass(b, f64::from(wx + dx - x), f64::from(wz + dz - z)), + x, + z, + ); + colors.tall_upper[i] = colors.grass[i]; + colors.foliage[i] = avg(&|b, _, _| biomes.get(b).foliage, x, z); + colors.dry[i] = avg(&|b, _, _| biomes.get(b).dry_foliage, x, z); + colors.water[i] = avg(&|b, _, _| biomes.get(b).water, x, z); + } + } + colors +} +fn shade(direction: horizon_assets::model::Direction) -> f32 { + use horizon_assets::model::Direction as D; + match direction { + D::Down => 0.5, + D::Up => 1.0, + D::North | D::South => 0.8, + D::West | D::East => 0.6, + } +} +fn pack_color(rgb: u32, brightness: f32) -> u32 { + let r = ((rgb >> 16 & 255) as f32 * brightness) as u32; + let g = ((rgb >> 8 & 255) as f32 * brightness) as u32; + let b = ((rgb & 255) as f32 * brightness) as u32; + 0xFF00_0000 | b << 16 | g << 8 | r +} +fn pack_light(sky: f32, block: f32) -> u32 { + (sky * 16.0).clamp(0.0, 255.0) as u32 | ((block * 16.0).clamp(0.0, 255.0) as u32) << 8 +} +pub struct Mesher<'a> { + pub assets: &'a Assets, + pub tables: &'a MeshTables, + pub biomes: &'a Biomes, + pub visibility: FaceVisibility, +} +impl Mesher<'_> { + /// `region[dz][dx]` are the chunks around the meshed column (centre 1,1). + pub fn mesh(&mut self, region: &[[Option<&Chunk>; 3]; 3], sy: i32) -> SectionMesh { + let mut out = SectionMesh::default(); + let center = region[1][1].expect("centre chunk"); + let section = ¢er.sections[sy as usize]; + if section.is_uniform(0) { + return out; + } + let pad = Padded::new(region, sy); + let base_y = MIN_Y + sy * 16; + let colors = blend(region, self.biomes, center.x, center.z, base_y + 8); + let info = &self.tables.info; + for y in 0..16 { + for z in 0..16 { + for x in 0..16 { + let id = pad.blocks[pi(x, y, z)]; + if id == 0 { + continue; + } + let state = info[id as usize]; + if state.solid + && Direction::ALL.iter().all(|d| { + let [dx, dy, dz] = d.normal(); + info[pad.blocks[pi(x + dx, y + dy, z + dz)] as usize].solid + }) + { + continue; + } + if state.fluid != Fluid::None { + self.fluid(&pad, &colors, &mut out, x, y, z, id); + } + if !state.model { + continue; + } + let world = BlockPos::new(center.x * 16 + x, base_y + y, center.z * 16 + z); + let Ok(models) = self.assets.model_catalog.collect(BlockStateId(id.into()), world) + else { + continue; + }; + let mut visible = [false; 6]; + for d in Direction::ALL { + let [dx, dy, dz] = d.normal(); + let neighbor = pad.blocks[pi(x + dx, y + dy, z + dz)]; + visible[d as usize] = self + .visibility + .should_render_face( + BlockStateId(id.into()), + BlockStateId(neighbor.into()), + d, + true, + ) + .unwrap_or(true); + } + for (_, model) in models { + for face in &model.faces { + if face.quad.cull.is_some_and(|d| !visible[d as usize]) { + continue; + } + self.face( + &pad, + &colors, + &mut out, + [x, y, z], + face, + model.ambient_occlusion, + state, + ); + } + } + } + } + } + out + } + fn tint(state: Info, index: i32, colors: &Colors, x: i32, z: i32) -> u32 { + if index < 0 { + return 0xFF_FFFF; + } + let column = (z * 16 + x) as usize; + match state.tints[(index as usize).min(1)] { + Tint::None => 0xFF_FFFF, + Tint::Grass => colors.grass[column], + Tint::TallGrassUpper => colors.tall_upper[column], + Tint::Foliage => colors.foliage[column], + Tint::DryFoliage => colors.dry[column], + Tint::Water => colors.water[column], + Tint::Constant(c) => c, + Tint::Redstone(p) => redstone_color(p), + Tint::Stem(age) => { + let a = u32::from(age); + (a * 32) << 16 | (255 - a * 8) << 8 | a * 4 + } + } + } + #[allow(clippy::too_many_arguments)] + fn face( + &self, + pad: &Padded, + colors: &Colors, + out: &mut SectionMesh, + [x, y, z]: [i32; 3], + face: &BakedFace, + ao: bool, + state: Info, + ) { + let q = &face.quad; + let facing = q.facing; + let normal = Direction::ALL[facing as usize].normal(); + let axis = normal.iter().position(|&n| n != 0).unwrap_or(1); + let positive = normal[axis] > 0; + let on_boundary = q.positions.iter().all(|p| { + if positive { + p[axis] >= 1.0 - 1e-4 + } else { + p[axis] <= 1e-4 + } + }); + let base = if on_boundary { + [x + normal[0], y + normal[1], z + normal[2]] + } else { + [x, y, z] + }; + let tint = Self::tint(state, q.tint_index, colors, x, z); + let directional = match q.shade_direction_override { + Some(d) => shade(d), + None => shade(facing), + }; + let info = &self.tables.info; + let light_at = |p: [i32; 3]| -> u32 { + let i = pi(p[0], p[1], p[2]); + let packed = pad.light[i]; + let s = info[pad.blocks[i] as usize]; + let block = (packed & 15).max(s.emission); + u32::from(packed >> 4) << 16 | u32::from(block) + }; + let shade_at = |p: [i32; 3]| -> f32 { + if info[pad.blocks[pi(p[0], p[1], p[2])] as usize].full { + 0.2 + } else { + 1.0 + } + }; + let open_at = |p: [i32; 3]| -> bool { info[pad.blocks[pi(p[0], p[1], p[2])] as usize].translucent }; + // Tangent axes of the face plane. + let (ua, va) = match axis { + 0 => (2, 1), + 1 => (0, 2), + _ => (0, 1), + }; + let center_light = light_at(base); + let center_shade = shade_at(base); + // Corner values for (su, sv) in {0,1}^2 -> (sky, block, ao). + let mut corners = [[0f32; 3]; 4]; + for (ci, corner) in corners.iter_mut().enumerate() { + let su = if ci & 1 == 0 { -1 } else { 1 }; + let sv = if ci & 2 == 0 { -1 } else { 1 }; + let mut p1 = base; + p1[ua] += su; + let mut p2 = base; + p2[va] += sv; + let mut pc = base; + pc[ua] += su; + pc[va] += sv; + let (l1, l2) = (light_at(p1), light_at(p2)); + let (lc, ac) = if open_at(p1) || open_at(p2) { + (light_at(pc), shade_at(pc)) + } else { + (l1, shade_at(p1)) + }; + // ModelBlockRenderer.blend: zero samples take the centre value. + let fix = |v: u32| if v == 0 { center_light } else { v }; + let sum = fix(l1) + fix(l2) + fix(lc) + center_light; + corner[0] = (sum >> 16) as f32 / 4.0; + corner[1] = (sum & 0xFFFF) as f32 / 4.0; + corner[2] = (shade_at(p1) + shade_at(p2) + ac + center_shade) / 4.0; + } + let flat_sky = (center_light >> 16) as f32; + let flat_block = (center_light & 0xFFFF) as f32; + let target = if face.translucent { + &mut out.translucent + } else { + &mut out.solid + }; + for (p, uv) in q.positions.iter().zip(q.uv) { + let (sky, block, occlusion) = if ao { + let u = p[ua].clamp(0.0, 1.0); + let v = p[va].clamp(0.0, 1.0); + let lerp = |k: usize| { + let a = corners[0][k] * (1.0 - u) + corners[1][k] * u; + let b = corners[2][k] * (1.0 - u) + corners[3][k] * u; + a * (1.0 - v) + b * v + }; + (lerp(0), lerp(1), lerp(2)) + } else { + (flat_sky, flat_block, 1.0) + }; + target.push(Vertex { + pos: [p[0] + x as f32, p[1] + y as f32, p[2] + z as f32], + uv, + layer: face.layer, + color: pack_color(tint, directional * occlusion), + light: pack_light(sky, block), + }); + } + } + #[allow(clippy::too_many_arguments)] + fn fluid(&self, pad: &Padded, colors: &Colors, out: &mut SectionMesh, x: i32, y: i32, z: i32, id: u16) { + let info = &self.tables.info; + let me = info[id as usize]; + let water = me.fluid == Fluid::Water; + let same = |p: [i32; 3]| info[pad.blocks[pi(p[0], p[1], p[2])] as usize].fluid == me.fluid; + let solid = |p: [i32; 3]| { + let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize]; + s.solid || s.full + }; + let height = |p: [i32; 3]| -> f32 { + let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize]; + if s.fluid == me.fluid { + if same([p[0], p[1] + 1, p[2]]) { + 1.0 + } else { + f32::from(s.level) / 9.0 + } + } else if !(s.solid || s.full) { + 0.0 + } else { + -1.0 + } + }; + let own = height([x, y, z]); + let corner = |a: f32, b: f32, c: [i32; 3]| -> f32 { + if a >= 1.0 || b >= 1.0 { + return 1.0; + } + let mut sum = [0.0f32; 2]; + let mut add = |h: f32| { + if h >= 0.8 { + sum[0] += h * 10.0; + sum[1] += 10.0; + } else if h >= 0.0 { + sum[0] += h; + sum[1] += 1.0; + } + }; + if a > 0.0 || b > 0.0 { + let hc = height(c); + if hc >= 1.0 { + return 1.0; + } + add(hc); + } + add(own); + add(a); + add(b); + sum[0] / sum[1] + }; + let (nw, sw, se, ne) = if own >= 1.0 { + (1.0, 1.0, 1.0, 1.0) + } else { + let n = height([x, y, z - 1]); + let s = height([x, y, z + 1]); + let e = height([x + 1, y, z]); + let w = height([x - 1, y, z]); + ( + corner(n, w, [x - 1, y, z - 1]), + corner(s, w, [x - 1, y, z + 1]), + corner(s, e, [x + 1, y, z + 1]), + corner(n, e, [x + 1, y, z - 1]), + ) + }; + let tint = if water { + colors.water[(z * 16 + x) as usize] + } else { + 0xFF_FFFF + }; + let (still, flow) = if water { + (self.tables.water_still, self.tables.water_flow) + } else { + (self.tables.lava_still, self.tables.lava_flow) + }; + let light = |p: [i32; 3]| { + let packed = pad.light[pi(p[0], p[1], p[2])]; + let emission = if water { 0 } else { 15 }; + pack_light(f32::from(packed >> 4), f32::from((packed & 15).max(emission))) + }; + let target = if water { + &mut out.translucent + } else { + &mut out.solid + }; + let (fx, fy, fz) = (x as f32, y as f32, z as f32); + let quad = |target: &mut Vec, v: [([f32; 3], [f32; 2]); 4], layer: u32, b: f32, l: u32, back: bool| { + for (p, uv) in v { + target.push(Vertex { + pos: p, + uv, + layer, + color: pack_color(tint, b), + light: l, + }); + } + if back { + for i in [0, 3, 2, 1] { + let (p, uv) = v[i]; + target.push(Vertex { + pos: p, + uv, + layer, + color: pack_color(tint, b), + light: l, + }); + } + } + }; + let above_same = same([x, y + 1, z]); + if !above_same && !solid([x, y + 1, z]) || !above_same && own < 1.0 { + let o = 0.001; + let (h0, h1, h2, h3) = (nw - o, sw - o, se - o, ne - o); + // Flow direction from neighbour height differences. + let mut fxv = 0.0f32; + let mut fzv = 0.0f32; + if own < 1.0 && me.level < 8 || own < 0.88 { + for (dx, dz) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { + let h = height([x + dx, y, z + dz]); + if h >= 0.0 { + let d = own - h.max(0.0); + fxv += dx as f32 * d; + fzv += dz as f32 * d; + } + } + } + let (layer, uvs) = if fxv.abs() < 1e-4 && fzv.abs() < 1e-4 { + (still, [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]) + } else { + let angle = fzv.atan2(fxv) - std::f32::consts::FRAC_PI_2; + let (s, c) = (angle.sin() * 0.25, angle.cos() * 0.25); + // Flowing sprites are sampled over their top-left quarter-scaled region (getU(0.5+..) of 16 units). + ( + flow, + [ + [0.5 + (-c - s), 0.5 + (-c + s)], + [0.5 + (-c + s), 0.5 + (c + s)], + [0.5 + (c + s), 0.5 + (c - s)], + [0.5 + (c - s), 0.5 + (-c - s)], + ], + ) + }; + quad( + target, + [ + ([fx, fy + h0, fz], uvs[0]), + ([fx, fy + h1, fz + 1.0], uvs[1]), + ([fx + 1.0, fy + h2, fz + 1.0], uvs[2]), + ([fx + 1.0, fy + h3, fz], uvs[3]), + ], + layer, + 1.0, + light([x, y, z]), + water && !solid([x, y + 1, z]), + ); + } + if !same([x, y - 1, z]) && !solid([x, y - 1, z]) { + quad( + target, + [ + ([fx, fy + 0.001, fz], [0.0, 0.0]), + ([fx + 1.0, fy + 0.001, fz], [1.0, 0.0]), + ([fx + 1.0, fy + 0.001, fz + 1.0], [1.0, 1.0]), + ([fx, fy + 0.001, fz + 1.0], [0.0, 1.0]), + ], + still, + 0.5, + light([x, y - 1, z]), + false, + ); + } + let o = 0.001; + for (dx, dz, h0, h1, p0, p1, sh) in [ + (0, -1, nw, ne, [fx, fz + o], [fx + 1.0, fz + o], 0.8), + (0, 1, se, sw, [fx + 1.0, fz + 1.0 - o], [fx, fz + 1.0 - o], 0.8), + (-1, 0, sw, nw, [fx + o, fz + 1.0], [fx + o, fz], 0.6), + (1, 0, ne, se, [fx + 1.0 - o, fz], [fx + 1.0 - o, fz + 1.0], 0.6), + ] { + let n = [x + dx, y, z + dz]; + if same(n) || solid(n) { + continue; + } + let v0 = (1.0 - h0) * 0.5; + let v1 = (1.0 - h1) * 0.5; + quad( + target, + [ + ([p0[0], fy + h0, p0[1]], [0.0, v0]), + ([p1[0], fy + h1, p1[1]], [0.5, v1]), + ([p1[0], fy, p1[1]], [0.5, 0.5]), + ([p0[0], fy, p0[1]], [0.0, 0.5]), + ], + flow, + sh, + light([x, y, z]), + water, + ); + } + } +} +/// Snapshot of the 3x3 chunk neighbourhood used by a worker job. +pub type Region = [[Option>; 3]; 3]; +pub fn borrow(region: &Region) -> [[Option<&Chunk>; 3]; 3] { + std::array::from_fn(|z| std::array::from_fn(|x| region[z][x].as_deref())) +} diff --git a/crates/horizon-client/src/models.rs b/crates/horizon-client/src/models.rs index 1921d2faf..23280150b 100644 --- a/crates/horizon-client/src/models.rs +++ b/crates/horizon-client/src/models.rs @@ -1,5 +1,5 @@ //! A blockstate-driven inspection gallery, separate from gameplay simulation. -mod catalog; +pub mod catalog; mod cube; use crate::{Result, sprites::Sprites}; pub use catalog::StateModels; diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index 050138493..fa223905b 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -35,6 +35,7 @@ pub struct BakedFace { pub translucent: bool, } pub struct BakedModel { + pub ambient_occlusion: bool, pub faces: Vec, pub cube: Option<[super::cube::CubeStyle; 6]>, } @@ -59,6 +60,14 @@ impl StateModels { let mut choices = Vec::new(); let mut states = BTreeMap::new(); let mut variants = BTreeSet::new(); + let mut by_name: std::collections::HashMap<&str, Vec> = + std::collections::HashMap::new(); + for i in 0..registry.len() { + let id = BlockStateId(i as u32); + if let Some(state) = registry.state(id) { + by_name.entry(state.name.as_str()).or_default().push(id); + } + } for block in blocks.iter().copied().collect::>() { let name = format!("minecraft:{block}"); let facts = facts.get(&name).ok_or("missing block model state schema")?; @@ -103,12 +112,12 @@ impl StateModels { )?; let definition = BlockStateDefinition::from_json(&resource)?; let bound = definition.bind(&schema, &possible)?; - let native_order: Vec<_> = (0..registry.len()) - .filter_map(|i| { - let id = BlockStateId(i as u32); - let state = registry.state(id)?; - (state.name == name).then_some((id, &state.properties)) - }) + let native_order: Vec<_> = by_name + .get(name.as_str()) + .map(Vec::as_slice) + .unwrap_or_default() + .iter() + .map(|&id| (id, ®istry.state(id).expect("indexed state").properties)) .collect(); if native_order.len() != possible.len() || native_order @@ -181,7 +190,14 @@ impl StateModels { }) .collect::>()?; let cube = super::cube::cube_styles(&faces); - baked.insert((name, turns, lock), BakedModel { faces, cube }); + baked.insert( + (name, turns, lock), + BakedModel { + ambient_occlusion: model.ambient_occlusion, + faces, + cube, + }, + ); } Ok(Self { choices, diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index d43da72b8..5703b2906 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1,7 +1,7 @@ //! Stored movement state for the resident scene. This binds the validated air, //! jump, collision, support, restitution and stored health bindings. Entity lifecycle, //! block-inside effects and audiovisual event consumers remain separate work. -use crate::{Result, assets::Assets, collisions::SceneCollisions, world::TestWorld}; +use crate::{Result, assets::Assets, collisions::SceneCollisions, world::World}; use horizon_core::{ geometry::{Aabb, Vec3, VoxelShape, traverse_blocks}, position::BlockPos, @@ -300,7 +300,7 @@ impl PlayerMotion { pub struct MotionWorld<'p, 'w, 'r> { pub player: &'p mut PlayerMotion, - pub scene: &'w mut TestWorld<'r>, + pub scene: &'w mut World, pub assets: &'r Assets, pub collision_binding: &'w BlockCollisionRegistry<'r>, pub resources: &'w MotionResources, diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs new file mode 100644 index 000000000..aaac918f3 --- /dev/null +++ b/crates/horizon-client/src/particles.rs @@ -0,0 +1,87 @@ +//! Block particles (`TerrainParticle`): destroy bursts and mining crumbs that +//! sample a random quarter of the block's texture, fall with gravity and +//! expire after a randomized lifetime. +use crate::world::World; +use horizon_core::random::{LegacyRandom, RandomSource}; + +#[derive(Clone, Debug)] +pub struct Particle { + pub position: [f64; 3], + pub previous: [f64; 3], + pub velocity: [f64; 3], + pub age: u32, + pub lifetime: u32, + pub size: f32, + pub sprite: String, + /// Sub-rectangle of the sprite in 0..1 (u0, v0, u1, v1). + pub uv: [f32; 4], + pub tint: u32, + pub gravity: f64, + pub on_ground: bool, +} +impl Particle { + /// TerrainParticle(level, x, y, z, xa, ya, za, state) + pub fn terrain(random: &mut LegacyRandom, position: [f64; 3], velocity: [f64; 3], sprite: String, tint: u32) -> Self { + // Particle constructor: random jitter of velocity, normalized speed. + let mut v = [ + velocity[0] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4, + velocity[1] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4, + velocity[2] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4, + ]; + let speed = f64::from(random.next_float() + random.next_float() + 1.0) * 0.15; + let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-9); + for (i, c) in v.iter_mut().enumerate() { + *c = *c / length * speed * 0.4; + if i == 1 { + *c += 0.1; + } + } + let u = random.next_float() * 3.0 / 4.0; + let w = random.next_float() * 3.0 / 4.0; + // SingleQuadParticle quadSize: 0.1 * (rand*0.5+0.5) * 2, halved for terrain. + let size = 0.1 * (random.next_float() * 0.5 + 0.5); + let lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as u32; + Self { + position, + previous: position, + velocity: v, + age: 0, + lifetime, + size, + sprite, + uv: [u, w, u + 0.25, w + 0.25], + tint, + gravity: 1.0, + on_ground: false, + } + } + pub fn tick(&mut self, world: &World, solid: impl Fn(u16) -> bool) -> bool { + self.previous = self.position; + self.age += 1; + if self.age >= self.lifetime { + return false; + } + self.velocity[1] -= 0.04 * self.gravity; + for axis in 0..3 { + let mut next = self.position; + next[axis] += self.velocity[axis]; + let block = world.block(next[0].floor() as i32, next[1].floor() as i32, next[2].floor() as i32); + if solid(block.0 as u16) { + if axis == 1 && self.velocity[1] < 0.0 { + self.on_ground = true; + } + self.velocity[axis] = 0.0; + } else { + self.position = next; + } + } + for c in &mut self.velocity { + *c *= 0.98; + } + if self.on_ground { + self.velocity[0] *= 0.7; + self.velocity[2] *= 0.7; + } + true + } +} diff --git a/crates/horizon-client/src/render.rs b/crates/horizon-client/src/render.rs deleted file mode 100644 index 69560263c..000000000 --- a/crates/horizon-client/src/render.rs +++ /dev/null @@ -1,442 +0,0 @@ -use crate::{Result, assets::Assets, camera::Camera, mesh::Quad, models::ModelInstance}; -use std::{sync::Arc, time::Instant}; -use wgpu::util::DeviceExt; -use winit::window::Window; -#[repr(C)] -#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] -struct Uniforms { - matrix: [[f32; 4]; 4], - position: [f32; 4], - fog: [f32; 4], -} -pub struct Renderer { - instance: wgpu::Instance, - surface: wgpu::Surface<'static>, - window: Arc, - device: wgpu::Device, - queue: wgpu::Queue, - config: wgpu::SurfaceConfiguration, - pipeline: wgpu::RenderPipeline, - model_pipeline: wgpu::RenderPipeline, - model_quads: wgpu::Buffer, - model_quad_count: u32, - sprite_texture: wgpu::Texture, - sprite_size: u32, - animations: Vec<(crate::sprites::SpriteAnimation, usize)>, - animation_started: Instant, - pub animation_uploads: u64, - group: wgpu::BindGroup, - uniform: wgpu::Buffer, - quads: wgpu::Buffer, - depth: wgpu::TextureView, - pub quad_count: u32, - pub info: wgpu::AdapterInfo, - pub suspended: bool, - fog_distance: f32, -} -impl Renderer { - pub fn replace_mesh(&mut self, quads: &[Quad], model_faces: &[ModelInstance]) -> Result<()> { - let quad_count = u32::try_from(quads.len())?; - let model_quad_count = u32::try_from(model_faces.len())?; - self.quads = self - .device - .create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("Updated resident cube faces"), - contents: bytemuck::cast_slice(quads), - usage: wgpu::BufferUsages::VERTEX, - }); - self.model_quads = self - .device - .create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("Updated resident model faces"), - contents: bytemuck::cast_slice(model_faces), - usage: wgpu::BufferUsages::VERTEX, - }); - self.quad_count = quad_count; - self.model_quad_count = model_quad_count; - Ok(()) - } - pub async fn new( - window: Arc, - assets: &Assets, - quads: &[Quad], - model_faces: &[ModelInstance], - fog_distance: f32, - ) -> Result { - let instance = - wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); - let surface = instance.create_surface(window.clone())?; - let adapter = instance - .request_adapter(&wgpu::RequestAdapterOptions { - power_preference: wgpu::PowerPreference::HighPerformance, - compatible_surface: Some(&surface), - force_fallback_adapter: false, - ..Default::default() - }) - .await?; - let info = adapter.get_info(); - eprintln!( - "Horizon renderer: {} ({:?}, {:?})", - info.name, info.backend, info.device_type - ); - let (device, queue) = adapter - .request_device(&wgpu::DeviceDescriptor { - label: Some("Horizon device"), - ..Default::default() - }) - .await?; - let size = window.inner_size(); - let mut config = surface - .get_default_config(&adapter, size.width.max(1), size.height.max(1)) - .ok_or("surface has no supported configuration")?; - let caps = surface.get_capabilities(&adapter); - config.format = caps - .formats - .iter() - .copied() - .find(wgpu::TextureFormat::is_srgb) - .unwrap_or(config.format); - config.present_mode = wgpu::PresentMode::Fifo; - surface.configure(&device, &config); - let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("Horizon cube renderer"), - source: wgpu::ShaderSource::Wgsl(include_str!("world.wgsl").into()), - }); - let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("Horizon world bindings"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2Array, - multisampled: false, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 2, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), - count: None, - }, - ], - }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("Horizon world layout"), - bind_group_layouts: &[Some(&bindings)], - ..Default::default() - }); - let create_pipeline = - |label: &str, vertex: &str, fragment: &str, buffer: wgpu::VertexBufferLayout<'_>| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some(vertex), - compilation_options: Default::default(), - buffers: &[Some(buffer)], - }, - primitive: wgpu::PrimitiveState { - cull_mode: Some(wgpu::Face::Back), - ..Default::default() - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::Less), - stencil: Default::default(), - bias: Default::default(), - }), - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some(fragment), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: config.format, - blend: None, - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }) - }; - let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Uint32,4=>Float32x2,5=>Float32x2,6=>Float32x2,7=>Float32]; - let pipeline = create_pipeline( - "Horizon opaque cubes", - "vs_main", - "fs_main", - wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as u64, - step_mode: wgpu::VertexStepMode::Instance, - attributes: &attributes, - }, - ); - let model_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3,2=>Float32x3,3=>Float32x3,4=>Float32x2,5=>Float32x2,6=>Float32x2,7=>Float32x2,8=>Uint32,9=>Float32]; - let model_pipeline = create_pipeline( - "Horizon model geometry", - "vs_model", - "fs_model", - wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as u64, - step_mode: wgpu::VertexStepMode::Instance, - attributes: &model_attributes, - }, - ); - let uniform = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("Horizon camera"), - size: std::mem::size_of::() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - let texture = device.create_texture_with_data( - &queue, - &wgpu::TextureDescriptor { - label: Some("Pinned block sprites"), - size: wgpu::Extent3d { - width: assets.sprite_size, - height: assets.sprite_size, - depth_or_array_layers: assets.texture_layers, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8UnormSrgb, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }, - wgpu::util::TextureDataOrder::LayerMajor, - &assets.pixels, - ); - let view = texture.create_view(&wgpu::TextureViewDescriptor { - dimension: Some(wgpu::TextureViewDimension::D2Array), - ..Default::default() - }); - let sampler = device.create_sampler(&wgpu::SamplerDescriptor { - label: Some("Repeating nearest cube sprites"), - address_mode_u: wgpu::AddressMode::Repeat, - address_mode_v: wgpu::AddressMode::Repeat, - mag_filter: wgpu::FilterMode::Nearest, - min_filter: wgpu::FilterMode::Nearest, - ..Default::default() - }); - let group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("Horizon world resources"), - layout: &bindings, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: uniform.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::TextureView(&view), - }, - wgpu::BindGroupEntry { - binding: 2, - resource: wgpu::BindingResource::Sampler(&sampler), - }, - ], - }); - let quad_count = u32::try_from(quads.len())?; - let quads = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("Greedy cube faces"), - contents: bytemuck::cast_slice(quads), - usage: wgpu::BufferUsages::VERTEX, - }); - let model_quad_count = u32::try_from(model_faces.len())?; - let model_quads = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("Baked vanilla model faces"), - contents: bytemuck::cast_slice(model_faces), - usage: wgpu::BufferUsages::VERTEX, - }); - let depth = Self::depth(&device, &config); - Ok(Self { - instance, - surface, - window, - device, - queue, - config, - pipeline, - model_pipeline, - model_quads, - model_quad_count, - sprite_texture: texture, - sprite_size: assets.sprite_size, - animations: assets - .animations - .iter() - .map(|a| (a.clone(), a.frame(0))) - .collect(), - animation_started: Instant::now(), - animation_uploads: 0, - group, - uniform, - quads, - depth, - quad_count, - info, - suspended: size.width == 0 || size.height == 0, - fog_distance, - }) - } - fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView { - device - .create_texture(&wgpu::TextureDescriptor { - label: Some("Horizon depth"), - size: wgpu::Extent3d { - width: config.width, - height: config.height, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Depth32Float, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }) - .create_view(&Default::default()) - } - pub fn resize(&mut self, width: u32, height: u32) { - self.suspended = width == 0 || height == 0; - if self.suspended { - return; - } - self.config.width = width; - self.config.height = height; - self.surface.configure(&self.device, &self.config); - self.depth = Self::depth(&self.device, &self.config); - } - pub fn render(&mut self, camera: &Camera) -> Result { - if self.suspended { - return Ok(false); - } - let (frame, reconfigure) = match self.surface.get_current_texture() { - wgpu::CurrentSurfaceTexture::Success(frame) => (frame, false), - wgpu::CurrentSurfaceTexture::Suboptimal(frame) => (frame, true), - wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => { - return Ok(false); - } - wgpu::CurrentSurfaceTexture::Outdated => { - self.surface.configure(&self.device, &self.config); - return Ok(false); - } - wgpu::CurrentSurfaceTexture::Lost => { - self.surface = self.instance.create_surface(self.window.clone())?; - self.surface.configure(&self.device, &self.config); - return Ok(false); - } - wgpu::CurrentSurfaceTexture::Validation => { - return Err("surface acquisition failed validation".into()); - } - }; - // Inspection textures advance at 20 ticks/s independently of presentation. - let tick = self.animation_started.elapsed().as_millis() / 50; - for (animation, previous) in &mut self.animations { - let frame = animation.frame(tick as u64); - if frame != *previous { - self.queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &self.sprite_texture, - mip_level: 0, - origin: wgpu::Origin3d { - x: 0, - y: 0, - z: animation.layer, - }, - aspect: wgpu::TextureAspect::All, - }, - animation.pixels(frame), - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(self.sprite_size * 4), - rows_per_image: Some(self.sprite_size), - }, - wgpu::Extent3d { - width: self.sprite_size, - height: self.sprite_size, - depth_or_array_layers: 1, - }, - ); - *previous = frame; - self.animation_uploads += 1; - } - } - let fog = [0.35, 0.55, 0.80, 1.0]; - let p = camera.position.as_vec3(); - let uniforms = Uniforms { - matrix: camera - .matrix(self.config.width as f32 / self.config.height as f32) - .to_cols_array_2d(), - position: [p.x, p.y, p.z, self.fog_distance], - fog, - }; - self.queue - .write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniforms)); - let view = frame.texture.create_view(&Default::default()); - let mut encoder = self - .device - .create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("Horizon frame"), - }); - { - let attachments = [Some(wgpu::RenderPassColorAttachment { - view: &view, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color { - r: f64::from(fog[0]), - g: f64::from(fog[1]), - b: f64::from(fog[2]), - a: 1.0, - }), - store: wgpu::StoreOp::Store, - }, - })]; - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("Horizon world"), - color_attachments: &attachments, - depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Clear(1.0), - store: wgpu::StoreOp::Discard, - }), - stencil_ops: None, - }), - ..Default::default() - }); - pass.set_pipeline(&self.pipeline); - pass.set_bind_group(0, &self.group, &[]); - pass.set_vertex_buffer(0, self.quads.slice(..)); - pass.draw(0..6, 0..self.quad_count); - pass.set_pipeline(&self.model_pipeline); - pass.set_vertex_buffer(0, self.model_quads.slice(..)); - pass.draw(0..6, 0..self.model_quad_count); - } - self.queue.submit([encoder.finish()]); - self.window.pre_present_notify(); - self.queue.present(frame); - if reconfigure { - self.surface.configure(&self.device, &self.config); - } - Ok(true) - } -} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs new file mode 100644 index 000000000..59f2ea069 --- /dev/null +++ b/crates/horizon-client/src/save.rs @@ -0,0 +1,421 @@ +//! World persistence in vanilla's Anvil layout: `region/r.X.Z.mca` files with +//! zlib-compressed chunk NBT (paletted `block_states`/`biomes` per section) and +//! a gzip `level.dat`. Light is not stored (`isLightOn: 0`), so both Horizon and +//! vanilla relight saved chunks on load. +use crate::{ + Result, + biome::Biomes, + chunk::{Blocks, Chunk, MIN_Y, SECTIONS}, + streaming::ChunkGenerator, +}; +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + chunk::BlockState, + compression::Compression, + nbt::{self, Limits, NamedTag, Tag}, + region::{ChunkRecord, RegionFile, RegionWriter}, + registry::{BlockRegistry, BlockStateId}, +}; +use std::{ + collections::{BTreeMap, HashMap}, + fs, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +fn pack(indices: &[u16], bits: u32) -> Vec { + let per_long = (64 / bits) as usize; + let mut longs = vec![0i64; indices.len().div_ceil(per_long)]; + for (i, &v) in indices.iter().enumerate() { + longs[i / per_long] |= (i64::from(v) & ((1i64 << bits) - 1)) << ((i % per_long) as u32 * bits); + } + longs +} +fn unpack(longs: &[i64], bits: u32, count: usize) -> Vec { + let per_long = (64 / bits) as usize; + let mask = (1u64 << bits) - 1; + (0..count) + .map(|i| { + longs + .get(i / per_long) + .map_or(0, |&l| ((l as u64 >> ((i % per_long) as u32 * bits)) & mask) as u16) + }) + .collect() +} +fn bits_for(len: usize, min: u32) -> u32 { + (usize::BITS - (len.max(1) - 1).leading_zeros()).max(min) +} +fn string(s: &str) -> Tag { + Tag::String(s.into()) +} +pub fn encode(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes) -> NamedTag { + let mut sections = Vec::new(); + for (si, section) in chunk.sections.iter().enumerate() { + let y = (MIN_Y >> 4) + si as i32; + let ids: Vec = match §ion.blocks { + Blocks::Uniform(v) => vec![*v], + Blocks::Full(a) => a.to_vec(), + }; + let mut palette: Vec = Vec::new(); + let mut lookup: HashMap = HashMap::new(); + let indices: Vec = ids + .iter() + .map(|id| { + *lookup.entry(*id).or_insert_with(|| { + palette.push(*id); + (palette.len() - 1) as u16 + }) + }) + .collect(); + let mut states = vec![( + "palette", + Tag::List( + palette + .iter() + .map(|id| { + registry + .state(BlockStateId(u32::from(*id))) + .map_or_else(|| Tag::compound([("Name", string("minecraft:air"))]), BlockState::to_nbt) + }) + .collect(), + ), + )]; + if palette.len() > 1 { + states.push(("data", Tag::LongArray(pack(&indices, bits_for(palette.len(), 4))))); + } + let quart: Vec = (0..64).map(|i| chunk.biomes[si * 64 + i]).collect(); + let mut biome_palette: Vec = Vec::new(); + let biome_indices: Vec = quart + .iter() + .map(|b| match biome_palette.iter().position(|p| p == b) { + Some(i) => i as u16, + None => { + biome_palette.push(*b); + (biome_palette.len() - 1) as u16 + } + }) + .collect(); + let mut biome_tag = vec![( + "palette", + Tag::List(biome_palette.iter().map(|b| string(&biomes.get(*b).name)).collect()), + )]; + if biome_palette.len() > 1 { + biome_tag.push(("data", Tag::LongArray(pack(&biome_indices, bits_for(biome_palette.len(), 0))))); + } + sections.push(Tag::compound([ + ("Y", Tag::Byte(y as i8)), + ("block_states", Tag::compound(states)), + ("biomes", Tag::compound(biome_tag)), + ])); + } + NamedTag { + name: "".into(), + tag: Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("xPos", Tag::Int(chunk.x)), + ("zPos", Tag::Int(chunk.z)), + ("yPos", Tag::Int(MIN_Y >> 4)), + ("Status", string("minecraft:full")), + ("LastUpdate", Tag::Long(0)), + ("InhabitedTime", Tag::Long(0)), + ("isLightOn", Tag::Byte(0)), + ("sections", Tag::List(sections)), + ("block_entities", Tag::List(vec![])), + ]), + } +} +pub fn decode(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes) -> Option { + let tag = &root.tag; + let Tag::Int(x) = tag.get("xPos")? else { return None }; + let Tag::Int(z) = tag.get("zPos")? else { return None }; + let mut chunk = Chunk::empty(*x, *z); + let air = registry.default_state("minecraft:air")?.0 as u16; + let mut cache: HashMap = HashMap::new(); + let mut biome_data = (*chunk.biomes).clone(); + let Some(Tag::List(sections)) = tag.get("sections") else { return Some(chunk) }; + for section in sections { + let Some(Tag::Byte(y)) = section.get("Y") else { continue }; + let si = i32::from(*y) - (MIN_Y >> 4); + if !(0..SECTIONS as i32).contains(&si) { + continue; + } + if let Some(states) = section.get("block_states") + && let Some(Tag::List(palette)) = states.get("palette") + { + let ids: Vec = palette + .iter() + .map(|p| { + let state = BlockState::from_nbt(p).ok(); + let key = state.as_ref().map(|s| format!("{}{:?}", s.name, s.properties)).unwrap_or_default(); + *cache.entry(key).or_insert_with(|| { + state + .and_then(|s| registry.id(&s).or_else(|| registry.default_state(&s.name))) + .map_or(air, |id| id.0 as u16) + }) + }) + .collect(); + let target = Arc::make_mut(&mut chunk.sections[si as usize]); + if ids.len() <= 1 { + target.blocks = Blocks::Uniform(ids.first().copied().unwrap_or(air)); + } else if let Some(Tag::LongArray(data)) = states.get("data") { + let indices = unpack(data, bits_for(ids.len(), 4), 4096); + let mut full = Box::new([air; 4096]); + for (i, idx) in indices.iter().enumerate() { + full[i] = ids.get(*idx as usize).copied().unwrap_or(air); + } + target.blocks = Blocks::Full(full); + } + } + if let Some(b) = section.get("biomes") + && let Some(Tag::List(palette)) = b.get("palette") + { + let ids: Vec = palette + .iter() + .map(|p| match p { + Tag::String(s) => biomes.id(&s.to_string_lossy()), + _ => 0, + }) + .collect(); + let indices = match b.get("data") { + Some(Tag::LongArray(data)) if ids.len() > 1 => unpack(data, bits_for(ids.len(), 0), 64), + _ => vec![0; 64], + }; + for (i, idx) in indices.iter().enumerate() { + biome_data[si as usize * 64 + i] = ids.get(*idx as usize).copied().unwrap_or(0); + } + } + } + chunk.biomes = Arc::new(biome_data); + Some(chunk) +} +/// The world folder. Region files are read lazily by worker threads. +pub struct SaveDir { + pub root: PathBuf, + regions: Mutex>>>>, +} +impl SaveDir { + pub fn new(root: PathBuf) -> Self { + Self { + root, + regions: Mutex::new(HashMap::new()), + } + } + fn region_path(&self, rx: i32, rz: i32) -> PathBuf { + self.root.join(format!("region/r.{rx}.{rz}.mca")) + } + pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option { + let key = (x >> 5, z >> 5); + let region = { + let mut regions = self.regions.lock().ok()?; + regions + .entry(key) + .or_insert_with(|| RegionFile::open(self.region_path(key.0, key.1)).ok().map(|r| Arc::new(Mutex::new(r)))) + .clone()? + }; + let record = region.lock().ok()?.read(ChunkPos::new(x, z)).ok()??; + let root = record.nbt(Limits::default()).ok()?; + decode(&root, registry, biomes) + } + /// Rewrite every region touched by `chunks`, keeping their other chunks. + pub fn save(&self, chunks: &[Arc], registry: &BlockRegistry, biomes: &Biomes) -> Result { + let mut by_region: BTreeMap<(i32, i32), Vec<&Arc>> = BTreeMap::new(); + for c in chunks { + by_region.entry((c.x >> 5, c.z >> 5)).or_default().push(c); + } + let staging = self.root.join("region/.staging"); + fs::create_dir_all(&staging)?; + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as u32); + for ((rx, rz), list) in by_region { + let path = self.region_path(rx, rz); + let mut records: BTreeMap<(i32, i32), ChunkRecord> = BTreeMap::new(); + if let Ok(mut existing) = RegionFile::open(&path) { + let positions: Vec = existing.chunks().map(|(p, _)| p).collect(); + for p in positions { + if let Ok(Some(r)) = existing.read(p) { + records.insert((p.x, p.z), r); + } + } + } + for c in list { + let record = ChunkRecord::from_nbt(&encode(c, registry, biomes), Compression::Zlib, timestamp, Limits::default())?; + records.insert((c.x, c.z), record); + } + let temporary = staging.join(format!("r.{rx}.{rz}.mca")); + let _ = fs::remove_file(&temporary); + let mut writer = RegionWriter::create(&temporary)?; + for ((x, z), r) in &records { + writer.write(ChunkPos::new(*x, *z), r)?; + } + writer.finish()?; + fs::rename(&temporary, &path)?; + self.regions.lock().map_err(|_| "region cache poisoned")?.remove(&(rx, rz)); + } + Ok(chunks.len()) + } +} +/// Player and world state stored in `level.dat`. +#[derive(Clone, Debug, Default)] +pub struct Level { + pub name: String, + pub seed: i64, + pub creative: bool, + pub time: i64, + pub day_time: i64, + pub spawn: Option<[f64; 3]>, + pub position: Option<[f64; 3]>, + pub rotation: [f32; 2], + pub health: f32, + pub food: i32, + pub saturation: f32, + pub inventory: Vec<(u8, String, u32, u32)>, +} +impl Level { + pub fn read(dir: &Path) -> Option { + let bytes = fs::read(dir.join("level.dat")).ok()?; + let raw = Compression::Gzip.decode(&bytes, 64 << 20).ok()?; + let (root, _) = nbt::read_named(&raw, Limits::default()).ok()?; + let data = root.tag.get("Data")?; + let long = |t: Option<&Tag>| match t { + Some(Tag::Long(v)) => *v, + Some(Tag::Int(v)) => i64::from(*v), + _ => 0, + }; + let doubles = |t: Option<&Tag>| match t { + Some(Tag::List(l)) if l.len() == 3 => { + let v: Vec = l.iter().map(|d| if let Tag::Double(b) = d { f64::from_bits(*b) } else { 0.0 }).collect(); + Some([v[0], v[1], v[2]]) + } + _ => None, + }; + let player = data.get("Player"); + let float = |t: Option<&Tag>| if let Some(Tag::Float(b)) = t { f32::from_bits(*b) } else { 0.0 }; + let mut inventory = Vec::new(); + if let Some(Tag::List(items)) = player.and_then(|p| p.get("Inventory")) { + for it in items { + let slot = if let Some(Tag::Byte(s)) = it.get("Slot") { *s as u8 } else { continue }; + let id = if let Some(Tag::String(s)) = it.get("id") { s.to_string_lossy() } else { continue }; + let count = long(it.get("count")).max(1) as u32; + let damage = it + .get("components") + .and_then(|c| c.get("minecraft:damage")) + .map_or(0, |d| long(Some(d)) as u32); + inventory.push((slot, id, count, damage)); + } + } + let rotation = match player.and_then(|p| p.get("Rotation")) { + Some(Tag::List(r)) if r.len() == 2 => [float(r.first()), float(r.get(1))], + _ => [0.0; 2], + }; + Some(Self { + name: match data.get("LevelName") { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => "World".into(), + }, + seed: long(data.get("WorldGenSettings").and_then(|w| w.get("seed"))), + creative: long(data.get("GameType")) == 1, + time: long(data.get("Time")), + day_time: long(data.get("DayTime")), + spawn: Some([long(data.get("SpawnX")) as f64, long(data.get("SpawnY")) as f64, long(data.get("SpawnZ")) as f64]), + position: doubles(player.and_then(|p| p.get("Pos"))), + rotation, + health: player.map_or(20.0, |p| float(p.get("Health"))), + food: player.map_or(20, |p| long(p.get("foodLevel")) as i32), + saturation: player.map_or(5.0, |p| float(p.get("foodSaturationLevel"))), + inventory, + }) + } + pub fn write(&self, dir: &Path) -> Result<()> { + fs::create_dir_all(dir)?; + let spawn = self.spawn.unwrap_or([0.0, 64.0, 0.0]); + let mut player = vec![ + ("Health", Tag::Float(self.health.to_bits())), + ("foodLevel", Tag::Int(self.food)), + ("foodSaturationLevel", Tag::Float(self.saturation.to_bits())), + ("playerGameType", Tag::Int(i32::from(self.creative))), + ( + "Rotation", + Tag::List(vec![Tag::Float(self.rotation[0].to_bits()), Tag::Float(self.rotation[1].to_bits())]), + ), + ( + "Inventory", + Tag::List( + self.inventory + .iter() + .map(|(slot, id, count, damage)| { + let mut entries = vec![ + ("Slot", Tag::Byte(*slot as i8)), + ("id", string(id)), + ("count", Tag::Int(*count as i32)), + ]; + if *damage > 0 { + entries.push(("components", Tag::compound([("minecraft:damage", Tag::Int(*damage as i32))]))); + } + Tag::compound(entries) + }) + .collect(), + ), + ), + ("Dimension", string("minecraft:overworld")), + ]; + if let Some(p) = self.position { + player.push(("Pos", Tag::List(p.iter().map(|v| Tag::Double(v.to_bits())).collect()))); + } + let root = NamedTag { + name: "".into(), + tag: Tag::compound([( + "Data", + Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("version", Tag::Int(19133)), + ("LevelName", string(&self.name)), + ("GameType", Tag::Int(i32::from(self.creative))), + ("Time", Tag::Long(self.time)), + ("DayTime", Tag::Long(self.day_time)), + ("SpawnX", Tag::Int(spawn[0].floor() as i32)), + ("SpawnY", Tag::Int(spawn[1].floor() as i32)), + ("SpawnZ", Tag::Int(spawn[2].floor() as i32)), + ("initialized", Tag::Byte(1)), + ("allowCommands", Tag::Byte(0)), + ("hardcore", Tag::Byte(0)), + ("Difficulty", Tag::Byte(2)), + ("WorldGenSettings", Tag::compound([("seed", Tag::Long(self.seed)), ("generate_features", Tag::Byte(1)), ("bonus_chest", Tag::Byte(0))])), + ("Player", Tag::compound(player)), + ]), + )]), + }; + let bytes = nbt::write_named(&root, Limits::default()).map_err(|e| e.to_string())?; + let compressed = Compression::Gzip.encode(&bytes)?; + let temporary = dir.join("level.dat_new"); + fs::write(&temporary, compressed)?; + if dir.join("level.dat").exists() { + let _ = fs::rename(dir.join("level.dat"), dir.join("level.dat_old")); + } + fs::rename(temporary, dir.join("level.dat"))?; + Ok(()) + } +} +/// Loads saved chunks before falling back to generation. +pub struct Persistent { + pub inner: Arc, + pub save: Arc, + pub registry: Arc, + pub biomes: Arc, +} +impl ChunkGenerator for Persistent { + type Worker = G::Worker; + fn worker(&self) -> G::Worker { + self.inner.worker() + } + fn generate(&self, worker: &mut G::Worker, x: i32, z: i32) -> Chunk { + if let Some(mut chunk) = self.save.load(x, z, &self.registry.registry, &self.biomes) { + for s in &mut chunk.sections { + Arc::make_mut(s).compact(); + } + return chunk; + } + self.inner.generate(worker, x, z) + } +} diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs new file mode 100644 index 000000000..2cf5888b2 --- /dev/null +++ b/crates/horizon-client/src/streaming.rs @@ -0,0 +1,338 @@ +//! Chunk streaming: a worker pool generates, lights and meshes chunk columns +//! around the player, closest first. The game thread owns the world and only +//! hands immutable `Arc` snapshots to workers; results carry a sequence number +//! so stale work is dropped. +use crate::{ + chunk::{Chunk, SECTIONS}, + light::{LightTables, light_chunk}, + mesher::{MeshTables, Mesher, Region, SectionMesh, borrow}, + world::World, +}; +use std::{ + collections::{BinaryHeap, HashMap, HashSet}, + sync::{ + Arc, Condvar, Mutex, + atomic::{AtomicBool, Ordering}, + mpsc, + }, + thread, +}; + +/// Produces fully generated chunk columns. Implementations must be thread-safe; +/// each worker thread owns one `Worker` for per-thread caches. +pub trait ChunkGenerator: Send + Sync + 'static { + type Worker: Send + 'static; + fn worker(&self) -> Self::Worker; + fn generate(&self, worker: &mut Self::Worker, x: i32, z: i32) -> Chunk; +} +enum Job { + Generate(i32, i32), + Light(i32, i32, Box, u64), + Mesh(i32, i32, i32, Box, u64), +} +pub enum Done { + Generated(Chunk), + Lit(i32, i32, Vec>, u64), + Meshed(i32, i32, i32, SectionMesh, u64), +} +struct Queued { + priority: i64, + order: u64, + job: Job, +} +impl PartialEq for Queued { + fn eq(&self, o: &Self) -> bool { + self.priority == o.priority && self.order == o.order + } +} +impl Eq for Queued {} +impl PartialOrd for Queued { + fn partial_cmp(&self, o: &Self) -> Option { + Some(self.cmp(o)) + } +} +impl Ord for Queued { + fn cmp(&self, o: &Self) -> std::cmp::Ordering { + // BinaryHeap is a max-heap: lower priority value = more urgent. + o.priority + .cmp(&self.priority) + .then(o.order.cmp(&self.order)) + } +} +struct Shared { + queue: Mutex>, + ready: Condvar, + stop: AtomicBool, +} +pub struct Streaming { + shared: Arc, + results: mpsc::Receiver, + threads: Vec>, + order: u64, + generating: HashSet<(i32, i32)>, + lighting: HashMap<(i32, i32), u64>, + meshing: HashMap<(i32, i32, i32), u64>, + /// Chunks whose light is current. + lit: HashSet<(i32, i32)>, + /// Columns whose sections have been meshed at least once. + meshed: HashSet<(i32, i32)>, + sequence: u64, + pub center: (i32, i32), + pub radius: i32, + pub generated_total: u64, + pub meshed_total: u64, +} +pub struct WorkerContext { + pub assets: Arc, + pub tables: Arc, + pub biomes: Arc, + pub light: Arc, +} +impl Streaming { + pub fn new(generator: Arc, context: Arc, threads: usize) -> Self { + let shared = Arc::new(Shared { + queue: Mutex::new(BinaryHeap::new()), + ready: Condvar::new(), + stop: AtomicBool::new(false), + }); + let (send, results) = mpsc::channel(); + let threads = (0..threads.max(1)) + .map(|i| { + let shared = shared.clone(); + let send = send.clone(); + let generator = generator.clone(); + let context = context.clone(); + thread::Builder::new() + .name(format!("horizon-worker-{i}")) + .spawn(move || { + let mut worker = generator.worker(); + let mut mesher = Mesher { + assets: &context.assets, + tables: &context.tables, + biomes: &context.biomes, + visibility: context.tables.visibility.clone(), + }; + loop { + let job = { + let mut queue = shared.queue.lock().unwrap(); + loop { + if shared.stop.load(Ordering::Relaxed) { + return; + } + if let Some(job) = queue.pop() { + break job.job; + } + queue = shared.ready.wait(queue).unwrap(); + } + }; + let done = match job { + Job::Generate(x, z) => { + Done::Generated(generator.generate(&mut worker, x, z)) + } + Job::Light(x, z, region, seq) => { + Done::Lit(x, z, light_chunk(&borrow(®ion), &context.light), seq) + } + Job::Mesh(x, sy, z, region, seq) => { + Done::Meshed(x, sy, z, mesher.mesh(&borrow(®ion), sy), seq) + } + }; + if send.send(done).is_err() { + return; + } + } + }) + .expect("spawn worker") + }) + .collect(); + Self { + shared, + results, + threads, + order: 0, + generating: HashSet::new(), + lighting: HashMap::new(), + meshing: HashMap::new(), + lit: HashSet::new(), + meshed: HashSet::new(), + sequence: 0, + center: (0, 0), + radius: 8, + generated_total: 0, + meshed_total: 0, + } + } + fn submit(&mut self, priority: i64, job: Job) { + self.order += 1; + self.shared.queue.lock().unwrap().push(Queued { + priority, + order: self.order, + job, + }); + self.shared.ready.notify_one(); + } + fn distance(&self, x: i32, z: i32) -> i64 { + let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1)); + dx * dx + dz * dz + } + fn region(world: &World, x: i32, z: i32) -> Option> { + let mut region: Region = Default::default(); + for dz in 0..3 { + for dx in 0..3 { + region[dz][dx] = Some(world.chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))?.clone()); + } + } + Some(Box::new(region)) + } + pub fn is_lit(&self, x: i32, z: i32) -> bool { + self.lit.contains(&(x, z)) + } + pub fn pending(&self) -> usize { + self.shared.queue.lock().unwrap().len() + } + /// Advance streaming: collect finished work, then schedule more. + /// Returns meshes ready for upload and columns that were unloaded. + pub fn update(&mut self, world: &mut World) -> (Vec<((i32, i32, i32), SectionMesh)>, Vec>) { + let mut uploads = Vec::new(); + while let Ok(done) = self.results.try_recv() { + match done { + Done::Generated(chunk) => { + let key = (chunk.x, chunk.z); + self.generating.remove(&key); + if self.in_range(key.0, key.1, 2) { + self.generated_total += 1; + world.chunks.insert(key, Arc::new(chunk)); + for dz in -1..=1 { + for dx in -1..=1 { + world.dirty_light.insert((key.0 + dx, key.1 + dz)); + } + } + } + } + Done::Lit(x, z, sections, seq) => { + if self.lighting.get(&(x, z)) != Some(&seq) { + continue; + } + self.lighting.remove(&(x, z)); + if let Some(chunk) = world.chunks.get_mut(&(x, z)) { + let chunk = Arc::make_mut(chunk); + // Keep blocks edited since the snapshot; take only light. + for (target, lit) in chunk.sections.iter_mut().zip(sections) { + let mut section = (**target).clone(); + section.light = lit.light.clone(); + *target = Arc::new(section); + } + chunk.lit = true; + self.lit.insert((x, z)); + for dz in -1..=1 { + for dx in -1..=1 { + for sy in 0..SECTIONS as i32 { + world.dirty_sections.insert((x + dx, sy, z + dz)); + } + } + } + } + } + Done::Meshed(x, sy, z, mesh, seq) => { + if self.meshing.get(&(x, sy, z)) != Some(&seq) { + continue; + } + self.meshing.remove(&(x, sy, z)); + self.meshed_total += 1; + uploads.push(((x, sy, z), mesh)); + } + } + } + // Unload far columns. + let far: Vec<_> = world + .chunks + .keys() + .copied() + .filter(|&(x, z)| !self.in_range(x, z, 3)) + .collect(); + let mut removed = Vec::with_capacity(far.len()); + for key in &far { + if let Some(chunk) = world.chunks.remove(key) { + removed.push(chunk); + } + self.lit.remove(key); + self.meshed.remove(key); + } + // Generation, closest first, bounded in flight. + let workers = self.threads.len(); + if self.generating.len() < workers * 3 { + let r = self.radius + 1; + let mut wanted = Vec::new(); + for dz in -r..=r { + for dx in -r..=r { + let (x, z) = (self.center.0 + dx, self.center.1 + dz); + if !self.in_range(x, z, 1) + || world.chunks.contains_key(&(x, z)) + || self.generating.contains(&(x, z)) + { + continue; + } + wanted.push((self.distance(x, z), x, z)); + } + } + wanted.sort_unstable(); + for (d, x, z) in wanted.into_iter().take(workers * 3 - self.generating.len()) { + self.generating.insert((x, z)); + self.submit(d * 4, Job::Generate(x, z)); + } + } + // Lighting once all neighbours exist. + let light: Vec<_> = world.dirty_light.iter().copied().collect(); + for (x, z) in light { + if !world.chunks.contains_key(&(x, z)) { + world.dirty_light.remove(&(x, z)); + continue; + } + let Some(region) = Self::region(world, x, z) else { + continue; + }; + world.dirty_light.remove(&(x, z)); + self.sequence += 1; + self.lighting.insert((x, z), self.sequence); + self.submit(self.distance(x, z) * 4 + 1, Job::Light(x, z, region, self.sequence)); + } + // Meshing once the column and its neighbours are lit. + let dirty: Vec<_> = world.dirty_sections.iter().copied().collect(); + let mut columns: HashMap<(i32, i32), Option>> = HashMap::new(); + for (x, sy, z) in dirty { + if !world.chunks.contains_key(&(x, z)) || !self.in_range(x, z, 0) { + world.dirty_sections.remove(&(x, sy, z)); + continue; + } + let ready = (-1..=1).all(|dz| (-1..=1).all(|dx| self.lit.contains(&(x + dx, z + dz)))); + if !ready || self.lighting.contains_key(&(x, z)) { + continue; + } + let region = columns + .entry((x, z)) + .or_insert_with(|| Self::region(world, x, z)); + let Some(region) = region.clone() else { continue }; + world.dirty_sections.remove(&(x, sy, z)); + let first = self.meshed.insert((x, z)); + self.sequence += 1; + self.meshing.insert((x, sy, z), self.sequence); + self.submit( + self.distance(x, z) * 4 + if first { 2 } else { 0 }, + Job::Mesh(x, sy, z, region, self.sequence), + ); + } + (uploads, removed) + } + fn in_range(&self, x: i32, z: i32, margin: i32) -> bool { + let r = i64::from(self.radius + margin); + self.distance(x, z) <= r * r + } +} +impl Drop for Streaming { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.shared.ready.notify_all(); + for t in self.threads.drain(..) { + let _ = t.join(); + } + } +} diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl new file mode 100644 index 000000000..585942a77 --- /dev/null +++ b/crates/horizon-client/src/terrain.wgsl @@ -0,0 +1,115 @@ +// Terrain, sky and outline shaders, ported from the pinned vanilla +// terrain.vsh/fsh, fog.glsl and sample_lightmap.glsl. +struct Globals { + view_proj: mat4x4, + fog_color: vec4, + // environmental start/end, render-distance start/end + fog: vec4, + sky_color: vec4, + // x: sky darkening, y: game time, z: aspect, w: tan(fov/2) + misc: vec4, + inverse_view: mat4x4, + sunrise: vec4, + // xyz: sun direction, w: star brightness + sun: vec4, +} +@group(0) @binding(0) var globals: Globals; +@group(0) @binding(1) var sprites: texture_2d_array; +@group(0) @binding(2) var sprite_sampler: sampler; +@group(0) @binding(3) var lightmap: texture_2d; +@group(0) @binding(4) var lightmap_sampler: sampler; + +struct TerrainOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) layer: u32, + @location(2) color: vec4, + @location(3) spherical: f32, + @location(4) cylindrical: f32, +} +fn sample_lightmap(sky: f32, block: f32) -> vec4 { + let uv = vec2(block, sky) * 16.0; + return textureSampleLevel(lightmap, lightmap_sampler, + clamp(uv / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); +} +@vertex fn vs_terrain( + @location(0) position: vec3, @location(1) uv: vec2, + @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec4, + @location(5) origin: vec4) -> TerrainOut { + let pos = position + origin.xyz; + var out: TerrainOut; + out.clip = globals.view_proj * vec4(pos, 1.0); + out.uv = uv; + out.layer = layer; + out.color = color * sample_lightmap(f32(light.x) / 16.0, f32(light.y) / 16.0); + out.spherical = length(pos); + out.cylindrical = max(length(pos.xz), abs(pos.y)); + return out; +} +fn linear_fog(d: f32, start: f32, end: f32) -> f32 { + if d <= start { return 0.0; } + if d >= end { return 1.0; } + return (d - start) / (end - start); +} +fn apply_fog(color: vec4, spherical: f32, cylindrical: f32) -> vec4 { + let f = max(linear_fog(spherical, globals.fog.x, globals.fog.y), + linear_fog(cylindrical, globals.fog.z, globals.fog.w)); + return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); +} +@fragment fn fs_solid(in: TerrainOut) -> @location(0) vec4 { + let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color; + if color.a < 0.5 { discard; } + return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical); +} +@fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4 { + let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color; + if color.a < 0.01 { discard; } + return apply_fog(color, in.spherical, in.cylindrical); +} + +// Sky: vanilla draws a sky disc in the sky colour and blends towards the fog +// colour at the horizon; sunrise/sunset tints the horizon facing the sun. +struct SkyOut { + @builtin(position) clip: vec4, + @location(0) ndc: vec2, +} +@vertex fn vs_sky(@builtin(vertex_index) i: u32) -> SkyOut { + let p = vec2(f32(i32(i & 1u) * 4 - 1), f32(i32(i >> 1u) * 4 - 1)); + var out: SkyOut; + out.clip = vec4(p, 0.0, 1.0); + out.ndc = p; + return out; +} +@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4 { + let view = normalize((globals.inverse_view * vec4(in.ndc.x * globals.misc.z * globals.misc.w, + in.ndc.y * globals.misc.w, -1.0, 0.0)).xyz); + let up = clamp(view.y, -1.0, 1.0); + // Fog band towards the horizon (vanilla sky end distance blending). + let horizon = 1.0 - smoothstep(0.0, 0.35, up); + var color = mix(globals.sky_color.rgb, globals.fog_color.rgb, horizon); + let toward_sun = max(dot(normalize(vec3(view.x, 0.0, view.z) + vec3(0.0001)), normalize(vec3(globals.sun.x, 0.0, globals.sun.z) + vec3(0.0001))), 0.0); + let band = (1.0 - smoothstep(-0.1, 0.4, abs(up))) * pow(toward_sun, 3.0); + color = mix(color, globals.sunrise.rgb, band * globals.sunrise.a); + if up < 0.0 { + // Void below the horizon. + color = mix(color, globals.sky_color.rgb * 0.2, smoothstep(0.0, -0.3, up) * (1.0 - globals.misc.x)); + } + // Sun disc. + let sun_dot = dot(view, normalize(globals.sun.xyz)); + if sun_dot > 0.9985 { color = mix(color, vec3(1.0, 1.0, 0.85), 0.95); } + let moon_dot = dot(view, -normalize(globals.sun.xyz)); + if moon_dot > 0.9993 { color = mix(color, vec3(0.85, 0.87, 0.95), 0.9); } + // Stars. + let cell = floor(view * 300.0); + let h = fract(sin(dot(cell, vec3(12.9898, 78.233, 37.719))) * 43758.5453); + if h > 0.9985 && up > 0.0 { color += vec3(globals.sun.w * 2.0); } + return vec4(color, 1.0); +} + +struct LineOut { @builtin(position) clip: vec4 } +@vertex fn vs_line(@location(0) position: vec3) -> LineOut { + var out: LineOut; + out.clip = globals.view_proj * vec4(position, 1.0); + return out; +} +@fragment fn fs_line() -> @location(0) vec4 { return vec4(0.0, 0.0, 0.0, 0.4); } diff --git a/crates/horizon-client/src/testgen.rs b/crates/horizon-client/src/testgen.rs new file mode 100644 index 000000000..6f06366aa --- /dev/null +++ b/crates/horizon-client/src/testgen.rs @@ -0,0 +1,123 @@ +//! Simple rolling terrain used only until the vanilla overworld generator is +//! bound (`--test-terrain`). Not vanilla generation. +use crate::{chunk::Chunk, streaming::ChunkGenerator}; +use horizon_world::registry::BlockRegistry; + +pub struct TestTerrain { + stone: u16, + dirt: u16, + grass: u16, + water: u16, + sand: u16, + bedrock: u16, + log: u16, + leaves: u16, + short_grass: u16, + plains: u16, +} +impl TestTerrain { + pub fn new(registry: &BlockRegistry, biomes: &crate::biome::Biomes) -> crate::Result { + let id = |name: &str| -> crate::Result { + Ok(registry + .default_state(name) + .ok_or_else(|| format!("missing {name}"))? + .0 as u16) + }; + Ok(Self { + stone: id("minecraft:stone")?, + dirt: id("minecraft:dirt")?, + grass: id("minecraft:grass_block")?, + water: id("minecraft:water")?, + sand: id("minecraft:sand")?, + bedrock: id("minecraft:bedrock")?, + log: id("minecraft:oak_log")?, + leaves: registry + .resolve(&horizon_world::chunk::BlockState { + name: "minecraft:oak_leaves".into(), + properties: [ + ("distance".to_owned(), "1".to_owned()), + ("persistent".to_owned(), "false".to_owned()), + ("waterlogged".to_owned(), "false".to_owned()), + ] + .into(), + })? + .0 as u16, + short_grass: id("minecraft:short_grass")?, + plains: biomes.id("minecraft:plains"), + }) + } + fn height(x: i32, z: i32) -> i32 { + let (x, z) = (f64::from(x), f64::from(z)); + let h = 68.0 + + 10.0 * (x / 47.0).sin() * (z / 61.0).cos() + + 5.0 * ((x + z) / 23.0).sin() + + 3.0 * (x / 11.0).cos() * (z / 13.0).sin(); + h as i32 + } +} +fn hash(x: i32, z: i32) -> u32 { + let mut h = (x as u32).wrapping_mul(0x9E37_79B1) ^ (z as u32).wrapping_mul(0x85EB_CA77); + h ^= h >> 15; + h = h.wrapping_mul(0x2C1B_3C6D); + h ^ (h >> 12) +} +impl ChunkGenerator for TestTerrain { + type Worker = (); + fn worker(&self) {} + fn generate(&self, _: &mut (), cx: i32, cz: i32) -> Chunk { + let mut chunk = Chunk::empty(cx, cz); + chunk.biomes = std::sync::Arc::new(vec![self.plains; chunk.biomes.len()]); + for z in 0..16 { + for x in 0..16 { + let (wx, wz) = (cx * 16 + x, cz * 16 + z); + let h = Self::height(wx, wz); + for y in -64..=h.max(62) { + let b = if y == -64 { + self.bedrock + } else if y > h { + self.water + } else if y < h - 3 { + self.stone + } else if h <= 63 { + self.sand + } else if y == h { + self.grass + } else { + self.dirt + }; + chunk.set(x, y, z, b); + } + if h > 63 && hash(wx, wz) % 13 == 0 { + chunk.set(x, h + 1, z, self.short_grass); + } + } + } + // Trees fully inside the chunk. + for z in 2..14 { + for x in 2..14 { + let (wx, wz) = (cx * 16 + x, cz * 16 + z); + let h = Self::height(wx, wz); + if h <= 64 || hash(wx, wz) % 97 != 0 { + continue; + } + for y in h + 1..h + 6 { + chunk.set(x, y, z, self.log); + } + for dy in 3..7 { + let r = if dy >= 5 { 1 } else { 2 }; + for dz in -r..=r { + for dx in -r..=r { + if chunk.get(x + dx, h + dy, z + dz) == 0 { + chunk.set(x + dx, h + dy, z + dz, self.leaves); + } + } + } + } + } + } + for s in &mut chunk.sections { + std::sync::Arc::make_mut(s).compact(); + } + chunk + } +} diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index e44ff9da2..62e0666bc 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -1,110 +1,93 @@ -//! A controlled blockstate scene for exercising the native renderer. This is -//! not the vanilla world generator or an authoritative gameplay simulation. -use crate::{ - Result, - assets::{Assets, Properties}, +//! Resident client world: streamed chunk columns plus the bookkeeping the game +//! loop needs to relight and remesh after edits. +use crate::chunk::{Chunk, MIN_Y, SECTIONS}; +use horizon_core::random::LegacyRandom; +use horizon_world::registry::BlockStateId; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, }; -use horizon_core::{position::ChunkPos, random::LegacyRandom}; -use horizon_world::{registry::BlockStateId, worldgen::terrain::TerrainChunk}; -use std::collections::BTreeMap; -pub struct TestWorld<'a> { - pub chunks: BTreeMap<(i32, i32), TerrainChunk<'a, Properties>>, +pub struct World { + pub chunks: HashMap<(i32, i32), Arc>, pub random: LegacyRandom, pub revision: u64, pub health_rules: crate::health::HealthRules, - air: BlockStateId, + pub air: BlockStateId, + /// Sections whose geometry changed and need remeshing. + pub dirty_sections: HashSet<(i32, i32, i32)>, + /// Chunks whose light must be recomputed. + pub dirty_light: HashSet<(i32, i32)>, + /// Chunks changed since the last save. + pub modified: HashSet<(i32, i32)>, + pub game_time: i64, + pub day_time: i64, } -impl<'a> TestWorld<'a> { - pub fn new(assets: &'a Assets, radius: i32) -> Result { - let air = assets - .registry - .default_state("minecraft:air") - .ok_or("missing air state")?; - let mut world = Self { - chunks: BTreeMap::new(), - random: LegacyRandom::new(0), +impl World { + pub fn new(air: BlockStateId, seed: i64) -> Self { + Self { + chunks: HashMap::new(), + random: LegacyRandom::new(seed), revision: 0, health_rules: crate::health::HealthRules::default(), air, - }; - for cz in -radius..=radius { - for cx in -radius..=radius { - let mut chunk = TerrainChunk::new( - ChunkPos::new(cx, cz), - 0, - 16, - &assets.registry, - assets.properties.clone(), - )?; - for z in 0..16 { - for x in 0..16 { - for y in 0..4 { - let layer = match y { - 0 => 0, - 1 | 2 => 1, - _ => { - if (cx + cz) & 1 == 0 { - 2 - } else { - 3 - } - } - }; - chunk.set_block_worldgen( - cx * 16 + x, - y, - cz * 16 + z, - assets.material_states[layer], - )?; - } - } - } - world.chunks.insert((cx, cz), chunk); - } + dirty_sections: HashSet::new(), + dirty_light: HashSet::new(), + modified: HashSet::new(), + game_time: 0, + day_time: 1000, } - for y in 4..11 { - for z in -10_i32..=10 { - for x in -10_i32..=10 { - if x.abs().max(z.abs()) <= 10 - (y - 4) { - world.set( - x, - y, - z, - assets.material_states[if y & 1 == 0 { 4 } else { 5 }], - )?; - } - } - } - } - for (position, state) in &assets.model_placements { - world.set(position.x, position.y, position.z, *state)?; - } - world.revision = 0; - Ok(world) } - /// Resident storage write. Neighbor updates, drops and block-entity - /// lifecycle must be dispatched by the owning gameplay runtime. - pub fn set(&mut self, x: i32, y: i32, z: i32, state: BlockStateId) -> Result<()> { - let chunk = self - .chunks - .get_mut(&(x >> 4, z >> 4)) - .ok_or("test scene exceeds resident chunks")?; - if y < chunk.min_y() || y >= chunk.min_y() + chunk.height() { - return Err("test scene write exceeds resident height".into()); + /// Resident storage write; marks the touched sections (and neighbours on + /// section borders) for remeshing and the surrounding chunks for relighting. + /// Neighbour updates, drops and block entities belong to the gameplay layer. + pub fn set(&mut self, x: i32, y: i32, z: i32, state: BlockStateId) -> crate::Result<()> { + let Some(chunk) = self.chunks.get_mut(&(x >> 4, z >> 4)) else { + return Err("write outside resident chunks".into()); + }; + if y < MIN_Y || y >= MIN_Y + (SECTIONS as i32) * 16 { + return Err("write outside world height".into()); } - let previous = chunk.set_block_worldgen(x, y, z, state)?; - if previous != state { + let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0 as u16); + if u32::from(previous) != state.0 { self.revision = self.revision.wrapping_add(1); + self.modified.insert((x >> 4, z >> 4)); + let sy = (y - MIN_Y) >> 4; + for dz in -1..=1 { + for dy in -1..=1 { + for dx in -1..=1 { + let (bx, by, bz) = (x + dx, y + dy, z + dz); + let s = (by - MIN_Y) >> 4; + if !(0..SECTIONS as i32).contains(&s) { + continue; + } + self.dirty_sections.insert((bx >> 4, s, bz >> 4)); + } + } + } + let _ = sy; + for dz in -1..=1 { + for dx in -1..=1 { + self.dirty_light.insert(((x >> 4) + dx, (z >> 4) + dz)); + } + } } Ok(()) } pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { self.chunks .get(&(x >> 4, z >> 4)) - .map_or(self.air, |chunk| chunk.block(x, y, z)) + .map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15)) + } + pub fn light(&self, x: i32, y: i32, z: i32) -> u8 { + self.chunks + .get(&(x >> 4, z >> 4)) + .map_or(0xF0, |chunk| chunk.light(x & 15, y, z & 15)) } pub fn is_air(&self, state: BlockStateId) -> bool { state == self.air } + pub fn loaded(&self, x: i32, z: i32) -> bool { + self.chunks.contains_key(&(x >> 4, z >> 4)) + } } diff --git a/crates/horizon-client/src/world.wgsl b/crates/horizon-client/src/world.wgsl deleted file mode 100644 index 16c2b24a9..000000000 --- a/crates/horizon-client/src/world.wgsl +++ /dev/null @@ -1,71 +0,0 @@ -struct Camera { - view_projection: mat4x4, - position: vec4, - fog: vec4, -} -@group(0) @binding(0) var camera: Camera; -@group(0) @binding(1) var sprites: texture_2d_array; -@group(0) @binding(2) var sprite_sampler: sampler; -struct VertexOut { - @builtin(position) clip: vec4, - @location(0) uv: vec2, - @location(1) @interpolate(flat) layer: u32, - @location(2) shade: f32, - @location(3) world_position: vec3, -} -@vertex fn vs_main(@builtin(vertex_index) vertex: u32, - @location(0) origin: vec3, @location(1) extent: vec2, - @location(2) face: u32, @location(3) layer: u32, - @location(4) uv_origin: vec2, @location(5) uv_u: vec2, - @location(6) uv_v: vec2, @location(7) shade: f32) -> VertexOut { - let corners = array,4>(vec2(0.0,0.0),vec2(1.0,0.0),vec2(1.0,1.0),vec2(0.0,1.0)); - let normal_order = array(0u,1u,2u,0u,2u,3u); - let reversed_order = array(0u,2u,1u,0u,3u,2u); - let flipped = face==1u || face==2u || face==5u; - let corner = corners[select(normal_order[vertex],reversed_order[vertex],flipped)]; - let offset = corner*extent; - var position = origin; - if face<2u { position+=vec3(offset.x,0.0,offset.y); } - else if face<4u { position+=vec3(offset.x,offset.y,0.0); } - else { position+=vec3(0.0,offset.y,offset.x); } - var output: VertexOut; - output.clip=camera.view_projection*vec4(position,1.0); - output.uv=uv_origin+uv_u*offset.x+uv_v*offset.y; - output.layer=layer; - output.shade=shade; - output.world_position=position; - return output; -} -@fragment fn fs_main(input:VertexOut)->@location(0) vec4 { - let color=textureSample(sprites,sprite_sampler,input.uv,i32(input.layer)); - let distance=length(input.world_position-camera.position.xyz); - let fog_amount=smoothstep(camera.position.w*0.65,camera.position.w,distance); - return vec4(mix(color.rgb*input.shade,camera.fog.rgb,fog_amount),1.0); -} - -@vertex fn vs_model(@builtin(vertex_index) vertex: u32, - @location(0) p0: vec3, @location(1) p1: vec3, - @location(2) p2: vec3, @location(3) p3: vec3, - @location(4) uv0: vec2, @location(5) uv1: vec2, - @location(6) uv2: vec2, @location(7) uv3: vec2, - @location(8) layer: u32, @location(9) shade: f32) -> VertexOut { - let order=array(0u,1u,2u,0u,2u,3u); - let positions=array,4>(p0,p1,p2,p3); - let uvs=array,4>(uv0,uv1,uv2,uv3); - let corner=order[vertex]; - var output: VertexOut; - output.clip=camera.view_projection*vec4(positions[corner],1.0); - output.uv=uvs[corner]; - output.layer=layer; - output.shade=shade; - output.world_position=positions[corner]; - return output; -} -@fragment fn fs_model(input:VertexOut)->@location(0) vec4 { - let color=textureSample(sprites,sprite_sampler,input.uv,i32(input.layer)); - // Inspection sprites are validated to contain only zero or full alpha. - if color.a<0.5 { discard; } - let distance=length(input.world_position-camera.position.xyz); - let fog_amount=smoothstep(camera.position.w*0.65,camera.position.w,distance); - return vec4(mix(color.rgb*input.shade,camera.fog.rgb,fog_amount),1.0); -} diff --git a/crates/horizon-world/src/block_render.rs b/crates/horizon-world/src/block_render.rs index 129614cf4..2d3932c81 100644 --- a/crates/horizon-world/src/block_render.rs +++ b/crates/horizon-world/src/block_render.rs @@ -39,6 +39,7 @@ struct State { } /// Prepared face geometry and a bounded cache shared across state pairs. Geometry /// is deduplicated by the imported immutable shape, not copied for every state. +#[derive(Clone)] pub struct FaceVisibility { states: Vec, faces: Vec, @@ -156,6 +157,18 @@ impl FaceVisibility { } } } + /// Whether the state's occlusion face toward `direction` is the full square. + pub fn full_face(&self, state: BlockStateId, direction: Direction) -> bool { + self.states + .get(state.0 as usize) + .is_some_and(|s| s.faces[direction as usize] == 1) + } + /// Whether the state's occlusion face toward `direction` is empty. + pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool { + self.states + .get(state.0 as usize) + .is_none_or(|s| s.faces[direction as usize] == 0) + } pub fn skip_rendering( &self, state: BlockStateId, diff --git a/docs/native-client.md b/docs/native-client.md index 560f99659..7cd8bf7c2 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -1,94 +1,77 @@ -# Horizon native development client +# Horizon native client -`horizon-client` opens a native Rust window and renders a controlled block scene -stored in Horizon's resident chunks. Every occupied cell selects models from its -registry state, including the terrain and sixteen featured placements. It loads -block definitions, cuboid models, sprites and occlusion grids from pinned Java -Edition 26.3 resources. Model selection uses the default block position seed; -neighbor visibility uses the validated Rust face rules across chunk boundaries. -The default camera is an inspection tool. F4 enables a standing-sized collision -volume that queries the rendered resident chunks through the shared world -collision implementation. The camera can still fly; it does not simulate a player. -F5 switches to a dry walking test with gravity, ground support, stepping and -held-jump timing over the same resident chunks. Its movement runs at 20 ticks/s; -the camera interpolates between tick positions. Landing damage now updates stored -health, absorption and hurt cooldown state. Hunger and regeneration tick after -movement. Left Shift crouches, with pose-dependent collision bounds and eye height. -F3 diagnostics include health, food, sprinting and pose. +`horizon-client` is the playable Rust client for Minecraft Java Edition 26.3. +It streams a world around the player on worker threads, renders every vanilla +block model with smooth lighting and biome tints, and runs the validated player +physics, health and hunger at 20 ticks per second. You can mine with vanilla +hardness/tool rules, collect drops from the block loot tables, place blocks, +craft in the 2x2 inventory grid or on a crafting table, and save and reload worlds +in vanilla's Anvil format. -Eligible opaque unit-cube faces use greedy rectangles only when texture layer, -UV rotation/mirroring and shading match. Each rectangle retains its signed UV -basis, so weighted texture variation survives merging. Other baked geometry and -binary-alpha cutouts use the separate model-face instance pipeline. Geometry -with nonintegral UV-lock rounding also stays on that path. - -This checkpoint has partial player movement, landing damage and hunger. Vanilla world generation, block -interaction, inventory, sound, networking and world save/load remain unbound in -the native client. It does not meet -the [playable-build acceptance criteria](rust-parity.md#completion-criteria-and-playable-builds). -The controlled chunk scene now uses blockstate dispatch, weighted variants, -multipart conditions and transformed baking. Full block-catalog material support, -fractional transparency, tinting, lighting, resource packs, chunk streaming and -full visual parity remain unfinished. - -The resource gallery sits beside the pyramid and includes oak stairs, a slab, -an anvil, a torch, a lantern, connected fences and iron bars, a cobweb, a wall -grindstone, a ladder, a sideways amethyst cluster and four weighted stone -placements. Registry state properties select the models: the stairs are an -upside-down inner corner, the slab is a top slab and the fence gate is open. -These are resident chunk states; simulation callbacks remain unfinished. Binary-alpha cutouts are rendered; -the lantern's three frames advance every eight inspection ticks at 20 ticks/s. -The animation metadata codec and frame selection now use the shared -`horizon-assets` implementation checked against the pinned client. GPU -interpolation and synchronization with the eventual game loop remain unfinished. -Sprites currently require matching square frame dimensions. +**Status:** playable, not yet at parity. Terrain currently comes from a simple +test generator until the vanilla overworld generator (already byte-identical +to vanilla up to the carver stage in `horizon-world`) is bound to streaming. +There are no mobs, block behaviours (fluid spreading, redstone, crop growth), +structures, furnaces/containers or multiplayer yet. See +[Rust rewrite status](rust-parity.md). ## Run from a checkout -Use current stable Rust (the locked client dependencies require Rust 1.90 or -newer), Python 3.10+ and JDK 25. A native desktop display and compatible graphics -driver are required. Resource preparation verifies the pinned game artifacts, -exports the registry using the reference server and property schemas using the -reference client, and extracts selected client -resources into ignored `.local/horizon-client/26.3/`. +Use current stable Rust (1.90+), Python 3.10+ and JDK 25. Resource preparation +verifies the pinned game artifacts, runs vanilla's data generator and small +exporters against the reference jars, and extracts the jar's assets and data +into ignored `.local/horizon-client/26.3/`. Sounds come from Mojang's asset +index (about 380 MB). Prepared resources are private; never commit them. ```sh python3 tools/prepare_native_client.py --prepare -cargo +stable run --locked -p horizon-client +python3 tools/fetch_sounds.py +cargo run --release -p horizon-client -- --render-distance 12 ``` -Java is used during preparation. The native executable itself runs without a -JVM. Prepared resources stay private; do not commit or publish the extracted game -files. Final distributable builds still need resource provisioning and packaging. +Development builds that link quickly: `cargo build --profile fast -p horizon-client`. -Use `--resources PATH` for a prepared resource directory. The executable also -looks for a sibling `resources/` directory before the checkout default. Use -`--radius N` to select 1–16 chunks around the origin; this is a finite test scene, -not a render-distance or world-streaming implementation. +| Option | Meaning | +| --- | --- | +| `--world NAME` | World folder under `saves/` (default "New World"); reopened if it exists | +| `--seed N` | Seed for a new world (numbers or text, like vanilla) | +| `--creative` | Creative mode (instant breaking, pick block) | +| `--render-distance N` | Chunks, 2..64 (default 12) | +| `--resources PATH` | Prepared resource directory | | Control | Action | | --- | --- | -| WASD | Move horizontally | -| Space / either Shift | Rise / descend in inspection mode; Space jumps in walking mode | -| Either Ctrl | Boost inspection speed | -| Left Shift | Crouch in walking mode | -| Left Ctrl while moving forward, or double-tap W | Start sprinting in walking mode when eligible | -| Arrow keys | Rotate camera | -| Left click | Capture mouse for camera rotation | -| Escape | Release mouse | -| F3 | Toggle FPS/chunk/mesh/health/food/sprint/pose diagnostics in the window title | -| F4 | Toggle inspection camera collisions; enabling requires an unobstructed position | -| F5 | Toggle walking test at the current camera position; enabling requires an unobstructed position | -| Ctrl+Q or window close | Exit | +| Mouse | Look (vanilla default sensitivity) | +| WASD / Space / Left Shift / Left Ctrl | Move, jump, sneak, sprint | +| Left / right click | Break (hold) / place or use; right click opens crafting tables | +| Middle click | Pick block (creative) | +| 1–9, scroll | Select hotbar slot | +| E | Inventory and 2x2 crafting (shift-click to quick-move or craft all) | +| Q / Ctrl+Q | Drop one / drop stack | +| F3 | Debug overlay (position, chunk, light, biome, FPS) | +| Esc | Pause menu (Save and Quit) | -Controls bind physical keyboard positions. Losing focus clears held keys and -releases the mouse. Walking pauses while unfocused and resets partial tick time -on focus changes. Sprinting continues after releasing Left Ctrl while forward -input remains held; hunger and collisions can stop it. Walking currently has no flight, item use or block interaction. F5 returns to inspection mode; the finite scene has no -streaming or boundary wall. `--trace-input` logs keyboard, mouse-button and focus events -for diagnosis. On headless Linux use `vscreen run ./target/debug/horizon-client`, -then `vscreen shot`. The `wtype` tool's default generated keymap does not preserve -physical key positions; typing the character W can report physical Escape. +Worlds autosave every 6000 ticks (5 minutes), when chunks unload and on quit. +On headless Linux use `vscreen start ./target/release/horizon-client` and +`vscreen shot`. + +## How it fits together + +- `streaming.rs`: worker pool that generates or loads, lights and meshes chunk + columns closest-first; stale results are discarded by sequence number. +- `light.rs`: vanilla sky/block light rules (sky sources down to the first + occluding edge, `max(1, dampening)` falloff) over a 3x3 chunk region. +- `mesher.rs`: blockstate models with neighbour culling, `ModelBlockRenderer` + smooth lighting/ambient occlusion, `BlockTintSources` tints with 5x5 biome + blending, and `FluidRenderer` water/lava surfaces. +- `gfx.rs` + `terrain.wgsl`: camera-relative section rendering with frustum + culling, the vanilla lightmap formula, timeline-driven sky/fog, and + solid/cutout/translucent passes; `entity.wgsl` draws dropped items. +- `environment.rs`: the data-driven day timeline (sky colour, light factor, + celestial angles) sampled with vanilla's keyframe/easing rules. +- `items.rs`, `crafting.rs`: item components from vanilla's reports, tool + mining rules, loot tables and crafting recipes from the data pack. +- `save.rs`: Anvil region files and `level.dat`. ## Validation diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityModelExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityModelExporter.java new file mode 100644 index 000000000..0298bd98a --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityModelExporter.java @@ -0,0 +1,69 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.client.model.geom.LayerDefinitions; +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.server.Bootstrap; + +/** + * Original exporter of every baked entity model layer (part tree, initial poses and + * textured polygons) produced by vanilla's own LayerDefinitions. + */ +public final class VanillaEntityModelExporter { + private static Field cubes; + private static Field children; + + @SuppressWarnings("unchecked") + private static JsonObject part(ModelPart part) throws Exception { + var o = new JsonObject(); + var pose = new JsonArray(); + for (float f : new float[] {part.x, part.y, part.z, part.xRot, part.yRot, part.zRot, part.xScale, part.yScale, part.zScale}) + pose.add(f); + o.add("pose", pose); + var polygons = new JsonArray(); + for (ModelPart.Cube cube : (List) cubes.get(part)) { + for (ModelPart.Polygon polygon : cube.polygons) { + var p = new JsonArray(); + for (ModelPart.Vertex v : polygon.vertices()) { + var vertex = new JsonArray(); + vertex.add(v.x()); + vertex.add(v.y()); + vertex.add(v.z()); + vertex.add(v.u()); + vertex.add(v.v()); + p.add(vertex); + } + polygons.add(p); + } + } + o.add("polygons", polygons); + var kids = new JsonObject(); + for (var entry : ((Map) children.get(part)).entrySet()) + kids.add(entry.getKey(), part(entry.getValue())); + o.add("children", kids); + return o; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + cubes = ModelPart.class.getDeclaredField("cubes"); + cubes.setAccessible(true); + children = ModelPart.class.getDeclaredField("children"); + children.setAccessible(true); + var out = new JsonObject(); + for (var entry : LayerDefinitions.createRoots().entrySet()) { + try { + out.add(entry.getKey().toString(), part(entry.getValue().bakeRoot())); + } catch (RuntimeException error) { + System.err.println("skipped " + entry.getKey() + ": " + error); + } + } + Files.writeString(Path.of(args[0]), new Gson().toJson(out), StandardCharsets.UTF_8); + } +} diff --git a/tools/fetch_sounds.py b/tools/fetch_sounds.py new file mode 100644 index 000000000..394c03db6 --- /dev/null +++ b/tools/fetch_sounds.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Fetch the pinned version's sound assets (sounds.json and .ogg files) from +Mojang's asset index into the private client resource directory, verifying +every object's SHA-1. The files stay in ignored .local/ and are never committed.""" +import concurrent.futures +import hashlib +import json +from pathlib import Path +import urllib.request + +ROOT = Path(__file__).resolve().parent.parent +LOCAL = ROOT / '.local' + + +def fetch(url): + with urllib.request.urlopen(url, timeout=120) as response: + return response.read() + + +def main(): + manifest = json.loads((LOCAL / 'minecraft/26.3/manifest.json').read_text()) + index_info = manifest['assetIndex'] + target = LOCAL / 'horizon-client/26.3' + index_path = target / 'asset-index.json' + if not index_path.exists() or hashlib.sha1(index_path.read_bytes()).hexdigest() != index_info['sha1']: + data = fetch(index_info['url']) + if hashlib.sha1(data).hexdigest() != index_info['sha1']: + raise ValueError('asset index checksum mismatch') + index_path.write_bytes(data) + objects = json.loads(index_path.read_text())['objects'] + wanted = {name: info for name, info in objects.items() + if name == 'minecraft/sounds.json' or name.startswith('minecraft/sounds/')} + + def download(item): + name, info = item + path = target / 'assets' / name + if path.exists() and hashlib.sha1(path.read_bytes()).hexdigest() == info['hash']: + return 0 + h = info['hash'] + data = fetch(f'https://resources.download.minecraft.net/{h[:2]}/{h}') + if hashlib.sha1(data).hexdigest() != h: + raise ValueError(f'checksum mismatch for {name}') + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return len(data) + + total = 0 + with concurrent.futures.ThreadPoolExecutor(16) as pool: + for size in pool.map(download, wanted.items()): + total += size + print(f'Sound assets ready: {len(wanted)} files, {total / 1e6:.1f} MB downloaded') + + +if __name__ == '__main__': + main() diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 0615f7db1..62b023550 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -207,6 +207,20 @@ def main(): (root / 'biome-parameters').mkdir(exist_ok=True) for f in (reports / 'biome_parameters' / 'minecraft').glob('*.json'): (root / 'biome-parameters' / f.name).write_bytes(f.read_bytes()) + entity_models = root / 'entity-models.json' + entity_oracle = oracle.with_name('VanillaEntityModelExporter.java') + entity_sources = base.source_hashes([entity_oracle]) + if not (previous.get('entity_model_exporters_sha256') == entity_sources and entity_models.exists() + and previous.get('client_sha256') == origin['client_sha256']): + classes = lab.LOCAL / 'entity-models' / 'classes'; classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + with (root / 'entity-model-export.log').open('w') as log: + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', + '-cp', dependencies, '-d', str(classes), str(entity_oracle)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaEntityModelExporter', str(entity_models)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) lab.write_json(manifest, {'schema': 7, **origin, 'health_exporters_sha256': health_sources, 'health_files_sha256': {name: lab.digest(root/name, 'sha256') for name in health_files}, @@ -218,6 +232,7 @@ def main(): 'render_files_sha256': {name: lab.digest(root/name, 'sha256') for name in render_files}, 'model_state_exporters_sha256': binding_sources, 'gameplay_exporters_sha256': gameplay_sources, + 'entity_model_exporters_sha256': entity_sources, 'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'], 'facts_sha256': lab.digest(facts, 'sha256'), 'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count})